Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add xmldoc to mem layout attributes. | using System;
namespace AsmResolver.DotNet.Memory
{
[Flags]
public enum MemoryLayoutAttributes
{
Is32Bit = 0b0,
Is64Bit = 0b1,
BitnessMask = 0b1,
IsPlatformDependent = 0b10,
}
}
| using System;
namespace AsmResolver.DotNet.Memory
{
/// <summary>
/// Defines members for all possible attributes that can be assigned to a <see cref="TypeMemoryLayout"/> instance.
/// </summary>
[Flags]
public enum MemoryLayoutAttributes
{
/// <summary>
/// Indicates the layout was determined assuming a 32-bit environment.
/// </summary>
Is32Bit = 0b0,
/// <summary>
/// Indicates the layout was determined assuming a 32-bit environment.
/// </summary>
Is64Bit = 0b1,
/// <summary>
/// Used to mask out the bitness of the type layout.
/// </summary>
BitnessMask = 0b1,
/// <summary>
/// Indicates the type layout depends on the bitness of the environment.
/// </summary>
IsPlatformDependent = 0b10,
}
}
|
Test Server-side function called in transaction fails | using System;
using NUnit.Framework;
namespace Business.Core.Test
{
[TestFixture]
public class TestDBFunctions
{
[Test]
public void Book() {
var profile = new Profile.Profile();
var database = new Fake.Database(profile);
database.Connect();
var bookName = "Sales";
float bookAmount = 111.11F;
int? entryId = 1;
database.SetValue(entryId);
var entry = database.Book(bookName, bookAmount);
Assert.IsNotNull(entry);
Assert.Greater(entry, 0);
Assert.AreEqual(entryId, entry);
}
}
} | using System;
using NUnit.Framework;
namespace Business.Core.Test
{
[TestFixture]
public class TestDBFunctions
{
[Test]
public void Book() {
var profile = new Profile.Profile();
var database = new Fake.Database(profile);
database.Connect();
var bookName = "Sales";
float bookAmount = 111.11F;
int? entryId = 1;
database.SetValue(entryId);
Assert.IsFalse(database.Connection.TransactionStarted);
var entry = database.Book(bookName, bookAmount);
Assert.IsTrue(database.Connection.TransactionStarted);
Assert.IsFalse(database.Connection.TransactionRollback);
Assert.IsTrue(database.Connection.TransactionCommited);
Assert.IsNotNull(entry);
Assert.Greater(entry, 0);
Assert.AreEqual(entryId, entry);
}
}
} |
Comment out game logic and replace table code | using System;
namespace Hangman {
public class Hangman {
public static void Main(string[] args) {
char key = Console.ReadKey(true).KeyChar;
var game = new Game("HANG THE MAN");
bool wasCorrect = game.GuessLetter(key);
Console.WriteLine(wasCorrect.ToString());
var output = game.ShownWord();
Console.WriteLine(output);
// Table table = new Table(2, 3);
// string output = table.Draw();
// Console.WriteLine(output);
}
}
}
| using System;
namespace Hangman {
public class Hangman {
public static void Main(string[] args) {
// char key = Console.ReadKey(true).KeyChar;
// var game = new Game("HANG THE MAN");
// bool wasCorrect = game.GuessLetter(key);
// Console.WriteLine(wasCorrect.ToString());
// var output = game.ShownWord();
// Console.WriteLine(output);
Table table = new Table(2, 3);
string output = table.Draw();
Console.WriteLine(output);
}
}
}
|
Exclude files that can not be accessed | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace FileReplacer
{
public static class FileHelper
{
public static readonly Encoding UTF8N = new UTF8Encoding();
public static void ReplaceContent(FileInfo file, string oldValue, string newValue)
{
string oldContent;
Encoding encoding;
using (var reader = new StreamReader(file.FullName, UTF8N, true))
{
oldContent = reader.ReadToEnd();
encoding = reader.CurrentEncoding;
}
if (!oldContent.Contains(oldValue)) return;
var newContent = oldContent.Replace(oldValue, newValue);
File.WriteAllText(file.FullName, newContent, encoding);
Console.WriteLine($"Replaced content: {file.FullName}");
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace FileReplacer
{
public static class FileHelper
{
public static readonly Encoding UTF8N = new UTF8Encoding();
public static void ReplaceContent(FileInfo file, string oldValue, string newValue)
{
if (file.Attributes.HasFlag(FileAttributes.ReadOnly) || file.Attributes.HasFlag(FileAttributes.Hidden)) return;
string oldContent;
Encoding encoding;
using (var reader = new StreamReader(file.FullName, UTF8N, true))
{
oldContent = reader.ReadToEnd();
encoding = reader.CurrentEncoding;
}
if (!oldContent.Contains(oldValue)) return;
var newContent = oldContent.Replace(oldValue, newValue);
File.WriteAllText(file.FullName, newContent, encoding);
Console.WriteLine($"Replaced content: {file.FullName}");
}
}
}
|
Add caching option when downloading package. | namespace NuPack {
using System;
using System.IO;
using System.Net;
using System.Net.Cache;
// REVIEW: This class isn't super clean. Maybe this object should be passed around instead
// of being static
public static class HttpWebRequestor {
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Reliability",
"CA2000:Dispose objects before losing scope",
Justification="We can't dispose an object if we want to return it.")]
public static ZipPackage DownloadPackage(Uri uri) {
return new ZipPackage(() => {
using (Stream responseStream = GetResponseStream(uri)) {
// ZipPackages require a seekable stream
var memoryStream = new MemoryStream();
// Copy the stream
responseStream.CopyTo(memoryStream);
// Move it back to the beginning
memoryStream.Seek(0, SeekOrigin.Begin);
return memoryStream;
}
});
}
public static Stream GetResponseStream(Uri uri) {
WebRequest request = WebRequest.Create(uri);
InitializeRequest(request);
WebResponse response = request.GetResponse();
return response.GetResponseStream();
}
internal static void InitializeRequest(WebRequest request) {
request.CachePolicy = new HttpRequestCachePolicy();
request.UseDefaultCredentials = true;
if (request.Proxy != null) {
// If we are going through a proxy then just set the default credentials
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
}
}
}
}
| namespace NuPack {
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net;
using System.Net.Cache;
// REVIEW: This class isn't super clean. Maybe this object should be passed around instead
// of being static
public static class HttpWebRequestor {
public static ZipPackage DownloadPackage(Uri uri) {
return DownloadPackage(uri, useCache: true);
}
[SuppressMessage(
"Microsoft.Reliability",
"CA2000:Dispose objects before losing scope",
Justification = "We can't dispose an object if we want to return it.")]
public static ZipPackage DownloadPackage(Uri uri, bool useCache) {
byte[] cachedBytes = null;
return new ZipPackage(() => {
if (useCache && cachedBytes != null) {
return new MemoryStream(cachedBytes);
}
using (Stream responseStream = GetResponseStream(uri)) {
// ZipPackages require a seekable stream
var memoryStream = new MemoryStream();
// Copy the stream
responseStream.CopyTo(memoryStream);
// Move it back to the beginning
memoryStream.Seek(0, SeekOrigin.Begin);
if (useCache) {
// Cache the bytes for this package
cachedBytes = memoryStream.ToArray();
}
return memoryStream;
}
});
}
public static Stream GetResponseStream(Uri uri) {
WebRequest request = WebRequest.Create(uri);
InitializeRequest(request);
WebResponse response = request.GetResponse();
return response.GetResponseStream();
}
internal static void InitializeRequest(WebRequest request) {
request.CachePolicy = new HttpRequestCachePolicy();
request.UseDefaultCredentials = true;
if (request.Proxy != null) {
// If we are going through a proxy then just set the default credentials
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
}
}
}
}
|
Add map from view model to db model. | namespace CountryFood.Web.Infrastructure.Mappings
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using AutoMapper;
public class AutoMapperConfig
{
private Assembly assembly;
public AutoMapperConfig(Assembly assembly)
{
this.assembly = assembly;
}
public void Execute()
{
var types = this.assembly.GetExportedTypes();
LoadStandardMappings(types);
LoadCustomMappings(types);
}
private static void LoadStandardMappings(IEnumerable<Type> types)
{
var maps = (from t in types
from i in t.GetInterfaces()
where i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapFrom<>) &&
!t.IsAbstract &&
!t.IsInterface
select new
{
Source = i.GetGenericArguments()[0],
Destination = t
}).ToArray();
foreach (var map in maps)
{
Mapper.CreateMap(map.Source, map.Destination);
}
}
private static void LoadCustomMappings(IEnumerable<Type> types)
{
var maps = (from t in types
from i in t.GetInterfaces()
where typeof(IHaveCustomMappings).IsAssignableFrom(t) &&
!t.IsAbstract &&
!t.IsInterface
select (IHaveCustomMappings)Activator.CreateInstance(t)).ToArray();
foreach (var map in maps)
{
map.CreateMappings(Mapper.Configuration);
}
}
}
} | namespace CountryFood.Web.Infrastructure.Mappings
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using AutoMapper;
public class AutoMapperConfig
{
private Assembly assembly;
public AutoMapperConfig(Assembly assembly)
{
this.assembly = assembly;
}
public void Execute()
{
var types = this.assembly.GetExportedTypes();
LoadStandardMappings(types);
LoadCustomMappings(types);
}
private static void LoadStandardMappings(IEnumerable<Type> types)
{
var maps = (from t in types
from i in t.GetInterfaces()
where i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapFrom<>) &&
!t.IsAbstract &&
!t.IsInterface
select new
{
Source = i.GetGenericArguments()[0],
Destination = t
}).ToArray();
foreach (var map in maps)
{
Mapper.CreateMap(map.Source, map.Destination);
Mapper.CreateMap(map.Destination, map.Source);
}
}
private static void LoadCustomMappings(IEnumerable<Type> types)
{
var maps = (from t in types
from i in t.GetInterfaces()
where typeof(IHaveCustomMappings).IsAssignableFrom(t) &&
!t.IsAbstract &&
!t.IsInterface
select (IHaveCustomMappings)Activator.CreateInstance(t)).ToArray();
foreach (var map in maps)
{
map.CreateMappings(Mapper.Configuration);
}
}
}
} |
Rename unit test function to be more explicit on its purpose. | using System.IO;
using System.Text;
using System.Threading.Tasks;
using Shouldly;
using Xunit;
namespace MediatR.Tests
{
public class NotificationHandlerTests
{
public class Ping : INotification
{
public string Message { get; set; }
}
public class PongChildHandler : NotificationHandler<Ping>
{
private readonly TextWriter _writer;
public PongChildHandler(TextWriter writer)
{
_writer = writer;
}
protected override void Handle(Ping notification)
{
_writer.WriteLine(notification.Message + " Pong");
}
}
[Fact]
public async Task Should_call_abstract_handler()
{
var builder = new StringBuilder();
var writer = new StringWriter(builder);
INotificationHandler<Ping> handler = new PongChildHandler(writer);
await handler.Handle(
new Ping() { Message = "Ping" },
default
);
var result = builder.ToString();
result.ShouldContain("Ping Pong");
}
}
}
| using System.IO;
using System.Text;
using System.Threading.Tasks;
using Shouldly;
using Xunit;
namespace MediatR.Tests
{
public class NotificationHandlerTests
{
public class Ping : INotification
{
public string Message { get; set; }
}
public class PongChildHandler : NotificationHandler<Ping>
{
private readonly TextWriter _writer;
public PongChildHandler(TextWriter writer)
{
_writer = writer;
}
protected override void Handle(Ping notification)
{
_writer.WriteLine(notification.Message + " Pong");
}
}
[Fact]
public async Task Should_call_abstract_handle_method()
{
var builder = new StringBuilder();
var writer = new StringWriter(builder);
INotificationHandler<Ping> handler = new PongChildHandler(writer);
await handler.Handle(
new Ping() { Message = "Ping" },
default
);
var result = builder.ToString();
result.ShouldContain("Ping Pong");
}
}
}
|
Use ObservableCollection for ComboBox item source so that the ComboBox updates when the list changes. | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Text.RegularExpressions;
using Common.Logging;
namespace GesturesViewer {
class ModelSelector : INotifyPropertyChanged {
static readonly ILog Log = LogManager.GetCurrentClassLogger();
static readonly String ModelFilePattern = "*.mat";
// File names that ends with time stamp.
static readonly String TimeRegex = @"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}";
public event PropertyChangedEventHandler PropertyChanged;
public List<String> ModelFiles { get; private set; }
public String SelectedModel {
get {
return selectedModel;
}
set {
selectedModel = value;
OnPropteryChanged("SelectedModel");
}
}
String selectedModel, dir;
public ModelSelector(String dir) {
this.dir = dir;
ModelFiles = new List<String>();
Refresh();
}
public void Refresh() {
Log.Debug("Refresh models.");
var files = Directory.GetFiles(dir, ModelFilePattern);
ModelFiles.Clear();
foreach (var f in files) {
ModelFiles.Add(f);
var fileName = Path.GetFileName(f);
if (SelectedModel == null || Regex.IsMatch(fileName, TimeRegex))
SelectedModel = f;
}
}
void OnPropteryChanged(String prop) {
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
}
| using System;
using System.IO;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Collections.ObjectModel;
using Common.Logging;
namespace GesturesViewer {
class ModelSelector : INotifyPropertyChanged {
static readonly ILog Log = LogManager.GetCurrentClassLogger();
static readonly String ModelFilePattern = "*.mat";
// File names that ends with time stamp.
static readonly String TimeRegex = @"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}";
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<String> ModelFiles { get; private set; }
public String SelectedModel {
get {
return selectedModel;
}
set {
selectedModel = value;
OnPropteryChanged("SelectedModel");
}
}
String selectedModel, dir;
public ModelSelector(String dir) {
this.dir = dir;
ModelFiles = new ObservableCollection<String>();
Refresh();
}
public void Refresh() {
Log.Debug("Refresh models.");
var files = Directory.GetFiles(dir, ModelFilePattern);
ModelFiles.Clear();
foreach (var f in files) {
ModelFiles.Add(f);
var fileName = Path.GetFileName(f);
if (SelectedModel == null || Regex.IsMatch(fileName, TimeRegex))
SelectedModel = f;
}
}
void OnPropteryChanged(String prop) {
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
}
|
Fix regression in puzzle 10 | // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.ProjectEuler.Puzzles
{
using System;
/// <summary>
/// A class representing the solution to <c>https://projecteuler.net/problem=10</c>. This class cannot be inherited.
/// </summary>
internal sealed class Puzzle010 : Puzzle
{
/// <inheritdoc />
public override string Question => "Find the sum of all the primes below the specified value.";
/// <inheritdoc />
protected override int MinimumArguments => 1;
/// <inheritdoc />
protected override int SolveCore(string[] args)
{
int max;
if (!TryParseInt32(args[0], out max) || max < 2)
{
Console.Error.WriteLine("The specified number is invalid.");
return -1;
}
long sum = 0;
for (int n = 2; n < max - 2; n++)
{
if (Maths.IsPrime(n))
{
sum += n;
}
}
Answer = sum;
return 0;
}
}
}
| // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.ProjectEuler.Puzzles
{
using System;
/// <summary>
/// A class representing the solution to <c>https://projecteuler.net/problem=10</c>. This class cannot be inherited.
/// </summary>
internal sealed class Puzzle010 : Puzzle
{
/// <inheritdoc />
public override string Question => "Find the sum of all the primes below the specified value.";
/// <inheritdoc />
protected override int MinimumArguments => 1;
/// <inheritdoc />
protected override int SolveCore(string[] args)
{
int max;
if (!TryParseInt32(args[0], out max) || max < 2)
{
Console.Error.WriteLine("The specified number is invalid.");
return -1;
}
long sum = 0;
for (int n = 2; n < max; n++)
{
if (Maths.IsPrime(n))
{
sum += n;
}
}
Answer = sum;
return 0;
}
}
}
|
Fix category of revision log RSS feeds. | <?xml version="1.0"?>
<!-- RSS generated by Trac v<?cs var:trac.version ?> on <?cs var:trac.time ?> -->
<rss version="2.0">
<channel><?cs
if:project.name_encoded ?>
<title><?cs var:project.name_encoded ?>: Revisions of <?cs var:log.path ?></title><?cs
else ?>
<title>Revisions of <?cs var:log.path ?></title><?cs
/if ?>
<link><?cs var:base_host ?><?cs var:log.log_href ?></link>
<description>Trac Log - Revisions of <?cs var:log.path ?></description>
<language>en-us</language>
<generator>Trac v<?cs var:trac.version ?></generator><?cs
each:item = log.items ?><?cs
with:change = log.changes[item.rev] ?>
<item>
<author><?cs var:change.author ?></author>
<pubDate><?cs var:change.date ?></pubDate>
<title>Revision <?cs var:item.rev ?>: <?cs var:change.shortlog ?></title>
<link><?cs var:base_host ?><?cs var:item.changeset_href ?></link>
<description><?cs var:change.message ?></description>
<category>Report</category>
</item><?cs
/with ?><?cs
/each ?>
</channel>
</rss>
| <?xml version="1.0"?>
<!-- RSS generated by Trac v<?cs var:trac.version ?> on <?cs var:trac.time ?> -->
<rss version="2.0">
<channel><?cs
if:project.name_encoded ?>
<title><?cs var:project.name_encoded ?>: Revisions of <?cs var:log.path ?></title><?cs
else ?>
<title>Revisions of <?cs var:log.path ?></title><?cs
/if ?>
<link><?cs var:base_host ?><?cs var:log.log_href ?></link>
<description>Trac Log - Revisions of <?cs var:log.path ?></description>
<language>en-us</language>
<generator>Trac v<?cs var:trac.version ?></generator><?cs
each:item = log.items ?><?cs
with:change = log.changes[item.rev] ?>
<item>
<author><?cs var:change.author ?></author>
<pubDate><?cs var:change.date ?></pubDate>
<title>Revision <?cs var:item.rev ?>: <?cs var:change.shortlog ?></title>
<link><?cs var:base_host ?><?cs var:item.changeset_href ?></link>
<description><?cs var:change.message ?></description>
<category>Log</category>
</item><?cs
/with ?><?cs
/each ?>
</channel>
</rss>
|
Enumerate via self instead of directly | using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Pingu.Chunks;
namespace Pingu
{
public class PngFile : IEnumerable<Chunk>
{
List<Chunk> chunksToWrite = new List<Chunk>();
static readonly byte[] magic = new byte[] { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a };
public void Add(Chunk chunk) => chunksToWrite.Add(chunk);
IEnumerator<Chunk> IEnumerable<Chunk>.GetEnumerator() => chunksToWrite.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => chunksToWrite.GetEnumerator();
public int ChunkCount => chunksToWrite.Count;
public async Task WriteFileAsync(Stream target)
{
await target.WriteAsync(magic, 0, magic.Length);
foreach (var chunk in chunksToWrite)
await chunk.WriteSelfToStreamAsync(target);
}
}
}
| using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Pingu.Chunks;
namespace Pingu
{
public class PngFile : IEnumerable<Chunk>
{
List<Chunk> chunksToWrite = new List<Chunk>();
static readonly byte[] magic = new byte[] { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a };
public void Add(Chunk chunk) => chunksToWrite.Add(chunk);
IEnumerator<Chunk> IEnumerable<Chunk>.GetEnumerator() => chunksToWrite.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => chunksToWrite.GetEnumerator();
public int ChunkCount => chunksToWrite.Count;
public async Task WriteFileAsync(Stream target)
{
await target.WriteAsync(magic, 0, magic.Length);
foreach (var chunk in this)
await chunk.WriteSelfToStreamAsync(target);
}
}
}
|
Debug log store saves logs only when debugger is attached | #define DEBUG
using System;
using System.Threading.Tasks;
using Bit.Core.Contracts;
using Bit.Core.Models;
using System.Diagnostics;
namespace Bit.Owin.Implementations
{
public class DebugLogStore : ILogStore
{
private readonly IContentFormatter _formatter;
public DebugLogStore(IContentFormatter formatter)
{
_formatter = formatter;
}
protected DebugLogStore()
{
}
public virtual void SaveLog(LogEntry logEntry)
{
Debug.WriteLine(_formatter.Serialize(logEntry) + Environment.NewLine);
}
public virtual async Task SaveLogAsync(LogEntry logEntry)
{
Debug.WriteLine(_formatter.Serialize(logEntry) + Environment.NewLine);
}
}
}
| #define DEBUG
using System;
using System.Threading.Tasks;
using Bit.Core.Contracts;
using Bit.Core.Models;
using System.Diagnostics;
namespace Bit.Owin.Implementations
{
public class DebugLogStore : ILogStore
{
private readonly IContentFormatter _formatter;
public DebugLogStore(IContentFormatter formatter)
{
_formatter = formatter;
}
protected DebugLogStore()
{
}
public virtual void SaveLog(LogEntry logEntry)
{
if (Debugger.IsAttached)
Debug.WriteLine(_formatter.Serialize(logEntry) + Environment.NewLine);
}
public virtual async Task SaveLogAsync(LogEntry logEntry)
{
if (Debugger.IsAttached)
Debug.WriteLine(_formatter.Serialize(logEntry) + Environment.NewLine);
}
}
}
|
Use null-forgiving operator rather than assertion | // 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using NUnit.Framework;
namespace osu.Framework.Extensions.ObjectExtensions
{
/// <summary>
/// Extensions that apply to all objects.
/// </summary>
public static class ObjectExtensions
{
/// <summary>
/// Coerces a nullable object as non-nullable. This is an alternative to the C# 8 null-forgiving operator "<c>!</c>".
/// </summary>
/// <remarks>
/// This should only be used when an assertion or other handling is not a reasonable alternative.
/// </remarks>
/// <param name="obj">The nullable object.</param>
/// <typeparam name="T">The type of the object.</typeparam>
/// <returns>The non-nullable object corresponding to <paramref name="obj"/>.</returns>
public static T AsNonNull<T>(this T? obj)
where T : class
{
Trace.Assert(obj != null);
Debug.Assert(obj != null);
return obj;
}
/// <summary>
/// If the given object is null.
/// </summary>
public static bool IsNull<T>([NotNullWhen(false)] this T obj) => ReferenceEquals(obj, null);
/// <summary>
/// <c>true</c> if the given object is not null, <c>false</c> otherwise.
/// </summary>
public static bool IsNotNull<T>([NotNullWhen(true)] this T obj) => !ReferenceEquals(obj, null);
}
}
| // 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.Diagnostics.CodeAnalysis;
namespace osu.Framework.Extensions.ObjectExtensions
{
/// <summary>
/// Extensions that apply to all objects.
/// </summary>
public static class ObjectExtensions
{
/// <summary>
/// Coerces a nullable object as non-nullable. This is an alternative to the C# 8 null-forgiving operator "<c>!</c>".
/// </summary>
/// <remarks>
/// This should only be used when an assertion or other handling is not a reasonable alternative.
/// </remarks>
/// <param name="obj">The nullable object.</param>
/// <typeparam name="T">The type of the object.</typeparam>
/// <returns>The non-nullable object corresponding to <paramref name="obj"/>.</returns>
public static T AsNonNull<T>(this T? obj)
where T : class
{
return obj!;
}
/// <summary>
/// If the given object is null.
/// </summary>
public static bool IsNull<T>([NotNullWhen(false)] this T obj) => ReferenceEquals(obj, null);
/// <summary>
/// <c>true</c> if the given object is not null, <c>false</c> otherwise.
/// </summary>
public static bool IsNotNull<T>([NotNullWhen(true)] this T obj) => !ReferenceEquals(obj, null);
}
}
|
Add obsolete wrappers for compatability | using System;
using System.Runtime.InteropServices;
namespace Sodium
{
/// <summary>
/// libsodium core information.
/// </summary>
public static class SodiumCore
{
static SodiumCore()
{
SodiumLibrary.init();
}
/// <summary>Gets random bytes</summary>
/// <param name="count">The count of bytes to return.</param>
/// <returns>An array of random bytes.</returns>
public static byte[] GetRandomBytes(int count)
{
var buffer = new byte[count];
SodiumLibrary.randombytes_buff(buffer, count);
return buffer;
}
/// <summary>
/// Returns the version of libsodium in use.
/// </summary>
/// <returns>
/// The sodium version string.
/// </returns>
public static string SodiumVersionString()
{
var ptr = SodiumLibrary.sodium_version_string();
return Marshal.PtrToStringAnsi(ptr);
}
}
}
| using System;
using System.Runtime.InteropServices;
namespace Sodium
{
/// <summary>
/// libsodium core information.
/// </summary>
public static class SodiumCore
{
static SodiumCore()
{
SodiumLibrary.init();
}
/// <summary>Gets random bytes</summary>
/// <param name="count">The count of bytes to return.</param>
/// <returns>An array of random bytes.</returns>
public static byte[] GetRandomBytes(int count)
{
var buffer = new byte[count];
SodiumLibrary.randombytes_buff(buffer, count);
return buffer;
}
/// <summary>
/// Returns the version of libsodium in use.
/// </summary>
/// <returns>
/// The sodium version string.
/// </returns>
public static string SodiumVersionString()
{
var ptr = SodiumLibrary.sodium_version_string();
return Marshal.PtrToStringAnsi(ptr);
}
[Obsolete("Use SodiumLibrary.is64")]
internal static bool Is64
{
get
{
return SodiumLibrary.is64;
}
}
[Obsolete("Use SodiumLibrary.isRunningOnMono")]
internal static bool IsRunningOnMono()
{
return SodiumLibrary.isRunningOnMono;
}
[Obsolete("Use SodiumLibrary.name")]
internal static string LibraryName()
{
return SodiumLibrary.name;
}
}
}
|
Attach SetEditorOnly function to GameObjects rather than MonoBehaviors | using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using System.Linq;
namespace YesAndEditor {
// Static class packed to the brim with helpful Unity editor utilities.
public static class YesAndEditorUtil {
// Forcefully mark open loaded scenes dirty and save them.
[MenuItem ("File/Force Save")]
public static void ForceSaveOpenScenes () {
EditorSceneManager.MarkAllScenesDirty ();
EditorSceneManager.SaveOpenScenes ();
}
// Mark an object editor-only.
public static void SetEditorOnly(this MonoBehaviour obj, bool editorOnly = true) {
if (editorOnly) {
obj.gameObject.hideFlags ^= HideFlags.NotEditable;
obj.gameObject.hideFlags ^= HideFlags.HideAndDontSave;
}
else {
obj.gameObject.hideFlags &= HideFlags.NotEditable;
obj.gameObject.hideFlags &= HideFlags.HideAndDontSave;
}
}
}
}
| using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using System.Linq;
namespace YesAndEditor {
// Static class packed to the brim with helpful Unity editor utilities.
public static class YesAndEditorUtil {
// Forcefully mark open loaded scenes dirty and save them.
[MenuItem ("File/Force Save")]
public static void ForceSaveOpenScenes () {
EditorSceneManager.MarkAllScenesDirty ();
EditorSceneManager.SaveOpenScenes ();
}
// Mark an object editor-only.
public static void SetEditorOnly(this GameObject obj, bool editorOnly = true) {
if (editorOnly) {
obj.gameObject.hideFlags ^= HideFlags.NotEditable;
obj.gameObject.hideFlags ^= HideFlags.HideAndDontSave;
}
else {
obj.gameObject.hideFlags &= HideFlags.NotEditable;
obj.gameObject.hideFlags &= HideFlags.HideAndDontSave;
}
}
}
}
|
Create node_modules/@types after project creation | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.VisualStudio.TemplateWizard;
namespace Microsoft.NodejsTools.ProjectWizard
{
/// <summary>
/// Provides a project wizard extension which will optionally do an
/// npm install after the project is created.
/// </summary>
public sealed class NpmWizardExtension : IWizard
{
#region IWizard Members
public void BeforeOpeningFile(EnvDTE.ProjectItem projectItem)
{
}
public void ProjectFinishedGenerating(EnvDTE.Project project)
{
Debug.Assert(project != null && project.Object != null);
Debug.Assert(project.Object is INodePackageModulesCommands);
((INodePackageModulesCommands)project.Object).InstallMissingModulesAsync();
}
public void ProjectItemFinishedGenerating(EnvDTE.ProjectItem projectItem)
{
}
public void RunFinished()
{
}
public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
{
}
public bool ShouldAddProjectItem(string filePath)
{
return true;
}
#endregion
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Microsoft.VisualStudio.TemplateWizard;
namespace Microsoft.NodejsTools.ProjectWizard
{
/// <summary>
/// Provides a project wizard extension which will optionally do an
/// npm install after the project is created.
/// </summary>
public sealed class NpmWizardExtension : IWizard
{
#region IWizard Members
public void BeforeOpeningFile(EnvDTE.ProjectItem projectItem)
{
}
public void ProjectFinishedGenerating(EnvDTE.Project project)
{
Debug.Assert(project != null && project.Object != null);
Debug.Assert(project.Object is INodePackageModulesCommands);
// Create the "node_modules/@types" folder before opening any files (which creates the
// context for the project). This allows tsserver to start watching for type definitions
// before any are installed (which is needed as "npm install" runs async, so the modules
// usually aren't installed before the project context is loaded).
var fullname = project.FullName;
var projectFolder = Path.GetDirectoryName(fullname);
Directory.CreateDirectory(Path.Combine(projectFolder, @"node_modules\@types"));
((INodePackageModulesCommands)project.Object).InstallMissingModulesAsync();
}
public void ProjectItemFinishedGenerating(EnvDTE.ProjectItem projectItem)
{
}
public void RunFinished()
{
}
public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
{
}
public bool ShouldAddProjectItem(string filePath)
{
return true;
}
#endregion
}
}
|
Remove unused field from previous commit | using Microsoft.VisualStudio.ConnectedServices;
using System;
using System.ComponentModel.Composition;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace Salesforce.VisualStudio.Services.ConnectedService
{
[Export(typeof(ConnectedServiceProvider))]
[ExportMetadata(Constants.ProviderId, Constants.ProviderIdValue)]
internal class SalesforceConnectedServiceProvider : ConnectedServiceProvider
{
private BitmapImage icon;
public SalesforceConnectedServiceProvider()
{
this.Category = Resources.ConnectedServiceProvider_Category;
this.CreatedBy = Resources.ConnectedServiceProvider_CreatedBy;
this.Description = Resources.ConnectedServiceProvider_Description;
this.Icon = new BitmapImage(new Uri("pack://application:,,/" + Assembly.GetAssembly(this.GetType()).ToString() + ";component/ConnectedService/Views/Resources/ProviderIcon.png"));
this.MoreInfoUri = new Uri(Constants.MoreInfoLink);
this.Name = Resources.ConnectedServiceProvider_Name;
this.Version = typeof(SalesforceConnectedServiceProvider).Assembly.GetName().Version;
}
public override Task<ConnectedServiceConfigurator> CreateConfiguratorAsync(ConnectedServiceProviderHost host)
{
ConnectedServiceConfigurator wizard = new SalesforceConnectedServiceWizard(host);
return Task.FromResult(wizard);
}
}
}
| using Microsoft.VisualStudio.ConnectedServices;
using System;
using System.ComponentModel.Composition;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
namespace Salesforce.VisualStudio.Services.ConnectedService
{
[Export(typeof(ConnectedServiceProvider))]
[ExportMetadata(Constants.ProviderId, Constants.ProviderIdValue)]
internal class SalesforceConnectedServiceProvider : ConnectedServiceProvider
{
public SalesforceConnectedServiceProvider()
{
this.Category = Resources.ConnectedServiceProvider_Category;
this.CreatedBy = Resources.ConnectedServiceProvider_CreatedBy;
this.Description = Resources.ConnectedServiceProvider_Description;
this.Icon = new BitmapImage(new Uri("pack://application:,,/" + Assembly.GetAssembly(this.GetType()).ToString() + ";component/ConnectedService/Views/Resources/ProviderIcon.png"));
this.MoreInfoUri = new Uri(Constants.MoreInfoLink);
this.Name = Resources.ConnectedServiceProvider_Name;
this.Version = typeof(SalesforceConnectedServiceProvider).Assembly.GetName().Version;
}
public override Task<ConnectedServiceConfigurator> CreateConfiguratorAsync(ConnectedServiceProviderHost host)
{
ConnectedServiceConfigurator wizard = new SalesforceConnectedServiceWizard(host);
return Task.FromResult(wizard);
}
}
}
|
Comment on custom display option properties | using Newtonsoft.Json;
using System.Collections.Generic;
namespace SurveyMonkey.Containers
{
[JsonConverter(typeof(TolerantJsonConverter))]
public class QuestionDisplayOptionsCustomOptions
{
public List<string> OptionSet { get; set; }
public int StartingPosition { get; set; }
public int StepSize { get; set; }
public string Color { get; set; }
}
} | using Newtonsoft.Json;
using System.Collections.Generic;
namespace SurveyMonkey.Containers
{
[JsonConverter(typeof(TolerantJsonConverter))]
public class QuestionDisplayOptionsCustomOptions
{
public List<string> OptionSet { get; set; }
public int StartingPosition { get; set; } //slider questions
public int StepSize { get; set; } //slider questions
public string Color { get; set; } //star rating questions
}
} |
Add comment to count word number. | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using CSharpViaTest.Collections.Annotations;
using CSharpViaTest.Collections.Helpers;
using Xunit;
namespace CSharpViaTest.Collections._30_MapReducePractices
{
[SuperEasy]
public class CountNumberOfWordsInMultipleTextFiles
{
#region Please modifies the code to pass the test
static int CountNumberOfWords(IEnumerable<Stream> streams)
{
throw new NotImplementedException();
}
#endregion
[Fact]
public void should_count_number_of_words()
{
const int fileCount = 5;
const int wordsInEachFile = 10;
Stream[] streams = Enumerable
.Repeat(0, fileCount)
.Select(_ => TextStreamFactory.Create(wordsInEachFile))
.ToArray();
int count = CountNumberOfWords(streams);
Assert.Equal(fileCount * wordsInEachFile, count);
foreach (Stream stream in streams) { stream.Dispose(); }
}
}
} | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using CSharpViaTest.Collections.Annotations;
using CSharpViaTest.Collections.Helpers;
using Xunit;
namespace CSharpViaTest.Collections._30_MapReducePractices
{
[SuperEasy]
public class CountNumberOfWordsInMultipleTextFiles
{
#region Please modifies the code to pass the test
// You can add additional functions for readability and performance considerations.
static int CountNumberOfWords(IEnumerable<Stream> streams)
{
throw new NotImplementedException();
}
#endregion
[Fact]
public void should_count_number_of_words()
{
const int fileCount = 5;
const int wordsInEachFile = 10;
Stream[] streams = Enumerable
.Repeat(0, fileCount)
.Select(_ => TextStreamFactory.Create(wordsInEachFile))
.ToArray();
int count = CountNumberOfWords(streams);
Assert.Equal(fileCount * wordsInEachFile, count);
foreach (Stream stream in streams) { stream.Dispose(); }
}
}
} |
Add total memory to cat indices response | using Newtonsoft.Json;
namespace Nest
{
[JsonObject]
public class CatIndicesRecord : ICatRecord
{
[JsonProperty("docs.count")]
public string DocsCount { get; set; }
[JsonProperty("docs.deleted")]
public string DocsDeleted { get; set; }
[JsonProperty("health")]
public string Health { get; set; }
[JsonProperty("index")]
public string Index { get; set; }
[JsonProperty("pri")]
public string Primary { get; set; }
[JsonProperty("pri.store.size")]
public string PrimaryStoreSize { get; set; }
[JsonProperty("rep")]
public string Replica { get; set; }
[JsonProperty("store.size")]
public string StoreSize { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
}
} | using Newtonsoft.Json;
namespace Nest
{
[JsonObject]
public class CatIndicesRecord : ICatRecord
{
[JsonProperty("docs.count")]
public string DocsCount { get; set; }
[JsonProperty("docs.deleted")]
public string DocsDeleted { get; set; }
[JsonProperty("health")]
public string Health { get; set; }
[JsonProperty("index")]
public string Index { get; set; }
[JsonProperty("pri")]
public string Primary { get; set; }
[JsonProperty("pri.store.size")]
public string PrimaryStoreSize { get; set; }
[JsonProperty("rep")]
public string Replica { get; set; }
[JsonProperty("store.size")]
public string StoreSize { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("tm")]
public string TotalMemory { get; set; }
}
} |
Remove forced WebGL test code | using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
namespace Rs317.Sharp
{
public static class RsUnityPlatform
{
public static bool isWebGLBuild => true;
public static bool isPlaystationBuild => Application.platform == RuntimePlatform.PS4 || Application.platform == RuntimePlatform.PS3;
public static bool isAndroidMobileBuild => Application.platform == RuntimePlatform.Android;
public static bool isInEditor => Application.isEditor;
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
namespace Rs317.Sharp
{
public static class RsUnityPlatform
{
public static bool isWebGLBuild => Application.platform == RuntimePlatform.WebGLPlayer;
public static bool isPlaystationBuild => Application.platform == RuntimePlatform.PS4 || Application.platform == RuntimePlatform.PS3;
public static bool isAndroidMobileBuild => Application.platform == RuntimePlatform.Android;
public static bool isInEditor => Application.isEditor;
}
}
|
Fix for serialization errors with Loadout events caused by game bug | namespace DW.ELA.Interfaces.Events
{
using Newtonsoft.Json;
public class ModuleEngineering
{
[JsonProperty("Engineer")]
public string Engineer { get; set; }
[JsonProperty("EngineerID")]
public ulong EngineerId { get; set; }
[JsonProperty("BlueprintID")]
public long BlueprintId { get; set; }
[JsonProperty("BlueprintName")]
public string BlueprintName { get; set; }
[JsonProperty("Level")]
public short Level { get; set; }
[JsonProperty("Quality")]
public double Quality { get; set; }
[JsonProperty("Modifiers")]
public Modifier[] Modifiers { get; set; }
[JsonProperty("ExperimentalEffect")]
public string ExperimentalEffect { get; set; }
[JsonProperty("ExperimentalEffect_Localised")]
public string ExperimentalEffectLocalised { get; set; }
}
}
| namespace DW.ELA.Interfaces.Events
{
using Newtonsoft.Json;
public class ModuleEngineering
{
[JsonProperty("Engineer")]
public string Engineer { get; set; }
[JsonProperty("EngineerID")]
public ulong EngineerId { get; set; }
[JsonProperty("BlueprintID")]
public ulong BlueprintId { get; set; }
[JsonProperty("BlueprintName")]
public string BlueprintName { get; set; }
[JsonProperty("Level")]
public short Level { get; set; }
[JsonProperty("Quality")]
public double Quality { get; set; }
[JsonProperty("Modifiers")]
public Modifier[] Modifiers { get; set; }
[JsonProperty("ExperimentalEffect")]
public string ExperimentalEffect { get; set; }
[JsonProperty("ExperimentalEffect_Localised")]
public string ExperimentalEffectLocalised { get; set; }
}
}
|
Document model updated as per save document changes. | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Awesomium.Core;
using ProjectMarkdown.Annotations;
namespace ProjectMarkdown.Model
{
public class DocumentModel : INotifyPropertyChanged
{
private string _header;
private string _markdownText;
private Uri _source;
public string Header
{
get { return _header; }
set
{
if (value == _header) return;
_header = value;
OnPropertyChanged(nameof(Header));
}
}
public string MarkdownText
{
get { return _markdownText; }
set
{
if (value == _markdownText) return;
_markdownText = value;
OnPropertyChanged(nameof(MarkdownText));
}
}
public Uri Source
{
get { return _source; }
set
{
if (Equals(value, _source)) return;
_source = value;
OnPropertyChanged(nameof(Source));
}
}
public string MarkdownPath { get; set; }
public string HtmlPath { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public DocumentModel(string documentName)
{
Header = documentName;
MarkdownText = "";
Source = "".ToUri();
}
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Awesomium.Core;
using ProjectMarkdown.Annotations;
namespace ProjectMarkdown.Model
{
public class DocumentModel : INotifyPropertyChanged
{
public DocumentMetadata Metadata
{
get { return _metadata; }
set
{
if (Equals(value, _metadata)) return;
_metadata = value;
OnPropertyChanged(nameof(Metadata));
}
}
public DocumentMarkdown Markdown
{
get { return _markdown; }
set
{
if (Equals(value, _markdown)) return;
_markdown = value;
OnPropertyChanged(nameof(Markdown));
}
}
public DocumentHtml Html
{
get { return _html; }
set
{
if (Equals(value, _html)) return;
_html = value;
OnPropertyChanged(nameof(Html));
}
}
private DocumentMetadata _metadata;
private DocumentMarkdown _markdown;
private DocumentHtml _html;
public event PropertyChangedEventHandler PropertyChanged;
public DocumentModel(string documentName)
{
Metadata = new DocumentMetadata(documentName);
Markdown = new DocumentMarkdown("");
Html = new DocumentHtml("".ToUri());
}
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
|
Add Snapshots option to listing shares | //-----------------------------------------------------------------------
// <copyright file="ShareListingDetails.cs" company="Microsoft">
// Copyright 2013 Microsoft Corporation
//
// 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>
//-----------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Storage.File
{
using System;
/// <summary>
/// Specifies which details to include when listing the shares in this storage account.
/// </summary>
[Flags]
public enum ShareListingDetails
{
/// <summary>
/// No additional details.
/// </summary>
None = 0x0,
/// <summary>
/// Retrieve share metadata.
/// </summary>
Metadata = 0x1,
/// <summary>
/// Retrieve all available details.
/// </summary>
All = Metadata
}
}
| //-----------------------------------------------------------------------
// <copyright file="ShareListingDetails.cs" company="Microsoft">
// Copyright 2013 Microsoft Corporation
//
// 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>
//-----------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Storage.File
{
using System;
/// <summary>
/// Specifies which details to include when listing the shares in this storage account.
/// </summary>
[Flags]
public enum ShareListingDetails
{
/// <summary>
/// No additional details.
/// </summary>
None = 0x0,
/// <summary>
/// Retrieve share metadata.
/// </summary>
Metadata = 0x1,
/// <summary>
/// Retrieve share snapshots.
/// </summary>
Snapshots = 0x2,
/// <summary>
/// Retrieve all available details.
/// </summary>
All = Metadata | Snapshots
}
}
|
Replace log4net dependency with LibLog | // <auto-generated/>
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitleAttribute("Elders.Multithreading.Scheduler")]
[assembly: AssemblyDescriptionAttribute("The idea is to create a dedicated threads for a particular work. The WorkPool class does not use the standard .NET thread pool.")]
[assembly: ComVisibleAttribute(false)]
[assembly: AssemblyProductAttribute("Elders.Multithreading.Scheduler")]
[assembly: AssemblyCopyrightAttribute("Copyright © 2015")]
[assembly: AssemblyVersionAttribute("1.1.0.0")]
[assembly: AssemblyFileVersionAttribute("1.1.0.0")]
[assembly: AssemblyInformationalVersionAttribute("1.1.0-beta.1+0.Branch.release/1.1.0.Sha.c42b1e80ff319dc8fecfcd9396662a96fcafbfaf")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "1.1.0.0";
}
}
| // <auto-generated/>
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitleAttribute("Elders.Multithreading.Scheduler")]
[assembly: AssemblyDescriptionAttribute("The idea is to create a dedicated threads for a particular work. The WorkPool class does not use the standard .NET thread pool.")]
[assembly: ComVisibleAttribute(false)]
[assembly: AssemblyProductAttribute("Elders.Multithreading.Scheduler")]
[assembly: AssemblyCopyrightAttribute("Copyright © 2015")]
[assembly: AssemblyVersionAttribute("1.1.0.0")]
[assembly: AssemblyFileVersionAttribute("1.1.0.0")]
[assembly: AssemblyInformationalVersionAttribute("1.1.0+1.Branch.master.Sha.25442a58c8498465a9335b9bb288b5450d3d2cba")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "1.1.0.0";
}
}
|
Fix a minor async delayer issue | using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Tgstation.Server.Host.Core.Tests
{
[TestClass]
public sealed class TestAsyncDelayer
{
[TestMethod]
public async Task TestDelay()
{
var delayer = new AsyncDelayer();
var startDelay = delayer.Delay(TimeSpan.FromSeconds(1), default);
var checkDelay = Task.Delay(TimeSpan.FromSeconds(1) - TimeSpan.FromMilliseconds(10), default);
await startDelay.ConfigureAwait(false);
Assert.IsTrue(checkDelay.IsCompleted);
}
[TestMethod]
public async Task TestCancel()
{
var delayer = new AsyncDelayer();
using (var cts = new CancellationTokenSource())
{
cts.Cancel();
await Assert.ThrowsExceptionAsync<TaskCanceledException>(() => delayer.Delay(TimeSpan.FromSeconds(1), cts.Token)).ConfigureAwait(false);
}
}
}
}
| using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Tgstation.Server.Host.Core.Tests
{
[TestClass]
public sealed class TestAsyncDelayer
{
[TestMethod]
public async Task TestDelay()
{
var delayer = new AsyncDelayer();
var startDelay = delayer.Delay(TimeSpan.FromSeconds(1), default);
var checkDelay = Task.Delay(TimeSpan.FromSeconds(1) - TimeSpan.FromMilliseconds(100), default);
await startDelay.ConfigureAwait(false);
Assert.IsTrue(checkDelay.IsCompleted);
}
[TestMethod]
public async Task TestCancel()
{
var delayer = new AsyncDelayer();
using var cts = new CancellationTokenSource();
cts.Cancel();
await Assert.ThrowsExceptionAsync<TaskCanceledException>(() => delayer.Delay(TimeSpan.FromSeconds(1), cts.Token)).ConfigureAwait(false);
}
}
}
|
Update nullable annotations in TodoComments folder | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.Editor.Implementation.TodoComments
{
internal static class TodoCommentOptions
{
public static readonly Option<string> TokenList = new Option<string>(nameof(TodoCommentOptions), nameof(TokenList), defaultValue: "HACK:1|TODO:1|UNDONE:1|UnresolvedMergeConflict:0");
}
[ExportOptionProvider, Shared]
internal class TodoCommentOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TodoCommentOptionsProvider()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
TodoCommentOptions.TokenList);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.Editor.Implementation.TodoComments
{
internal static class TodoCommentOptions
{
public static readonly Option<string> TokenList = new Option<string>(nameof(TodoCommentOptions), nameof(TokenList), defaultValue: "HACK:1|TODO:1|UNDONE:1|UnresolvedMergeConflict:0");
}
[ExportOptionProvider, Shared]
internal class TodoCommentOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TodoCommentOptionsProvider()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
TodoCommentOptions.TokenList);
}
}
|
Use more standard parsing method | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Beatmaps.Formats;
using System;
using System.Globalization;
namespace osu.Game.Skinning
{
public class LegacySkinDecoder : LegacyDecoder<SkinConfiguration>
{
public LegacySkinDecoder()
: base(1)
{
}
protected override void ParseLine(SkinConfiguration skin, Section section, string line)
{
line = StripComments(line);
var pair = SplitKeyVal(line);
switch (section)
{
case Section.General:
switch (pair.Key)
{
case @"Name":
skin.SkinInfo.Name = pair.Value;
break;
case @"Author":
skin.SkinInfo.Creator = pair.Value;
break;
case @"CursorExpand":
skin.CursorExpand = pair.Value != "0";
break;
case @"SliderBorderSize":
if (Single.TryParse(pair.Value, NumberStyles.Number, CultureInfo.CreateSpecificCulture("en-US"), out float size))
skin.SliderBorderSize = size;
break;
}
break;
case Section.Fonts:
switch (pair.Key)
{
case "HitCirclePrefix":
skin.HitCircleFont = pair.Value;
break;
case "HitCircleOverlap":
skin.HitCircleOverlap = int.Parse(pair.Value);
break;
}
break;
}
base.ParseLine(skin, section, line);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Beatmaps.Formats;
using System;
using System.Globalization;
namespace osu.Game.Skinning
{
public class LegacySkinDecoder : LegacyDecoder<SkinConfiguration>
{
public LegacySkinDecoder()
: base(1)
{
}
protected override void ParseLine(SkinConfiguration skin, Section section, string line)
{
line = StripComments(line);
var pair = SplitKeyVal(line);
switch (section)
{
case Section.General:
switch (pair.Key)
{
case @"Name":
skin.SkinInfo.Name = pair.Value;
break;
case @"Author":
skin.SkinInfo.Creator = pair.Value;
break;
case @"CursorExpand":
skin.CursorExpand = pair.Value != "0";
break;
case @"SliderBorderSize":
skin.SliderBorderSize = Parsing.ParseFloat(pair.Value);
break;
}
break;
case Section.Fonts:
switch (pair.Key)
{
case "HitCirclePrefix":
skin.HitCircleFont = pair.Value;
break;
case "HitCircleOverlap":
skin.HitCircleOverlap = int.Parse(pair.Value);
break;
}
break;
}
base.ParseLine(skin, section, line);
}
}
}
|
Move TestEnvironmentSetUpFixture into project root namespace | using JetBrains.Application.BuildScript.Application.Zones;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.ReSharper.TestFramework;
using JetBrains.TestFramework;
using JetBrains.TestFramework.Application.Zones;
using NUnit.Framework;
using ReSharperExtensionsShared.Tests;
[assembly: RequiresSTA]
namespace ReSharperExtensionsShared.Tests
{
[ZoneDefinition]
public interface ITestEnvironmentZone : ITestsZone, IRequire<PsiFeatureTestZone>
{
}
[ZoneMarker]
public class ZoneMarker : IRequire<ILanguageCSharpZone>, IRequire<ITestEnvironmentZone>
{
}
}
// ReSharper disable once CheckNamespace
[SetUpFixture]
public class TestEnvironmentSetUpFixture : ExtensionTestEnvironmentAssembly<ITestEnvironmentZone>
{
}
| using JetBrains.Application.BuildScript.Application.Zones;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.ReSharper.TestFramework;
using JetBrains.TestFramework;
using JetBrains.TestFramework.Application.Zones;
using NUnit.Framework;
[assembly: RequiresSTA]
namespace ReSharperExtensionsShared.Tests
{
[ZoneDefinition]
public interface ITestEnvironmentZone : ITestsZone, IRequire<PsiFeatureTestZone>
{
}
[ZoneMarker]
public class ZoneMarker : IRequire<ILanguageCSharpZone>, IRequire<ITestEnvironmentZone>
{
}
[SetUpFixture]
public class TestEnvironmentSetUpFixture : ExtensionTestEnvironmentAssembly<ITestEnvironmentZone>
{
}
}
|
Add test for INPUT union | // Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using PInvoke;
using Xunit;
using static PInvoke.User32;
public partial class User32Facts
{
[Fact]
public void MessageBeep_Asterisk()
{
Assert.True(MessageBeep(MessageBeepType.MB_ICONASTERISK));
}
}
| // Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using PInvoke;
using Xunit;
using static PInvoke.User32;
public partial class User32Facts
{
[Fact]
public void MessageBeep_Asterisk()
{
Assert.True(MessageBeep(MessageBeepType.MB_ICONASTERISK));
}
[Fact]
public void INPUT_Union()
{
INPUT i = default(INPUT);
i.type = InputType.INPUT_HARDWARE;
// Assert that the first field (type) has its own memory space.
Assert.Equal(0u, i.hi.uMsg);
Assert.Equal(0, (int)i.ki.wScan);
Assert.Equal(0, i.mi.dx);
// Assert that these three fields (hi, ki, mi) share memory space.
i.hi.uMsg = 1;
Assert.Equal(1, (int)i.ki.wVk);
Assert.Equal(1, i.mi.dx);
}
}
|
Support for Title on Windows. | using ruibarbo.core.ElementFactory;
using ruibarbo.core.Wpf.Invoker;
namespace ruibarbo.core.Wpf.Base
{
public class WpfWindowBase<TNativeElement> : WpfFrameworkElementBase<TNativeElement>
where TNativeElement : System.Windows.Window
{
public WpfWindowBase(ISearchSourceElement searchParent, TNativeElement frameworkElement)
: base(searchParent, frameworkElement)
{
}
public void MakeSureWindowIsTopmost()
{
OnUiThread.Invoke(this, fe => fe.Activate());
}
}
} | using ruibarbo.core.ElementFactory;
using ruibarbo.core.Wpf.Invoker;
namespace ruibarbo.core.Wpf.Base
{
public class WpfWindowBase<TNativeElement> : WpfFrameworkElementBase<TNativeElement>
where TNativeElement : System.Windows.Window
{
public WpfWindowBase(ISearchSourceElement searchParent, TNativeElement frameworkElement)
: base(searchParent, frameworkElement)
{
}
public void MakeSureWindowIsTopmost()
{
OnUiThread.Invoke(this, frameworkElement => frameworkElement.Activate());
}
public string Title
{
get { return OnUiThread.Get(this, frameworkElement => frameworkElement.Title); }
}
}
} |
Fix attempting to filter by project filtered by context instead | using System;
using System.Collections.Generic;
using System.Linq;
using EZLibrary;
using TodotxtTouch.WindowsPhone.ViewModel;
namespace TodotxtTouch.WindowsPhone.Tasks
{
public class TaskFilterFactory
{
private const char Delimiter = ',';
public static TaskFilter CreateTaskFilterFromString(string filter)
{
if (filter.StartsWith("context:"))
{
string target = filter.Replace("context:", String.Empty);
return new ContextTaskFilter(
task => task.Contexts.Contains(target),
target);
}
if (filter.StartsWith("project:"))
{
string target = filter.Replace("project: ", "+");
return new ContextTaskFilter(
task => task.Projects.Contains(target),
target);
}
return null;
}
public static List<TaskFilter> ParseFilterString(string filter)
{
string[] filters = filter.Split(Delimiter);
return filters.Where(f => !String.IsNullOrEmpty(f)).Select(CreateTaskFilterFromString).ToList();
}
public static string CreateFilterString(List<TaskFilter> filters)
{
return filters.ToDelimitedList(t => t.ToString(), Delimiter.ToString());
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using EZLibrary;
using TodotxtTouch.WindowsPhone.ViewModel;
namespace TodotxtTouch.WindowsPhone.Tasks
{
public class TaskFilterFactory
{
private const char Delimiter = ',';
public static TaskFilter CreateTaskFilterFromString(string filter)
{
if (filter.StartsWith("context:"))
{
string target = filter.Replace("context:", String.Empty);
return new ContextTaskFilter(
task => task.Contexts.Contains(target),
target);
}
if (filter.StartsWith("project:"))
{
string target = filter.Replace("project: ", "+");
return new ProjectTaskFilter(
task => task.Projects.Contains(target),
target);
}
return null;
}
public static List<TaskFilter> ParseFilterString(string filter)
{
string[] filters = filter.Split(Delimiter);
return filters.Where(f => !String.IsNullOrEmpty(f)).Select(CreateTaskFilterFromString).ToList();
}
public static string CreateFilterString(List<TaskFilter> filters)
{
return filters.ToDelimitedList(t => t.ToString(), Delimiter.ToString());
}
}
} |
Fix potential test failure due to not waiting long enough on track start | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
namespace osu.Framework.Tests.Audio
{
[TestFixture]
public class DevicelessAudioTest : AudioThreadTest
{
public override void SetUp()
{
base.SetUp();
// lose all devices
Manager.SimulateDeviceLoss();
}
[Test]
public void TestPlayTrackWithoutDevices()
{
var track = Manager.Tracks.Get("Tracks.sample-track.mp3");
// start track
track.Restart();
Assert.IsTrue(track.IsRunning);
CheckTrackIsProgressing(track);
// stop track
track.Stop();
WaitForOrAssert(() => !track.IsRunning, "Track did not stop", 1000);
Assert.IsFalse(track.IsRunning);
// seek track
track.Seek(0);
Assert.IsFalse(track.IsRunning);
WaitForOrAssert(() => track.CurrentTime == 0, "Track did not seek correctly", 1000);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
namespace osu.Framework.Tests.Audio
{
[TestFixture]
public class DevicelessAudioTest : AudioThreadTest
{
public override void SetUp()
{
base.SetUp();
// lose all devices
Manager.SimulateDeviceLoss();
}
[Test]
public void TestPlayTrackWithoutDevices()
{
var track = Manager.Tracks.Get("Tracks.sample-track.mp3");
// start track
track.Restart();
WaitForOrAssert(() => track.IsRunning, "Track started", 1000);
CheckTrackIsProgressing(track);
// stop track
track.Stop();
WaitForOrAssert(() => !track.IsRunning, "Track did not stop", 1000);
Assert.IsFalse(track.IsRunning);
// seek track
track.Seek(0);
Assert.IsFalse(track.IsRunning);
WaitForOrAssert(() => track.CurrentTime == 0, "Track did not seek correctly", 1000);
}
}
}
|
Update Markdown output to match linter now used in NUnit docs | using Nito.AsyncEx;
using Octokit;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Alteridem.GetChanges
{
class Program
{
static int Main(string[] args)
{
var options = new Options();
if (!CommandLine.Parser.Default.ParseArguments(args, options))
{
return -1;
}
AsyncContext.Run(() => MainAsync(options));
//Console.WriteLine("*** Press ENTER to Exit ***");
//Console.ReadLine();
return 0;
}
static async void MainAsync(Options options)
{
var github = new GitHubApi(options.Organization, options.Repository);
var milestones = await github.GetOpenMilestones();
foreach (var milestone in milestones.Where(m => m.DueOn != null && m.DueOn.Value.Subtract(DateTimeOffset.Now).TotalDays < 30))
{
var milestoneIssues = await github.GetClosedIssuesForMilestone(milestone);
DisplayIssuesForMilestone(options, milestone.Title, milestoneIssues);
}
}
static void DisplayIssuesForMilestone(Options options, string milestone, IEnumerable<Issue> issues)
{
Console.WriteLine("## {0}", milestone);
Console.WriteLine();
foreach (var issue in issues)
{
if(options.LinkIssues)
Console.WriteLine($" * [{issue.Number:####}](https://github.com/{options.Organization}/{options.Repository}/issues/{issue.Number}) {issue.Title}");
else
Console.WriteLine($" * {issue.Number:####} {issue.Title}");
}
Console.WriteLine();
}
}
}
| using Nito.AsyncEx;
using Octokit;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Alteridem.GetChanges
{
class Program
{
static int Main(string[] args)
{
var options = new Options();
if (!CommandLine.Parser.Default.ParseArguments(args, options))
{
return -1;
}
AsyncContext.Run(() => MainAsync(options));
//Console.WriteLine("*** Press ENTER to Exit ***");
//Console.ReadLine();
return 0;
}
static async void MainAsync(Options options)
{
var github = new GitHubApi(options.Organization, options.Repository);
var milestones = await github.GetOpenMilestones();
foreach (var milestone in milestones.Where(m => m.DueOn != null && m.DueOn.Value.Subtract(DateTimeOffset.Now).TotalDays < 30))
{
var milestoneIssues = await github.GetClosedIssuesForMilestone(milestone);
DisplayIssuesForMilestone(options, milestone.Title, milestoneIssues);
}
}
static void DisplayIssuesForMilestone(Options options, string milestone, IEnumerable<Issue> issues)
{
Console.WriteLine("## {0}", milestone);
Console.WriteLine();
foreach (var issue in issues)
{
if(options.LinkIssues)
Console.WriteLine($"* [{issue.Number:####}](https://github.com/{options.Organization}/{options.Repository}/issues/{issue.Number}) {issue.Title}");
else
Console.WriteLine($"* {issue.Number:####} {issue.Title}");
}
Console.WriteLine();
}
}
}
|
Fix flaky test in free mod select test scene | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Graphics.Containers;
using osu.Framework.Testing;
using osu.Game.Overlays.Mods;
using osu.Game.Screens.OnlinePlay;
namespace osu.Game.Tests.Visual.Multiplayer
{
public class TestSceneFreeModSelectScreen : MultiplayerTestScene
{
[Test]
public void TestFreeModSelect()
{
FreeModSelectScreen freeModSelectScreen = null;
AddStep("create free mod select screen", () => Child = freeModSelectScreen = new FreeModSelectScreen
{
State = { Value = Visibility.Visible }
});
AddAssert("all visible mods are playable",
() => this.ChildrenOfType<ModPanel>()
.Where(panel => panel.IsPresent)
.All(panel => panel.Mod.HasImplementation && panel.Mod.UserPlayable));
AddToggleStep("toggle visibility", visible =>
{
if (freeModSelectScreen != null)
freeModSelectScreen.State.Value = visible ? Visibility.Visible : Visibility.Hidden;
});
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Graphics.Containers;
using osu.Framework.Testing;
using osu.Game.Overlays.Mods;
using osu.Game.Screens.OnlinePlay;
namespace osu.Game.Tests.Visual.Multiplayer
{
public class TestSceneFreeModSelectScreen : MultiplayerTestScene
{
[Test]
public void TestFreeModSelect()
{
FreeModSelectScreen freeModSelectScreen = null;
AddStep("create free mod select screen", () => Child = freeModSelectScreen = new FreeModSelectScreen
{
State = { Value = Visibility.Visible }
});
AddUntilStep("all column content loaded",
() => freeModSelectScreen.ChildrenOfType<ModColumn>().Any()
&& freeModSelectScreen.ChildrenOfType<ModColumn>().All(column => column.IsLoaded && column.ItemsLoaded));
AddUntilStep("all visible mods are playable",
() => this.ChildrenOfType<ModPanel>()
.Where(panel => panel.IsPresent)
.All(panel => panel.Mod.HasImplementation && panel.Mod.UserPlayable));
AddToggleStep("toggle visibility", visible =>
{
if (freeModSelectScreen != null)
freeModSelectScreen.State.Value = visible ? Visibility.Visible : Visibility.Hidden;
});
}
}
}
|
Join up hardcoded lines in a Row | using System;
namespace Hangman {
public class Row {
public Cell[] Cells;
public Row(Cell[] cells) {
Cells = cells;
}
public string Draw(int width) {
// return new String(' ', width - Text.Length) + Text;
return "I have many cells!";
}
}
}
| using System;
namespace Hangman {
public class Row {
public Cell[] Cells;
public Row(Cell[] cells) {
Cells = cells;
}
public string Draw(int width) {
// return new String(' ', width - Text.Length) + Text;
return String.Join("\n", Lines());
}
public string[] Lines() {
return new string[] {
"Line 1",
"Line 2"
};
}
}
}
|
Fix dependency context bug and add load overload | // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
namespace Microsoft.Extensions.DependencyModel
{
public class DependencyContext
{
private const string DepsResourceSufix = ".deps.json";
private static readonly Lazy<DependencyContext> _defaultContext = new Lazy<DependencyContext>(LoadDefault);
public DependencyContext(string target, string runtime, CompilationOptions compilationOptions, CompilationLibrary[] compileLibraries, RuntimeLibrary[] runtimeLibraries)
{
Target = target;
Runtime = runtime;
CompilationOptions = compilationOptions;
CompileLibraries = compileLibraries;
RuntimeLibraries = runtimeLibraries;
}
public static DependencyContext Default => _defaultContext.Value;
public string Target { get; }
public string Runtime { get; }
public CompilationOptions CompilationOptions { get; }
public IReadOnlyList<CompilationLibrary> CompileLibraries { get; }
public IReadOnlyList<RuntimeLibrary> RuntimeLibraries { get; }
private static DependencyContext LoadDefault()
{
var entryAssembly = Assembly.GetEntryAssembly();
var stream = entryAssembly?.GetManifestResourceStream(entryAssembly.GetName().Name + DepsResourceSufix);
if (stream == null)
{
return null;
}
using (stream)
{
return Load(stream);
}
}
public static DependencyContext Load(Stream stream)
{
return new DependencyContextReader().Read(stream);
}
}
}
| // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
namespace Microsoft.Extensions.DependencyModel
{
public class DependencyContext
{
private const string DepsResourceSufix = ".deps.json";
private static readonly Lazy<DependencyContext> _defaultContext = new Lazy<DependencyContext>(LoadDefault);
public DependencyContext(string target, string runtime, CompilationOptions compilationOptions, CompilationLibrary[] compileLibraries, RuntimeLibrary[] runtimeLibraries)
{
Target = target;
Runtime = runtime;
CompilationOptions = compilationOptions;
CompileLibraries = compileLibraries;
RuntimeLibraries = runtimeLibraries;
}
public static DependencyContext Default => _defaultContext.Value;
public string Target { get; }
public string Runtime { get; }
public CompilationOptions CompilationOptions { get; }
public IReadOnlyList<CompilationLibrary> CompileLibraries { get; }
public IReadOnlyList<RuntimeLibrary> RuntimeLibraries { get; }
private static DependencyContext LoadDefault()
{
var entryAssembly = Assembly.GetEntryAssembly();
return Load(entryAssembly);
}
public static DependencyContext Load(Assembly assembly)
{
var stream = assembly.GetManifestResourceStream(assembly.GetName().Name + DepsResourceSufix);
if (stream == null)
{
return null;
}
using (stream)
{
return Load(stream);
}
}
public static DependencyContext Load(Stream stream)
{
return new DependencyContextReader().Read(stream);
}
}
}
|
Fix mouse position in game view | using System.Numerics;
using ImGuiNET;
namespace OpenSage.Viewer.UI.Views
{
internal abstract class GameView : AssetView
{
private readonly AssetViewContext _context;
protected GameView(AssetViewContext context)
{
_context = context;
}
public override void Draw(ref bool isGameViewFocused)
{
var windowPos = ImGui.GetWindowPosition();
var availableSize = ImGui.GetContentRegionAvailable();
_context.GamePanel.EnsureFrame(
new Mathematics.Rectangle(
(int) windowPos.X,
(int) windowPos.Y,
(int) availableSize.X,
(int) availableSize.Y));
_context.Game.Tick();
ImGuiNative.igSetItemAllowOverlap();
var imagePointer = _context.ImGuiRenderer.GetOrCreateImGuiBinding(
_context.GraphicsDevice.ResourceFactory,
_context.Game.Panel.Framebuffer.ColorTargets[0].Target);
if (ImGui.ImageButton(
imagePointer,
ImGui.GetContentRegionAvailable(),
Vector2.Zero,
Vector2.One,
0,
Vector4.Zero,
Vector4.One))
{
isGameViewFocused = true;
}
}
}
}
| using System.Numerics;
using ImGuiNET;
namespace OpenSage.Viewer.UI.Views
{
internal abstract class GameView : AssetView
{
private readonly AssetViewContext _context;
protected GameView(AssetViewContext context)
{
_context = context;
}
public override void Draw(ref bool isGameViewFocused)
{
var windowPos = ImGui.GetCursorScreenPos();
var availableSize = ImGui.GetContentRegionAvailable();
_context.GamePanel.EnsureFrame(
new Mathematics.Rectangle(
(int) windowPos.X,
(int) windowPos.Y,
(int) availableSize.X,
(int) availableSize.Y));
_context.Game.Tick();
ImGuiNative.igSetItemAllowOverlap();
var imagePointer = _context.ImGuiRenderer.GetOrCreateImGuiBinding(
_context.GraphicsDevice.ResourceFactory,
_context.Game.Panel.Framebuffer.ColorTargets[0].Target);
if (ImGui.ImageButton(
imagePointer,
ImGui.GetContentRegionAvailable(),
Vector2.Zero,
Vector2.One,
0,
Vector4.Zero,
Vector4.One))
{
isGameViewFocused = true;
}
}
}
}
|
Update model for transaction to not need the person id as it will get set from the jwt later | using MoneyEntry.DataAccess.EFCore.Expenses.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace MoneyEntry.ExpensesAPI.Models
{
public class TransactionModel
{
public int TransactionId { get; set; }
[Required]
public decimal Amount { get; set; }
[Required, MaxLength(128)]
public string Description { get; set; }
[Required, Range(1,2)]
public int TypeId { get; set; }
[Required, Range(1,99)]
public int CategoryId { get; set; }
[Required, DataType(DataType.DateTime)]
public DateTime CreatedDate { get; set; }
[Required, Range(1,10)]
public int PersonId { get; set; }
public bool Reconciled { get; set; }
}
}
| using MoneyEntry.DataAccess.EFCore.Expenses.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace MoneyEntry.ExpensesAPI.Models
{
public class TransactionModel
{
public int TransactionId { get; set; }
[Required]
public decimal Amount { get; set; }
[Required, MaxLength(128)]
public string Description { get; set; }
[Required, Range(1,2)]
public int TypeId { get; set; }
[Required, Range(1,99)]
public int CategoryId { get; set; }
[Required, DataType(DataType.DateTime)]
public DateTime CreatedDate { get; set; }
public int PersonId { get; set; }
public bool Reconciled { get; set; }
}
}
|
Change model reference with old namespace to new | @model IEnumerable<Oogstplanner.Models.Crop>
@{
ViewBag.Title = "Gewassen";
}
<div id="top"></div>
<div id="yearCalendar">
<h1>Dit zijn de gewassen in onze database:</h1>
<table class="table table-striped">
<tr>
<th>Naam</th><th>Ras</th><th>Categorie</th><th>Opp. per 1</th>
<th>Opp. per zak</th><th>Prijs per zakje</th><th>Zaaimaanden</th><th>Oogstmaanden</th>
</tr>
<tbody>
@foreach (var crop in Model) {
<tr>
<td>@crop.Name</td><td>@crop.Race</td><td>@crop.Category</td><td>@crop.AreaPerCrop</td>
<td>@crop.AreaPerBag</td><td>@crop.PricePerBag</td>
<td>@crop.SowingMonths</td><td>@crop.HarvestingMonths</td>
</tr>
}
</tbody>
</table>
</div>
@Html.ActionLink("Terug naar Zaaien en oogsten", "Index", "Home", null, null) | @model IEnumerable<Crop>
@{
ViewBag.Title = "Gewassen";
}
<div id="top"></div>
<div id="yearCalendar">
<h1>Dit zijn de gewassen in onze database:</h1>
<table class="table table-striped">
<tr>
<th>Naam</th><th>Ras</th><th>Categorie</th><th>Opp. per 1</th>
<th>Opp. per zak</th><th>Prijs per zakje</th><th>Zaaimaanden</th><th>Oogstmaanden</th>
</tr>
<tbody>
@foreach (var crop in Model) {
<tr>
<td>@crop.Name</td><td>@crop.Race</td><td>@crop.Category</td><td>@crop.AreaPerCrop</td>
<td>@crop.AreaPerBag</td><td>@crop.PricePerBag</td>
<td>@crop.SowingMonths</td><td>@crop.HarvestingMonths</td>
</tr>
}
</tbody>
</table>
</div>
@Html.ActionLink("Terug naar Zaaien en oogsten", "Index", "Home", null, null) |
Fix last bug in parameters | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WienerLinien.Api.Routing
{
public static class RoutingUrlBuilder
{
private const string BaseUrl = "http://www.wienerlinien.at/ogd_routing/XML_TRIP_REQUEST2?";
public static string Build(RoutingRequest request)
{
const string urlFormatString = BaseUrl +
"type_origin=stopID&name_origin={0}&type_destination=stopID&name_destination={1}&ptOptionsActive=1&itOptionsActive=1" +
"&itdDate={2:yyyyddMM}&idtTime={2:HHmm}&routeType={3}" +
"&outputFormat=JSON";
// &itdTripDateTimeDepArr={4}
var url = String.Format(urlFormatString,
request.FromStation, request.ToStation,
request.When, RouteTypeToQueryStringParameter(request.RouteType));
return url;
}
private static string RouteTypeToQueryStringParameter(RouteTypeOption option)
{
switch (option)
{
case RouteTypeOption.LeastTime:
return "LEASTTIME";
break;
case RouteTypeOption.LeastInterchange:
return "LEASTINTERCHANGE";
break;
case RouteTypeOption.LeastWalking:
return "LEASTWALKING";
break;
default:
throw new ArgumentOutOfRangeException("option");
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WienerLinien.Api.Routing
{
public static class RoutingUrlBuilder
{
private const string BaseUrl = "http://www.wienerlinien.at/ogd_routing/XML_TRIP_REQUEST2?";
public static string Build(RoutingRequest request)
{
const string urlFormatString = BaseUrl +
"type_origin=stopID&name_origin={0}&type_destination=stopID&name_destination={1}&ptOptionsActive=1&itOptionsActive=1" +
"&itdDate={2:yyyyMMdd}&itdTime={2:HHmm}&routeType={3}" +
"&outputFormat=JSON";
// &itdTripDateTimeDepArr={4}
var url = String.Format(urlFormatString,
request.FromStation, request.ToStation,
request.When, RouteTypeToQueryStringParameter(request.RouteType));
return url;
}
private static string RouteTypeToQueryStringParameter(RouteTypeOption option)
{
switch (option)
{
case RouteTypeOption.LeastTime:
return "LEASTTIME";
break;
case RouteTypeOption.LeastInterchange:
return "LEASTINTERCHANGE";
break;
case RouteTypeOption.LeastWalking:
return "LEASTWALKING";
break;
default:
throw new ArgumentOutOfRangeException("option");
}
}
}
}
|
Fix bug: Clearing the cache says "All items have been cleared from the recent packages list." Work items: 986 | using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using NuGet.VisualStudio;
namespace NuGet.Options {
public partial class GeneralOptionControl : UserControl {
private IRecentPackageRepository _recentPackageRepository;
private IProductUpdateSettings _productUpdateSettings;
public GeneralOptionControl() {
InitializeComponent();
_productUpdateSettings = ServiceLocator.GetInstance<IProductUpdateSettings>();
Debug.Assert(_productUpdateSettings != null);
_recentPackageRepository = ServiceLocator.GetInstance<IRecentPackageRepository>();
Debug.Assert(_recentPackageRepository != null);
}
private void OnClearRecentPackagesClick(object sender, EventArgs e) {
_recentPackageRepository.Clear();
MessageHelper.ShowInfoMessage(Resources.ShowInfo_ClearRecentPackages, Resources.ShowWarning_Title);
}
internal void OnActivated() {
checkForUpdate.Checked = _productUpdateSettings.ShouldCheckForUpdate;
browsePackageCacheButton.Enabled = clearPackageCacheButton.Enabled = Directory.Exists(MachineCache.Default.Source);
}
internal void OnApply() {
_productUpdateSettings.ShouldCheckForUpdate = checkForUpdate.Checked;
}
private void OnClearPackageCacheClick(object sender, EventArgs e) {
MachineCache.Default.Clear();
MessageHelper.ShowInfoMessage(Resources.ShowInfo_ClearRecentPackages, Resources.ShowWarning_Title);
}
private void OnBrowsePackageCacheClick(object sender, EventArgs e) {
if (Directory.Exists(MachineCache.Default.Source)) {
Process.Start(MachineCache.Default.Source);
}
}
}
} | using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using NuGet.VisualStudio;
namespace NuGet.Options {
public partial class GeneralOptionControl : UserControl {
private IRecentPackageRepository _recentPackageRepository;
private IProductUpdateSettings _productUpdateSettings;
public GeneralOptionControl() {
InitializeComponent();
_productUpdateSettings = ServiceLocator.GetInstance<IProductUpdateSettings>();
Debug.Assert(_productUpdateSettings != null);
_recentPackageRepository = ServiceLocator.GetInstance<IRecentPackageRepository>();
Debug.Assert(_recentPackageRepository != null);
}
private void OnClearRecentPackagesClick(object sender, EventArgs e) {
_recentPackageRepository.Clear();
MessageHelper.ShowInfoMessage(Resources.ShowInfo_ClearRecentPackages, Resources.ShowWarning_Title);
}
internal void OnActivated() {
checkForUpdate.Checked = _productUpdateSettings.ShouldCheckForUpdate;
browsePackageCacheButton.Enabled = clearPackageCacheButton.Enabled = Directory.Exists(MachineCache.Default.Source);
}
internal void OnApply() {
_productUpdateSettings.ShouldCheckForUpdate = checkForUpdate.Checked;
}
private void OnClearPackageCacheClick(object sender, EventArgs e) {
MachineCache.Default.Clear();
MessageHelper.ShowInfoMessage(Resources.ShowInfo_ClearPackageCache, Resources.ShowWarning_Title);
}
private void OnBrowsePackageCacheClick(object sender, EventArgs e) {
if (Directory.Exists(MachineCache.Default.Source)) {
Process.Start(MachineCache.Default.Source);
}
}
}
} |
Fix the possibility of a NullReferenceException | using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace GUtils.MVVM
{
/// <summary>
/// Implements a few utility functions for a ViewModel base
/// </summary>
public abstract class ViewModelBase : INotifyPropertyChanged
{
/// <inheritdoc/>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Does the logic for calling <see cref="PropertyChanged"/> if the value has changed (and
/// also sets the value of the field)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="field"></param>
/// <param name="newValue"></param>
/// <param name="propertyName"></param>
[MethodImpl ( MethodImplOptions.NoInlining )]
protected virtual void SetField<T> ( ref T field, T newValue, [CallerMemberName] String propertyName = null )
{
if ( field.Equals ( newValue ) )
return;
field = newValue;
this.OnPropertyChanged ( propertyName );
}
/// <summary>
/// Invokes <see cref="PropertyChanged"/>
/// </summary>
/// <param name="propertyName"></param>
/// <exception cref="ArgumentNullException">
/// Invoked if a <paramref name="propertyName"/> is not provided (and the value isn't
/// auto-filled by the compiler)
/// </exception>
[MethodImpl ( MethodImplOptions.NoInlining )]
protected virtual void OnPropertyChanged ( [CallerMemberName] String propertyName = null ) =>
this.PropertyChanged?.Invoke (
this,
new PropertyChangedEventArgs ( propertyName ?? throw new ArgumentNullException ( nameof ( propertyName ) ) ) );
}
} | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace GUtils.MVVM
{
/// <summary>
/// Implements a few utility functions for a ViewModel base
/// </summary>
public abstract class ViewModelBase : INotifyPropertyChanged
{
/// <inheritdoc/>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Does the logic for calling <see cref="PropertyChanged"/> if the value has changed (and
/// also sets the value of the field)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="field"></param>
/// <param name="newValue"></param>
/// <param name="propertyName"></param>
[MethodImpl ( MethodImplOptions.NoInlining )]
protected virtual void SetField<T> ( ref T field, T newValue, [CallerMemberName] String propertyName = null )
{
if ( EqualityComparer<T>.Default.Equals ( field, newValue ) )
return;
field = newValue;
this.OnPropertyChanged ( propertyName );
}
/// <summary>
/// Invokes <see cref="PropertyChanged"/>
/// </summary>
/// <param name="propertyName"></param>
/// <exception cref="ArgumentNullException">
/// Invoked if a <paramref name="propertyName"/> is not provided (and the value isn't
/// auto-filled by the compiler)
/// </exception>
[MethodImpl ( MethodImplOptions.NoInlining )]
protected virtual void OnPropertyChanged ( [CallerMemberName] String propertyName = null ) =>
this.PropertyChanged?.Invoke (
this,
new PropertyChangedEventArgs ( propertyName ?? throw new ArgumentNullException ( nameof ( propertyName ) ) ) );
}
} |
Update copyright year span to include 2014. This change was generated by the build script. | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: ComVisible(false)]
[assembly: AssemblyProduct("Fixie")]
[assembly: AssemblyVersion("0.0.1.0")]
[assembly: AssemblyFileVersion("0.0.1.0")]
[assembly: AssemblyCopyright("Copyright (c) 2013 Patrick Lioi")]
[assembly: AssemblyCompany("Patrick Lioi")]
[assembly: AssemblyDescription("A convention-based test framework.")]
[assembly: AssemblyConfiguration("Release")]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: ComVisible(false)]
[assembly: AssemblyProduct("Fixie")]
[assembly: AssemblyVersion("0.0.1.0")]
[assembly: AssemblyFileVersion("0.0.1.0")]
[assembly: AssemblyCopyright("Copyright (c) 2013-2014 Patrick Lioi")]
[assembly: AssemblyCompany("Patrick Lioi")]
[assembly: AssemblyDescription("A convention-based test framework.")]
[assembly: AssemblyConfiguration("Release")]
|
Add address permission constants for permissions card | using System;
namespace Alexa.NET.Response
{
public static class RequestedPermission
{
public const string ReadHouseholdList = "read::alexa:household:list";
public const string WriteHouseholdList = "write::alexa:household:list";
}
}
| using System;
namespace Alexa.NET.Response
{
public static class RequestedPermission
{
public const string ReadHouseholdList = "read::alexa:household:list";
public const string WriteHouseholdList = "write::alexa:household:list";
public const string FullAddress = "read::alexa:device:all:address";
public const string AddressCountryAndPostalCode = "read::alexa:device:all:address:country_and_postal_code";
}
}
|
Fix probing for git on non-Windows machines | using System;
using System.IO;
using System.Linq;
using LibGit2Sharp;
namespace GitIStage
{
internal static class Program
{
private static void Main()
{
var repositoryPath = ResolveRepositoryPath();
if (!Repository.IsValid(repositoryPath))
{
Console.WriteLine("fatal: Not a git repository");
return;
}
var pathToGit = ResolveGitPath();
if (string.IsNullOrEmpty(pathToGit))
{
Console.WriteLine("fatal: git is not in your path");
return;
}
var application = new Application(repositoryPath, pathToGit);
application.Run();
}
private static string ResolveRepositoryPath()
{
return Directory.GetCurrentDirectory();
}
private static string ResolveGitPath()
{
var path = Environment.GetEnvironmentVariable("PATH");
if (string.IsNullOrEmpty(path))
return null;
var paths = path.Split(Path.PathSeparator);
var searchPaths = paths.Select(p => Path.Combine(p, "git.exe"));
return searchPaths.FirstOrDefault(File.Exists);
}
}
} | using System;
using System.IO;
using System.Linq;
using LibGit2Sharp;
namespace GitIStage
{
internal static class Program
{
private static void Main()
{
var repositoryPath = ResolveRepositoryPath();
if (!Repository.IsValid(repositoryPath))
{
Console.WriteLine("fatal: Not a git repository");
return;
}
var pathToGit = ResolveGitPath();
if (string.IsNullOrEmpty(pathToGit))
{
Console.WriteLine("fatal: git is not in your path");
return;
}
var application = new Application(repositoryPath, pathToGit);
application.Run();
}
private static string ResolveRepositoryPath()
{
return Directory.GetCurrentDirectory();
}
private static string ResolveGitPath()
{
var path = Environment.GetEnvironmentVariable("PATH");
if (string.IsNullOrEmpty(path))
return null;
var paths = path.Split(Path.PathSeparator);
// In order to have this work across all operating systems, we
// need to include other extensions.
//
// NOTE: On .NET Core, we should use RuntimeInformation in order
// to limit the extensions based on operating system.
var fileNames = new[] { "git.exe", "git" };
var searchPaths = paths.SelectMany(p => fileNames.Select(f => Path.Combine(p, f)));
return searchPaths.FirstOrDefault(File.Exists);
}
}
} |
Fix overlined participants test scene not working | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Game.Screens.Multi.Components;
using osuTK;
namespace osu.Game.Tests.Visual.Multiplayer
{
public class TestSceneOverlinedParticipants : MultiplayerTestScene
{
protected override bool UseOnlineAPI => true;
[SetUp]
public new void Setup() => Schedule(() =>
{
Room.RoomID.Value = 7;
});
[Test]
public void TestHorizontalLayout()
{
AddStep("create component", () =>
{
Child = new ParticipantsDisplay(Direction.Horizontal)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Width = 500,
};
});
}
[Test]
public void TestVerticalLayout()
{
AddStep("create component", () =>
{
Child = new ParticipantsDisplay(Direction.Vertical)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(500)
};
});
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Game.Screens.Multi.Components;
using osu.Game.Users;
namespace osu.Game.Tests.Visual.Multiplayer
{
public class TestSceneOverlinedParticipants : MultiplayerTestScene
{
[SetUp]
public new void Setup() => Schedule(() =>
{
Room.RoomID.Value = 7;
for (int i = 0; i < 50; i++)
{
Room.RecentParticipants.Add(new User
{
Username = "peppy",
Id = 2
});
}
});
[Test]
public void TestHorizontalLayout()
{
AddStep("create component", () =>
{
Child = new ParticipantsDisplay(Direction.Horizontal)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Width = 0.2f,
};
});
}
[Test]
public void TestVerticalLayout()
{
AddStep("create component", () =>
{
Child = new ParticipantsDisplay(Direction.Vertical)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Width = 0.2f,
Height = 0.2f,
};
});
}
}
}
|
Implement mouse drag event as IObservable | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MouseRx2Wpf
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MouseRx2Wpf
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public IObservable<IObservable<Vector>> MouseDrag { get; }
public MainWindow()
{
InitializeComponent();
// Replace events with IObservable objects.
var mouseDown = Observable.FromEventPattern<MouseButtonEventArgs>(this, nameof(MouseDown)).Select(e => e.EventArgs);
var mouseUp = Observable.FromEventPattern<MouseButtonEventArgs>(this, nameof(MouseUp)).Select(e => e.EventArgs);
var mouseLeave = Observable.FromEventPattern<MouseEventArgs>(this, nameof(MouseLeave)).Select(e => e.EventArgs);
var mouseMove = Observable.FromEventPattern<MouseEventArgs>(this, nameof(MouseMove)).Select(e => e.EventArgs);
var mouseEnd = mouseUp.Merge(mouseLeave.Select(e => default(MouseButtonEventArgs)));
MouseDrag = mouseDown
.Select(e => e.GetPosition(this))
.Select(p0 => mouseMove
.Select(e => e.GetPosition(this) - p0)
.TakeUntil(mouseEnd));
}
}
}
|
Make sample app more helpful |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Abstractspoon.Tdl.PluginHelpers;
namespace SampleImpExp
{
public class SampleImpExpCore
{
public bool Export(TaskList srcTasks, string sDestFilePath, bool bSilent, Preferences prefs, string sKey)
{
int nVal = prefs.GetProfileInt("bob", "dave", 20);
int nVal2 = prefs.GetProfileInt("bob", "phil", 20);
// add some dummy values to prefs
prefs.WriteProfileInt("bob", "dave", 10);
Task task = srcTasks.GetFirstTask();
String sTitle = task.GetTitle();
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Abstractspoon.Tdl.PluginHelpers;
namespace SampleImpExp
{
public class SampleImpExpCore
{
public bool Export(TaskList srcTasks, string sDestFilePath, bool bSilent, Preferences prefs, string sKey)
{
// Possibly display a dialog to get input on how to
// map ToDoList task attributes to the output format
// TODO
// Process the tasks
Task task = srcTasks.GetFirstTask();
while (task.IsValid())
{
if (!ExportTask(task /*, probably with some additional parameters*/ ))
{
// Decide whether to stop or not
// TODO
}
task = task.GetNextTask();
}
return true;
}
protected bool ExportTask(Task task /*, probably with some additional parameters*/)
{
// TODO
return true;
}
}
}
|
Make transaction roll back per default until we figure out what to do | using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace RealmNet
{
public class Transaction : IDisposable
{
private SharedRealmHandle _sharedRealmHandle;
private bool _isOpen;
internal Transaction(SharedRealmHandle sharedRealmHandle)
{
this._sharedRealmHandle = sharedRealmHandle;
NativeSharedRealm.begin_transaction(sharedRealmHandle);
_isOpen = true;
}
public void Dispose()
{
if (!_isOpen)
return;
var exceptionOccurred = Marshal.GetExceptionPointers() != IntPtr.Zero || Marshal.GetExceptionCode() != 0;
if (exceptionOccurred)
Rollback();
else
Commit();
}
public void Rollback()
{
if (!_isOpen)
throw new Exception("Transaction was already closed. Cannot roll back");
NativeSharedRealm.cancel_transaction(_sharedRealmHandle);
_isOpen = false;
}
public void Commit()
{
if (!_isOpen)
throw new Exception("Transaction was already closed. Cannot commit");
NativeSharedRealm.commit_transaction(_sharedRealmHandle);
_isOpen = false;
}
}
}
| using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace RealmNet
{
public class Transaction : IDisposable
{
private SharedRealmHandle _sharedRealmHandle;
private bool _isOpen;
internal Transaction(SharedRealmHandle sharedRealmHandle)
{
this._sharedRealmHandle = sharedRealmHandle;
NativeSharedRealm.begin_transaction(sharedRealmHandle);
_isOpen = true;
}
public void Dispose()
{
if (!_isOpen)
return;
//var exceptionOccurred = Marshal.GetExceptionPointers() != IntPtr.Zero || Marshal.GetExceptionCode() != 0;
var exceptionOccurred = true; // TODO: Can we find this out on iOS? Otherwise, we have to remove it!
if (exceptionOccurred)
Rollback();
else
Commit();
}
public void Rollback()
{
if (!_isOpen)
throw new Exception("Transaction was already closed. Cannot roll back");
NativeSharedRealm.cancel_transaction(_sharedRealmHandle);
_isOpen = false;
}
public void Commit()
{
if (!_isOpen)
throw new Exception("Transaction was already closed. Cannot commit");
NativeSharedRealm.commit_transaction(_sharedRealmHandle);
_isOpen = false;
}
}
}
|
Remove obsolete delivery model names | using System;
using System.Text.Json.Serialization;
namespace SFA.DAS.CommitmentsV2.Types
{
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum DeliveryModel : byte
{
Regular = 0,
PortableFlexiJob = 1,
[Obsolete("Use `Regular` instead of `Normal`", true)]
Normal = Regular,
[Obsolete("Use `PortableFlexiJob` instead of `Flexible`", true)]
Flexible = PortableFlexiJob,
}
} | using System.Text.Json.Serialization;
namespace SFA.DAS.CommitmentsV2.Types
{
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum DeliveryModel : byte
{
Regular = 0,
PortableFlexiJob = 1,
}
} |
Change AssemblyCompany to .NET Foundation | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Outercurve Foundation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyConfiguration("")]
// If you change this version, make sure to change Build\build.proj accordingly
[assembly: AssemblyVersion("45.0.0.0")]
[assembly: AssemblyFileVersion("45.0.0.0")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
| using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany(".NET Foundation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyConfiguration("")]
// If you change this version, make sure to change Build\build.proj accordingly
[assembly: AssemblyVersion("45.0.0.0")]
[assembly: AssemblyFileVersion("45.0.0.0")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
|
Remove trailing spaces from <br> |
using System;
using HtmlAgilityPack;
namespace ReverseMarkdown.Converters
{
public class Br
: ConverterBase
{
public Br(Converter converter)
: base(converter)
{
this.Converter.Register("br", this);
}
public override string Convert(HtmlNode node)
{
return " " + Environment.NewLine;
}
}
}
|
using System;
using HtmlAgilityPack;
namespace ReverseMarkdown.Converters
{
public class Br
: ConverterBase
{
public Br(Converter converter)
: base(converter)
{
this.Converter.Register("br", this);
}
public override string Convert(HtmlNode node)
{
return Environment.NewLine;
}
}
}
|
Use existing extension method to get default value for a type. | using System;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;
namespace Unit.Tests
{
/// <summary>
/// Proxy that records method invocations.
/// </summary>
public class MethodRecorder<T> : RealProxy
{
/// <summary>
/// Creates a new interceptor that records method invocations.
/// </summary>
public MethodRecorder()
: base(typeof(T))
{
_proxy = new Lazy<T>(() => (T)base.GetTransparentProxy());
}
/// <summary>
/// The underlying proxy.
/// </summary>
public T Proxy
{
get { return _proxy.Value; }
}
/// <summary>
/// The most recent invocation made on the proxy.
/// </summary>
public IMethodCallMessage LastInvocation { get; private set; }
/// <see cref="RealProxy.Invoke"/>
public override IMessage Invoke(IMessage msg)
{
var methodCall = msg as IMethodCallMessage;
LastInvocation = methodCall;
object returnValue = null;
var method = methodCall.MethodBase as MethodInfo;
if (method != null)
{
Type returnType = method.ReturnType;
if (returnType.IsValueType && returnType != typeof(void)) // can't create an instance of Void
returnValue = Activator.CreateInstance(returnType);
}
return new ReturnMessage(returnValue, new object[0], 0, methodCall.LogicalCallContext, methodCall);
}
private readonly Lazy<T> _proxy;
}
}
| using System;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;
using Utilities.Reflection;
namespace Unit.Tests
{
/// <summary>
/// Proxy that records method invocations.
/// </summary>
public class MethodRecorder<T> : RealProxy
{
/// <summary>
/// Creates a new interceptor that records method invocations.
/// </summary>
public MethodRecorder()
: base(typeof(T))
{
_proxy = new Lazy<T>(() => (T)base.GetTransparentProxy());
}
/// <summary>
/// The underlying proxy.
/// </summary>
public T Proxy
{
get { return _proxy.Value; }
}
/// <summary>
/// The most recent invocation made on the proxy.
/// </summary>
public IMethodCallMessage LastInvocation { get; private set; }
/// <see cref="RealProxy.Invoke"/>
public override IMessage Invoke(IMessage msg)
{
var methodCall = msg as IMethodCallMessage;
LastInvocation = methodCall;
object returnValue = null;
var method = methodCall.MethodBase as MethodInfo;
if (method != null)
returnValue = method.ReturnType.GetDefaultValue();
return new ReturnMessage(returnValue, new object[0], 0, methodCall.LogicalCallContext, methodCall);
}
private readonly Lazy<T> _proxy;
}
}
|
Support ReturnUrl to public pages | <div class="user-display">
@if (!User.Identity.IsAuthenticated)
{
<span class="welcome"><a href="@Url.LogOn()">Log On</a></span>
<a href="@Url.Action(MVC.Users.Register())" class="register">Register</a>
}
else
{
<span class="welcome"><a href="@Url.Action(MVC.Users.Account())">@User.Identity.Name</a></span>
<span class="user-actions">
<a href="@Url.LogOff()">Log Off</a>
</span>
}
</div> | <div class="user-display">
@if (!User.Identity.IsAuthenticated)
{
<span class="welcome">@Html.ActionLink("Log On", "LogOn", "Authentication", new { returnUrl = Request.RequestContext.HttpContext.Request.RawUrl }, null)</span>
<a href="@Url.Action(MVC.Users.Register())" class="register">Register</a>
}
else
{
<span class="welcome"><a href="@Url.Action(MVC.Users.Account())">@User.Identity.Name</a></span>
<span class="user-actions">
<a href="@Url.LogOff()">Log Off</a>
</span>
}
</div> |
Set system timer resolution for the sleep call in the wait loop | using System;
using System.Windows.Forms;
namespace elbsms_ui
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
| using System;
using System.Windows.Forms;
using elb_utilities.NativeMethods;
namespace elbsms_ui
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// set timer resolution to 1ms to try and get the sleep accurate in the wait loop
WinMM.TimeBeginPeriod(1);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
|
Set Magenta as a default color for shapes | using Urho.Resources;
namespace Urho.Shapes
{
public abstract class Shape : StaticModel
{
Material material;
public override void OnAttachedToNode(Node node)
{
Model = Application.ResourceCache.GetModel(ModelResource);
Color = color;
}
protected abstract string ModelResource { get; }
Color color;
public Color Color
{
set
{
if (material == null)
{
//try to restore material (after deserialization)
material = GetMaterial(0);
if (material == null)
{
material = new Material();
material.SetTechnique(0, Application.ResourceCache.GetTechnique("Techniques/NoTextureAlpha.xml"), 1, 1);
}
SetMaterial(material);
}
material.SetShaderParameter("MatDiffColor", value);
color = value;
}
get
{
return color;
}
}
public override void OnDeserialize(IComponentDeserializer d)
{
color = d.Deserialize<Color>(nameof(Color));
}
public override void OnSerialize(IComponentSerializer s)
{
s.Serialize(nameof(Color), Color);
}
}
}
| using Urho.Resources;
namespace Urho.Shapes
{
public abstract class Shape : StaticModel
{
Material material;
public override void OnAttachedToNode(Node node)
{
Model = Application.ResourceCache.GetModel(ModelResource);
Color = color;
}
protected abstract string ModelResource { get; }
Color color = Color.Magenta;
public Color Color
{
set
{
if (material == null)
{
//try to restore material (after deserialization)
material = GetMaterial(0);
if (material == null)
{
material = new Material();
material.SetTechnique(0, Application.ResourceCache.GetTechnique("Techniques/NoTextureAlpha.xml"), 1, 1);
}
SetMaterial(material);
}
material.SetShaderParameter("MatDiffColor", value);
color = value;
}
get
{
return color;
}
}
public override void OnDeserialize(IComponentDeserializer d)
{
color = d.Deserialize<Color>(nameof(Color));
}
public override void OnSerialize(IComponentSerializer s)
{
s.Serialize(nameof(Color), Color);
}
}
}
|
Add ResolveByName attribute to TargetTextBlock property | using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Xaml.Interactivity;
namespace Avalonia.Xaml.Interactions.Custom;
/// <summary>
/// A behavior that displays cursor position on <see cref="InputElement.PointerMoved"/> event for the <see cref="Behavior{T}.AssociatedObject"/> using <see cref="TextBlock.Text"/> property.
/// </summary>
public class ShowPointerPositionBehavior : Behavior<Control>
{
/// <summary>
/// Identifies the <seealso cref="TargetTextBlockProperty"/> avalonia property.
/// </summary>
public static readonly StyledProperty<TextBlock?> TargetTextBlockProperty =
AvaloniaProperty.Register<ShowPointerPositionBehavior, TextBlock?>(nameof(TargetTextBlock));
/// <summary>
/// Gets or sets the target TextBlock object in which this behavior displays cursor position on PointerMoved event.
/// </summary>
public TextBlock? TargetTextBlock
{
get => GetValue(TargetTextBlockProperty);
set => SetValue(TargetTextBlockProperty, value);
}
/// <inheritdoc />
protected override void OnAttachedToVisualTree()
{
if (AssociatedObject is { })
{
AssociatedObject.PointerMoved += AssociatedObject_PointerMoved;
}
}
/// <inheritdoc />
protected override void OnDetachedFromVisualTree()
{
if (AssociatedObject is { })
{
AssociatedObject.PointerMoved -= AssociatedObject_PointerMoved;
}
}
private void AssociatedObject_PointerMoved(object? sender, PointerEventArgs e)
{
if (TargetTextBlock is { })
{
TargetTextBlock.Text = e.GetPosition(AssociatedObject).ToString();
}
}
}
| using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Xaml.Interactivity;
namespace Avalonia.Xaml.Interactions.Custom;
/// <summary>
/// A behavior that displays cursor position on <see cref="InputElement.PointerMoved"/> event for the <see cref="Behavior{T}.AssociatedObject"/> using <see cref="TextBlock.Text"/> property.
/// </summary>
public class ShowPointerPositionBehavior : Behavior<Control>
{
/// <summary>
/// Identifies the <seealso cref="TargetTextBlockProperty"/> avalonia property.
/// </summary>
public static readonly StyledProperty<TextBlock?> TargetTextBlockProperty =
AvaloniaProperty.Register<ShowPointerPositionBehavior, TextBlock?>(nameof(TargetTextBlock));
/// <summary>
/// Gets or sets the target TextBlock object in which this behavior displays cursor position on PointerMoved event.
/// </summary>
[ResolveByName]
public TextBlock? TargetTextBlock
{
get => GetValue(TargetTextBlockProperty);
set => SetValue(TargetTextBlockProperty, value);
}
/// <inheritdoc />
protected override void OnAttachedToVisualTree()
{
if (AssociatedObject is { })
{
AssociatedObject.PointerMoved += AssociatedObject_PointerMoved;
}
}
/// <inheritdoc />
protected override void OnDetachedFromVisualTree()
{
if (AssociatedObject is { })
{
AssociatedObject.PointerMoved -= AssociatedObject_PointerMoved;
}
}
private void AssociatedObject_PointerMoved(object? sender, PointerEventArgs e)
{
if (TargetTextBlock is { })
{
TargetTextBlock.Text = e.GetPosition(AssociatedObject).ToString();
}
}
}
|
Update ContentItemDisplay mapper to set IsContainer and IsChildOfListView correctly | using Opten.Umbraco.ListView.Extensions;
using System;
using System.Linq;
using Umbraco.Core;
using Umbraco.Web.Trees;
namespace ClassLibrary1
{
public class TreeEventHandler : ApplicationEventHandler
{
protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
ContentTreeController.TreeNodesRendering += ContentTreeController_TreeNodesRendering;
}
private void ContentTreeController_TreeNodesRendering(TreeControllerBase sender, TreeNodesRenderingEventArgs e)
{
if (e.QueryStrings["application"].Equals("content") &&
e.QueryStrings["isDialog"].Equals("false") &&
string.IsNullOrWhiteSpace(e.QueryStrings["id"]) == false)
{
var content = sender.Services.ContentService.GetById(int.Parse(e.QueryStrings["id"]));
e.Nodes.RemoveAll(treeNode => treeNode.AdditionalData.ContainsKey("contentType") && content.IsInListView(treeNode.AdditionalData["contentType"].ToString()));
}
}
}
}
| using AutoMapper;
using Opten.Umbraco.ListView.Extensions;
using System.Linq;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Web.Models.ContentEditing;
using Umbraco.Web.Trees;
namespace ClassLibrary1
{
public class TreeEventHandler : ApplicationEventHandler
{
protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
ContentTreeController.TreeNodesRendering += ContentTreeController_TreeNodesRendering;
var typeMaps = Mapper.GetAllTypeMaps();
var contentMapper = typeMaps.First(map => map.DestinationType.Equals(typeof(ContentItemDisplay)) && map.SourceType.Equals(typeof(IContent)));
contentMapper.AddAfterMapAction((src, dest) =>
{
var srcTyped = src as IContent;
var destTyped = dest as ContentItemDisplay;
destTyped.IsChildOfListView = destTyped.IsChildOfListView || srcTyped.Parent().IsInListView(srcTyped.ContentType.Alias);
destTyped.IsContainer = destTyped.IsContainer || srcTyped.FindGridListViewContentTypeAliases().Any();
});
}
private void ContentTreeController_TreeNodesRendering(TreeControllerBase sender, TreeNodesRenderingEventArgs e)
{
if (e.QueryStrings["application"].Equals("content") &&
e.QueryStrings["isDialog"].Equals("false") &&
string.IsNullOrWhiteSpace(e.QueryStrings["id"]) == false)
{
var content = sender.Services.ContentService.GetById(int.Parse(e.QueryStrings["id"]));
e.Nodes.RemoveAll(treeNode => treeNode.AdditionalData.ContainsKey("contentType") && content.IsInListView(treeNode.AdditionalData["contentType"].ToString()));
}
}
}
}
|
Remove reference to statistic manager from timerdecorator. | namespace Moya.Runner.Runners
{
using System.Diagnostics;
using System.Reflection;
using Models;
using Statistics;
public class TimerDecorator : ITestRunner
{
private readonly IDurationManager duration;
public ITestRunner DecoratedTestRunner { get; set; }
public TimerDecorator(ITestRunner testRunner)
{
DecoratedTestRunner = testRunner;
duration = DurationManager.DefaultInstance;
}
public ITestResult Execute(MethodInfo methodInfo)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
var result = DecoratedTestRunner.Execute(methodInfo);
stopwatch.Stop();
duration.AddOrUpdateDuration(methodInfo.GetHashCode(), stopwatch.ElapsedMilliseconds);
result.Duration = stopwatch.ElapsedMilliseconds;
return result;
}
}
} | namespace Moya.Runner.Runners
{
using System.Diagnostics;
using System.Reflection;
using Models;
public class TimerDecorator : ITestRunner
{
public ITestRunner DecoratedTestRunner { get; set; }
public TimerDecorator(ITestRunner testRunner)
{
DecoratedTestRunner = testRunner;
}
public ITestResult Execute(MethodInfo methodInfo)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
var result = DecoratedTestRunner.Execute(methodInfo);
stopwatch.Stop();
result.Duration = stopwatch.ElapsedMilliseconds;
return result;
}
}
} |
Use owinContext.Request.CallCancelled in default page middleware | using System.Threading;
using System.Threading.Tasks;
using Microsoft.Owin;
using Foundation.Api.Contracts;
using Foundation.Core.Contracts;
namespace Foundation.Api.Middlewares
{
public class DefaultPageMiddleware : OwinMiddleware
{
public DefaultPageMiddleware(OwinMiddleware next)
: base(next)
{
}
public override async Task Invoke(IOwinContext context)
{
IDependencyResolver dependencyResolver = context.GetDependencyResolver();
string defaultPage = await dependencyResolver.Resolve<IDefaultHtmlPageProvider>().GetDefaultPageAsync(CancellationToken.None);
context.Response.ContentType = "text/html; charset=utf-8";
await context.Response.WriteAsync(defaultPage);
}
}
} | using System.Threading;
using System.Threading.Tasks;
using Microsoft.Owin;
using Foundation.Api.Contracts;
using Foundation.Core.Contracts;
namespace Foundation.Api.Middlewares
{
public class DefaultPageMiddleware : OwinMiddleware
{
public DefaultPageMiddleware(OwinMiddleware next)
: base(next)
{
}
public override async Task Invoke(IOwinContext context)
{
IDependencyResolver dependencyResolver = context.GetDependencyResolver();
string defaultPage = await dependencyResolver.Resolve<IDefaultHtmlPageProvider>().GetDefaultPageAsync(context.Request.CallCancelled);
context.Response.ContentType = "text/html; charset=utf-8";
await context.Response.WriteAsync(defaultPage);
}
}
} |
Add MLC and SMC to education levels | using System.ComponentModel.DataAnnotations;
namespace BatteryCommander.Web.Models
{
public enum MilitaryEducationLevel : byte
{
Unknown,
[Display(Name = "(AIT) Advanced Individual Training", ShortName = "AIT")]
AIT = 1,
[Display(Name = "(BLC) Basic Leader Course", ShortName = "BLC")]
BLC = 2,
[Display(Name = "(ALC) Advanced Leader Course", ShortName = "ALC")]
ALC = 3,
[Display(Name = "(SLC) Senior Leader Course", ShortName = "SLC")]
SLC = 4,
[Display(Name = "(BOLC) Basic Officer Leaders Course", ShortName = "BOLC")]
BOLC = 10,
[Display(Name = "(CCC) Captains Career Course", ShortName = "CCC")]
CCC = 11
}
} | using System.ComponentModel.DataAnnotations;
namespace BatteryCommander.Web.Models
{
public enum MilitaryEducationLevel : byte
{
Unknown,
[Display(Name = "(AIT) Advanced Individual Training", ShortName = "AIT")]
AIT = 1,
[Display(Name = "(BLC) Basic Leader Course", ShortName = "BLC")]
BLC = 2,
[Display(Name = "(ALC) Advanced Leader Course", ShortName = "ALC")]
ALC = 3,
[Display(Name = "(SLC) Senior Leader Course", ShortName = "SLC")]
SLC = 4,
[Display(Name = "(MLC) Master Leader Course", ShortName = "MLC")]
MLC = 5,
[Display(Name = "(SMC) Sergeants Major Course", ShortName = "SMC")]
SMC = 6,
[Display(Name = "(BOLC) Basic Officer Leaders Course", ShortName = "BOLC")]
BOLC = 10,
[Display(Name = "(CCC) Captains Career Course", ShortName = "CCC")]
CCC = 11
}
} |
Rename assembly to proper name | using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("Library")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("khalil")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("Intercom.Dotnet.Client")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("khalil")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
|
Fix incorrect array pool usage | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Buffers;
using osu.Framework.Graphics.Primitives;
using osuTK.Graphics.ES30;
using SixLabors.ImageSharp.PixelFormats;
namespace osu.Framework.Graphics.Textures
{
public class ArrayPoolTextureUpload : ITextureUpload
{
private readonly ArrayPool<Rgba32> arrayPool;
private readonly Rgba32[] data;
/// <summary>
/// Create an empty raw texture with an efficient shared memory backing.
/// </summary>
/// <param name="width">The width of the texture.</param>
/// <param name="height">The height of the texture.</param>
/// <param name="arrayPool">The source pool to retrieve memory from. Shared default is used if null.</param>
public ArrayPoolTextureUpload(int width, int height, ArrayPool<Rgba32> arrayPool = null)
{
data = (this.arrayPool = ArrayPool<Rgba32>.Shared).Rent(width * height);
}
public void Dispose()
{
arrayPool.Return(data);
}
public Span<Rgba32> RawData => data;
public ReadOnlySpan<Rgba32> Data => data;
public int Level { get; set; }
public virtual PixelFormat Format => PixelFormat.Rgba;
public RectangleI Bounds { get; set; }
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Buffers;
using osu.Framework.Graphics.Primitives;
using osuTK.Graphics.ES30;
using SixLabors.ImageSharp.PixelFormats;
namespace osu.Framework.Graphics.Textures
{
public class ArrayPoolTextureUpload : ITextureUpload
{
private readonly ArrayPool<Rgba32> arrayPool;
private readonly Rgba32[] data;
/// <summary>
/// Create an empty raw texture with an efficient shared memory backing.
/// </summary>
/// <param name="width">The width of the texture.</param>
/// <param name="height">The height of the texture.</param>
/// <param name="arrayPool">The source pool to retrieve memory from. Shared default is used if null.</param>
public ArrayPoolTextureUpload(int width, int height, ArrayPool<Rgba32> arrayPool = null)
{
this.arrayPool = arrayPool ?? ArrayPool<Rgba32>.Shared;
data = this.arrayPool.Rent(width * height);
}
public void Dispose()
{
arrayPool.Return(data);
}
public Span<Rgba32> RawData => data;
public ReadOnlySpan<Rgba32> Data => data;
public int Level { get; set; }
public virtual PixelFormat Format => PixelFormat.Rgba;
public RectangleI Bounds { get; set; }
}
}
|
Rename acceptance test with proper underscores. | namespace PastaPricer.Tests.Acceptance
{
using NSubstitute;
using NUnit.Framework;
[TestFixture]
public class PastaPricerAcceptanceTests
{
[Test]
public void Should_PublishPastaPriceOnceStartedAndMarketDataIsAvailable()
{
// Mocks instantiation
var publisher = Substitute.For<IPastaPricerPublisher>();
var marketDataProvider = new MarketDataProvider();
var pastaPricer = new PastaPricerEngine(marketDataProvider, publisher);
publisher.DidNotReceiveWithAnyArgs().Publish(string.Empty, 0);
pastaPricer.Start();
publisher.DidNotReceiveWithAnyArgs().Publish(string.Empty, 0);
marketDataProvider.Start();
// It publishes!
publisher.ReceivedWithAnyArgs().Publish(string.Empty, 0);
}
}
} | namespace PastaPricer.Tests.Acceptance
{
using NSubstitute;
using NUnit.Framework;
[TestFixture]
public class PastaPricerAcceptanceTests
{
[Test]
public void Should_Publish_Pasta_Price_Once_Started_And_MarketData_Is_Available()
{
// Mocks instantiation
var publisher = Substitute.For<IPastaPricerPublisher>();
var marketDataProvider = new MarketDataProvider();
var pastaPricer = new PastaPricerEngine(marketDataProvider, publisher);
publisher.DidNotReceiveWithAnyArgs().Publish(string.Empty, 0);
pastaPricer.Start();
publisher.DidNotReceiveWithAnyArgs().Publish(string.Empty, 0);
marketDataProvider.Start();
// It publishes!
publisher.ReceivedWithAnyArgs().Publish(string.Empty, 0);
}
}
} |
Add enumerated ports to the list of serial ports, this currently causes duplicates but meh. |
using System;
using System.Collections.Generic;
namespace LazerTagHostLibrary
{
public class LazerTagSerial
{
public LazerTagSerial ()
{
}
static public List<string> GetSerialPorts()
{
List<string> result = new List<string>();
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo("/dev");
System.IO.FileInfo[] fi = di.GetFiles("ttyUSB*");
foreach (System.IO.FileInfo f in fi) {
result.Add(f.FullName);
}
return result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO.Ports;
namespace LazerTagHostLibrary
{
public class LazerTagSerial
{
public LazerTagSerial ()
{
}
static public List<string> GetSerialPorts()
{
List<string> result = new List<string>();
try {
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo("/dev");
System.IO.FileInfo[] fi = di.GetFiles("ttyUSB*");
foreach (System.IO.FileInfo f in fi) {
result.Add(f.FullName);
}
} catch (Exception) {
//eh
}
try {
String[] ports = SerialPort.GetPortNames();
foreach (String p in ports) {
result.Add(p);
}
} catch (Exception) {
//eh
}
return result;
}
}
}
|
Update OData assembly version to 5.4.0.0 | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
#if !BUILD_GENERATED_VERSION
[assembly: AssemblyCompany("Microsoft Open Technologies, Inc.")]
[assembly: AssemblyCopyright("© Microsoft Open Technologies, Inc. All rights reserved.")]
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
#if !NOT_CLS_COMPLIANT
[assembly: CLSCompliant(true)]
#endif
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyMetadata("Serviceable", "True")]
// ===========================================================================
// DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT.
// Version numbers are automatically generated based on regular expressions.
// ===========================================================================
#if ASPNETODATA
#if !BUILD_GENERATED_VERSION
[assembly: AssemblyVersion("5.3.1.0")] // ASPNETODATA
[assembly: AssemblyFileVersion("5.3.1.0")] // ASPNETODATA
#endif
[assembly: AssemblyProduct("Microsoft ASP.NET Web API OData")]
#endif | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
#if !BUILD_GENERATED_VERSION
[assembly: AssemblyCompany("Microsoft Open Technologies, Inc.")]
[assembly: AssemblyCopyright("© Microsoft Open Technologies, Inc. All rights reserved.")]
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
#if !NOT_CLS_COMPLIANT
[assembly: CLSCompliant(true)]
#endif
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyMetadata("Serviceable", "True")]
// ===========================================================================
// DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT.
// Version numbers are automatically generated based on regular expressions.
// ===========================================================================
#if ASPNETODATA
#if !BUILD_GENERATED_VERSION
[assembly: AssemblyVersion("5.4.0.0")] // ASPNETODATA
[assembly: AssemblyFileVersion("5.4.0.0")] // ASPNETODATA
#endif
[assembly: AssemblyProduct("Microsoft ASP.NET Web API OData")]
#endif |
Check native registry view for Windows version | using System;
using System.IO;
using Microsoft.Win32;
namespace FreenetTray.Browsers {
class Edge: Browser {
private static string NTVersionRegistryKey = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion";
public Edge() {
// for this key we want registry redirection enabled, so no registry view is used
var reg = Registry.LocalMachine.OpenSubKey(NTVersionRegistryKey);
string productName = reg.GetValue("ProductName") as string;
// there's no version info but it isn't useful anyway
_version = new System.Version(0, 0);
_isInstalled = productName.StartsWith("Windows 10");
_isUsable = _isInstalled;
_args = "microsoft-edge:";
// there is no .exe, instead a url like scheme is used with explorer.exe
_path = Path.Combine(Environment.GetEnvironmentVariable("windir"), "explorer.exe");
_name = "Edge";
}
}
}
| using System;
using System.IO;
using Microsoft.Win32;
namespace FreenetTray.Browsers {
class Edge: Browser {
private static string NTVersionRegistryKey = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion";
public Edge() {
RegistryKey reg = null;
if (Environment.Is64BitOperatingSystem) {
RegistryKey local64 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
reg = local64.OpenSubKey(NTVersionRegistryKey);
} else {
RegistryKey local32 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
reg = local32.OpenSubKey(NTVersionRegistryKey);
}
if (reg != null) {
string productName = reg.GetValue("ProductName") as string;
_isInstalled = productName.StartsWith("Windows 10");
} else {
_isInstalled = false;
}
_isUsable = _isInstalled;
// there's no version info but it isn't useful anyway
_version = new System.Version(0, 0);
_args = "microsoft-edge:";
// there is no .exe, instead a url like scheme is used with explorer.exe
_path = Path.Combine(Environment.GetEnvironmentVariable("windir"), "explorer.exe");
_name = "Edge";
}
}
}
|
Improve user question when node conflict is not auto-resolved | using System;
using System.Xml.Linq;
namespace Project {
public abstract class Item: IEquatable<Item>, IConflictableItem {
public abstract override int GetHashCode();
public virtual string Action { get { return GetType().Name; } }
public abstract string Key { get; }
public bool IsResolveOption { get; set; }
protected Item() {
IsResolveOption = true;
}
public abstract bool Equals( Item other );
public static bool operator ==( Item i1, Item i2 ) {
if ( ReferenceEquals( null, i1 ) ^ ReferenceEquals( null, i2 ) ) {
return false;
}
return ReferenceEquals( null, i1 ) || i1.Equals( i2 );
}
public abstract override bool Equals( object obj );
public static bool operator !=( Item i1, Item i2 ) {
return !( i1 == i2 );
}
public abstract XElement ToElement( XNamespace ns );
public override string ToString() {
return Key;
}
}
} | using System;
using System.Xml.Linq;
namespace Project {
public abstract class Item: IEquatable<Item>, IConflictableItem {
public abstract override int GetHashCode();
public virtual string Action { get { return GetType().Name; } }
public abstract string Key { get; }
public bool IsResolveOption { get; set; }
protected Item() {
IsResolveOption = true;
}
public abstract bool Equals( Item other );
public static bool operator ==( Item i1, Item i2 ) {
if ( ReferenceEquals( null, i1 ) ^ ReferenceEquals( null, i2 ) ) {
return false;
}
return ReferenceEquals( null, i1 ) || i1.Equals( i2 );
}
public abstract override bool Equals( object obj );
public static bool operator !=( Item i1, Item i2 ) {
return !( i1 == i2 );
}
public abstract XElement ToElement( XNamespace ns );
public override string ToString() {
var element = ToElement( "" );
return element?.ToString() ?? Key;
}
}
} |
Use a fixed size buffer rather than marshalling | /* Copyright © 2018 Jeremy Herbison
This file is part of AudioWorks.
AudioWorks is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public
License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
version.
AudioWorks 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 Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along with AudioWorks. If not, see
<https://www.gnu.org/licenses/>. */
using System.Runtime.InteropServices;
namespace AudioWorks.Extensions.Flac
{
[StructLayout(LayoutKind.Sequential)]
readonly struct StreamInfo
{
readonly uint MinBlockSize;
readonly uint MaxBlockSize;
readonly uint MinFrameSize;
readonly uint MaxFrameSize;
internal readonly uint SampleRate;
internal readonly uint Channels;
internal readonly uint BitsPerSample;
internal readonly ulong TotalSamples;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] readonly byte[] Md5Sum;
}
} | /* Copyright © 2018 Jeremy Herbison
This file is part of AudioWorks.
AudioWorks is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public
License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
version.
AudioWorks 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 Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along with AudioWorks. If not, see
<https://www.gnu.org/licenses/>. */
using System.Runtime.InteropServices;
namespace AudioWorks.Extensions.Flac
{
[StructLayout(LayoutKind.Sequential)]
unsafe struct StreamInfo
{
readonly uint MinBlockSize;
readonly uint MaxBlockSize;
readonly uint MinFrameSize;
readonly uint MaxFrameSize;
internal readonly uint SampleRate;
internal readonly uint Channels;
internal readonly uint BitsPerSample;
internal readonly ulong TotalSamples;
fixed byte Md5Sum[16];
}
} |
Increase project version number to 0.9.0 | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Yevgeniy Shunevych")]
[assembly: AssemblyProduct("Atata")]
[assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2016")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.8.0.0")]
[assembly: AssemblyFileVersion("0.8.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Yevgeniy Shunevych")]
[assembly: AssemblyProduct("Atata")]
[assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2016")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.9.0.0")]
[assembly: AssemblyFileVersion("0.9.0.0")]
|
Add more languages to settings dropdown | // 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.ComponentModel;
namespace osu.Game.Localisation
{
public enum Language
{
[Description(@"English")]
en,
[Description(@"日本語")]
ja
}
}
| // 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.ComponentModel;
namespace osu.Game.Localisation
{
public enum Language
{
[Description(@"English")]
en,
// TODO: Requires Arabic glyphs to be added to resources (and possibly also RTL support).
// [Description(@"اَلْعَرَبِيَّةُ")]
// ar,
// TODO: Some accented glyphs are missing. Revisit when adding Inter.
// [Description(@"Беларуская мова")]
// be,
[Description(@"Български")]
bg,
[Description(@"Česky")]
cs,
[Description(@"Dansk")]
da,
[Description(@"Deutsch")]
de,
// TODO: Some accented glyphs are missing. Revisit when adding Inter.
// [Description(@"Ελληνικά")]
// el,
[Description(@"español")]
es,
[Description(@"Suomi")]
fi,
[Description(@"français")]
fr,
[Description(@"Magyar")]
hu,
[Description(@"Bahasa Indonesia")]
id,
[Description(@"Italiano")]
it,
[Description(@"日本語")]
ja,
[Description(@"한국어")]
ko,
[Description(@"Nederlands")]
nl,
[Description(@"Norsk")]
no,
[Description(@"polski")]
pl,
[Description(@"Português")]
pt,
[Description(@"Português (Brasil)")]
pt_br,
[Description(@"Română")]
ro,
[Description(@"Русский")]
ru,
[Description(@"Slovenčina")]
sk,
[Description(@"Svenska")]
se,
[Description(@"ไทย")]
th,
[Description(@"Tagalog")]
tl,
[Description(@"Türkçe")]
tr,
// TODO: Some accented glyphs are missing. Revisit when adding Inter.
// [Description(@"Українська мова")]
// uk,
[Description(@"Tiếng Việt")]
vn,
[Description(@"简体中文")]
zh,
[Description(@"繁體中文(香港)")]
zh_hk,
[Description(@"繁體中文(台灣)")]
zh_tw
}
}
|
Fix SSL/TLS exception during application startup | using System;
using System.Threading.Tasks;
using Octokit;
namespace MangaRipper.Helpers
{
public class UpdateNotification
{
public static async Task<string> GetLatestVersion()
{
var client = new GitHubClient(new ProductHeaderValue("MyAmazingApp"));
var release = await client.Repository.Release.GetLatest("NguyenDanPhuong", "MangaRipper");
return release.TagName;
}
public static long GetLatestBuildNumber(string version)
{
return Convert.ToInt64(version.Remove(0, version.LastIndexOf(".", StringComparison.Ordinal) + 1));
}
}
} | using System;
using System.Threading.Tasks;
using Octokit;
using System.Net;
namespace MangaRipper.Helpers
{
public class UpdateNotification
{
public static async Task<string> GetLatestVersion()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var client = new GitHubClient(new ProductHeaderValue("MyAmazingApp"));
var release = await client.Repository.Release.GetLatest("NguyenDanPhuong", "MangaRipper");
return release.TagName;
}
public static long GetLatestBuildNumber(string version)
{
return Convert.ToInt64(version.Remove(0, version.LastIndexOf(".", StringComparison.Ordinal) + 1));
}
}
} |
Use LINQ to sort results. | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ProjectTracker.Library;
namespace PTWin
{
public partial class ProjectSelect : Form
{
private Guid _projectId;
public Guid ProjectId
{
get { return _projectId; }
}
public ProjectSelect()
{
InitializeComponent();
}
private void OK_Button_Click(object sender, EventArgs e)
{
_projectId = (Guid)this.ProjectListListBox.SelectedValue;
this.Close();
}
private void Cancel_Button_Click(object sender, EventArgs e)
{
this.Close();
}
private void ProjectSelect_Load(object sender, EventArgs e)
{
DisplayList(ProjectList.GetProjectList());
}
private void DisplayList(ProjectList list)
{
Csla.SortedBindingList<ProjectInfo> sortedList =
new Csla.SortedBindingList<ProjectInfo>(list);
sortedList.ApplySort("Name", ListSortDirection.Ascending);
this.projectListBindingSource.DataSource = sortedList;
}
private void GetListButton_Click(
object sender, EventArgs e)
{
DisplayList(ProjectList.GetProjectList(NameTextBox.Text));
}
}
} | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ProjectTracker.Library;
using System.Linq;
namespace PTWin
{
public partial class ProjectSelect : Form
{
private Guid _projectId;
public Guid ProjectId
{
get { return _projectId; }
}
public ProjectSelect()
{
InitializeComponent();
}
private void OK_Button_Click(object sender, EventArgs e)
{
_projectId = (Guid)this.ProjectListListBox.SelectedValue;
this.Close();
}
private void Cancel_Button_Click(object sender, EventArgs e)
{
this.Close();
}
private void ProjectSelect_Load(object sender, EventArgs e)
{
DisplayList(ProjectList.GetProjectList());
}
private void DisplayList(ProjectList list)
{
var sortedList = from p in list orderby p.Name select p;
this.projectListBindingSource.DataSource = sortedList;
}
private void GetListButton_Click(
object sender, EventArgs e)
{
DisplayList(ProjectList.GetProjectList(NameTextBox.Text));
}
}
} |
Add implementation for authorization serialization example. | namespace TraktSerializeAuthorizationExample
{
class Program
{
static void Main(string[] args)
{
}
}
}
| namespace TraktSerializeAuthorizationExample
{
using System;
using TraktApiSharp;
using TraktApiSharp.Authentication;
using TraktApiSharp.Enums;
using TraktApiSharp.Services;
class Program
{
private const string CLIENT_ID = "FAKE_CLIENT_ID";
private const string CLIENT_SECRET = "FAKE_CLIENT_SECRET";
static void Main(string[] args)
{
TraktClient client = new TraktClient(CLIENT_ID, CLIENT_SECRET);
TraktAuthorization fakeAuthorization = new TraktAuthorization
{
AccessToken = "FakeAccessToken",
RefreshToken = "FakeRefreshToken",
ExpiresIn = 90 * 24 * 3600,
AccessScope = TraktAccessScope.Public,
TokenType = TraktAccessTokenType.Bearer
};
Console.WriteLine("Fake Authorization:");
Console.WriteLine($"Created (UTC): {fakeAuthorization.Created}");
Console.WriteLine($"Access Scope: {fakeAuthorization.AccessScope.DisplayName}");
Console.WriteLine($"Refresh Possible: {fakeAuthorization.IsRefreshPossible}");
Console.WriteLine($"Valid: {fakeAuthorization.IsValid}");
Console.WriteLine($"Token Type: {fakeAuthorization.TokenType.DisplayName}");
Console.WriteLine($"Access Token: {fakeAuthorization.AccessToken}");
Console.WriteLine($"Refresh Token: {fakeAuthorization.RefreshToken}");
Console.WriteLine($"Token Expired: {fakeAuthorization.IsExpired}");
Console.WriteLine($"Expires in {fakeAuthorization.ExpiresIn / 3600 / 24} days");
Console.WriteLine("-------------------------------------------------------------");
//string fakeAuthorizationJson = TraktSerializationService.Serialize(client.Authorization);
string fakeAuthorizationJson = TraktSerializationService.Serialize(fakeAuthorization);
if (!string.IsNullOrEmpty(fakeAuthorizationJson))
{
Console.WriteLine("Serialized Fake Authorization:");
Console.WriteLine(fakeAuthorizationJson);
Console.WriteLine("-------------------------------------------------------------");
TraktAuthorization deserializedFakeAuthorization = TraktSerializationService.DeserializeAuthorization(fakeAuthorizationJson);
if (deserializedFakeAuthorization != null)
{
client.Authorization = deserializedFakeAuthorization;
Console.WriteLine("Deserialized Fake Authorization:");
Console.WriteLine($"Created (UTC): {deserializedFakeAuthorization.Created}");
Console.WriteLine($"Access Scope: {deserializedFakeAuthorization.AccessScope.DisplayName}");
Console.WriteLine($"Refresh Possible: {deserializedFakeAuthorization.IsRefreshPossible}");
Console.WriteLine($"Valid: {deserializedFakeAuthorization.IsValid}");
Console.WriteLine($"Token Type: {deserializedFakeAuthorization.TokenType.DisplayName}");
Console.WriteLine($"Access Token: {deserializedFakeAuthorization.AccessToken}");
Console.WriteLine($"Refresh Token: {deserializedFakeAuthorization.RefreshToken}");
Console.WriteLine($"Token Expired: {deserializedFakeAuthorization.IsExpired}");
Console.WriteLine($"Expires in {deserializedFakeAuthorization.ExpiresIn / 3600 / 24} days");
}
}
Console.ReadLine();
}
}
}
|
Update assembly version to 1.2 to match the version set in Microsoft.Web.Xdt package. | using System.Reflection;
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
|
Add support on fetching Uri with local filepath like "file:///C:/website/style.css" | using System;
using System.IO;
using System.Net;
using System.Text;
namespace PreMailer.Net.Downloaders
{
public class WebDownloader : IWebDownloader
{
private static IWebDownloader _sharedDownloader;
public static IWebDownloader SharedDownloader
{
get
{
if (_sharedDownloader == null)
{
_sharedDownloader = new WebDownloader();
}
return _sharedDownloader;
}
set
{
_sharedDownloader = value;
}
}
public string DownloadString(Uri uri)
{
var request = WebRequest.Create(uri);
using (var response = (HttpWebResponse)request.GetResponse())
{
var charset = response.CharacterSet;
var encoding = Encoding.GetEncoding(charset);
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream, encoding))
{
return reader.ReadToEnd();
}
}
}
}
}
| using System;
using System.IO;
using System.Net;
using System.Text;
namespace PreMailer.Net.Downloaders
{
public class WebDownloader : IWebDownloader
{
private static IWebDownloader _sharedDownloader;
public static IWebDownloader SharedDownloader
{
get
{
if (_sharedDownloader == null)
{
_sharedDownloader = new WebDownloader();
}
return _sharedDownloader;
}
set
{
_sharedDownloader = value;
}
}
public string DownloadString(Uri uri)
{
var request = WebRequest.Create(uri);
using (var response = request.GetResponse())
{
switch (response)
{
case HttpWebResponse httpWebResponse:
{
var charset = httpWebResponse.CharacterSet;
var encoding = Encoding.GetEncoding(charset);
using (var stream = httpWebResponse.GetResponseStream())
using (var reader = new StreamReader(stream, encoding))
{
return reader.ReadToEnd();
}
}
case FileWebResponse fileWebResponse:
{
using (var stream = fileWebResponse.GetResponseStream())
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
default:
throw new NotSupportedException($"The Uri type is giving a response in unsupported type '{response.GetType()}'.");
}
}
}
}
}
|
Improve test / code coverage of System.ComponentModel | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.ComponentModel;
using Xunit;
namespace Test
{
public class ComponentModelTests
{
[Fact]
public static void TestComponentModelBasic()
{
// dummy tests to make sure the System.ComponentModel library loaded successfully
#pragma warning disable 0219
IRevertibleChangeTracking iRevertibleChangeTracking = null;
IChangeTracking iChangeTracking = iRevertibleChangeTracking;
Assert.Null(iChangeTracking);
IEditableObject iEditableObject = null;
CancelEventArgs cancelEventArgs = new CancelEventArgs();
Assert.NotNull(cancelEventArgs);
IServiceProvider iServiceProvider = null;
Assert.Null(iServiceProvider);
#pragma warning restore 0219
}
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.ComponentModel;
using Xunit;
namespace Test
{
public class ComponentModelTests
{
[Fact]
public static void TestComponentModelBasic()
{
// dummy tests to make sure the System.ComponentModel library loaded successfully
#pragma warning disable 0219
IRevertibleChangeTracking iRevertibleChangeTracking = null;
IChangeTracking iChangeTracking = iRevertibleChangeTracking;
Assert.Null(iChangeTracking);
IEditableObject iEditableObject = null;
CancelEventArgs cancelEventArgs = new CancelEventArgs();
Assert.NotNull(cancelEventArgs);
IServiceProvider iServiceProvider = null;
Assert.Null(iServiceProvider);
#pragma warning restore 0219
}
[Fact]
public static void TestCancelEventArgs()
{
// Verify the ctor parameter is passed through to Cancel
Assert.False(new CancelEventArgs().Cancel);
Assert.False(new CancelEventArgs(false).Cancel);
Assert.True(new CancelEventArgs(true).Cancel);
// Verify updates to Cancel stick
var ce = new CancelEventArgs();
for (int i = 0; i < 2; i++)
{
ce.Cancel = false;
Assert.False(ce.Cancel);
ce.Cancel = true;
Assert.True(ce.Cancel);
}
}
}
}
|
Move namespace Microsoft.AspNetCore.Routing -> Microsoft.AspNetCore.Builder | using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using MagicOnion.Server.Glue;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Routing
{
public static class MagicOnionEndpointRouteBuilderExtensions
{
public static GrpcServiceEndpointConventionBuilder MapMagicOnionService(this IEndpointRouteBuilder builder)
{
var descriptor = builder.ServiceProvider.GetRequiredService<MagicOnionServiceDefinitionGlueDescriptor>();
// builder.MapGrpcService<GlueServiceType>();
var mapGrpcServiceMethod = typeof(GrpcEndpointRouteBuilderExtensions)
.GetMethod(nameof(GrpcEndpointRouteBuilderExtensions.MapGrpcService), BindingFlags.Static | BindingFlags.Public)!
.MakeGenericMethod(descriptor.GlueServiceType);
return (GrpcServiceEndpointConventionBuilder)mapGrpcServiceMethod.Invoke(null, new[] { builder })!;
}
}
}
| using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using MagicOnion.Server.Glue;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Builder
{
public static class MagicOnionEndpointRouteBuilderExtensions
{
public static GrpcServiceEndpointConventionBuilder MapMagicOnionService(this IEndpointRouteBuilder builder)
{
var descriptor = builder.ServiceProvider.GetRequiredService<MagicOnionServiceDefinitionGlueDescriptor>();
// builder.MapGrpcService<GlueServiceType>();
var mapGrpcServiceMethod = typeof(GrpcEndpointRouteBuilderExtensions)
.GetMethod(nameof(GrpcEndpointRouteBuilderExtensions.MapGrpcService), BindingFlags.Static | BindingFlags.Public)!
.MakeGenericMethod(descriptor.GlueServiceType);
return (GrpcServiceEndpointConventionBuilder)mapGrpcServiceMethod.Invoke(null, new[] { builder })!;
}
}
}
|
Fix iOS nullref on orientation change | // 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 CoreGraphics;
using osu.Framework.Platform;
using UIKit;
namespace osu.Framework.iOS
{
internal class GameViewController : UIViewController
{
private readonly IOSGameView view;
private readonly GameHost host;
public override bool PrefersStatusBarHidden() => true;
public override UIRectEdge PreferredScreenEdgesDeferringSystemGestures => UIRectEdge.All;
public GameViewController(IOSGameView view, GameHost host)
{
View = view;
this.host = host;
}
public override void DidReceiveMemoryWarning()
{
base.DidReceiveMemoryWarning();
host.Collect();
}
public override void ViewWillTransitionToSize(CGSize toSize, IUIViewControllerTransitionCoordinator coordinator)
{
coordinator.AnimateAlongsideTransition(_ => { }, _ => UIView.AnimationsEnabled = true);
UIView.AnimationsEnabled = false;
base.ViewWillTransitionToSize(toSize, coordinator);
view.RequestResizeFrameBuffer();
}
}
}
| // 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 CoreGraphics;
using osu.Framework.Platform;
using UIKit;
namespace osu.Framework.iOS
{
internal class GameViewController : UIViewController
{
private readonly IOSGameView gameView;
private readonly GameHost gameHost;
public override bool PrefersStatusBarHidden() => true;
public override UIRectEdge PreferredScreenEdgesDeferringSystemGestures => UIRectEdge.All;
public GameViewController(IOSGameView view, GameHost host)
{
View = view;
gameView = view;
gameHost = host;
}
public override void DidReceiveMemoryWarning()
{
base.DidReceiveMemoryWarning();
gameHost.Collect();
}
public override void ViewWillTransitionToSize(CGSize toSize, IUIViewControllerTransitionCoordinator coordinator)
{
coordinator.AnimateAlongsideTransition(_ => { }, _ => UIView.AnimationsEnabled = true);
UIView.AnimationsEnabled = false;
base.ViewWillTransitionToSize(toSize, coordinator);
gameView.RequestResizeFrameBuffer();
}
}
}
|
Set MasterReqRuntime to discover types | using System;
using System.Collections.Generic;
using Microsoft.Framework.DependencyInjection;
namespace Glimpse.Web
{
public class MasterRequestRuntime
{
private readonly IEnumerable<IRequestRuntime> _requestRuntimes;
public MasterRequestRuntime(IServiceProvider serviceProvider)
{
_requestRuntimes = serviceProvider.GetService<IDiscoverableCollection<IRequestRuntime>>();
}
public void Begin(IContext newContext)
{
}
public void End(IContext newContext)
{
}
}
} | using System;
using System.Collections.Generic;
using Microsoft.Framework.DependencyInjection;
namespace Glimpse.Web
{
public class MasterRequestRuntime
{
private readonly IDiscoverableCollection<IRequestRuntime> _requestRuntimes;
public MasterRequestRuntime(IServiceProvider serviceProvider)
{
_requestRuntimes = serviceProvider.GetService<IDiscoverableCollection<IRequestRuntime>>();
_requestRuntimes.Discover();
}
public void Begin(IContext newContext)
{
}
public void End(IContext newContext)
{
}
}
} |
Fix AmbiguousMatchException in multiple indexers, make getters and setters invocation consistent | using System.Globalization;
using System.Reflection;
using Jint.Native;
namespace Jint.Runtime.Descriptors.Specialized
{
public sealed class IndexDescriptor : PropertyDescriptor
{
private readonly Engine _engine;
private readonly object _key;
private readonly object _item;
private readonly MethodInfo _getter;
private readonly MethodInfo _setter;
public IndexDescriptor(Engine engine, string key, object item)
{
_engine = engine;
_item = item;
_getter = item.GetType().GetMethod("get_Item", BindingFlags.Instance | BindingFlags.Public);
_setter = item.GetType().GetMethod("set_Item", BindingFlags.Instance | BindingFlags.Public);
_key = _engine.Options.GetTypeConverter().Convert(key, _getter.GetParameters()[0].ParameterType, CultureInfo.InvariantCulture);
Writable = true;
}
public override JsValue? Value
{
get
{
object[] parameters = { _key };
return JsValue.FromObject(_engine, _getter.Invoke(_item, parameters));
}
set
{
var defaultValue = _item.GetType().IsValueType ? System.Activator.CreateInstance(_item.GetType()) : null;
object[] parameters = { _key, value.HasValue ? value.Value.ToObject() : null };
_setter.Invoke(_item, parameters);
}
}
}
} | using System;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Jint.Native;
namespace Jint.Runtime.Descriptors.Specialized
{
public sealed class IndexDescriptor : PropertyDescriptor
{
private readonly Engine _engine;
private readonly object _key;
private readonly object _item;
private readonly PropertyInfo _indexer;
public IndexDescriptor(Engine engine, string key, object item)
{
_engine = engine;
_item = item;
// get all instance indexers with exactly 1 argument
var indexers = item
.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
.Where(x => x.GetIndexParameters().Length == 1);
// try to find first indexer having either public getter or setter with matching argument type
foreach (var indexer in indexers)
{
if (indexer.GetGetMethod() != null || indexer.GetSetMethod() != null)
{
var paramType = indexer.GetIndexParameters()[0].ParameterType;
try
{
_key = _engine.Options.GetTypeConverter().Convert(key, paramType, CultureInfo.InvariantCulture);
_indexer = indexer;
break;
}
catch { }
}
}
// throw if no indexer found
if(_indexer == null)
throw new InvalidOperationException("No matching indexer found.");
Writable = true;
}
public override JsValue? Value
{
get
{
var getter = _indexer.GetGetMethod();
if(getter == null)
throw new InvalidOperationException("Indexer has no public getter.");
object[] parameters = { _key };
return JsValue.FromObject(_engine, getter.Invoke(_item, parameters));
}
set
{
var setter = _indexer.GetSetMethod();
if (setter == null)
throw new InvalidOperationException("Indexer has no public setter.");
object[] parameters = { _key, value.HasValue ? value.Value.ToObject() : null };
setter.Invoke(_item, parameters);
}
}
}
} |
Fix - Notifica cancellazione utente | using Microsoft.AspNetCore.SignalR;
using SO115App.Models.Servizi.CQRS.Commands.GestioneUtenti.CancellazioneUtente;
using SO115App.Models.Servizi.Infrastruttura.GestioneUtenti.GetUtenti;
using SO115App.Models.Servizi.Infrastruttura.Notification.GestioneUtenti;
using System;
using System.Threading.Tasks;
namespace SO115App.SignalR.Sender.GestioneUtenti
{
public class NotificationDeleteUtente : INotifyDeleteUtente
{
private readonly IHubContext<NotificationHub> _notificationHubContext;
private readonly IGetUtenteByCF _getUtenteByCF;
public NotificationDeleteUtente(IHubContext<NotificationHub> notificationHubContext, IGetUtenteByCF getUtenteByCF)
{
_notificationHubContext = notificationHubContext;
_getUtenteByCF = getUtenteByCF;
}
public async Task Notify(DeleteUtenteCommand command)
{
await _notificationHubContext.Clients.Group(command.CodiceSede).SendAsync("NotifyRefreshUtenti", true);
await _notificationHubContext.Clients.Group(command.UtenteRimosso.Sede.Codice).SendAsync("NotifyRefreshUtenti", true);
await _notificationHubContext.Clients.All.SendAsync("NotifyDeleteUtente", command.UtenteRimosso.Id);
}
}
}
| using Microsoft.AspNetCore.SignalR;
using SO115App.Models.Servizi.CQRS.Commands.GestioneUtenti.CancellazioneUtente;
using SO115App.Models.Servizi.Infrastruttura.GestioneUtenti.GetUtenti;
using SO115App.Models.Servizi.Infrastruttura.Notification.GestioneUtenti;
using System;
using System.Threading.Tasks;
namespace SO115App.SignalR.Sender.GestioneUtenti
{
public class NotificationDeleteUtente : INotifyDeleteUtente
{
private readonly IHubContext<NotificationHub> _notificationHubContext;
private readonly IGetUtenteByCF _getUtenteByCF;
public NotificationDeleteUtente(IHubContext<NotificationHub> notificationHubContext, IGetUtenteByCF getUtenteByCF)
{
_notificationHubContext = notificationHubContext;
_getUtenteByCF = getUtenteByCF;
}
public async Task Notify(DeleteUtenteCommand command)
{
var utente = _getUtenteByCF.Get(command.CodFiscale);
await _notificationHubContext.Clients.Group(utente.Sede.Codice).SendAsync("NotifyRefreshUtenti", true);
await _notificationHubContext.Clients.Group(command.UtenteRimosso.Sede.Codice).SendAsync("NotifyRefreshUtenti", true);
await _notificationHubContext.Clients.All.SendAsync("NotifyDeleteUtente", command.UtenteRimosso.Id);
}
}
}
|
Fix slider velocity not being applied. | //Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
//Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Collections.Generic;
using OpenTK.Graphics;
using osu.Game.Beatmaps.Timing;
using osu.Game.Database;
using osu.Game.Modes.Objects;
namespace osu.Game.Beatmaps
{
public class Beatmap
{
public BeatmapInfo BeatmapInfo { get; set; }
public BeatmapMetadata Metadata => BeatmapInfo?.Metadata ?? BeatmapInfo?.BeatmapSet?.Metadata;
public List<HitObject> HitObjects { get; set; }
public List<ControlPoint> ControlPoints { get; set; }
public List<Color4> ComboColors { get; set; }
public double BeatLengthAt(double time, bool applyMultipliers = false)
{
int point = 0;
int samplePoint = 0;
for (int i = 0; i < ControlPoints.Count; i++)
if (ControlPoints[i].Time <= time)
{
if (ControlPoints[i].TimingChange)
point = i;
else
samplePoint = i;
}
double mult = 1;
if (applyMultipliers && samplePoint > point && ControlPoints[samplePoint].BeatLength < 0)
mult = ControlPoints[samplePoint].VelocityAdjustment;
return ControlPoints[point].BeatLength * mult;
}
}
}
| //Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
//Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Collections.Generic;
using OpenTK.Graphics;
using osu.Game.Beatmaps.Timing;
using osu.Game.Database;
using osu.Game.Modes.Objects;
namespace osu.Game.Beatmaps
{
public class Beatmap
{
public BeatmapInfo BeatmapInfo { get; set; }
public BeatmapMetadata Metadata => BeatmapInfo?.Metadata ?? BeatmapInfo?.BeatmapSet?.Metadata;
public List<HitObject> HitObjects { get; set; }
public List<ControlPoint> ControlPoints { get; set; }
public List<Color4> ComboColors { get; set; }
public double BeatLengthAt(double time, bool applyMultipliers = false)
{
int point = 0;
int samplePoint = 0;
for (int i = 0; i < ControlPoints.Count; i++)
if (ControlPoints[i].Time <= time)
{
if (ControlPoints[i].TimingChange)
point = i;
else
samplePoint = i;
}
double mult = 1;
if (applyMultipliers && samplePoint > point)
mult = ControlPoints[samplePoint].VelocityAdjustment;
return ControlPoints[point].BeatLength * mult;
}
}
}
|
Check if logger is null and throw | using Serilog.Events;
namespace Serilog
{
/// <summary>
/// Extension method 'ForContext' for ILogger.
/// </summary>
public static class ForContextExtension
{
/// <summary>
/// Create a logger that enriches log events with the specified property based on log event level.
/// </summary>
/// <typeparam name="TValue"> The type of the property value. </typeparam>
/// <param name="logger">The logger</param>
/// <param name="level">The log event level used to determine if log is enriched with property.</param>
/// <param name="propertyName">The name of the property. Must be non-empty.</param>
/// <param name="value">The property value.</param>
/// <param name="destructureObjects">If true, the value will be serialized as a structured
/// object if possible; if false, the object will be recorded as a scalar or simple array.</param>
/// <returns>A logger that will enrich log events as specified.</returns>
/// <returns></returns>
public static ILogger ForContext<TValue>(
this ILogger logger,
LogEventLevel level,
string propertyName,
TValue value,
bool destructureObjects = false)
{
return !logger.IsEnabled(level)
? logger
: logger.ForContext(propertyName, value, destructureObjects);
}
}
}
| using System;
using Serilog.Events;
namespace Serilog
{
/// <summary>
/// Extension method 'ForContext' for ILogger.
/// </summary>
public static class ForContextExtension
{
/// <summary>
/// Create a logger that enriches log events with the specified property based on log event level.
/// </summary>
/// <typeparam name="TValue"> The type of the property value. </typeparam>
/// <param name="logger">The logger</param>
/// <param name="level">The log event level used to determine if log is enriched with property.</param>
/// <param name="propertyName">The name of the property. Must be non-empty.</param>
/// <param name="value">The property value.</param>
/// <param name="destructureObjects">If true, the value will be serialized as a structured
/// object if possible; if false, the object will be recorded as a scalar or simple array.</param>
/// <returns>A logger that will enrich log events as specified.</returns>
/// <returns></returns>
public static ILogger ForContext<TValue>(
this ILogger logger,
LogEventLevel level,
string propertyName,
TValue value,
bool destructureObjects = false)
{
if (logger == null)
throw new ArgumentNullException(nameof(logger));
return !logger.IsEnabled(level)
? logger
: logger.ForContext(propertyName, value, destructureObjects);
}
}
}
|
Increase the maximum time we wait for long running tests from 5 to 10. | using System;
using System.Threading;
using NUnit.Framework;
namespace JustSaying.TestingFramework
{
public static class Patiently
{
public static void VerifyExpectation(Action expression)
{
VerifyExpectation(expression, 5.Seconds());
}
public static void VerifyExpectation(Action expression, TimeSpan timeout)
{
bool hasTimedOut;
var started = DateTime.Now;
do
{
try
{
expression.Invoke();
return;
}
catch { }
hasTimedOut = timeout < DateTime.Now - started;
Thread.Sleep(TimeSpan.FromMilliseconds(50));
Console.WriteLine("Waiting for {0} ms - Still Checking.", (DateTime.Now - started).TotalMilliseconds);
} while (!hasTimedOut);
expression.Invoke();
}
public static void AssertThat(Func<bool> func)
{
AssertThat(func, 5.Seconds());
}
public static void AssertThat(Func<bool> func, TimeSpan timeout)
{
bool result;
bool hasTimedOut;
var started = DateTime.Now;
do
{
result = func.Invoke();
hasTimedOut = timeout < DateTime.Now - started;
Thread.Sleep(TimeSpan.FromMilliseconds(50));
Console.WriteLine("Waiting for {0} ms - Still Checking.", (DateTime.Now - started).TotalMilliseconds);
} while (!result && !hasTimedOut);
Assert.True(result);
}
}
public static class Extensions
{
public static TimeSpan Seconds(this int seconds)
{
return TimeSpan.FromSeconds(seconds);
}
}
}
| using System;
using System.Threading;
using NUnit.Framework;
namespace JustSaying.TestingFramework
{
public static class Patiently
{
public static void VerifyExpectation(Action expression)
{
VerifyExpectation(expression, 5.Seconds());
}
public static void VerifyExpectation(Action expression, TimeSpan timeout)
{
bool hasTimedOut;
var started = DateTime.Now;
do
{
try
{
expression.Invoke();
return;
}
catch { }
hasTimedOut = timeout < DateTime.Now - started;
Thread.Sleep(TimeSpan.FromMilliseconds(50));
Console.WriteLine("Waiting for {0} ms - Still Checking.", (DateTime.Now - started).TotalMilliseconds);
} while (!hasTimedOut);
expression.Invoke();
}
public static void AssertThat(Func<bool> func)
{
AssertThat(func, 10.Seconds());
}
public static void AssertThat(Func<bool> func, TimeSpan timeout)
{
bool result;
bool hasTimedOut;
var started = DateTime.Now;
do
{
result = func.Invoke();
hasTimedOut = timeout < DateTime.Now - started;
Thread.Sleep(TimeSpan.FromMilliseconds(50));
Console.WriteLine("Waiting for {0} ms - Still Checking.", (DateTime.Now - started).TotalMilliseconds);
} while (!result && !hasTimedOut);
Assert.True(result);
}
}
public static class Extensions
{
public static TimeSpan Seconds(this int seconds)
{
return TimeSpan.FromSeconds(seconds);
}
}
}
|
Remove cursor color type for now | namespace BigEgg.Tools.PowerMode.Settings
{
public enum ParticlesColorType
{
Cursor,
Random,
Fixed
}
}
| namespace BigEgg.Tools.PowerMode.Settings
{
public enum ParticlesColorType
{
Random,
Fixed
}
}
|
Add method to unescape string. | using dotless.Infrastructure;
namespace dotless.Tree
{
public class Quoted : Node
{
public string Value { get; set; }
public string Contents { get; set; }
public Quoted(string value, string contents)
{
Value = value;
Contents = contents;
}
public override string ToCSS(Env env)
{
return Value;
}
}
} | using System.Text.RegularExpressions;
using dotless.Infrastructure;
namespace dotless.Tree
{
public class Quoted : Node
{
public string Value { get; set; }
public string Contents { get; set; }
public Quoted(string value, string contents)
{
Value = value;
Contents = contents;
}
public Quoted(string value)
: this(value, value)
{
}
public override string ToCSS(Env env)
{
return Value;
}
private readonly Regex _unescape = new Regex(@"(^|[^\\])\\(.)");
public string UnescapeContents()
{
return _unescape.Replace(Contents, @"$1$2");
}
}
} |
Revert visibility change and add null check | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.IO;
#nullable enable
namespace osu.Framework.Audio.Callbacks
{
/// <summary>
/// Implementation of <see cref="IFileProcedures"/> that supports reading from a <see cref="Stream"/>.
/// </summary>
internal class DataStreamFileProcedures : IFileProcedures
{
private readonly Stream dataStream;
public DataStreamFileProcedures(Stream data)
{
dataStream = data;
}
public void Close(IntPtr user)
{
}
public long Length(IntPtr user)
{
if (!dataStream.CanSeek) return 0;
try
{
return dataStream.Length;
}
catch
{
return 0;
}
}
public unsafe int Read(IntPtr buffer, int length, IntPtr user)
{
if (!dataStream.CanRead) return 0;
try
{
return dataStream.Read(new Span<byte>((void*)buffer, length));
}
catch
{
return 0;
}
}
public bool Seek(long offset, IntPtr user)
{
if (!dataStream.CanSeek) return false;
try
{
return dataStream.Seek(offset, SeekOrigin.Begin) == offset;
}
catch
{
return false;
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.IO;
#nullable enable
namespace osu.Framework.Audio.Callbacks
{
/// <summary>
/// Implementation of <see cref="IFileProcedures"/> that supports reading from a <see cref="Stream"/>.
/// </summary>
public class DataStreamFileProcedures : IFileProcedures
{
private readonly Stream dataStream;
public DataStreamFileProcedures(Stream data)
{
dataStream = data ?? throw new ArgumentNullException(nameof(data));
}
public void Close(IntPtr user)
{
}
public long Length(IntPtr user)
{
if (!dataStream.CanSeek) return 0;
try
{
return dataStream.Length;
}
catch
{
return 0;
}
}
public unsafe int Read(IntPtr buffer, int length, IntPtr user)
{
if (!dataStream.CanRead) return 0;
try
{
return dataStream.Read(new Span<byte>((void*)buffer, length));
}
catch
{
return 0;
}
}
public bool Seek(long offset, IntPtr user)
{
if (!dataStream.CanSeek) return false;
try
{
return dataStream.Seek(offset, SeekOrigin.Begin) == offset;
}
catch
{
return false;
}
}
}
}
|
Use notification instead of debug to allow testing outside of editor | using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class LoadTest : MonoBehaviour
{
public void SignInButtonClicked()
{
GameJolt.UI.Manager.Instance.ShowSignIn((bool success) => {
if (success)
{
Debug.Log("Logged In");
}
else
{
Debug.Log("Dismissed");
}
});
}
public void IsSignedInButtonClicked() {
bool isSignedIn = GameJolt.API.Manager.Instance.CurrentUser != null;
if (isSignedIn) {
Debug.Log("Signed In");
}
else {
Debug.Log("Not Signed In");
}
}
public void LoadSceneButtonClicked(string sceneName) {
Debug.Log("Loading Scene " + sceneName);
#if UNITY_5_0 || UNITY_5_1 || UNITY_5_2
Application.LoadLevel(sceneName);
#else
UnityEngine.SceneManagement.SceneManager.LoadScene(sceneName);
#endif
}
}
| using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class LoadTest : MonoBehaviour
{
public void SignInButtonClicked()
{
GameJolt.UI.Manager.Instance.ShowSignIn((bool success) => {
if (success)
{
GameJolt.UI.Manager.Instance.QueueNotification("Welcome");
}
else
{
GameJolt.UI.Manager.Instance.QueueNotification("Closed the window :(");
}
});
}
public void IsSignedInButtonClicked() {
if (GameJolt.API.Manager.Instance.CurrentUser != null) {
GameJolt.UI.Manager.Instance.QueueNotification(
"Signed in as " + GameJolt.API.Manager.Instance.CurrentUser.Name);
}
else {
GameJolt.UI.Manager.Instance.QueueNotification("Not Signed In :(");
}
}
public void LoadSceneButtonClicked(string sceneName) {
Debug.Log("Loading Scene " + sceneName);
#if UNITY_5_0 || UNITY_5_1 || UNITY_5_2
Application.LoadLevel(sceneName);
#else
UnityEngine.SceneManagement.SceneManager.LoadScene(sceneName);
#endif
}
}
|
Add comments for none generic generator | namespace GeneratorAPI {
/// <summary>
/// Represents a generic generator which can generate any ammount of elements.
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IGenerator<out T> : IGenerator {
/// <summary>
/// Generate next element.
/// </summary>
new T Generate();
}
public interface IGenerator {
object Generate();
}
} | namespace GeneratorAPI {
/// <summary>
/// Represents a generic generator which can generate any ammount of elements.
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IGenerator<out T> : IGenerator {
/// <summary>
/// Generate next element.
/// </summary>
new T Generate();
}
/// <summary>
/// Represent a generator which can generate any ammount of elements.
/// </summary>
public interface IGenerator {
/// <summary>
/// Generate next element.
/// </summary>
object Generate();
}
} |
Set velocity and forward vector when resetting ball position | using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class Ball : NetworkBehaviour {
private Rigidbody rigidBody = null;
private Vector3 startingPosition = Vector3.zero;
float minimumVelocity = 5;
float startingMinVelocity = -10;
float startingMaxVelocity = 10;
// Use this for initialization
void Start () {
if (!isServer) return;
rigidBody = GetComponent<Rigidbody>();
startingPosition = transform.position;
}
private void FixedUpdate()
{
if (!isServer) return;
if (rigidBody.velocity.magnitude < minimumVelocity)
{
rigidBody.velocity = rigidBody.velocity * 1.25f;
}
}
public void ResetPosition()
{
if (!isServer) return;
transform.position = startingPosition;
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class Ball : NetworkBehaviour {
private Rigidbody rigidBody = null;
private Vector3 startingPosition = Vector3.zero;
float minimumVelocity = 5;
float startingMinVelocity = -10;
float startingMaxVelocity = 10;
// Use this for initialization
void Start () {
if (!isServer) return;
rigidBody = GetComponent<Rigidbody>();
startingPosition = transform.position;
}
private void FixedUpdate()
{
if (!isServer) return;
if (rigidBody.velocity.magnitude < minimumVelocity)
{
rigidBody.velocity = rigidBody.velocity * 1.25f;
}
}
public void ResetPosition()
{
if (!isServer) return;
rigidBody.velocity = Vector3.zero;
transform.forward = new Vector3(1, 0, 1);
transform.position = startingPosition;
}
}
|
Fix the wrong conditional statement. | using NuGet.OutputWindowConsole;
using NuGetConsole;
namespace NuGet.Dialog.PackageManagerUI {
internal class SmartOutputConsoleProvider : IOutputConsoleProvider {
private readonly IOutputConsoleProvider _baseProvider;
private bool _isFirstTime = true;
public SmartOutputConsoleProvider(IOutputConsoleProvider baseProvider) {
_baseProvider = baseProvider;
}
public IConsole CreateOutputConsole(bool requirePowerShellHost) {
IConsole console = _baseProvider.CreateOutputConsole(requirePowerShellHost);
if (_isFirstTime) {
// the first time the console is accessed after dialog is opened, we clear the console.
console.Clear();
}
else {
_isFirstTime = false;
}
return console;
}
}
} | using NuGet.OutputWindowConsole;
using NuGetConsole;
namespace NuGet.Dialog.PackageManagerUI {
internal class SmartOutputConsoleProvider : IOutputConsoleProvider {
private readonly IOutputConsoleProvider _baseProvider;
private bool _isFirstTime = true;
public SmartOutputConsoleProvider(IOutputConsoleProvider baseProvider) {
_baseProvider = baseProvider;
}
public IConsole CreateOutputConsole(bool requirePowerShellHost) {
IConsole console = _baseProvider.CreateOutputConsole(requirePowerShellHost);
if (_isFirstTime) {
// the first time the console is accessed after dialog is opened, we clear the console.
console.Clear();
_isFirstTime = false;
}
return console;
}
}
} |
Update b/c of new dockpanel | namespace SuperPutty
{
partial class ToolWindow
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ToolWindow));
this.SuspendLayout();
//
// ToolWindow
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 264);
this.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "ToolWindow";
this.Text = "ToolWindow";
this.ResumeLayout(false);
}
#endregion
}
} | namespace SuperPutty
{
partial class ToolWindow
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ToolWindow));
this.SuspendLayout();
//
// ToolWindow
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(279, 253);
this.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "ToolWindow";
this.Text = "ToolWindow";
this.ResumeLayout(false);
}
#endregion
}
} |
Set the document language to English | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/themes/base/css", "~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
@RenderBody()
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</body>
</html>
| <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/themes/base/css", "~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
@RenderBody()
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</body>
</html>
|
Update website URI to root domain | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
public class MattBobke : IAmACommunityMember, IFilterMyBlogPosts
{
public string FirstName => "Matt";
public string LastName => "Bobke";
public string ShortBioOrTagLine => "Desktop Support Specialist with admninistrative tendencies excited about PowerShell and automation.";
public string StateOrRegion => "California, United States";
public string GravatarHash => "6f38a96cd055f95eacd1d3d102e309fa";
public string EmailAddress => "matt@mattbobke.com";
public string TwitterHandle => "MattBobke";
public string GitHubHandle => "mcbobke";
public GeoPosition Position => new GeoPosition(33.6469, -117.6861);
public Uri WebSite => new Uri("https://blog.mattbobke.com");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://blog.mattbobke.com/feed/atom/"); } }
public bool Filter(SyndicationItem item)
{
// This filters out only the posts that have the "PowerShell" category
return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell"));
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
public class MattBobke : IAmACommunityMember, IFilterMyBlogPosts
{
public string FirstName => "Matt";
public string LastName => "Bobke";
public string ShortBioOrTagLine => "Desktop Support Specialist with admninistrative tendencies excited about PowerShell and automation.";
public string StateOrRegion => "California, United States";
public string GravatarHash => "6f38a96cd055f95eacd1d3d102e309fa";
public string EmailAddress => "matt@mattbobke.com";
public string TwitterHandle => "MattBobke";
public string GitHubHandle => "mcbobke";
public GeoPosition Position => new GeoPosition(33.6469, -117.6861);
public Uri WebSite => new Uri("https://mattbobke.com");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://mattbobke.com/feed/atom/"); } }
public bool Filter(SyndicationItem item)
{
// This filters out only the posts that have the "PowerShell" category
return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell"));
}
} |
Remove Category link in menu | <li>@Html.ActionLink("Courses", "Index", "Race")</li>
<li>@Html.ActionLink("Catégories", "Index", "Category")</li>
@if (User.IsInRole("Administrateur"))
{
<li>@Html.ActionLink("Liste des points", "Index", "Point")</li>
<li>@Html.ActionLink("Importer les résultats", "Import", "Resultat")</li>
}
@if (User.IsInRole("Administrateur"))
{
<li>@Html.ActionLink("Type de Point", "Index", "TypePoint")</li>
}
@if (Request.IsAuthenticated) {
<li>@Html.ActionLink("Mes Inscriptions", "Index", "Participant")</li>
}
| <li>@Html.ActionLink("Courses", "Index", "Race")</li>
@if (User.IsInRole("Administrateur"))
{
<li>@Html.ActionLink("Liste des points", "Index", "Point")</li>
<li>@Html.ActionLink("Importer les résultats", "Import", "Resultat")</li>
}
@if (User.IsInRole("Administrateur"))
{
<li>@Html.ActionLink("Type de Point", "Index", "TypePoint")</li>
}
@if (Request.IsAuthenticated) {
<li>@Html.ActionLink("Mes Inscriptions", "Index", "Participant")</li>
}
|
Disable ConsoleLogAdapter in test output | using System;
using GitHub.Unity;
using NUnit.Framework;
namespace IntegrationTests
{
[SetUpFixture]
public class SetUpFixture
{
[SetUp]
public void Setup()
{
Logging.TracingEnabled = true;
Logging.LogAdapter = new MultipleLogAdapter(
new FileLogAdapter($"..\\{DateTime.UtcNow.ToString("yyyyMMddHHmmss")}-integration-tests.log")
, new ConsoleLogAdapter()
);
}
}
}
| using System;
using GitHub.Unity;
using NUnit.Framework;
namespace IntegrationTests
{
[SetUpFixture]
public class SetUpFixture
{
[SetUp]
public void Setup()
{
Logging.TracingEnabled = true;
Logging.LogAdapter = new MultipleLogAdapter(
new FileLogAdapter($"..\\{DateTime.UtcNow.ToString("yyyyMMddHHmmss")}-integration-tests.log")
//, new ConsoleLogAdapter()
);
}
}
}
|
Move hardcoded values into static fields | using System;
using System.Collections.Generic;
using System.Linq;
namespace Silverpop.Core.Performance
{
internal class Program
{
private static void Main(string[] args)
{
var tagValue = new string(
Enumerable.Repeat("ABC", 1000)
.SelectMany(x => x)
.ToArray());
var personalizationTags = new TestPersonalizationTags()
{
TagA = tagValue,
TagB = tagValue,
TagC = tagValue,
TagD = tagValue,
TagE = tagValue,
TagF = tagValue,
TagG = tagValue,
TagH = tagValue,
TagI = tagValue,
TagJ = tagValue,
TagK = tagValue,
TagL = tagValue,
TagM = tagValue,
TagN = tagValue,
TagO = tagValue
};
var numberOfTags = personalizationTags.GetType().GetProperties().Count();
Console.WriteLine("Testing 1 million recipients with {0} tags using batches of 5000:", numberOfTags);
new TransactMessagePerformance()
.InvokeGetRecipientBatchedMessages(1000000, 5000, personalizationTags);
Console.WriteLine("Testing 5 million recipients with {0} tags using batches of 5000:", numberOfTags);
new TransactMessagePerformance()
.InvokeGetRecipientBatchedMessages(5000000, 5000, personalizationTags);
Console.ReadLine();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
namespace Silverpop.Core.Performance
{
internal class Program
{
private static IEnumerable<int> TestRecipientCounts = new List<int>()
{
1000000,
5000000,
};
private static int TestRecipientsPerBatch = 5000;
private static void Main(string[] args)
{
var tagValue = new string(
Enumerable.Repeat("ABC", 1000)
.SelectMany(x => x)
.ToArray());
var personalizationTags = new TestPersonalizationTags()
{
TagA = tagValue,
TagB = tagValue,
TagC = tagValue,
TagD = tagValue,
TagE = tagValue,
TagF = tagValue,
TagG = tagValue,
TagH = tagValue,
TagI = tagValue,
TagJ = tagValue,
TagK = tagValue,
TagL = tagValue,
TagM = tagValue,
TagN = tagValue,
TagO = tagValue
};
var numberOfTags = personalizationTags.GetType().GetProperties().Count();
foreach (var testRecipientCount in TestRecipientCounts)
{
Console.WriteLine(
"Testing {0} recipients with {1} tags using batches of {2}:",
testRecipientCount,
numberOfTags,
TestRecipientsPerBatch);
new TransactMessagePerformance()
.InvokeGetRecipientBatchedMessages(
testRecipientCount,
TestRecipientsPerBatch,
personalizationTags);
}
Console.ReadLine();
}
}
} |
Add SupportedInterface strings to allow discovery. Including VideoApp for new directive. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Alexa.NET.Request
{
public class SupportedInterfaces
{
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Alexa.NET.Request
{
public static class SupportedInterfaces
{
public const string Display = "Display";
public const string AudioPlayer = "AudioPlayer";
public const string VideoApp = "VideoApp";
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.