Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Clarify the apparently unused generic type parameter. | namespace Cassette.Configuration
{
public interface IFileSearchModifier<T>
{
void Modify(FileSearch fileSearch);
}
} | namespace Cassette.Configuration
{
// ReSharper disable UnusedTypeParameter
// The T type parameter makes it easy to distinguish between file search modifiers for the different type of bundles
public interface IFileSearchModifier<T>
where T : Bundle
// ReSharper restore UnusedTypeParameter
{
void Modify(FileSearch fileSearch);
}
} |
Add option for allowed user roles | using System;
namespace Glimpse.Server
{
public class GlimpseServerWebOptions
{
public bool AllowRemote { get; set; }
}
} | using System;
using System.Collections.Generic;
namespace Glimpse.Server
{
public class GlimpseServerWebOptions
{
public GlimpseServerWebOptions()
{
AllowedUserRoles = new List<string>();
}
public bool AllowRemote { get; set; }
public IList<string> AllowedUserRoles { get; }
}
} |
Disable optimisations validator (in line with framework project) | // 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 BenchmarkDotNet.Running;
namespace osu.Game.Benchmarks
{
public static class Program
{
public static void Main(string[] args)
{
BenchmarkSwitcher
.FromAssembly(typeof(Program).Assembly)
.Run(args);
}
}
}
| // 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 BenchmarkDotNet.Configs;
using BenchmarkDotNet.Running;
namespace osu.Game.Benchmarks
{
public static class Program
{
public static void Main(string[] args)
{
BenchmarkSwitcher
.FromAssembly(typeof(Program).Assembly)
.Run(args, DefaultConfig.Instance.WithOption(ConfigOptions.DisableOptimizationsValidator, true));
}
}
}
|
Remove misplaced access modifier in interface specification | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Game.Beatmaps;
using osu.Game.Database;
using osu.Game.Rulesets;
using osu.Game.Users;
namespace osu.Game.Scoring
{
public interface IScoreInfo : IHasOnlineID<long>
{
User User { get; }
long TotalScore { get; }
int MaxCombo { get; }
double Accuracy { get; }
bool HasReplay { get; }
DateTimeOffset Date { get; }
double? PP { get; }
IBeatmapInfo Beatmap { get; }
IRulesetInfo Ruleset { get; }
public ScoreRank Rank { get; }
// Mods is currently missing from this interface as the `IMod` class has properties which can't be fulfilled by `APIMod`,
// but also doesn't expose `Settings`. We can consider how to implement this in the future if required.
// Statistics is also missing. This can be reconsidered once changes in serialisation have been completed.
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Game.Beatmaps;
using osu.Game.Database;
using osu.Game.Rulesets;
using osu.Game.Users;
namespace osu.Game.Scoring
{
public interface IScoreInfo : IHasOnlineID<long>
{
User User { get; }
long TotalScore { get; }
int MaxCombo { get; }
double Accuracy { get; }
bool HasReplay { get; }
DateTimeOffset Date { get; }
double? PP { get; }
IBeatmapInfo Beatmap { get; }
IRulesetInfo Ruleset { get; }
ScoreRank Rank { get; }
// Mods is currently missing from this interface as the `IMod` class has properties which can't be fulfilled by `APIMod`,
// but also doesn't expose `Settings`. We can consider how to implement this in the future if required.
// Statistics is also missing. This can be reconsidered once changes in serialisation have been completed.
}
}
|
Declare storage permission at assembly level | // 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.Runtime.CompilerServices;
// We publish our internal attributes to other sub-projects of the framework.
// Note, that we omit visual tests as they are meant to test the framework
// behavior "in the wild".
[assembly: InternalsVisibleTo("osu.Framework.Tests")]
[assembly: InternalsVisibleTo("osu.Framework.Tests.Dynamic")]
| // 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.Runtime.CompilerServices;
using Android.App;
// We publish our internal attributes to other sub-projects of the framework.
// Note, that we omit visual tests as they are meant to test the framework
// behavior "in the wild".
[assembly: InternalsVisibleTo("osu.Framework.Tests")]
[assembly: InternalsVisibleTo("osu.Framework.Tests.Dynamic")]
// https://docs.microsoft.com/en-us/answers/questions/182601/does-xamarinandroid-suppor-manifest-merging.html
[assembly: UsesPermission(Android.Manifest.Permission.ReadExternalStorage)]
|
Fix mistake in registration (method not on interface) | using System;
namespace CSF.Screenplay.Scenarios
{
/// <summary>
/// Builder service which assists in the creation of service registrations.
/// </summary>
public interface IServiceRegistryBuilder
{
/// <summary>
/// Registers a service which will be used across all scenarios within a test run.
/// </summary>
/// <param name="instance">Instance.</param>
/// <param name="name">Name.</param>
/// <typeparam name="TService">The 1st type parameter.</typeparam>
void RegisterSingleton<TService>(TService instance, string name = null) where TService : class;
/// <summary>
/// Registers a service which will be constructed afresh (using the given factory function) for
/// each scenario within a test run.
/// </summary>
/// <param name="factory">Factory.</param>
/// <param name="name">Name.</param>
/// <typeparam name="TService">The 1st type parameter.</typeparam>
void RegisterPerScenario<TService>(Func<IServiceResolver,TService> factory, string name = null) where TService : class;
}
}
| using System;
namespace CSF.Screenplay.Scenarios
{
/// <summary>
/// Builder service which assists in the creation of service registrations.
/// </summary>
public interface IServiceRegistryBuilder
{
/// <summary>
/// Registers a service which will be used across all scenarios within a test run.
/// </summary>
/// <param name="instance">Instance.</param>
/// <param name="name">Name.</param>
/// <typeparam name="TService">The 1st type parameter.</typeparam>
void RegisterSingleton<TService>(TService instance, string name = null) where TService : class;
/// <summary>
/// Registers a service which will be used across all scenarios within a test run.
/// </summary>
/// <param name="initialiser">Initialiser.</param>
/// <param name="name">Name.</param>
/// <typeparam name="TService">The 1st type parameter.</typeparam>
void RegisterSingleton<TService>(Func<TService> initialiser, string name = null) where TService : class;
/// <summary>
/// Registers a service which will be constructed afresh (using the given factory function) for
/// each scenario within a test run.
/// </summary>
/// <param name="factory">Factory.</param>
/// <param name="name">Name.</param>
/// <typeparam name="TService">The 1st type parameter.</typeparam>
void RegisterPerScenario<TService>(Func<IServiceResolver,TService> factory, string name = null) where TService : class;
}
}
|
Upgrade OData WebAPI Version to 5.6.0 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. 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 Corporation.")]
[assembly: AssemblyCopyright("© Microsoft Corporation. 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.5.2.0")] // ASPNETODATA
[assembly: AssemblyFileVersion("5.5.2.0")] // ASPNETODATA
#endif
[assembly: AssemblyProduct("Microsoft OData Web API")]
#endif | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. 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 Corporation.")]
[assembly: AssemblyCopyright("© Microsoft Corporation. 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.6.0.0")] // ASPNETODATA
[assembly: AssemblyFileVersion("5.6.0.0")] // ASPNETODATA
#endif
[assembly: AssemblyProduct("Microsoft OData Web API")]
#endif |
Fix ctor, we must use initWithCoder when loading from a storyboard | using System;
using CoreGraphics;
using Foundation;
using UIKit;
namespace TextKitDemo
{
public partial class CollectionViewCell : UICollectionViewCell
{
public CollectionViewCell (IntPtr handle) : base (handle)
{
BackgroundColor = UIColor.DarkGray;
Layer.CornerRadius = 5;
UIApplication.Notifications.ObserveContentSizeCategoryChanged (delegate {
CalculateAndSetFonts ();
});
}
public void FormatCell (DemoModel demo)
{
containerView.Layer.CornerRadius = 2;
labelView.Text = demo.Title;
textView.AttributedText = demo.GetAttributedText ();
CalculateAndSetFonts ();
}
void CalculateAndSetFonts ()
{
const float cellTitleTextScaleFactor = 0.85f;
const float cellBodyTextScaleFactor = 0.7f;
UIFont cellTitleFont = Font.GetPreferredFont (labelView.Font.FontDescriptor.TextStyle, cellTitleTextScaleFactor);
UIFont cellBodyFont = Font.GetPreferredFont (textView.Font.FontDescriptor.TextStyle, cellBodyTextScaleFactor);
labelView.Font = cellTitleFont;
textView.Font = cellBodyFont;
}
}
}
| using System;
using CoreGraphics;
using Foundation;
using UIKit;
namespace TextKitDemo
{
public partial class CollectionViewCell : UICollectionViewCell
{
public CollectionViewCell (IntPtr handle) : base (handle)
{
Initialize ();
}
[Export ("initWithCoder:")]
public CollectionViewCell (NSCoder coder) : base (coder)
{
Initialize ();
}
void Initialize ()
{
BackgroundColor = UIColor.DarkGray;
Layer.CornerRadius = 5;
UIApplication.Notifications.ObserveContentSizeCategoryChanged (delegate {
CalculateAndSetFonts ();
});
}
public void FormatCell (DemoModel demo)
{
containerView.Layer.CornerRadius = 2;
labelView.Text = demo.Title;
textView.AttributedText = demo.GetAttributedText ();
CalculateAndSetFonts ();
}
void CalculateAndSetFonts ()
{
const float cellTitleTextScaleFactor = 0.85f;
const float cellBodyTextScaleFactor = 0.7f;
UIFont cellTitleFont = Font.GetPreferredFont (labelView.Font.FontDescriptor.TextStyle, cellTitleTextScaleFactor);
UIFont cellBodyFont = Font.GetPreferredFont (textView.Font.FontDescriptor.TextStyle, cellBodyTextScaleFactor);
labelView.Font = cellTitleFont;
textView.Font = cellBodyFont;
}
}
}
|
Change to call new API | using System.Threading.Tasks;
using MediatR;
using SFA.DAS.EmployerAccounts.Configuration;
using SFA.DAS.EmployerAccounts.Interfaces;
namespace SFA.DAS.EmployerAccounts.Commands.UnsubscribeProviderEmail
{
public class UnsubscribeProviderEmailQueryHandler : AsyncRequestHandler<UnsubscribeProviderEmailQuery>
{
private readonly EmployerAccountsConfiguration _configuration;
private readonly IHttpService _httpService;
public UnsubscribeProviderEmailQueryHandler(
IHttpServiceFactory httpServiceFactory,
EmployerAccountsConfiguration configuration)
{
_configuration = configuration;
_httpService = httpServiceFactory.Create(
configuration.ProviderRelationsApi.ClientId,
configuration.ProviderRelationsApi.ClientSecret,
configuration.ProviderRelationsApi.IdentifierUri,
configuration.ProviderRelationsApi.Tenant
);
}
protected override async Task HandleCore(UnsubscribeProviderEmailQuery message)
{
var baseUrl = GetBaseUrl();
var url = $"{baseUrl}unsubscribe/{message.CorrelationId.ToString()}";
await _httpService.GetAsync(url, false);
}
private string GetBaseUrl()
{
var baseUrl = _configuration.ProviderRelationsApi.BaseUrl.EndsWith("/")
? _configuration.ProviderRelationsApi.BaseUrl
: _configuration.ProviderRelationsApi.BaseUrl + "/";
return baseUrl;
}
}
} | using System.Threading.Tasks;
using MediatR;
using SFA.DAS.EmployerAccounts.Configuration;
using SFA.DAS.EmployerAccounts.Interfaces;
namespace SFA.DAS.EmployerAccounts.Commands.UnsubscribeProviderEmail
{
public class UnsubscribeProviderEmailQueryHandler : AsyncRequestHandler<UnsubscribeProviderEmailQuery>
{
private readonly EmployerAccountsConfiguration _configuration;
private readonly IHttpService _httpService;
public UnsubscribeProviderEmailQueryHandler(
IHttpServiceFactory httpServiceFactory,
EmployerAccountsConfiguration configuration)
{
_configuration = configuration;
_httpService = httpServiceFactory.Create(
configuration.ProviderRegistrationsApi.ClientId,
configuration.ProviderRegistrationsApi.ClientSecret,
configuration.ProviderRegistrationsApi.IdentifierUri,
configuration.ProviderRegistrationsApi.Tenant
);
}
protected override async Task HandleCore(UnsubscribeProviderEmailQuery message)
{
var baseUrl = GetBaseUrl();
var url = $"{baseUrl}api/unsubscribe/{message.CorrelationId.ToString()}";
await _httpService.GetAsync(url, false);
}
private string GetBaseUrl()
{
var baseUrl = _configuration.ProviderRegistrationsApi.BaseUrl.EndsWith("/")
? _configuration.ProviderRegistrationsApi.BaseUrl
: _configuration.ProviderRegistrationsApi.BaseUrl + "/";
return baseUrl;
}
}
} |
Allow the status to be any object instead of just a string. | using System;
namespace Dotnet.Microservice.Health
{
/// <summary>
/// Represents a health check response
/// </summary>
public struct HealthResponse
{
public readonly bool IsHealthy;
public readonly string Message;
private HealthResponse(bool isHealthy, string statusMessage)
{
IsHealthy = isHealthy;
Message = statusMessage;
}
public static HealthResponse Healthy()
{
return Healthy("OK");
}
public static HealthResponse Healthy(string message)
{
return new HealthResponse(true, message);
}
public static HealthResponse Unhealthy()
{
return Unhealthy("FAILED");
}
public static HealthResponse Unhealthy(string message)
{
return new HealthResponse(false, message);
}
public static HealthResponse Unhealthy(Exception exception)
{
var message = $"EXCEPTION: {exception.GetType().Name}, {exception.Message}";
return new HealthResponse(false, message);
}
}
}
| using System;
namespace Dotnet.Microservice.Health
{
/// <summary>
/// Represents a health check response
/// </summary>
public struct HealthResponse
{
public readonly bool IsHealthy;
public readonly object Response;
private HealthResponse(bool isHealthy, object statusObject)
{
IsHealthy = isHealthy;
Response = statusObject;
}
public static HealthResponse Healthy()
{
return Healthy("OK");
}
public static HealthResponse Healthy(object response)
{
return new HealthResponse(true, response);
}
public static HealthResponse Unhealthy()
{
return Unhealthy("FAILED");
}
public static HealthResponse Unhealthy(object response)
{
return new HealthResponse(false, response);
}
public static HealthResponse Unhealthy(Exception exception)
{
var message = $"EXCEPTION: {exception.GetType().Name}, {exception.Message}";
return new HealthResponse(false, message);
}
}
}
|
Fix path to SPARQL test suite files | using System.IO;
using NUnit.Framework;
namespace BrightstarDB.InternalTests
{
internal static class TestPaths
{
public static string DataPath => Path.Combine(TestContext.CurrentContext.TestDirectory, "..\\..\\..\\BrightstarDB.Tests\\Data\\");
}
}
| using System.IO;
using NUnit.Framework;
namespace BrightstarDB.InternalTests
{
internal static class TestPaths
{
public static string DataPath => Path.Combine(TestContext.CurrentContext.TestDirectory, "..\\..\\..\\..\\BrightstarDB.Tests\\Data\\");
}
}
|
Move initialization logic to ctor | using System;
using Newtonsoft.Json;
namespace BmpListener.Bmp
{
public class BmpHeader
{
public BmpHeader(byte[] data)
{
ParseBytes(data);
}
public byte Version { get; private set; }
[JsonIgnore]
public uint Length { get; private set; }
public MessageType Type { get; private set; }
public void ParseBytes(byte[] data)
{
Version = data[0];
//if (Version != 3)
//{
// throw new Exception("invalid BMP version");
//}
Length = data.ToUInt32(1);
Type = (MessageType) data[5];
}
}
} | using System;
using Newtonsoft.Json;
using System.Linq;
using BmpListener;
namespace BmpListener.Bmp
{
public class BmpHeader
{
public BmpHeader(byte[] data)
{
Version = data.First();
//if (Version != 3)
//{
// throw new Exception("invalid BMP version");
//}
Length = data.ToUInt32(1);
Type = (MessageType)data.ElementAt(5);
}
public byte Version { get; private set; }
[JsonIgnore]
public uint Length { get; private set; }
public MessageType Type { get; private set; }
}
} |
Add xmldoc mention of valid `OnlineID` values | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
namespace osu.Game.Database
{
public interface IHasOnlineID
{
/// <summary>
/// The server-side ID representing this instance, if one exists. -1 denotes a missing ID.
/// </summary>
int OnlineID { get; }
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
namespace osu.Game.Database
{
public interface IHasOnlineID
{
/// <summary>
/// The server-side ID representing this instance, if one exists. Any value 0 or less denotes a missing ID.
/// </summary>
/// <remarks>
/// Generally we use -1 when specifying "missing" in code, but values of 0 are also considered missing as the online source
/// is generally a MySQL autoincrement value, which can never be 0.
/// </remarks>
int OnlineID { get; }
}
}
|
Fix for blinking tests issue | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NSuperTest.Registration
{
public class RegistrationDiscoverer
{
public IEnumerable<IRegisterServers> FindRegistrations()
{
var type = typeof(IRegisterServers);
var registries = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(t => t.GetTypes())
.Where(t => type.IsAssignableFrom(t) && !t.IsInterface)
.Select(t => Activator.CreateInstance(t) as IRegisterServers);
return registries;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace NSuperTest.Registration
{
public static class AssemblyExtensions
{
public static IEnumerable<Type> GetLoadableTypes(this Assembly assembly)
{
try
{
return assembly.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
return e.Types.Where(t => t != null);
}
}
}
public class RegistrationDiscoverer
{
public IEnumerable<IRegisterServers> FindRegistrations()
{
var type = typeof(IRegisterServers);
var registries = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(t => t.GetLoadableTypes())
.Where(t => type.IsAssignableFrom(t) && !t.IsInterface)
.Select(t => Activator.CreateInstance(t) as IRegisterServers);
return registries;
}
}
}
|
Improve documentation of 0100664 mode usage | namespace LibGit2Sharp
{
/// <summary>
/// Git specific modes for entries.
/// </summary>
public enum Mode
{
// Inspired from http://stackoverflow.com/a/8347325/335418
/// <summary>
/// 000000 file mode (the entry doesn't exist)
/// </summary>
Nonexistent = 0,
/// <summary>
/// 040000 file mode
/// </summary>
Directory = 0x4000,
/// <summary>
/// 100644 file mode
/// </summary>
NonExecutableFile = 0x81A4,
/// <summary>
/// 100664 file mode
/// </summary>
NonExecutableGroupWritableFile = 0x81B4,
/// <summary>
/// 100755 file mode
/// </summary>
ExecutableFile = 0x81ED,
/// <summary>
/// 120000 file mode
/// </summary>
SymbolicLink = 0xA000,
/// <summary>
/// 160000 file mode
/// </summary>
GitLink = 0xE000
}
}
| namespace LibGit2Sharp
{
/// <summary>
/// Git specific modes for entries.
/// </summary>
public enum Mode
{
// Inspired from http://stackoverflow.com/a/8347325/335418
/// <summary>
/// 000000 file mode (the entry doesn't exist)
/// </summary>
Nonexistent = 0,
/// <summary>
/// 040000 file mode
/// </summary>
Directory = 0x4000,
/// <summary>
/// 100644 file mode
/// </summary>
NonExecutableFile = 0x81A4,
/// <summary>
/// Obsolete 100664 file mode.
/// <para>0100664 mode is an early Git design mistake. It's kept for
/// ascendant compatibility as some <see cref="Tree"/> and
/// <see cref="Repository.Index"/> entries may still bear
/// this mode in some old git repositories, but it's now deprecated.
/// </para>
/// </summary>
NonExecutableGroupWritableFile = 0x81B4,
/// <summary>
/// 100755 file mode
/// </summary>
ExecutableFile = 0x81ED,
/// <summary>
/// 120000 file mode
/// </summary>
SymbolicLink = 0xA000,
/// <summary>
/// 160000 file mode
/// </summary>
GitLink = 0xE000
}
}
|
Add method to get a computer’s printers | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using PrintNodeNet.Http;
namespace PrintNodeNet
{
public sealed class PrintNodeComputer
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("inet")]
public string Inet { get; set; }
[JsonProperty("inet6")]
public string Inet6 { get; set; }
[JsonProperty("hostName")]
public string HostName { get; set; }
[JsonProperty("jre")]
public string Jre { get; set; }
[JsonProperty("createTimeStamp")]
public DateTime CreateTimeStamp { get; set; }
[JsonProperty("state")]
public string State { get; set; }
public static async Task<IEnumerable<PrintNodeComputer>> ListAsync(PrintNodeRequestOptions options = null)
{
var response = await PrintNodeApiHelper.Get("/computers", options);
return JsonConvert.DeserializeObject<List<PrintNodeComputer>>(response);
}
public static async Task<PrintNodeComputer> GetAsync(long id, PrintNodeRequestOptions options = null)
{
var response = await PrintNodeApiHelper.Get($"/computers/{id}", options);
var list = JsonConvert.DeserializeObject<List<PrintNodeComputer>>(response);
return list.FirstOrDefault();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using PrintNodeNet.Http;
namespace PrintNodeNet
{
public sealed class PrintNodeComputer
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("inet")]
public string Inet { get; set; }
[JsonProperty("inet6")]
public string Inet6 { get; set; }
[JsonProperty("hostName")]
public string HostName { get; set; }
[JsonProperty("jre")]
public string Jre { get; set; }
[JsonProperty("createTimeStamp")]
public DateTime CreateTimeStamp { get; set; }
[JsonProperty("state")]
public string State { get; set; }
public static async Task<IEnumerable<PrintNodeComputer>> ListAsync(PrintNodeRequestOptions options = null)
{
var response = await PrintNodeApiHelper.Get("/computers", options);
return JsonConvert.DeserializeObject<List<PrintNodeComputer>>(response);
}
public static async Task<PrintNodeComputer> GetAsync(long id, PrintNodeRequestOptions options = null)
{
var response = await PrintNodeApiHelper.Get($"/computers/{id}", options);
var list = JsonConvert.DeserializeObject<List<PrintNodeComputer>>(response);
return list.FirstOrDefault();
}
public async Task<IEnumerable<PrintNodePrinter>> ListPrinters(PrintNodeRequestOptions options = null)
{
var response = await PrintNodeApiHelper.Get($"/computers/{Id}/printers", options);
return JsonConvert.DeserializeObject<List<PrintNodePrinter>>(response);
}
}
}
|
Build edit page for enabled RPs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Thinktecture.IdentityServer.Web.ViewModels
{
public class RelyingPartyViewModel
{
public int ID { get; set; }
public string DisplayName { get; set; }
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Thinktecture.IdentityServer.Web.ViewModels
{
public class RelyingPartyViewModel
{
public string ID { get; set; }
public string DisplayName { get; set; }
public bool Enabled { get; set; }
}
} |
Update in creation of table | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
namespace dbms_objects_data
{
class Table
{
public DataTable table = new DataTable();
public Table()
{
}
public bool insertRows(string[] listOfNames, Type[] listOfTypes)
{
if((listOfNames == null) || (listOfTypes == null))
{
return false;
}
for(int i = 0; i < listOfNames.Length; i++)
{
table.Columns.Add(listOfNames[i], listOfTypes[i]);
}
return true;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
namespace dbms_objects_data
{
class Table
{
public DataTable table = new DataTable();
public Table()
{
}
public bool insertRows(string[] listOfNames, Type[] listOfTypes)
{
if((listOfNames == null) || (listOfTypes == null))
{
return false;
}
if(listOfNames.Length != listOfTypes.Length)
{
return false;
}
for(int i = 0; i < listOfNames.Length; i++)
{
table.Columns.Add(listOfNames[i], listOfTypes[i]);
}
return true;
}
}
}
|
Add expiration to client secret | /*
* Copyright 2014 Dominick Baier, Brock Allen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Thinktecture.IdentityServer.Core.Models
{
public class ClientSecret
{
public string Id { get; set; }
public string Value { get; set; }
public ClientSecret(string value)
{
Value = value;
}
public ClientSecret(string id, string value)
{
Id = id;
Value = value;
}
}
} | /*
* Copyright 2014 Dominick Baier, Brock Allen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace Thinktecture.IdentityServer.Core.Models
{
/// <summary>
/// Models a client secret with identifier and expiration
/// </summary>
public class ClientSecret
{
/// <summary>
/// Gets or sets the identifier.
/// </summary>
/// <value>
/// The identifier.
/// </value>
public string Id { get; set; }
/// <summary>
/// Gets or sets the value.
/// </summary>
/// <value>
/// The value.
/// </value>
public string Value { get; set; }
/// <summary>
/// Gets or sets the expiration.
/// </summary>
/// <value>
/// The expiration.
/// </value>
public DateTimeOffset? Expiration { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="ClientSecret"/> class.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="expiration">The expiration.</param>
public ClientSecret(string value, DateTimeOffset? expiration = null)
{
Value = value;
Expiration = expiration;
}
/// <summary>
/// Initializes a new instance of the <see cref="ClientSecret"/> class.
/// </summary>
/// <param name="id">The identifier.</param>
/// <param name="value">The value.</param>
/// <param name="expiration">The expiration.</param>
public ClientSecret(string id, string value, DateTimeOffset? expiration = null)
{
Id = id;
Value = value;
Expiration = expiration;
}
}
} |
Create test for inherited private validator function | using UnityEngine;
namespace NaughtyAttributes.Test
{
public class ValidateInputTest : MonoBehaviour
{
[ValidateInput("NotZero0", "int0 must not be zero")]
public int int0;
private bool NotZero0(int value)
{
return value != 0;
}
public ValidateInputNest1 nest1;
}
[System.Serializable]
public class ValidateInputNest1
{
[ValidateInput("NotZero1")]
[AllowNesting] // Because it's nested we need to explicitly allow nesting
public int int1;
private bool NotZero1(int value)
{
return value != 0;
}
public ValidateInputNest2 nest2;
}
[System.Serializable]
public class ValidateInputNest2
{
[ValidateInput("NotZero2")]
[AllowNesting] // Because it's nested we need to explicitly allow nesting
public int int2;
private bool NotZero2(int value)
{
return value != 0;
}
}
}
| using UnityEngine;
namespace NaughtyAttributes.Test
{
public class ValidateInputTest : MonoBehaviour
{
[ValidateInput("NotZero0", "int0 must not be zero")]
public int int0;
private bool NotZero0(int value)
{
return value != 0;
}
public ValidateInputNest1 nest1;
public ValidateInputInheritedNest inheritedNest;
}
[System.Serializable]
public class ValidateInputNest1
{
[ValidateInput("NotZero1")]
[AllowNesting] // Because it's nested we need to explicitly allow nesting
public int int1;
private bool NotZero1(int value)
{
return value != 0;
}
public ValidateInputNest2 nest2;
}
[System.Serializable]
public class ValidateInputNest2
{
[ValidateInput("NotZero2")]
[AllowNesting] // Because it's nested we need to explicitly allow nesting
public int int2;
private bool NotZero2(int value)
{
return value != 0;
}
}
[System.Serializable]
public class ValidateInputInheritedNest : ValidateInputNest1
{
}
}
|
Add unqualified name lookup to the MissingMemberName test | using static System.Console;
public class Counter
{
public Counter() { }
public int Count;
public Counter Increment()
{
Count++;
return this;
}
}
public static class Program
{
public static readonly Counter printCounter = new Counter();
public static void Main()
{
WriteLine(printCounter.Increment().Coutn);
WriteLine(printCounter.Inrement().Count);
}
} | using static System.Console;
public class Counter
{
public Counter() { }
public int Count;
public Counter Increment()
{
Count++;
return this;
}
}
public static class Program
{
public static readonly Counter printCounter = new Counter();
public static void Main()
{
WriteLine(printCounter.Increment().Coutn);
WriteLine(printCounter.Inrement().Count);
WriteLine(printCoutner.Increment().Count);
}
} |
Test for sequence in JSON | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Xtrmstep.Extractor.Core.Tests
{
public class FileReaderTests
{
const string testDataFolder = @"f:\TestData\";
[Fact(DisplayName = "Read JSON Files / One entry")]
public void Should_read_an_entry()
{
var filePath = testDataFolder + "jsonFormat.txt";
var fileReader = new FileReader();
var values = fileReader.Read(filePath).ToArray();
Assert.Equal(1, values.Length);
Assert.Equal("url_text", values[0].url);
Assert.Equal("html_text", values[0].result);
}
[Fact(DisplayName = "Read JSON Files / Several entries")]
public void Should_read_sequence()
{
throw new NotImplementedException();
}
[Fact(DisplayName = "Read JSON Files / Big file")]
public void Should_read_big_file()
{
throw new NotImplementedException();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Xtrmstep.Extractor.Core.Tests
{
public class FileReaderTests
{
const string testDataFolder = @"c:\TestData\";
[Fact(DisplayName = "Read JSON Files / One entry")]
public void Should_read_an_entry()
{
var filePath = testDataFolder + "jsonFormat.txt";
var fileReader = new FileReader();
var values = fileReader.Read(filePath).ToArray();
Assert.Equal(1, values.Length);
Assert.Equal("url_text", values[0].url);
Assert.Equal("html_text", values[0].result);
}
[Fact(DisplayName = "Read JSON Files / Several entries")]
public void Should_read_sequence()
{
var filePath = testDataFolder + "jsonSequence.txt";
var fileReader = new FileReader();
var values = fileReader.Read(filePath).ToArray();
Assert.Equal(2, values.Length);
Assert.Equal("url_text_1", values[0].url);
Assert.Equal("html_text_1", values[0].result);
Assert.Equal("url_text_2", values[1].url);
Assert.Equal("html_text_2", values[1].result);
}
[Fact(DisplayName = "Read JSON Files / Big file")]
public void Should_read_big_file()
{
throw new NotImplementedException();
}
}
}
|
Revert "Force fix for new databases" | using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Newtonsoft.Json;
using VotingApplication.Data.Context;
using VotingApplication.Web.Api.Migrations;
namespace VotingApplication.Web.Api
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
// Fix the infinite recursion of Session.OptionSet.Options[0].OptionSets[0].Options[0].[...]
// by not populating the Option.OptionSets after already encountering Session.OptionSet
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
//Enable automatic migrations
//Database.SetInitializer(new MigrateDatabaseToLatestVersion<VotingContext, Configuration>());
//new VotingContext().Database.Initialize(false);
}
}
}
| using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Newtonsoft.Json;
using VotingApplication.Data.Context;
using VotingApplication.Web.Api.Migrations;
namespace VotingApplication.Web.Api
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
// Fix the infinite recursion of Session.OptionSet.Options[0].OptionSets[0].Options[0].[...]
// by not populating the Option.OptionSets after already encountering Session.OptionSet
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
//Enable automatic migrations
Database.SetInitializer(new MigrateDatabaseToLatestVersion<VotingContext, Configuration>());
new VotingContext().Database.Initialize(false);
}
}
}
|
Add recurring job for reading status | using Hangfire;
using StructureMap;
using SupportManager.Control.Infrastructure;
using Topshelf;
namespace SupportManager.Control
{
public class SupportManagerService : ServiceControl
{
private readonly IContainer container;
private BackgroundJobServer jobServer;
public SupportManagerService()
{
GlobalConfiguration.Configuration.UseSqlServerStorage("HangFire");
container = new Container(c => c.AddRegistry<AppRegistry>());
}
public bool Start(HostControl hostControl)
{
jobServer = new BackgroundJobServer(GetJobServerOptions());
return true;
}
public bool Stop(HostControl hostControl)
{
jobServer.Dispose();
return true;
}
private BackgroundJobServerOptions GetJobServerOptions()
{
return new BackgroundJobServerOptions
{
Activator = new NestedContainerActivator(container)
};
}
}
} | using Hangfire;
using StructureMap;
using SupportManager.Contracts;
using SupportManager.Control.Infrastructure;
using Topshelf;
namespace SupportManager.Control
{
public class SupportManagerService : ServiceControl
{
private readonly IContainer container;
private BackgroundJobServer jobServer;
public SupportManagerService()
{
GlobalConfiguration.Configuration.UseSqlServerStorage("HangFire");
container = new Container(c => c.AddRegistry<AppRegistry>());
}
public bool Start(HostControl hostControl)
{
jobServer = new BackgroundJobServer(GetJobServerOptions());
RecurringJob.AddOrUpdate<IForwarder>(f => f.ReadAllTeamStatus(), Cron.Minutely);
return true;
}
public bool Stop(HostControl hostControl)
{
jobServer.Dispose();
return true;
}
private BackgroundJobServerOptions GetJobServerOptions()
{
return new BackgroundJobServerOptions
{
Activator = new NestedContainerActivator(container)
};
}
}
} |
Fix converter for possible null values. | using DocumentFormat.OpenXml;
namespace ClosedXML.Utils
{
internal static class OpenXmlHelper
{
public static BooleanValue GetBooleanValue(bool value, bool defaultValue)
{
return value == defaultValue ? null : new BooleanValue(value);
}
public static bool GetBooleanValueAsBool(BooleanValue value, bool defaultValue)
{
return value.HasValue ? value.Value : defaultValue;
}
}
}
| using DocumentFormat.OpenXml;
namespace ClosedXML.Utils
{
internal static class OpenXmlHelper
{
public static BooleanValue GetBooleanValue(bool value, bool defaultValue)
{
return value == defaultValue ? null : new BooleanValue(value);
}
public static bool GetBooleanValueAsBool(BooleanValue value, bool defaultValue)
{
return (value?.HasValue ?? false) ? value.Value : defaultValue;
}
}
}
|
Move away from v0 approach. | using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sketchball.Elements
{
public class Ball : PinballElement, IPhysics
{
private Vector2 v;
private Vector2 v0;
long t = 0;
public Vector2 Velocity
{
get
{
return v;
}
set
{
v0 = value;
t = 0;
v = v0;
}
}
public Ball()
{
Velocity = new Vector2();
Mass = 0.2f;
Width = 60;
Height = 60;
}
public override void Draw(System.Drawing.Graphics g)
{
//g.FillEllipse(Brushes.Peru, 0, 0, Width, Height);
g.DrawImage(Properties.Resources.BallWithAlpha, 0, 0, Width, Height);
}
public override void Update(long delta)
{
t += delta;
base.Update(delta);
v = v0 + (t / 1000f) * World.Acceleration;
Location += v * (delta / 1000f);
}
public float Mass
{
get;
set;
}
}
}
| using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sketchball.Elements
{
public class Ball : PinballElement, IPhysics
{
public Vector2 Velocity
{
get;
set;
}
public Ball()
{
Velocity = new Vector2();
Mass = 0.2f;
Width = 60;
Height = 60;
}
public override void Draw(System.Drawing.Graphics g)
{
//g.FillEllipse(Brushes.Peru, 0, 0, Width, Height);
g.DrawImage(Properties.Resources.BallWithAlpha, 0, 0, Width, Height);
}
public override void Update(long delta)
{
base.Update(delta);
Velocity += World.Acceleration * (delta / 1000f);
Location += Velocity * (delta / 1000f);
}
public float Mass
{
get;
set;
}
}
}
|
Make the custom action not have to use Debugger.Launch to prove that it works. | using System;
using Microsoft.Deployment.WindowsInstaller;
namespace Wix.CustomActions
{
using System.IO;
using System.Diagnostics;
public class CustomActions
{
[CustomAction]
public static ActionResult CloseIt(Session session)
{
try
{
Debugger.Launch();
const string fileFullPath = @"c:\KensCustomAction.txt";
if (!File.Exists(fileFullPath))
File.Create(fileFullPath);
File.AppendAllText(fileFullPath, string.Format("{0}Yes, we have a hit at {1}", Environment.NewLine, DateTime.Now));
session.Log("Close DotTray!");
}
catch (Exception ex)
{
session.Log("ERROR in custom action CloseIt {0}", ex.ToString());
return ActionResult.Failure;
}
return ActionResult.Success;
}
}
}
| using Microsoft.Deployment.WindowsInstaller;
using System;
using System.IO;
namespace Wix.CustomActions
{
public class CustomActions
{
[CustomAction]
public static ActionResult CloseIt(Session session)
{
try
{
string fileFullPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "CustomAction.txt");
if (!File.Exists(fileFullPath))
File.Create(fileFullPath);
File.AppendAllText(fileFullPath, string.Format("{0}Yes, we have a hit at {1}", Environment.NewLine, DateTime.Now));
session.Log("Close DotTray!");
}
catch (Exception ex)
{
session.Log("ERROR in custom action CloseIt {0}", ex.ToString());
return ActionResult.Failure;
}
return ActionResult.Success;
}
}
} |
Add change handling for difficulty section | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.Beatmaps.ControlPoints;
namespace osu.Game.Screens.Edit.Timing
{
internal class DifficultySection : Section<DifficultyControlPoint>
{
private SliderWithTextBoxInput<double> multiplierSlider;
[BackgroundDependencyLoader]
private void load()
{
Flow.AddRange(new[]
{
multiplierSlider = new SliderWithTextBoxInput<double>("Speed Multiplier")
{
Current = new DifficultyControlPoint().SpeedMultiplierBindable
}
});
}
protected override void OnControlPointChanged(ValueChangedEvent<DifficultyControlPoint> point)
{
if (point.NewValue != null)
{
multiplierSlider.Current = point.NewValue.SpeedMultiplierBindable;
}
}
protected override DifficultyControlPoint CreatePoint()
{
var reference = Beatmap.Value.Beatmap.ControlPointInfo.DifficultyPointAt(SelectedGroup.Value.Time);
return new DifficultyControlPoint
{
SpeedMultiplier = reference.SpeedMultiplier,
};
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.Beatmaps.ControlPoints;
namespace osu.Game.Screens.Edit.Timing
{
internal class DifficultySection : Section<DifficultyControlPoint>
{
private SliderWithTextBoxInput<double> multiplierSlider;
[BackgroundDependencyLoader]
private void load()
{
Flow.AddRange(new[]
{
multiplierSlider = new SliderWithTextBoxInput<double>("Speed Multiplier")
{
Current = new DifficultyControlPoint().SpeedMultiplierBindable
}
});
}
protected override void OnControlPointChanged(ValueChangedEvent<DifficultyControlPoint> point)
{
if (point.NewValue != null)
{
multiplierSlider.Current = point.NewValue.SpeedMultiplierBindable;
multiplierSlider.Current.BindValueChanged(_ => ChangeHandler?.SaveState());
}
}
protected override DifficultyControlPoint CreatePoint()
{
var reference = Beatmap.Value.Beatmap.ControlPointInfo.DifficultyPointAt(SelectedGroup.Value.Time);
return new DifficultyControlPoint
{
SpeedMultiplier = reference.SpeedMultiplier,
};
}
}
}
|
Fix assertion, need to check if it's not null first. | namespace NEventStore
{
using FluentAssertions;
using NEventStore.Persistence.AcceptanceTests;
using NEventStore.Persistence.AcceptanceTests.BDD;
using System;
using Xunit;
public class DefaultSerializationWireupTests
{
public class when_building_an_event_store_without_an_explicit_serializer : SpecificationBase
{
private Wireup _wireup;
private Exception _exception;
private IStoreEvents _eventStore;
protected override void Context()
{
_wireup = Wireup.Init()
.UsingSqlPersistence("fakeConnectionString")
.WithDialect(new Persistence.Sql.SqlDialects.MsSqlDialect());
}
protected override void Because()
{
_exception = Catch.Exception(() => { _eventStore = _wireup.Build(); });
}
protected override void Cleanup()
{
_eventStore.Dispose();
}
[Fact]
public void should_not_throw_an_argument_null_exception()
{
_exception.GetType().Should().NotBe(typeof(ArgumentNullException));
}
}
}
}
| namespace NEventStore
{
using FluentAssertions;
using NEventStore.Persistence.AcceptanceTests;
using NEventStore.Persistence.AcceptanceTests.BDD;
using System;
using Xunit;
public class DefaultSerializationWireupTests
{
public class when_building_an_event_store_without_an_explicit_serializer : SpecificationBase
{
private Wireup _wireup;
private Exception _exception;
private IStoreEvents _eventStore;
protected override void Context()
{
_wireup = Wireup.Init()
.UsingSqlPersistence("fakeConnectionString")
.WithDialect(new Persistence.Sql.SqlDialects.MsSqlDialect());
}
protected override void Because()
{
_exception = Catch.Exception(() => { _eventStore = _wireup.Build(); });
}
protected override void Cleanup()
{
_eventStore.Dispose();
}
[Fact]
public void should_not_throw_an_argument_null_exception()
{
if (_exception != null)
{
_exception.GetType().Should().NotBe<ArgumentNullException>();
}
}
}
}
}
|
Change library command line option | namespace SnappyMap.CommandLine
{
using System.Collections.Generic;
using global::CommandLine;
using global::CommandLine.Text;
public class Options
{
[Option('s', "size", DefaultValue = "8x8", HelpText = "Set the size of the output map.")]
public string Size { get; set; }
[Option('l', "library", DefaultValue = "library", HelpText = "Set the directory to search for tilesets in.")]
public string LibraryPath { get; set; }
[Option('c', "config", DefaultValue = "config.xml", HelpText = "Set the path to the section config file.")]
public string ConfigFile { get; set; }
[ValueList(typeof(List<string>), MaximumElements = 2)]
public IList<string> Items { get; set; }
[HelpOption]
public string GetUsage()
{
var help = new HelpText
{
Heading = new HeadingInfo("Snappy Map", "alpha"),
Copyright = new CopyrightInfo("Armoured Fish", 2014),
AddDashesToOption = true,
AdditionalNewLineAfterOption = true,
};
help.AddPreOptionsLine(string.Format("Usage: {0} [-s NxM] [-l <library_path>] [-c <config_file>] <input_file> [output_file]", "SnappyMap"));
help.AddOptions(this);
return help;
}
}
}
| namespace SnappyMap.CommandLine
{
using System.Collections.Generic;
using global::CommandLine;
using global::CommandLine.Text;
public class Options
{
[Option('s', "size", DefaultValue = "8x8", HelpText = "Set the size of the output map.")]
public string Size { get; set; }
[Option('t', "tileset-dir", DefaultValue = "tilesets", HelpText = "Set the directory to search for tilesets in.")]
public string LibraryPath { get; set; }
[Option('c', "config", DefaultValue = "config.xml", HelpText = "Set the path to the section config file.")]
public string ConfigFile { get; set; }
[ValueList(typeof(List<string>), MaximumElements = 2)]
public IList<string> Items { get; set; }
[HelpOption]
public string GetUsage()
{
var help = new HelpText
{
Heading = new HeadingInfo("Snappy Map", "alpha"),
Copyright = new CopyrightInfo("Armoured Fish", 2014),
AddDashesToOption = true,
AdditionalNewLineAfterOption = true,
};
help.AddPreOptionsLine(string.Format("Usage: {0} [-s NxM] [-l <library_path>] [-c <config_file>] <input_file> [output_file]", "SnappyMap"));
help.AddOptions(this);
return help;
}
}
}
|
Update assembly to version 0. | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Sieve.NET.Core")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Sieve.NET.Core")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fe4a2ebf-8685-4948-87f4-56fe7d986c5a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Sieve.NET.Core")]
[assembly: AssemblyDescription("An expression-based filtering library for .NET")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Sieve.NET.Core")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fe4a2ebf-8685-4948-87f4-56fe7d986c5a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.0.0.0")]
[assembly: AssemblyFileVersion("0.0.0.0")]
|
Change parsing to only trigger on changed lines. | using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using TodoPad.Models;
using TodoPad.Task_Parser;
namespace TodoPad.Views
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void DocumentBoxTextChanged(object sender, TextChangedEventArgs e)
{
RichTextBox textBox = (RichTextBox)sender;
// Remove this handler so we don't trigger it when formatting.
textBox.TextChanged -= DocumentBoxTextChanged;
Paragraph currentParagraph = textBox.Document.Blocks.FirstBlock as Paragraph;
while (currentParagraph != null)
{
// Get the text on this row.
TextPointer start = currentParagraph.ContentStart;
TextPointer end = currentParagraph.ContentEnd;
TextRange currentTextRange = new TextRange(start, end);
// Parse the row.
Row currentRow = new Row(currentTextRange.Text);
// Format the displayed text.
TaskParser.FormatTextRange(currentTextRange, currentRow);
currentParagraph = currentParagraph.NextBlock as Paragraph;
}
// Restore this handler.
textBox.TextChanged += DocumentBoxTextChanged;
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using TodoPad.Models;
using TodoPad.Task_Parser;
namespace TodoPad.Views
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void DocumentBoxTextChanged(object sender, TextChangedEventArgs e)
{
RichTextBox textBox = (RichTextBox)sender;
// Remove this handler so we don't trigger it when formatting.
textBox.TextChanged -= DocumentBoxTextChanged;
// Get the line that was changed.
foreach (TextChange currentChange in e.Changes)
{
TextPointer offSet = textBox.Document.ContentStart.GetPositionAtOffset(currentChange.Offset, LogicalDirection.Forward);
if (offSet != null)
{
Paragraph currentParagraph = offSet.Paragraph;
if (offSet.Parent == textBox.Document)
{
// Format the entire document.
currentParagraph = textBox.Document.Blocks.FirstBlock as Paragraph;
while (currentParagraph != null)
{
FormatParagraph(currentParagraph);
currentParagraph = currentParagraph.NextBlock as Paragraph;
}
}
else if (currentParagraph != null)
{
FormatParagraph(currentParagraph);
}
}
}
// Restore this handler.
textBox.TextChanged += DocumentBoxTextChanged;
}
private static void FormatParagraph(Paragraph currentParagraph)
{
// Get the text on this row.
TextPointer start = currentParagraph.ContentStart;
TextPointer end = currentParagraph.ContentEnd;
TextRange currentTextRange = new TextRange(start, end);
// Parse the row.
Row currentRow = new Row(currentTextRange.Text);
// Format the displayed text.
TaskParser.FormatTextRange(currentTextRange, currentRow);
}
}
}
|
Add category to test run | using System.Linq;
using NUnit.Framework;
using Xamarin.UITest;
namespace MvvmLightBindings.UITest
{
[TestFixture(Platform.Android)]
[TestFixture(Platform.iOS)]
public class Tests
{
IApp app;
Platform platform;
public Tests(Platform platform)
{
this.platform = platform;
}
[SetUp]
public void BeforeEachTest()
{
app = AppInitializer.StartApp(platform);
}
[Test]
public void AppLaunches()
{
app.Repl();
}
[Test]
public void EnterAndSubmitText_ItAppearsInTheSubmittedTextLabel()
{
app.EnterText(q => q.Marked("InputMessageEntry"), "Hello from Xamarin Test Cloud");
app.Screenshot("Has entered text");
app.Tap(q => q.Marked("SubmitMessageButton"));
app.Screenshot("Has taped the submit button.");
Assert.IsFalse(string.IsNullOrEmpty(app.Query(q => q.Marked("SubmittedMessageLabel")).First().Text));
}
}
}
| using System.Linq;
using NUnit.Framework;
using Xamarin.UITest;
namespace MvvmLightBindings.UITest
{
[TestFixture(Platform.Android)]
[TestFixture(Platform.iOS)]
public class Tests
{
IApp app;
Platform platform;
public Tests(Platform platform)
{
this.platform = platform;
}
[SetUp]
public void BeforeEachTest()
{
app = AppInitializer.StartApp(platform);
}
[Test]
[Ignore]
public void AppLaunches()
{
app.Repl();
}
[Test]
[Category("all")]
public void EnterAndSubmitText_ItAppearsInTheSubmittedTextLabel()
{
app.EnterText(q => q.Marked("InputMessageEntry"), "Hello from Xamarin Test Cloud");
app.Screenshot("Has entered text");
app.Tap(q => q.Marked("SubmitMessageButton"));
app.Screenshot("Has taped the submit button.");
Assert.IsFalse(string.IsNullOrEmpty(app.Query(q => q.Marked("SubmittedMessageLabel")).First().Text));
}
}
}
|
Add support for fixed structures | using System;
namespace SPAD.neXt.Interfaces.SimConnect
{
public interface IDataItemAttributeBase
{
int ItemIndex
{
get;
set;
}
int ItemSize
{
get;
set;
}
float ItemEpsilon
{
get;
set;
}
int ItemOffset { get; set; }
}
public interface IDataItemBoundBase
{
string DatumName { get; }
string UnitsName { get; }
string ID { get; }
}
}
| using System;
namespace SPAD.neXt.Interfaces.SimConnect
{
public interface IDataItemAttributeBase
{
int ItemIndex
{
get;
set;
}
int ItemSize
{
get;
set;
}
float ItemEpsilon
{
get;
set;
}
int ItemOffset { get; set; }
bool IsFixedSize { get; set; }
}
public interface IDataItemBoundBase
{
string DatumName { get; }
string UnitsName { get; }
string ID { get; }
}
}
|
Add descriptor to IgnoreCase for parsing of enum | using System;
using Digipost.Api.Client.Domain.Enums;
namespace Digipost.Api.Client.Domain.Identify
{
public class IdentificationById : IIdentification
{
public IdentificationById(IdentificationType identificationType, string value)
{
IdentificationType = identificationType;
Value = value;
}
public IdentificationType IdentificationType { get; private set; }
public object Data
{
get { return IdentificationType; }
}
[Obsolete("Use IdentificationType instead. Will be removed in future versions" )]
public IdentificationChoiceType IdentificationChoiceType {
get
{
return ParseIdentificationChoiceToIdentificationChoiceType();
}
}
internal IdentificationChoiceType ParseIdentificationChoiceToIdentificationChoiceType()
{
if (IdentificationType == IdentificationType.OrganizationNumber)
{
return IdentificationChoiceType.OrganisationNumber;
}
return (IdentificationChoiceType)
Enum.Parse(typeof (IdentificationChoiceType), IdentificationType.ToString(), true);
}
public string Value { get; set; }
}
}
| using System;
using Digipost.Api.Client.Domain.Enums;
namespace Digipost.Api.Client.Domain.Identify
{
public class IdentificationById : IIdentification
{
public IdentificationById(IdentificationType identificationType, string value)
{
IdentificationType = identificationType;
Value = value;
}
public IdentificationType IdentificationType { get; private set; }
public object Data
{
get { return IdentificationType; }
}
[Obsolete("Use IdentificationType instead. Will be removed in future versions" )]
public IdentificationChoiceType IdentificationChoiceType {
get
{
return ParseIdentificationChoiceToIdentificationChoiceType();
}
}
internal IdentificationChoiceType ParseIdentificationChoiceToIdentificationChoiceType()
{
if (IdentificationType == IdentificationType.OrganizationNumber)
{
return IdentificationChoiceType.OrganisationNumber;
}
return (IdentificationChoiceType)
Enum.Parse(typeof (IdentificationChoiceType), IdentificationType.ToString(), ignoreCase: true);
}
public string Value { get; set; }
}
}
|
Correct action for send log in link form | @model SendLogInLinkModel
@{
ViewBag.Title = "Send Log In Link";
}
<div class="jumbotron">
<div class="row">
<div class="col-lg-6">
<h1>Welcome to Secret Santa!</h1>
@using (Html.BeginForm("LogIn", "Account", FormMethod.Post, new { role = "form", @class = "form-horizontal" }))
{
<fieldset>
<legend>@ViewBag.Title</legend>
<p>
If you misplaced your log-in email, you can use this form to have another
log-in link sent to you.
</p>
<div class="form-group">
<small>@Html.LabelFor(m => m.Email, new { @class = "control-label col-sm-4" })</small>
<div class="col-sm-6">
@Html.EditorFor(m => m.Email)
<small>@Html.ValidationMessageFor(m => m.Email)</small>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Send Log-In Link</button>
</div>
</div>
</fieldset>
}
</div>
<div class="col-lg-6">
<img class="img-responsive" src="@Url.Content("~/Content/Images/santa.png")" alt="Santa" />
</div>
</div>
</div> | @model SendLogInLinkModel
@{
ViewBag.Title = "Send Log In Link";
}
<div class="jumbotron">
<div class="row">
<div class="col-lg-6">
<h1>Welcome to Secret Santa!</h1>
@using (Html.BeginForm("SendLogInLink", "Account", FormMethod.Post, new { role = "form", @class = "form-horizontal" }))
{
<fieldset>
<legend>@ViewBag.Title</legend>
<p>
If you misplaced your log-in email, you can use this form to have another
log-in link sent to you.
</p>
<div class="form-group">
<small>@Html.LabelFor(m => m.Email, new { @class = "control-label col-sm-4" })</small>
<div class="col-sm-6">
@Html.EditorFor(m => m.Email)
<small>@Html.ValidationMessageFor(m => m.Email)</small>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Send Log-In Link</button>
</div>
</div>
</fieldset>
}
</div>
<div class="col-lg-6">
<img class="img-responsive" src="@Url.Content("~/Content/Images/santa.png")" alt="Santa" />
</div>
</div>
</div> |
Add Tests For DateTime Extensions | using System;
using FluentAssertions;
using NUnit.Framework;
using Withings.NET.Client;
namespace Withings.Specifications
{
[TestFixture]
public class DateTimeExtensionsTests
{
[Test]
public void DoubleFromUnixTimeTest()
{
((double)1491934309).FromUnixTime().Date.Should().Equals(DateTime.Parse("04/11/2017"));
}
[Test]
public void LongFromUnixTimeTest()
{
((long)1491934309).FromUnixTime().Date.Should().Equals(DateTime.Parse("04/11/2017"));
}
[Test]
public void IntFromUnixTimeTest()
{
1491934309.FromUnixTime().Date.Should().Equals(DateTime.Parse("04/11/2017"));
}
[Test]
public void DateTimeToUnixTimeTest()
{
DateTime.Parse("04/11/2017").Should().Equals(1491934309);
}
}
} | using System;
using FluentAssertions;
using NUnit.Framework;
using Withings.NET.Client;
namespace Withings.Specifications
{
[TestFixture]
public class DateTimeExtensionsTests
{
[Test]
public void DoubleFromUnixTimeTest()
{
((double)1491934309).FromUnixTime().Date.Should().Equals(DateTime.Parse("04/11/2017"));
}
[Test]
public void LongFromUnixTimeTest()
{
((long)1491934309).FromUnixTime().Date.Should().Equals(DateTime.Parse("04/11/2017"));
}
[Test]
public void IntFromUnixTimeTest()
{
1491934309.FromUnixTime().Date.Should().Equals(DateTime.Parse("04/11/2017"));
}
[Test]
public void DateTimeToUnixTimeTest()
{
DateTime.Parse("04/11/2017").ToUnixTime().Should().Equals(1491934309);
}
}
} |
Fix usage of deprecated Action.BeginInvoke() | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Threading;
using NUnit.Framework;
using osu.Framework.Platform;
namespace osu.Framework.Tests.Platform
{
[TestFixture]
public class HeadlessGameHostTest
{
private class Foobar
{
public string Bar;
}
[Test]
public void TestIpc()
{
using (var server = new HeadlessGameHost(@"server", true))
using (var client = new HeadlessGameHost(@"client", true))
{
Assert.IsTrue(server.IsPrimaryInstance, @"Server wasn't able to bind");
Assert.IsFalse(client.IsPrimaryInstance, @"Client was able to bind when it shouldn't have been able to");
var serverChannel = new IpcChannel<Foobar>(server);
var clientChannel = new IpcChannel<Foobar>(client);
Action waitAction = () =>
{
bool received = false;
serverChannel.MessageReceived += message =>
{
Assert.AreEqual("example", message.Bar);
received = true;
};
clientChannel.SendMessageAsync(new Foobar { Bar = "example" }).Wait();
while (!received)
Thread.Sleep(1);
};
Assert.IsTrue(waitAction.BeginInvoke(null, null).AsyncWaitHandle.WaitOne(10000),
@"Message was not received in a timely fashion");
}
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using osu.Framework.Platform;
namespace osu.Framework.Tests.Platform
{
[TestFixture]
public class HeadlessGameHostTest
{
private class Foobar
{
public string Bar;
}
[Test]
public void TestIpc()
{
using (var server = new HeadlessGameHost(@"server", true))
using (var client = new HeadlessGameHost(@"client", true))
{
Assert.IsTrue(server.IsPrimaryInstance, @"Server wasn't able to bind");
Assert.IsFalse(client.IsPrimaryInstance, @"Client was able to bind when it shouldn't have been able to");
var serverChannel = new IpcChannel<Foobar>(server);
var clientChannel = new IpcChannel<Foobar>(client);
Action waitAction = () =>
{
bool received = false;
serverChannel.MessageReceived += message =>
{
Assert.AreEqual("example", message.Bar);
received = true;
};
clientChannel.SendMessageAsync(new Foobar { Bar = "example" }).Wait();
while (!received)
Thread.Sleep(1);
};
Assert.IsTrue(Task.Run(waitAction).Wait(10000), @"Message was not received in a timely fashion");
}
}
}
}
|
Fix "welcome" intro test failure due to no wait logic | // 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.Screens;
using osu.Game.Screens.Menu;
namespace osu.Game.Tests.Visual.Menus
{
[TestFixture]
public class TestSceneIntroWelcome : IntroTestScene
{
protected override IScreen CreateScreen() => new IntroWelcome();
public TestSceneIntroWelcome()
{
AddAssert("check if menu music loops", () =>
{
var menu = IntroStack?.CurrentScreen as MainMenu;
if (menu == null)
return false;
return menu.Track.Looping;
});
}
}
}
| // 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.Audio.Track;
using osu.Framework.Screens;
using osu.Game.Screens.Menu;
namespace osu.Game.Tests.Visual.Menus
{
[TestFixture]
public class TestSceneIntroWelcome : IntroTestScene
{
protected override IScreen CreateScreen() => new IntroWelcome();
public TestSceneIntroWelcome()
{
AddUntilStep("wait for load", () => getTrack() != null);
AddAssert("check if menu music loops", () => getTrack().Looping);
}
private Track getTrack() => (IntroStack?.CurrentScreen as MainMenu)?.Track;
}
}
|
Revert last commit since it is currently not possible. | using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Permissions;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("MongoDBDriver")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[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("")]
[assembly: System.Runtime.InteropServices.ComVisible(false)]
[assembly: CLSCompliantAttribute(true)]
[assembly: InternalsVisibleTo("MongoDB.Driver.Tests")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bson")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bson")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, Execution = true)]
| using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Permissions;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("MongoDBDriver")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[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("")]
[assembly: System.Runtime.InteropServices.ComVisible(false)]
[assembly: CLSCompliantAttribute(true)]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bson")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Bson")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, Execution = true)]
|
Add method to parse ints and throw exception on failure. | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace SGEnviro.Utilities
{
public class NumberParseException : Exception
{
public NumberParseException(string message) { }
}
public class Parsing
{
public static void ParseFloatOrThrowException(string value, out float destination, string message)
{
if (!float.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out destination))
{
throw new Exception(message);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace SGEnviro.Utilities
{
public class NumberParseException : Exception
{
public NumberParseException(string message) { }
}
public class Parsing
{
public static void ParseFloatOrThrowException(string value, out float destination, string message)
{
if (!float.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out destination))
{
throw new NumberParseException(message);
}
}
public static void ParseIntOrThrowException(string value, out int destination, string message)
{
if (!int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out destination))
{
throw new NumberParseException(message);
}
}
}
}
|
Add max length to parrot | using System;
using System.Collections.Generic;
namespace WendySharp
{
class Parrot : Command
{
public Parrot()
{
Match = new List<string>
{
"parrot"
};
Usage = "<text>";
ArgumentMatch = "(?<text>.+)$";
HelpText = "Echo a message back to the channel.";
}
public override void OnCommand(CommandArguments command)
{
var text = command.Arguments.Groups["text"].Value;
Log.WriteInfo("Parrot", "'{0}' said to '{1}': {2}", command.Event.Sender, command.Event.Recipient, text);
Bootstrap.Client.Client.Message(command.Event.Recipient, string.Format("\u200B{0}", text));
}
}
}
| using System;
using System.Collections.Generic;
namespace WendySharp
{
class Parrot : Command
{
public Parrot()
{
Match = new List<string>
{
"parrot"
};
Usage = "<text>";
ArgumentMatch = "(?<text>.+)$";
HelpText = "Echo a message back to the channel.";
}
public override void OnCommand(CommandArguments command)
{
var text = command.Arguments.Groups["text"].Value;
if (text.Length > 140)
{
command.Reply("That message is too long to be parroted.");
return;
}
Log.WriteInfo("Parrot", "'{0}' said to '{1}': {2}", command.Event.Sender, command.Event.Recipient, text);
Bootstrap.Client.Client.Message(command.Event.Recipient, string.Format("\u200B{0}", text));
}
}
}
|
Disable Raven's Embedded HTTP server | using Ninject;
using Ninject.Modules;
using Ninject.Web.Common;
using Raven.Client;
using Raven.Client.Embedded;
namespace CGO.Web.NinjectModules
{
public class RavenModule : NinjectModule
{
public override void Load()
{
Kernel.Bind<IDocumentStore>().ToMethod(_ => InitialiseDocumentStore()).InSingletonScope();
Kernel.Bind<IDocumentSession>().ToMethod(_ => Kernel.Get<IDocumentStore>().OpenSession()).InRequestScope();
}
private static IDocumentStore InitialiseDocumentStore()
{
var documentStore = new EmbeddableDocumentStore
{
DataDirectory = "CGO.raven",
UseEmbeddedHttpServer = true,
Configuration = { Port = 28645 }
};
documentStore.Initialize();
documentStore.InitializeProfiling();
return documentStore;
}
}
} | using Ninject;
using Ninject.Modules;
using Ninject.Web.Common;
using Raven.Client;
using Raven.Client.Embedded;
namespace CGO.Web.NinjectModules
{
public class RavenModule : NinjectModule
{
public override void Load()
{
Kernel.Bind<IDocumentStore>().ToMethod(_ => InitialiseDocumentStore()).InSingletonScope();
Kernel.Bind<IDocumentSession>().ToMethod(_ => Kernel.Get<IDocumentStore>().OpenSession()).InRequestScope();
}
private static IDocumentStore InitialiseDocumentStore()
{
var documentStore = new EmbeddableDocumentStore
{
DataDirectory = "CGO.raven",
Configuration = { Port = 28645 }
};
documentStore.Initialize();
documentStore.InitializeProfiling();
return documentStore;
}
}
} |
Use for loop to avoid nested unregister case | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Statistics;
using System;
using System.Collections.Generic;
using osu.Framework.Audio;
namespace osu.Framework.Threading
{
public class AudioThread : GameThread
{
public AudioThread()
: base(name: "Audio")
{
OnNewFrame = onNewFrame;
}
internal override IEnumerable<StatisticsCounterType> StatisticsCounters => new[]
{
StatisticsCounterType.TasksRun,
StatisticsCounterType.Tracks,
StatisticsCounterType.Samples,
StatisticsCounterType.SChannels,
StatisticsCounterType.Components,
};
private readonly List<AudioManager> managers = new List<AudioManager>();
private void onNewFrame()
{
lock (managers)
foreach (var m in managers)
m.Update();
}
public void RegisterManager(AudioManager manager)
{
lock (managers)
{
if (managers.Contains(manager))
throw new InvalidOperationException($"{manager} was already registered");
managers.Add(manager);
}
}
public void UnregisterManager(AudioManager manager)
{
lock (managers)
managers.Remove(manager);
}
protected override void PerformExit()
{
base.PerformExit();
ManagedBass.Bass.Free();
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Statistics;
using System;
using System.Collections.Generic;
using osu.Framework.Audio;
namespace osu.Framework.Threading
{
public class AudioThread : GameThread
{
public AudioThread()
: base(name: "Audio")
{
OnNewFrame = onNewFrame;
}
internal override IEnumerable<StatisticsCounterType> StatisticsCounters => new[]
{
StatisticsCounterType.TasksRun,
StatisticsCounterType.Tracks,
StatisticsCounterType.Samples,
StatisticsCounterType.SChannels,
StatisticsCounterType.Components,
};
private readonly List<AudioManager> managers = new List<AudioManager>();
private void onNewFrame()
{
lock (managers)
{
for (var i = 0; i < managers.Count; i++)
{
var m = managers[i];
m.Update();
}
}
}
public void RegisterManager(AudioManager manager)
{
lock (managers)
{
if (managers.Contains(manager))
throw new InvalidOperationException($"{manager} was already registered");
managers.Add(manager);
}
}
public void UnregisterManager(AudioManager manager)
{
lock (managers)
managers.Remove(manager);
}
protected override void PerformExit()
{
base.PerformExit();
ManagedBass.Bass.Free();
}
}
}
|
Add BGP and BMP message lengths to JSON | using System.Collections.Generic;
namespace BmpListener.Serialization.Models
{
public class UpdateModel
{
public PeerHeaderModel Peer { get; set; }
public string Origin { get; set; }
public IList<int> AsPath { get; set; }
public IList<AnnounceModel> Announce { get; set; }
public IList<WithdrawModel> Withdraw { get; set; }
}
}
| using System.Collections.Generic;
namespace BmpListener.Serialization.Models
{
public class UpdateModel
{
public int BmpMsgLength { get; set; }
public int BgpMsgLength { get; set; }
public PeerHeaderModel Peer { get; set; }
public string Origin { get; set; }
public IList<int> AsPath { get; set; }
public IList<AnnounceModel> Announce { get; set; }
public IList<WithdrawModel> Withdraw { get; set; }
}
}
|
Fix "double question mark" bug in UriBuilder | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Raven.Contrib.AspNet.Demo.Extensions
{
public static class UriExtensions
{
public static Uri AddQueryParameter(this Uri uri, KeyValuePair<string, string> pair)
{
return uri.AddQueryParameter(pair.Key, pair.Value);
}
public static Uri AddQueryParameter(this Uri uri, string key, string value)
{
var builder = new UriBuilder(uri);
string encodedKey = Uri.EscapeDataString(key);
string encodedValue = Uri.EscapeDataString(value);
string queryString = String.Format("{0}={1}", encodedKey, encodedValue);
builder.Query += String.IsNullOrEmpty(builder.Query) ? queryString : "&" + queryString;
return builder.Uri;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Raven.Contrib.AspNet.Demo.Extensions
{
public static class UriExtensions
{
public static Uri AddQueryParameter(this Uri uri, KeyValuePair<string, string> pair)
{
return uri.AddQueryParameter(pair.Key, pair.Value);
}
public static Uri AddQueryParameter(this Uri uri, string key, string value)
{
var builder = new UriBuilder(uri);
string encodedKey = Uri.EscapeDataString(key);
string encodedValue = Uri.EscapeDataString(value);
string queryString = String.Format("{0}={1}", encodedKey, encodedValue);
builder.Query = String.IsNullOrEmpty(builder.Query) ? queryString : builder.Query.Substring(1) + "&" + queryString;
return builder.Uri;
}
}
}
|
Increase length of benchmark algorithm | using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
namespace QuantConnect.Algorithm.CSharp.Benchmarks
{
public class EmptyMinute400EquityAlgorithm : QCAlgorithm
{
public override void Initialize()
{
SetStartDate(2015, 09, 28);
SetEndDate(2015, 10, 28);
foreach (var symbol in Symbols.Equity.All.Take(400))
{
AddSecurity(SecurityType.Equity, symbol);
}
}
public override void OnData(Slice slice)
{
}
}
} | using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
namespace QuantConnect.Algorithm.CSharp.Benchmarks
{
public class EmptyMinute400EquityAlgorithm : QCAlgorithm
{
public override void Initialize()
{
SetStartDate(2015, 09, 28);
SetEndDate(2015, 11, 13);
foreach (var symbol in Symbols.Equity.All.Take(400))
{
AddSecurity(SecurityType.Equity, symbol);
}
}
public override void OnData(Slice slice)
{
}
}
} |
Use new author var for posts too | <?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title type="text"><?cs var:title ?></title>
<subtitle type="text"><?cs var:title ?></subtitle>
<id><?cs var:url ?>/</id>
<link rel="self" href="<?cs var:url ?><?cs var:CGI.RequestURI ?>" />
<link rel="alternate" type="text/html" href="<?cs var:url ?>" />
<updated><?cs var:gendate ?></updated>
<author><name><?cs var:author ?></name></author>
<generator uri="<?cs var:CBlog.url ?>" version="<?cs var:CBlog.version ?>"><?cs var:CBlog.version ?></generator>
<?cs each:post = Posts ?>
<entry>
<title type="text"><?cs var:post.title ?></title>
<author><name>Bapt</name></author>
<content type="html"><?cs var:html_escape(post.html) ?></content>
<?cs each:tag = post.tags ?><category term="<?cs var:tag.name ?>" /><?cs /each ?>
<id><?cs var:url ?>post/<?cs var:post.filename ?></id>
<link rel="alternate" href="<?cs var:url ?>/post/<?cs var:post.filename ?>" />
<updated><?cs var:post.date ?></updated>
<published><?cs var:post.date ?></published>
</entry>
<?cs /each ?>
</feed>
| <?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title type="text"><?cs var:title ?></title>
<subtitle type="text"><?cs var:title ?></subtitle>
<id><?cs var:url ?>/</id>
<link rel="self" href="<?cs var:url ?><?cs var:CGI.RequestURI ?>" />
<link rel="alternate" type="text/html" href="<?cs var:url ?>" />
<updated><?cs var:gendate ?></updated>
<author><name><?cs var:author ?></name></author>
<generator uri="<?cs var:CBlog.url ?>" version="<?cs var:CBlog.version ?>"><?cs var:CBlog.version ?></generator>
<?cs each:post = Posts ?>
<entry>
<title type="text"><?cs var:post.title ?></title>
<author><name><?cs var:author ?></name></author>
<content type="html"><?cs var:html_escape(post.html) ?></content>
<?cs each:tag = post.tags ?><category term="<?cs var:tag.name ?>" /><?cs /each ?>
<id><?cs var:url ?>post/<?cs var:post.filename ?></id>
<link rel="alternate" href="<?cs var:url ?>/post/<?cs var:post.filename ?>" />
<updated><?cs var:post.date ?></updated>
<published><?cs var:post.date ?></published>
</entry>
<?cs /each ?>
</feed>
|
Change to show alert if Secrets.cs is not edited | using System;
using Prism.Mvvm;
using Prism.Navigation;
using Reactive.Bindings;
namespace BlueMonkey.ViewModels
{
/// <summary>
/// ViewModel for MainPage.
/// </summary>
public class MainPageViewModel : BindableBase
{
/// <summary>
/// NavigationService
/// </summary>
private readonly INavigationService _navigationService;
/// <summary>
/// Command of navigate next pages.
/// </summary>
public ReactiveCommand<string> NavigateCommand { get; }
/// <summary>
/// Initialize instance.
/// </summary>
/// <param name="navigationService"></param>
public MainPageViewModel(INavigationService navigationService)
{
_navigationService = navigationService;
NavigateCommand = new ReactiveCommand<string>();
NavigateCommand.Subscribe(Navigate);
}
/// <summary>
/// Navigate next page.
/// </summary>
/// <param name="uri"></param>
private void Navigate(string uri)
{
_navigationService.NavigateAsync(uri);
}
}
}
| using System;
using Prism.Mvvm;
using Prism.Navigation;
using Prism.Services;
using Reactive.Bindings;
namespace BlueMonkey.ViewModels
{
/// <summary>
/// ViewModel for MainPage.
/// </summary>
public class MainPageViewModel : BindableBase
{
/// <summary>
/// NavigationService
/// </summary>
private readonly INavigationService _navigationService;
/// <summary>
/// The page dialog service.
/// </summary>
private readonly IPageDialogService _pageDialogService;
/// <summary>
/// Command of navigate next pages.
/// </summary>
public ReactiveCommand<string> NavigateCommand { get; }
/// <summary>
/// Initialize instance.
/// </summary>
/// <param name="navigationService"></param>
/// <param name="pageDialogService"></param>
public MainPageViewModel(INavigationService navigationService, IPageDialogService pageDialogService)
{
_navigationService = navigationService;
_pageDialogService = pageDialogService;
NavigateCommand = new ReactiveCommand<string>();
NavigateCommand.Subscribe(Navigate);
}
/// <summary>
/// Navigate next page.
/// </summary>
/// <param name="uri"></param>
private async void Navigate(string uri)
{
if (Secrets.ServerUri.Contains("your"))
{
await _pageDialogService.DisplayAlertAsync(
"Invalid Server Uri",
"You should write actual ServerUri and ConnectionString to Secrets.cs",
"Close");
return;
}
await _navigationService.NavigateAsync(uri);
}
}
}
|
Use newly created vector object | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool
// Changes to this file will be lost if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public abstract class Component
{
private Vector2D position
{
get;
set;
}
}
| //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool
// Changes to this file will be lost if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public abstract class Component
{
private Vector position
{
get;
set;
}
}
|
Test fix for appveyor CS0840 | using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace ZendeskApi_v2.Models.Targets
{
public class BaseTarget
{
[JsonProperty("id")]
public long? Id { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("type")]
public virtual string Type { get; }
[JsonProperty("active")]
public bool Active { get; set; }
[JsonProperty("created_at")]
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTimeOffset? CreatedAt { get; set; }
}
} | using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace ZendeskApi_v2.Models.Targets
{
public class BaseTarget
{
[JsonProperty("id")]
public long? Id { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("type")]
public virtual string Type { get; private set; }
[JsonProperty("active")]
public bool Active { get; set; }
[JsonProperty("created_at")]
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTimeOffset? CreatedAt { get; set; }
}
} |
Fix issue of file opened via Finder doesn't always display. | using System;
using System.Drawing;
using MonoMac.Foundation;
using MonoMac.AppKit;
using MonoMac.ObjCRuntime;
using NLog;
using Radish.Support;
using System.IO;
namespace Radish
{
public partial class AppDelegate : NSApplicationDelegate
{
private static Logger logger = LogManager.GetCurrentClassLogger();
MainWindowController controller;
public AppDelegate()
{
}
public override void FinishedLaunching(NSObject notification)
{
var urlList = new NSFileManager().GetUrls(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomain.User);
Preferences.Load(Path.Combine(
urlList[0].Path,
"Preferences",
"com.rangic.Radish.json"));
if (controller == null)
{
controller = new MainWindowController();
controller.Window.MakeKeyAndOrderFront(this);
}
}
public override bool OpenFile(NSApplication sender, string filename)
{
logger.Info("OpenFile '{0}'", filename);
if (controller == null)
{
controller = new MainWindowController();
controller.Window.MakeKeyAndOrderFront(this);
}
return controller.OpenFolderOrFile(filename);
}
}
}
| using System;
using System.Drawing;
using MonoMac.Foundation;
using MonoMac.AppKit;
using MonoMac.ObjCRuntime;
using NLog;
using Radish.Support;
using System.IO;
namespace Radish
{
public partial class AppDelegate : NSApplicationDelegate
{
private static Logger logger = LogManager.GetCurrentClassLogger();
private MainWindowController controller;
private string filename;
public AppDelegate()
{
}
public override void FinishedLaunching(NSObject notification)
{
var urlList = new NSFileManager().GetUrls(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomain.User);
Preferences.Load(Path.Combine(
urlList[0].Path,
"Preferences",
"com.rangic.Radish.json"));
controller = new MainWindowController();
controller.Window.MakeKeyAndOrderFront(this);
if (filename != null)
{
controller.OpenFolderOrFile(filename);
}
}
public override bool OpenFile(NSApplication sender, string filename)
{
if (controller == null)
{
this.filename = filename;
logger.Info("OpenFile '{0}'", filename);
return true;
}
return controller.OpenFolderOrFile(filename);
}
}
}
|
Add action type for status | using System.Xml.Serialization;
namespace DevelopmentInProgress.DipState
{
public enum DipStateActionType
{
[XmlEnum("1")]
Entry,
[XmlEnum("2")]
Exit
}
}
| using System.Xml.Serialization;
namespace DevelopmentInProgress.DipState
{
public enum DipStateActionType
{
[XmlEnum("1")]
Status,
[XmlEnum("2")]
Entry,
[XmlEnum("3")]
Exit
}
}
|
Test target framework written as expected (characterise current lack of validation) | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Moq;
using NuGet.Common;
using NuGet.Extensions.Nuspec;
using NUnit.Framework;
namespace NuGet.Extensions.Tests.Nuspec
{
[TestFixture]
public class NuspecBuilderTests
{
[Test]
public void AssemblyNameReplacesNullDescription()
{
var console = new Mock<IConsole>();
const string anyAssemblyName = "any.assembly.name";
var nullDataSource = new Mock<INuspecDataSource>().Object;
var nuspecBuilder = new NuspecBuilder(anyAssemblyName);
nuspecBuilder.SetMetadata(nullDataSource, new List<ManifestDependency>());
nuspecBuilder.Save(console.Object);
var nuspecContents = File.ReadAllText(nuspecBuilder.FilePath);
Assert.That(nuspecContents, Contains.Substring("<description>" + anyAssemblyName + "</description>"));
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Moq;
using NuGet.Common;
using NuGet.Extensions.Nuspec;
using NuGet.Extensions.Tests.MSBuild;
using NUnit.Framework;
namespace NuGet.Extensions.Tests.Nuspec
{
[TestFixture]
public class NuspecBuilderTests
{
[Test]
public void AssemblyNameReplacesNullDescription()
{
var console = new Mock<IConsole>();
const string anyAssemblyName = "any.assembly.name";
var nullDataSource = new Mock<INuspecDataSource>().Object;
var nuspecBuilder = new NuspecBuilder(anyAssemblyName);
nuspecBuilder.SetMetadata(nullDataSource, new List<ManifestDependency>());
nuspecBuilder.Save(console.Object);
var nuspecContents = File.ReadAllText(nuspecBuilder.FilePath);
Assert.That(nuspecContents, Contains.Substring("<description>" + anyAssemblyName + "</description>"));
ConsoleMock.AssertConsoleHasNoErrorsOrWarnings(console);
}
[TestCase("net40")]
[TestCase("net35")]
[TestCase("notARealTargetFramework", Description = "Characterisation: There is no validation on the target framework")]
public void TargetFrameworkAppearsVerbatimInOutput(string targetFramework)
{
var console = new Mock<IConsole>();
var nuspecBuilder = new NuspecBuilder("anyAssemblyName");
var anyDependencies = new List<ManifestDependency>{new ManifestDependency {Id="anyDependency", Version = "0.0.0.0"}};
nuspecBuilder.SetDependencies(anyDependencies, targetFramework);
nuspecBuilder.Save(console.Object);
var nuspecContents = File.ReadAllText(nuspecBuilder.FilePath);
var expectedAssemblyGroupStartTag = string.Format("<group targetFramework=\"{0}\">", targetFramework);
Assert.That(nuspecContents, Contains.Substring(expectedAssemblyGroupStartTag));
ConsoleMock.AssertConsoleHasNoErrorsOrWarnings(console);
}
}
}
|
Fix bug in fixture with unescaped underscore in username | using System;
using System.Linq;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
namespace Telegram.Bot.Tests.Integ.Framework
{
internal static class Extensions
{
public static User GetUser(this Update update)
{
switch (update.Type)
{
case UpdateType.Message:
return update.Message.From;
case UpdateType.InlineQuery:
return update.InlineQuery.From;
case UpdateType.CallbackQuery:
return update.CallbackQuery.From;
case UpdateType.PreCheckoutQuery:
return update.PreCheckoutQuery.From;
case UpdateType.ShippingQuery:
return update.ShippingQuery.From;
case UpdateType.ChosenInlineResult:
return update.ChosenInlineResult.From;
default:
throw new ArgumentException("Unsupported update type {0}.", update.Type.ToString());
}
}
public static string GetTesterMentions(this UpdateReceiver updateReceiver)
{
return string.Join(", ",
updateReceiver.AllowedUsernames.Select(username => '@' + username)
);
}
}
}
| using System;
using System.Linq;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
namespace Telegram.Bot.Tests.Integ.Framework
{
internal static class Extensions
{
public static User GetUser(this Update update)
{
switch (update.Type)
{
case UpdateType.Message:
return update.Message.From;
case UpdateType.InlineQuery:
return update.InlineQuery.From;
case UpdateType.CallbackQuery:
return update.CallbackQuery.From;
case UpdateType.PreCheckoutQuery:
return update.PreCheckoutQuery.From;
case UpdateType.ShippingQuery:
return update.ShippingQuery.From;
case UpdateType.ChosenInlineResult:
return update.ChosenInlineResult.From;
default:
throw new ArgumentException("Unsupported update type {0}.", update.Type.ToString());
}
}
public static string GetTesterMentions(this UpdateReceiver updateReceiver)
{
return string.Join(", ",
updateReceiver.AllowedUsernames.Select(username => $"@{username}".Replace("_", "\\_"))
);
}
}
}
|
Improve network game object detection codes | using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Networking;
public static class UnityUtils
{
public static bool IsAnyKeyUp(KeyCode[] keys)
{
foreach (KeyCode key in keys)
{
if (Input.GetKeyUp(key))
return true;
}
return false;
}
public static bool IsAnyKeyDown(KeyCode[] keys)
{
foreach (KeyCode key in keys)
{
if (Input.GetKeyDown(key))
return true;
}
return false;
}
public static bool IsAnyKey(KeyCode[] keys)
{
foreach (KeyCode key in keys)
{
if (Input.GetKey(key))
return true;
}
return false;
}
public static bool IsHeadless()
{
return SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null;
}
public static bool TryGetByNetId<T>(NetworkInstanceId targetNetId, out T output) where T : Component
{
output = null;
GameObject foundObject = ClientScene.FindLocalObject(targetNetId);
if (foundObject == null)
return false;
output = foundObject.GetComponent<T>();
if (output == null)
return false;
return true;
}
}
| using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Networking;
public static class UnityUtils
{
public static bool IsAnyKeyUp(KeyCode[] keys)
{
foreach (KeyCode key in keys)
{
if (Input.GetKeyUp(key))
return true;
}
return false;
}
public static bool IsAnyKeyDown(KeyCode[] keys)
{
foreach (KeyCode key in keys)
{
if (Input.GetKeyDown(key))
return true;
}
return false;
}
public static bool IsAnyKey(KeyCode[] keys)
{
foreach (KeyCode key in keys)
{
if (Input.GetKey(key))
return true;
}
return false;
}
public static bool IsHeadless()
{
return SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null;
}
public static bool TryGetGameObjectByNetId(NetworkInstanceId targetNetId, out GameObject output)
{
output = null;
if (NetworkServer.active)
output = NetworkServer.FindLocalObject(targetNetId);
else
output = ClientScene.FindLocalObject(targetNetId);
if (output == null)
return false;
return true;
}
public static bool TryGetComponentByNetId<T>(NetworkInstanceId targetNetId, out T output) where T : Component
{
output = null;
GameObject foundObject = null;
if (TryGetGameObjectByNetId(targetNetId, out foundObject))
{
output = foundObject.GetComponent<T>();
if (output == null)
return false;
return true;
}
return false;
}
}
|
Change samples to use PostApplicationStart instead of pre. | using System;
using System.Diagnostics;
using System.Threading;
using System.Web.Routing;
using SignalR.Hosting.AspNet.Routing;
using SignalR.Samples.App_Start;
using SignalR.Samples.Hubs.DemoHub;
[assembly: WebActivator.PreApplicationStartMethod(typeof(Startup), "Start")]
namespace SignalR.Samples.App_Start
{
public class Startup
{
public static void Start()
{
ThreadPool.QueueUserWorkItem(_ =>
{
var connection = Global.Connections.GetConnection<Streaming.Streaming>();
var demoClients = Global.Connections.GetClients<DemoHub>();
while (true)
{
try
{
connection.Broadcast(DateTime.Now.ToString());
demoClients.fromArbitraryCode(DateTime.Now.ToString());
}
catch (Exception ex)
{
Trace.TraceError("SignalR error thrown in Streaming broadcast: {0}", ex);
}
Thread.Sleep(2000);
}
});
RouteTable.Routes.MapConnection<Raw.Raw>("raw", "raw/{*operation}");
RouteTable.Routes.MapConnection<Streaming.Streaming>("streaming", "streaming/{*operation}");
}
}
} | using System;
using System.Diagnostics;
using System.Threading;
using System.Web.Routing;
using SignalR.Hosting.AspNet.Routing;
using SignalR.Samples.App_Start;
using SignalR.Samples.Hubs.DemoHub;
[assembly: WebActivator.PostApplicationStartMethod(typeof(Startup), "Start")]
namespace SignalR.Samples.App_Start
{
public class Startup
{
public static void Start()
{
ThreadPool.QueueUserWorkItem(_ =>
{
var connection = Global.Connections.GetConnection<Streaming.Streaming>();
var demoClients = Global.Connections.GetClients<DemoHub>();
while (true)
{
try
{
connection.Broadcast(DateTime.Now.ToString());
demoClients.fromArbitraryCode(DateTime.Now.ToString());
}
catch (Exception ex)
{
Trace.TraceError("SignalR error thrown in Streaming broadcast: {0}", ex);
}
Thread.Sleep(2000);
}
});
RouteTable.Routes.MapConnection<Raw.Raw>("raw", "raw/{*operation}");
RouteTable.Routes.MapConnection<Streaming.Streaming>("streaming", "streaming/{*operation}");
}
}
} |
Remove range constraint in destiny tuner | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JLChnToZ.LuckyPlayer {
public class DestinyTuner<T> {
static DestinyTuner<T> defaultInstance;
public static DestinyTuner<T> Default {
get {
if(defaultInstance == null)
defaultInstance = new DestinyTuner<T>();
return defaultInstance;
}
}
double fineTuneOnSuccess;
public double FineTuneOnSuccess {
get { return fineTuneOnSuccess; }
set {
if(value < 0 || value > 1)
throw new ArgumentOutOfRangeException("Value must be between 0 and 1");
fineTuneOnSuccess = value;
}
}
public DestinyTuner() {
fineTuneOnSuccess = -0.0001;
}
public DestinyTuner(double fineTuneOnSuccess) {
FineTuneOnSuccess = fineTuneOnSuccess;
}
protected internal virtual void TuneDestinyOnSuccess(LuckyController<T> luckyControl) {
luckyControl.fineTune *= 1 + fineTuneOnSuccess;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JLChnToZ.LuckyPlayer {
public class DestinyTuner<T> {
static DestinyTuner<T> defaultInstance;
public static DestinyTuner<T> Default {
get {
if(defaultInstance == null)
defaultInstance = new DestinyTuner<T>();
return defaultInstance;
}
}
double fineTuneOnSuccess;
public double FineTuneOnSuccess {
get { return fineTuneOnSuccess; }
set { fineTuneOnSuccess = value; }
}
public DestinyTuner() {
fineTuneOnSuccess = -0.0001;
}
public DestinyTuner(double fineTuneOnSuccess) {
FineTuneOnSuccess = fineTuneOnSuccess;
}
protected internal virtual void TuneDestinyOnSuccess(LuckyController<T> luckyControl) {
luckyControl.fineTune *= 1 + fineTuneOnSuccess;
}
}
}
|
Make model to text asset so it can be loaded just like everything else | using System;
using System.Collections.Generic;
using UnityEngine;
using CNTK;
using UnityEngine.Events;
using System.Threading;
using UnityEngine.Assertions;
namespace UnityCNTK
{
/// <summary>
/// the non-generic base class for all model
/// only meant to be used for model management and GUI scripting, not in-game
/// </summary>
public class _Model : MonoBehaviour{
public UnityEvent OnModelLoaded;
public string relativeModelPath;
public Function function;
private bool _isReady = false;
public bool isReady { get; protected set; }
/// <summary>
/// Load the model automatically on start
/// </summary>
public bool LoadOnStart = true;
protected Thread thread;
public virtual void LoadModel()
{
Assert.IsNotNull(relativeModelPath);
var absolutePath = System.IO.Path.Combine(Environment.CurrentDirectory, relativeModelPath);
Thread loadThread = new Thread(() =>
{
Debug.Log("Started thread");
try
{
function = Function.Load(absolutePath, CNTKManager.device);
}
catch (Exception e)
{
Debug.LogError(e);
}
if (OnModelLoaded != null)
OnModelLoaded.Invoke();
isReady = true;
Debug.Log("Model Loaded");
});
loadThread.Start();
}
public void UnloadModel()
{
if (function != null)
{
function.Dispose();
}
}
}
}
| using System;
using System.Collections.Generic;
using UnityEngine;
using CNTK;
using UnityEngine.Events;
using System.Threading;
using UnityEngine.Assertions;
namespace UnityCNTK
{
/// <summary>
/// the non-generic base class for all model
/// only meant to be used for model management and GUI scripting, not in-game
/// </summary>
public class _Model : MonoBehaviour{
public UnityEvent OnModelLoaded;
public TextAsset rawModel;
public Function function;
private bool _isReady = false;
public bool isReady { get; protected set; }
/// <summary>
/// Load the model automatically on start
/// </summary>
public bool LoadOnStart = true;
protected Thread thread;
public virtual void LoadModel()
{
Assert.IsNotNull(rawModel);
Debug.Log("Started thread");
try
{
function = Function.Load(rawModel.bytes, CNTKManager.device);
}
catch (Exception e)
{
Debug.LogError(e);
}
if (OnModelLoaded != null)
OnModelLoaded.Invoke();
isReady = true;
Debug.Log("Model Loaded : " +rawModel.name);
}
public void UnloadModel()
{
if (function != null)
{
function.Dispose();
}
}
}
}
|
Build script, no dep on branch for now | public class BuildConfig
{
private const string Version = "0.3.0";
public readonly string SrcDir = "./src/";
public readonly string OutDir = "./build/";
public string Target { get; private set; }
public string SemVer { get; private set; }
public string BuildProfile { get; private set; }
public bool IsTeamCityBuild { get; private set; }
public static BuildConfig Create(
ICakeContext context,
BuildSystem buildSystem)
{
if (context == null)
throw new ArgumentNullException("context");
var target = context.Argument("target", "Default");
var branch = context.Argument("branch", string.Empty);
var branchIsRelease = branch.ToLower() == "release";
var buildRevision = context.Argument("buildrevision", "0");
return new BuildConfig
{
Target = target,
SemVer = Version + (branchIsRelease ? string.Empty : "-b" + buildRevision),
BuildProfile = context.Argument("configuration", "Release"),
IsTeamCityBuild = buildSystem.TeamCity.IsRunningOnTeamCity
};
}
} | public class BuildConfig
{
private const string Version = "0.4.0";
private const bool IsPreRelease = true;
public readonly string SrcDir = "./src/";
public readonly string OutDir = "./build/";
public string Target { get; private set; }
public string SemVer { get; private set; }
public string BuildProfile { get; private set; }
public bool IsTeamCityBuild { get; private set; }
public static BuildConfig Create(
ICakeContext context,
BuildSystem buildSystem)
{
if (context == null)
throw new ArgumentNullException("context");
var target = context.Argument("target", "Default");
var buildRevision = context.Argument("buildrevision", "0");
return new BuildConfig
{
Target = target,
SemVer = Version + (IsPreRelease ? buildRevision : "-b" + buildRevision),
BuildProfile = context.Argument("configuration", "Release"),
IsTeamCityBuild = buildSystem.TeamCity.IsRunningOnTeamCity
};
}
} |
Fix crash on super high bpm kiai sections | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Audio.Track;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Graphics.Containers;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Osu.Skinning.Default
{
public class KiaiFlash : BeatSyncedContainer
{
private const double fade_length = 80;
private const float flash_opacity = 0.25f;
public KiaiFlash()
{
EarlyActivationMilliseconds = 80;
Blending = BlendingParameters.Additive;
Child = new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.White,
Alpha = 0f,
};
}
protected override void OnNewBeat(int beatIndex, TimingControlPoint timingPoint, EffectControlPoint effectPoint, ChannelAmplitudes amplitudes)
{
if (!effectPoint.KiaiMode)
return;
Child
.FadeTo(flash_opacity, EarlyActivationMilliseconds, Easing.OutQuint)
.Then()
.FadeOut(timingPoint.BeatLength - fade_length, Easing.OutSine);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Audio.Track;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Graphics.Containers;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Osu.Skinning.Default
{
public class KiaiFlash : BeatSyncedContainer
{
private const double fade_length = 80;
private const float flash_opacity = 0.25f;
public KiaiFlash()
{
EarlyActivationMilliseconds = 80;
Blending = BlendingParameters.Additive;
Child = new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.White,
Alpha = 0f,
};
}
protected override void OnNewBeat(int beatIndex, TimingControlPoint timingPoint, EffectControlPoint effectPoint, ChannelAmplitudes amplitudes)
{
if (!effectPoint.KiaiMode)
return;
Child
.FadeTo(flash_opacity, EarlyActivationMilliseconds, Easing.OutQuint)
.Then()
.FadeOut(Math.Max(0, timingPoint.BeatLength - fade_length), Easing.OutSine);
}
}
}
|
Add whitespace to type enum definitions | using System.Collections.Generic;
using System.Net.Mail;
namespace StressMeasurementSystem.Models
{
public class Patient
{
#region Structs
public struct Name
{
public string Prefix { get; set; }
public string First { get; set; }
public string Middle { get; set; }
public string Last { get; set; }
public string Suffix { get; set; }
}
public struct Organization
{
public string Company { get; set; }
public string JobTitle { get; set; }
}
public struct PhoneNumber
{
public enum Type {Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other}
public string Number { get; set; }
public Type T { get; set; }
}
public struct Email
{
public enum Type {Home, Work, Other}
public MailAddress Address { get; set; }
public Type T { get; set; }
}
#endregion
#region Fields
private Name _name;
private uint _age;
private Organization _organization;
private List<PhoneNumber> _phoneNumbers;
private List<Email> _emails;
#endregion
#region Constructors
public Patient(Name name, uint age, Organization organization,
List<PhoneNumber> phoneNumbers, List<Email> emails)
{
_name = name;
_age = age;
_organization = organization;
_phoneNumbers = phoneNumbers;
_emails = emails;
}
#endregion
}
}
| using System.Collections.Generic;
using System.Net.Mail;
namespace StressMeasurementSystem.Models
{
public class Patient
{
#region Structs
public struct Name
{
public string Prefix { get; set; }
public string First { get; set; }
public string Middle { get; set; }
public string Last { get; set; }
public string Suffix { get; set; }
}
public struct Organization
{
public string Company { get; set; }
public string JobTitle { get; set; }
}
public struct PhoneNumber
{
public enum Type { Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other }
public string Number { get; set; }
public Type T { get; set; }
}
public struct Email
{
public enum Type { Home, Work, Other }
public MailAddress Address { get; set; }
public Type T { get; set; }
}
#endregion
#region Fields
private Name _name;
private uint _age;
private Organization _organization;
private List<PhoneNumber> _phoneNumbers;
private List<Email> _emails;
#endregion
#region Constructors
public Patient(Name name, uint age, Organization organization,
List<PhoneNumber> phoneNumbers, List<Email> emails)
{
_name = name;
_age = age;
_organization = organization;
_phoneNumbers = phoneNumbers;
_emails = emails;
}
#endregion
}
}
|
Fix incorrect default value in interface. | //Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
//Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
namespace osu.Framework.Graphics.Transformations
{
public interface ITransform
{
double Duration { get; }
bool IsAlive { get; }
double StartTime { get; set; }
double EndTime { get; set; }
void Apply(Drawable d);
ITransform Clone();
ITransform CloneReverse();
void Reverse();
void Loop(double delay, int loopCount = 0);
}
} | //Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
//Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
namespace osu.Framework.Graphics.Transformations
{
public interface ITransform
{
double Duration { get; }
bool IsAlive { get; }
double StartTime { get; set; }
double EndTime { get; set; }
void Apply(Drawable d);
ITransform Clone();
ITransform CloneReverse();
void Reverse();
void Loop(double delay, int loopCount = -1);
}
} |
Fix typo in exception message | namespace CommonDomain.Core
{
using System.Globalization;
internal static class ExtensionMethods
{
public static string FormatWith(this string format, params object[] args)
{
return string.Format(CultureInfo.InvariantCulture, format ?? string.Empty, args);
}
public static void ThrowHandlerNotFound(this IAggregate aggregate, object eventMessage)
{
string exceptionMessage =
"Aggregate of type '{0}' raised an event of type '{1}' but not handler could be found to handle the message."
.FormatWith(aggregate.GetType().Name, eventMessage.GetType().Name);
throw new HandlerForDomainEventNotFoundException(exceptionMessage);
}
}
} | namespace CommonDomain.Core
{
using System.Globalization;
internal static class ExtensionMethods
{
public static string FormatWith(this string format, params object[] args)
{
return string.Format(CultureInfo.InvariantCulture, format ?? string.Empty, args);
}
public static void ThrowHandlerNotFound(this IAggregate aggregate, object eventMessage)
{
string exceptionMessage =
"Aggregate of type '{0}' raised an event of type '{1}' but no handler could be found to handle the message."
.FormatWith(aggregate.GetType().Name, eventMessage.GetType().Name);
throw new HandlerForDomainEventNotFoundException(exceptionMessage);
}
}
} |
Change the switch to set/update key to "/newkey:" | using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace PCSBingMapKeyManager
{
class Program
{
private const string NewKeySwitch = "/a:";
static void Main(string[] args)
{
if (args.Length > 1 || args.Any() && !args[0].StartsWith(NewKeySwitch))
{
Usage();
return;
}
var manager = new BingMapKeyManager();
if (!args.Any())
{
var key = manager.GetAsync().Result;
if (string.IsNullOrEmpty(key))
{
Console.WriteLine("No bing map key set");
}
else
{
Console.WriteLine($"Bing map key = {key}");
}
Console.WriteLine($"\nHint: Use {NewKeySwitch}<key> to set or update the key");
}
else
{
var key = args[0].Substring(NewKeySwitch.Length);
if (manager.SetAsync(key).Result)
{
Console.WriteLine($"Bing map key set as '{key}'");
}
}
}
private static void Usage()
{
var entry = Path.GetFileName(Assembly.GetEntryAssembly().CodeBase);
Console.WriteLine($"Usage: {entry} [{NewKeySwitch}<new key>]");
}
}
}
| using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace PCSBingMapKeyManager
{
class Program
{
private const string NewKeySwitch = "/newkey:";
static void Main(string[] args)
{
if (args.Length > 1 || args.Any() && !args[0].StartsWith(NewKeySwitch))
{
Usage();
return;
}
var manager = new BingMapKeyManager();
if (!args.Any())
{
var key = manager.GetAsync().Result;
if (string.IsNullOrEmpty(key))
{
Console.WriteLine("No bing map key set");
}
else
{
Console.WriteLine($"Bing map key = {key}");
}
Console.WriteLine($"\nHint: Use {NewKeySwitch}<key> to set or update the key");
}
else
{
var key = args[0].Substring(NewKeySwitch.Length);
if (manager.SetAsync(key).Result)
{
Console.WriteLine($"Bing map key set as '{key}'");
}
}
}
private static void Usage()
{
var entry = Path.GetFileName(Assembly.GetEntryAssembly().CodeBase);
Console.WriteLine($"Usage: {entry} [{NewKeySwitch}<new key>]");
}
}
}
|
Use NaturalStringComparer to compare titles | using NMaier.sdlna.Server;
namespace NMaier.sdlna.FileMediaServer.Comparers
{
class TitleComparer : IItemComparer
{
public virtual string Description
{
get { return "Sort alphabetically"; }
}
public virtual string Name
{
get { return "title"; }
}
public virtual int Compare(IMediaItem x, IMediaItem y)
{
return x.Title.ToLower().CompareTo(y.Title.ToLower());
}
}
} | using System;
using System.Collections;
using NMaier.sdlna.Server;
using NMaier.sdlna.Util;
namespace NMaier.sdlna.FileMediaServer.Comparers
{
class TitleComparer : IItemComparer, IComparer
{
private static StringComparer comp = new NaturalStringComparer();
public virtual string Description
{
get { return "Sort alphabetically"; }
}
public virtual string Name
{
get { return "title"; }
}
public virtual int Compare(IMediaItem x, IMediaItem y)
{
return comp.Compare(x.Title, y.Title);
}
public int Compare(object x, object y)
{
return comp.Compare(x, y);
}
}
} |
Make IEnumerable.IsNullOrEmpty extension method generic | //
// EnumerableExtensions.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2016 Roman M. Yagodin
//
// This program 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.
//
// This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
using System.Collections.Generic;
using System.Linq;
namespace R7.University.ModelExtensions
{
public static class EnumerableExtensions
{
public static bool IsNullOrEmpty (this IEnumerable<object> enumerable)
{
return enumerable == null || !enumerable.Any ();
}
}
}
| //
// EnumerableExtensions.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2016 Roman M. Yagodin
//
// This program 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.
//
// This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
using System.Collections.Generic;
using System.Linq;
namespace R7.University.ModelExtensions
{
public static class EnumerableExtensions
{
// TODO: Move to the base library
public static bool IsNullOrEmpty<T> (this IEnumerable<T> enumerable)
{
return enumerable == null || !enumerable.Any ();
}
}
}
|
Update MarkdownSnippets API to use new DirectoryMarkdownProcessor | using MarkdownSnippets;
using Xunit;
public class DocoUpdater
{
[Fact]
public void Run()
{
GitHubMarkdownProcessor.RunForFilePath();
}
} | using MarkdownSnippets;
using Xunit;
public class DocoUpdater
{
[Fact]
public void Run()
{
DirectoryMarkdownProcessor.RunForFilePath();
}
} |
Return result when dispatch a command | using Bartender.Tests.Context;
using Moq;
using Xunit;
namespace Bartender.Tests
{
public class AsyncCommandDispatcherTests : DispatcherTests
{
[Fact]
public async void ShouldHandleCommandOnce_WhenCallDispatchAsyncMethod()
{
await AsyncCommandDispatcher.DispatchAsync<Command, Result>(Command);
MockedAsyncCommandHandler.Verify(x => x.HandleAsync(It.IsAny<Command>()), Times.Once);
}
[Fact]
public async void ShouldHandleCommandOnce_WhenCallDispatchAsyncMethodWithoutResult()
{
await AsyncCommandDispatcher.DispatchAsync<Command>(Command);
MockedAsyncCommandWithoutResultHandler.Verify(x => x.HandleAsync(It.IsAny<Command>()), Times.Once);
}
}
} | using Bartender.Tests.Context;
using Moq;
using Shouldly;
using Xunit;
namespace Bartender.Tests
{
public class AsyncCommandDispatcherTests : DispatcherTests
{
[Fact]
public async void ShouldHandleCommandOnce_WhenCallDispatchAsyncMethod()
{
await AsyncCommandDispatcher.DispatchAsync<Command, Result>(Command);
MockedAsyncCommandHandler.Verify(x => x.HandleAsync(It.IsAny<Command>()), Times.Once);
}
[Fact]
public async void ShouldHandleCommandOnce_WhenCallDispatchAsyncMethodWithoutResult()
{
await AsyncCommandDispatcher.DispatchAsync<Command>(Command);
MockedAsyncCommandWithoutResultHandler.Verify(x => x.HandleAsync(It.IsAny<Command>()), Times.Once);
}
[Fact]
public async void ShouldReturnResult_WhenCallDispatchMethod()
{
var result = await AsyncCommandDispatcher.DispatchAsync<Command, Result>(Command);
result.ShouldBeSameAs(Result);
}
}
} |
Load comparer assembly from bytes | using System;
using System.IO;
using System.Reflection;
namespace Blueprint41.Modeller.Schemas
{
public abstract class DatastoreModelComparer
{
static public DatastoreModelComparer Instance { get { return instance.Value; } }
static private Lazy<DatastoreModelComparer> instance = new Lazy<DatastoreModelComparer>(delegate()
{
string dll = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Blueprint41.Modeller.Compare.dll");
if (!File.Exists(dll))
return null;
Assembly a = Assembly.LoadFile(dll);
Type t = a.GetType("Blueprint41.Modeller.Schemas.DatastoreModelComparerImpl");
return (DatastoreModelComparer)Activator.CreateInstance(t);
}, true);
public abstract void GenerateUpgradeScript(modeller model, string storagePath);
}
}
| using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Blueprint41.Modeller.Schemas
{
public abstract class DatastoreModelComparer
{
public static DatastoreModelComparer Instance { get { return instance.Value; } }
private static Lazy<DatastoreModelComparer> instance = new Lazy<DatastoreModelComparer>(delegate ()
{
string dll = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Blueprint41.Modeller.Compare.dll");
if (!File.Exists(dll))
return null;
byte[] assembly = File.ReadAllBytes(dll);
Assembly asm = Assembly.Load(assembly);
Type type = asm.GetTypes().First(x => x.Name == "DatastoreModelComparerImpl");
return (DatastoreModelComparer)Activator.CreateInstance(type);
}, true);
public abstract void GenerateUpgradeScript(modeller model, string storagePath);
}
}
|
Use MSBuild for Build and Pack | using System.Xml.Linq;
var target = Argument<string>("target", "Default");
var configuration = Argument<string>("configuration", "Release");
var projectName = "WeakEvent";
var libraryProject = $"./{projectName}/{projectName}.csproj";
var testProject = $"./{projectName}.Tests/{projectName}.Tests.csproj";
var outDir = $"./{projectName}/bin/{configuration}";
Task("Clean")
.Does(() =>
{
CleanDirectory(outDir);
});
Task("Restore").Does(DotNetCoreRestore);
Task("Build")
.IsDependentOn("Clean")
.IsDependentOn("Restore")
.Does(() =>
{
DotNetCoreBuild(".", new DotNetCoreBuildSettings { Configuration = configuration });
});
Task("Test")
.IsDependentOn("Build")
.Does(() =>
{
DotNetCoreTest(testProject, new DotNetCoreTestSettings { Configuration = configuration });
});
Task("Pack")
.IsDependentOn("Test")
.Does(() =>
{
DotNetCorePack(libraryProject, new DotNetCorePackSettings { Configuration = configuration });
});
Task("Push")
.IsDependentOn("Pack")
.Does(() =>
{
var doc = XDocument.Load(libraryProject);
string version = doc.Root.Elements("PropertyGroup").Elements("Version").First().Value;
string package = $"{projectName}/bin/{configuration}/{projectName}.{version}.nupkg";
NuGetPush(package, new NuGetPushSettings());
});
Task("Default")
.IsDependentOn("Pack");
RunTarget(target);
| using System.Xml.Linq;
var target = Argument<string>("target", "Default");
var configuration = Argument<string>("configuration", "Release");
var projectName = "WeakEvent";
var solution = $"{projectName}.sln";
var libraryProject = $"./{projectName}/{projectName}.csproj";
var testProject = $"./{projectName}.Tests/{projectName}.Tests.csproj";
var outDir = $"./{projectName}/bin/{configuration}";
Task("Clean")
.Does(() =>
{
CleanDirectory(outDir);
});
Task("Restore")
.Does(() => RunMSBuildTarget(solution, "Restore"));
Task("Build")
.IsDependentOn("Clean")
.IsDependentOn("Restore")
.Does(() => RunMSBuildTarget(solution, "Build"));
Task("Test")
.IsDependentOn("Build")
.Does(() =>
{
DotNetCoreTest(testProject, new DotNetCoreTestSettings { Configuration = configuration });
});
Task("Pack")
.IsDependentOn("Test")
.Does(() => RunMSBuildTarget(libraryProject, "Pack"));
Task("Push")
.IsDependentOn("Pack")
.Does(() =>
{
var doc = XDocument.Load(libraryProject);
string version = doc.Root.Elements("PropertyGroup").Elements("Version").First().Value;
string package = $"{projectName}/bin/{configuration}/{projectName}.{version}.nupkg";
NuGetPush(package, new NuGetPushSettings());
});
Task("Default")
.IsDependentOn("Pack");
void RunMSBuildTarget(string projectOrSolution, string target)
{
MSBuild(projectOrSolution, new MSBuildSettings
{
Targets = { target },
Configuration = configuration
});
}
RunTarget(target);
|
Fix formatting / usings in 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 osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Configuration;
using osu.Framework.Platform;
namespace osu.Framework.Tests.Visual.Platform
{
public class TestSceneAllowSuspension : FrameworkTestScene
{
private Bindable<bool> allowSuspension;
[BackgroundDependencyLoader]
private void load(GameHost host)
{
allowSuspension = host.AllowScreenSuspension.GetBoundCopy();
}
protected override void LoadComplete()
{
base.LoadComplete();
AddToggleStep("Toggle Suspension", b =>
{
allowSuspension.Value = b;
}
);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Platform;
namespace osu.Framework.Tests.Visual.Platform
{
public class TestSceneAllowSuspension : FrameworkTestScene
{
private Bindable<bool> allowSuspension;
[BackgroundDependencyLoader]
private void load(GameHost host)
{
allowSuspension = host.AllowScreenSuspension.GetBoundCopy();
}
protected override void LoadComplete()
{
base.LoadComplete();
AddToggleStep("Toggle Suspension", b => allowSuspension.Value = b);
}
}
}
|
Set default values for filter model | namespace Interapp.Services.Common
{
public class FilterModel
{
public string OrderBy { get; set; }
public string Order { get; set; }
public int Page { get; set; }
public int PageSize { get; set; }
public string Filter { get; set; }
}
}
| namespace Interapp.Services.Common
{
public class FilterModel
{
public FilterModel()
{
this.Page = 1;
this.PageSize = 10;
}
public string OrderBy { get; set; }
public string Order { get; set; }
public int Page { get; set; }
public int PageSize { get; set; }
public string Filter { get; set; }
}
}
|
Use XUnit v2 runner in Cake instead of XUnit v1 | #tool "nuget:?package=xunit.runners&version=1.9.2"
var config = Argument("configuration", "Release");
var runEnvironment = Argument("runenv", "local");
var buildDir = Directory("./Titan/bin/") + Directory(config);
var testDir = Directory("./TitanTest/bin/") + Directory(config);
Task("Clean")
.Does(() =>
{
CleanDirectory(buildDir);
});
Task("Restore-NuGet-Packages")
.IsDependentOn("Clean")
.Does(() =>
{
NuGetRestore("./Titan.sln");
});
Task("Build")
.IsDependentOn("Restore-NuGet-Packages")
.Does(() =>
{
if(IsRunningOnWindows())
{
// Use MSBuild
MSBuild("./Titan.sln", settings => settings.SetConfiguration(config));
}
else
{
// Use XBuild
XBuild("./Titan.sln", settings => settings.SetConfiguration(config));
}
});
Task("Run-Unit-Tests")
.IsDependentOn("Build")
.Does(() =>
{
XUnit(GetFiles("./TitanTest/bin/" + config + "/TitanTest.dll"), new XUnitSettings()
{
OutputDirectory = "./TitanTest/bin/" + config + "/results"
});
});
if(runEnvironment.ToLower() == "ci") {
Task("Default").IsDependentOn("Run-Unit-Tests");
} else {
Task("Default").IsDependentOn("Build");
}
RunTarget("Default");
| #tool "nuget:?package=xunit.runner.console"
var config = Argument("configuration", "Release");
var runEnvironment = Argument("runenv", "local");
var buildDir = Directory("./Titan/bin/") + Directory(config);
var testDir = Directory("./TitanTest/bin/") + Directory(config);
Task("Clean")
.Does(() =>
{
CleanDirectory(buildDir);
});
Task("Restore-NuGet-Packages")
.IsDependentOn("Clean")
.Does(() =>
{
NuGetRestore("./Titan.sln");
});
Task("Build")
.IsDependentOn("Restore-NuGet-Packages")
.Does(() =>
{
if(IsRunningOnWindows())
{
// Use MSBuild
MSBuild("./Titan.sln", settings => settings.SetConfiguration(config));
}
else
{
// Use XBuild
XBuild("./Titan.sln", settings => settings.SetConfiguration(config));
}
});
Task("Run-Unit-Tests")
.IsDependentOn("Build")
.Does(() =>
{
XUnit2(GetFiles("./TitanTest/bin/" + config + "/Titan*.dll"), new XUnit2Settings()
{
Parallelism = ParallelismOption.All,
OutputDirectory = "./TitanTest/bin/" + config + "/results"
});
});
if(runEnvironment.ToLower() == "ci") {
Task("Default").IsDependentOn("Run-Unit-Tests");
} else {
Task("Default").IsDependentOn("Build");
}
RunTarget("Default");
|
Increase toleranceSeconds in SafeWait_Timeout test | using System;
using System.Threading;
using NUnit.Framework;
namespace Atata.WebDriverExtras.Tests
{
[TestFixture]
[Parallelizable(ParallelScope.None)]
public class SafeWaitTests
{
private SafeWait<object> wait;
[SetUp]
public void SetUp()
{
wait = new SafeWait<object>(new object())
{
Timeout = TimeSpan.FromSeconds(.3),
PollingInterval = TimeSpan.FromSeconds(.05)
};
}
[Test]
public void SafeWait_Success_Immediate()
{
using (StopwatchAsserter.Within(0, .01))
wait.Until(_ =>
{
return true;
});
}
[Test]
public void SafeWait_Timeout()
{
using (StopwatchAsserter.Within(.3, .01))
wait.Until(_ =>
{
return false;
});
}
[Test]
public void SafeWait_PollingInterval()
{
using (StopwatchAsserter.Within(.3, .2))
wait.Until(_ =>
{
Thread.Sleep(TimeSpan.FromSeconds(.1));
return false;
});
}
[Test]
public void SafeWait_PollingInterval_GreaterThanTimeout()
{
wait.PollingInterval = TimeSpan.FromSeconds(1);
using (StopwatchAsserter.Within(.3, .015))
wait.Until(_ =>
{
return false;
});
}
}
}
| using System;
using System.Threading;
using NUnit.Framework;
namespace Atata.WebDriverExtras.Tests
{
[TestFixture]
[Parallelizable(ParallelScope.None)]
public class SafeWaitTests
{
private SafeWait<object> wait;
[SetUp]
public void SetUp()
{
wait = new SafeWait<object>(new object())
{
Timeout = TimeSpan.FromSeconds(.3),
PollingInterval = TimeSpan.FromSeconds(.05)
};
}
[Test]
public void SafeWait_Success_Immediate()
{
using (StopwatchAsserter.Within(0, .01))
wait.Until(_ =>
{
return true;
});
}
[Test]
public void SafeWait_Timeout()
{
using (StopwatchAsserter.Within(.3, .015))
wait.Until(_ =>
{
return false;
});
}
[Test]
public void SafeWait_PollingInterval()
{
using (StopwatchAsserter.Within(.3, .2))
wait.Until(_ =>
{
Thread.Sleep(TimeSpan.FromSeconds(.1));
return false;
});
}
[Test]
public void SafeWait_PollingInterval_GreaterThanTimeout()
{
wait.PollingInterval = TimeSpan.FromSeconds(1);
using (StopwatchAsserter.Within(.3, .015))
wait.Until(_ =>
{
return false;
});
}
}
}
|
Add IsDependent and GuardianId to patient profile | #region Copyright
// Copyright 2016 SnapMD, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
namespace SnapMD.ConnectedCare.ApiModels
{
/// <summary>
/// Represents patient details for administrator patient lists.
/// </summary>
public class PatientAccountInfo
{
public int PatientId { get; set; }
public int? UserId { get; set; }
public string ProfileImagePath { get; set; }
public string FullName { get; set; }
public string Phone { get; set; }
public bool IsAuthorized { get; set; }
public PatientAccountStatus Status { get; set; }
public string Email { get; set; }
}
}
| #region Copyright
// Copyright 2016 SnapMD, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
namespace SnapMD.ConnectedCare.ApiModels
{
/// <summary>
/// Represents patient details for administrator patient lists.
/// </summary>
public class PatientAccountInfo
{
public int PatientId { get; set; }
public int? UserId { get; set; }
public string ProfileImagePath { get; set; }
public string FullName { get; set; }
public string Phone { get; set; }
public bool IsAuthorized { get; set; }
public PatientAccountStatus Status { get; set; }
public string IsDependent { get; set; }
public int? GuardianId { get; set; }
public string Email { get; set; }
}
}
|
Make parallax container work with global mouse state (so it ignores bounds checks). | using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics;
using osu.Framework.Input;
using OpenTK;
using osu.Framework;
using osu.Framework.Allocation;
namespace osu.Game.Graphics.Containers
{
class ParallaxContainer : Container
{
public float ParallaxAmount = 0.02f;
public override bool Contains(Vector2 screenSpacePos) => true;
public ParallaxContainer()
{
RelativeSizeAxes = Axes.Both;
AddInternal(content = new Container
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre
});
}
private Container content;
protected override Container<Drawable> Content => content;
protected override bool OnMouseMove(InputState state)
{
content.Position = (state.Mouse.Position - DrawSize / 2) * ParallaxAmount;
return base.OnMouseMove(state);
}
protected override void Update()
{
base.Update();
content.Scale = new Vector2(1 + ParallaxAmount);
}
}
}
| using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics;
using osu.Framework.Input;
using OpenTK;
using osu.Framework;
using osu.Framework.Allocation;
namespace osu.Game.Graphics.Containers
{
class ParallaxContainer : Container
{
public float ParallaxAmount = 0.02f;
public override bool Contains(Vector2 screenSpacePos) => true;
public ParallaxContainer()
{
RelativeSizeAxes = Axes.Both;
AddInternal(content = new Container
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre
});
}
private Container content;
private InputManager input;
protected override Container<Drawable> Content => content;
[BackgroundDependencyLoader]
private void load(UserInputManager input)
{
this.input = input;
}
protected override void Update()
{
base.Update();
content.Position = (input.CurrentState.Mouse.Position - DrawSize / 2) * ParallaxAmount;
content.Scale = new Vector2(1 + ParallaxAmount);
}
}
}
|
Reorder screen tab control items | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.ComponentModel;
namespace osu.Game.Screens.Edit.Screens
{
public enum EditorScreenMode
{
[Description("compose")]
Compose,
[Description("design")]
Design,
[Description("timing")]
Timing,
[Description("song")]
SongSetup
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.ComponentModel;
namespace osu.Game.Screens.Edit.Screens
{
public enum EditorScreenMode
{
[Description("setup")]
SongSetup,
[Description("compose")]
Compose,
[Description("design")]
Design,
[Description("timing")]
Timing,
}
}
|
Update metadata resource to use callback instead of console.log | using System.Collections.Generic;
using System.Linq;
using Glimpse.Core2.Extensibility;
using Glimpse.Core2.Framework;
using Glimpse.Core2.ResourceResult;
namespace Glimpse.Core2.Resource
{
public class Metadata : IResource
{
internal const string InternalName = "metadata.js";
private const int CacheDuration = 12960000; //150 days
public string Name
{
get { return InternalName; }
}
public IEnumerable<string> ParameterKeys
{
get { return new[] { ResourceParameterKey.VersionNumber }; }
}
public IResourceResult Execute(IResourceContext context)
{
var metadata = context.PersistanceStore.GetMetadata();
if (metadata == null)
return new StatusCodeResourceResult(404);
return new JsonResourceResult(metadata, "console.log", CacheDuration, CacheSetting.Public);
}
}
} | using System.Collections.Generic;
using System.Linq;
using Glimpse.Core2.Extensibility;
using Glimpse.Core2.Framework;
using Glimpse.Core2.ResourceResult;
namespace Glimpse.Core2.Resource
{
public class Metadata : IResource
{
internal const string InternalName = "metadata.js";
private const int CacheDuration = 12960000; //150 days
public string Name
{
get { return InternalName; }
}
public IEnumerable<string> ParameterKeys
{
get { return new[] { ResourceParameterKey.VersionNumber, ResourceParameterKey.Callback }; }
}
public IResourceResult Execute(IResourceContext context)
{
var metadata = context.PersistanceStore.GetMetadata();
if (metadata == null)
return new StatusCodeResourceResult(404);
return new JsonResourceResult(metadata, context.Parameters[ResourceParameterKey.Callback], CacheDuration, CacheSetting.Public);
}
}
} |
Fix "Countdown" widget "EndDateTime" read only | using System;
using DesktopWidgets.Classes;
namespace DesktopWidgets.Widgets.CountdownClock
{
public class Settings : WidgetClockSettingsBase
{
public DateTime EndDateTime { get; } = DateTime.Now;
}
} | using System;
using DesktopWidgets.Classes;
namespace DesktopWidgets.Widgets.CountdownClock
{
public class Settings : WidgetClockSettingsBase
{
public DateTime EndDateTime { get; set; } = DateTime.Now;
}
} |
Add default database names to connectionfactory.cs | using System;
using System.Data;
using System.IO;
namespace Tests.Daterpillar.Helper
{
public static class ConnectionFactory
{
public static IDbConnection CreateMySQLConnection(string database = null)
{
var connStr = new MySql.Data.MySqlClient.MySqlConnectionStringBuilder("");
if (!string.IsNullOrEmpty(database)) connStr.Database = database;
return new MySql.Data.MySqlClient.MySqlConnection(connStr.ConnectionString);
}
public static IDbConnection CreateMSSQLConnection(string database = null)
{
var connStr = new System.Data.SqlClient.SqlConnectionStringBuilder("");
if (!string.IsNullOrEmpty(database)) connStr.Add("database", database);
return new System.Data.SqlClient.SqlConnection(connStr.ConnectionString);
}
public static IDbConnection CreateSQLiteConnection(string filePath = "")
{
if (!File.Exists(filePath))
{
filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "daterpillar-test.db3");
System.Data.SQLite.SQLiteConnection.CreateFile(filePath);
}
var connStr = new System.Data.SQLite.SQLiteConnectionStringBuilder() { DataSource = filePath };
return new System.Data.SQLite.SQLiteConnection(connStr.ConnectionString);
}
}
} | using System;
using System.Data;
using System.IO;
namespace Tests.Daterpillar.Helper
{
public static class ConnectionFactory
{
public static IDbConnection CreateSQLiteConnection(string filePath = "")
{
if (!File.Exists(filePath))
{
filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "daterpillar-test.db3");
System.Data.SQLite.SQLiteConnection.CreateFile(filePath);
}
var connStr = new System.Data.SQLite.SQLiteConnectionStringBuilder() { DataSource = filePath };
return new System.Data.SQLite.SQLiteConnection(connStr.ConnectionString);
}
public static IDbConnection CreateMySQLConnection(string database = "daterpillar")
{
var connStr = new MySql.Data.MySqlClient.MySqlConnectionStringBuilder(ConnectionString.GetMySQLServerConnectionString());
if (!string.IsNullOrEmpty(database)) connStr.Database = database;
return new MySql.Data.MySqlClient.MySqlConnection(connStr.ConnectionString);
}
public static IDbConnection CreateMSSQLConnection(string database = "daterpillar")
{
var connStr = new System.Data.SqlClient.SqlConnectionStringBuilder(ConnectionString.GetSQLServerConnectionString());
if (!string.IsNullOrEmpty(database)) connStr.Add("database", database);
return new System.Data.SqlClient.SqlConnection(connStr.ConnectionString);
}
}
} |
Fix test scene using local beatmap | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Testing;
using osu.Game.Audio;
using osu.Game.Beatmaps;
using osu.Game.IO.Archives;
using osu.Game.Tests.Resources;
using osu.Game.Tests.Visual;
namespace osu.Game.Tests.Skins
{
[HeadlessTest]
public class TestSceneBeatmapSkinResources : OsuTestScene
{
[Resolved]
private BeatmapManager beatmaps { get; set; }
private WorkingBeatmap beatmap;
[BackgroundDependencyLoader]
private void load()
{
var imported = beatmaps.Import(new ZipArchiveReader(TestResources.OpenResource("Archives/ogg-beatmap.osz"))).Result;
beatmap = beatmaps.GetWorkingBeatmap(imported.Beatmaps[0]);
}
[Test]
public void TestRetrieveOggSample() => AddAssert("sample is non-null", () => beatmap.Skin.GetSample(new SampleInfo("sample")) != null);
[Test]
public void TestRetrieveOggTrack() => AddAssert("track is non-null", () => MusicController.CurrentTrack.IsDummyDevice == 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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Testing;
using osu.Game.Audio;
using osu.Game.Beatmaps;
using osu.Game.IO.Archives;
using osu.Game.Tests.Resources;
using osu.Game.Tests.Visual;
namespace osu.Game.Tests.Skins
{
[HeadlessTest]
public class TestSceneBeatmapSkinResources : OsuTestScene
{
[Resolved]
private BeatmapManager beatmaps { get; set; }
[BackgroundDependencyLoader]
private void load()
{
var imported = beatmaps.Import(new ZipArchiveReader(TestResources.OpenResource("Archives/ogg-beatmap.osz"))).Result;
Beatmap.Value = beatmaps.GetWorkingBeatmap(imported.Beatmaps[0]);
}
[Test]
public void TestRetrieveOggSample() => AddAssert("sample is non-null", () => Beatmap.Value.Skin.GetSample(new SampleInfo("sample")) != null);
[Test]
public void TestRetrieveOggTrack() => AddAssert("track is non-null", () => MusicController.CurrentTrack.IsDummyDevice == false);
}
}
|
Fix potential crash in tests when attempting to lookup key bindings in cases the lookup is not available | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Game.Configuration
{
[ExcludeFromDynamicCompile]
public class DevelopmentOsuConfigManager : OsuConfigManager
{
protected override string Filename => base.Filename.Replace(".ini", ".dev.ini");
public DevelopmentOsuConfigManager(Storage storage)
: base(storage)
{
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Game.Configuration
{
[ExcludeFromDynamicCompile]
public class DevelopmentOsuConfigManager : OsuConfigManager
{
protected override string Filename => base.Filename.Replace(".ini", ".dev.ini");
public DevelopmentOsuConfigManager(Storage storage)
: base(storage)
{
LookupKeyBindings = _ => "unknown";
LookupSkinName = _ => "unknown";
}
}
}
|
Change StatusUpdater job to run every hour. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Common.Log;
using CompetitionPlatform.Data.AzureRepositories.Log;
using Quartz;
using Quartz.Impl;
namespace CompetitionPlatform.ScheduledJobs
{
public static class JobScheduler
{
public static async void Start(string connectionString, ILog log)
{
var schedFact = new StdSchedulerFactory();
var sched = await schedFact.GetScheduler();
await sched.Start();
var job = JobBuilder.Create<ProjectStatusIpdaterJob>()
.WithIdentity("myJob", "group1")
.Build();
var trigger = TriggerBuilder.Create()
.WithIdentity("myTrigger", "group1")
.WithSimpleSchedule(x => x
.WithIntervalInSeconds(50)
.RepeatForever())
.Build();
job.JobDataMap["connectionString"] = connectionString;
job.JobDataMap["log"] = log;
await sched.ScheduleJob(job, trigger);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Common.Log;
using CompetitionPlatform.Data.AzureRepositories.Log;
using Quartz;
using Quartz.Impl;
namespace CompetitionPlatform.ScheduledJobs
{
public static class JobScheduler
{
public static async void Start(string connectionString, ILog log)
{
var schedFact = new StdSchedulerFactory();
var sched = await schedFact.GetScheduler();
await sched.Start();
var job = JobBuilder.Create<ProjectStatusIpdaterJob>()
.WithIdentity("myJob", "group1")
.Build();
var trigger = TriggerBuilder.Create()
.WithIdentity("myTrigger", "group1")
.WithSimpleSchedule(x => x
.WithIntervalInHours(1)
.RepeatForever())
.Build();
job.JobDataMap["connectionString"] = connectionString;
job.JobDataMap["log"] = log;
await sched.ScheduleJob(job, trigger);
}
}
}
|
Fix new office name clearing after adding | using RealEstateAgencyFranchise.Database;
using Starcounter;
namespace RealEstateAgencyFranchise
{
partial class CorporationJson : Json
{
static CorporationJson()
{
DefaultTemplate.Offices.ElementType.InstanceType = typeof(AgencyOfficeJson);
}
void Handle(Input.SaveTrigger action)
{
Transaction.Commit();
}
void Handle(Input.NewOfficeTrigger action)
{
new Office()
{
Corporation = this.Data as Corporation,
Address = new Address(),
Trend = 0,
Name = this.NewOfficeName
};
}
}
}
| using RealEstateAgencyFranchise.Database;
using Starcounter;
namespace RealEstateAgencyFranchise
{
partial class CorporationJson : Json
{
static CorporationJson()
{
DefaultTemplate.Offices.ElementType.InstanceType = typeof(AgencyOfficeJson);
}
void Handle(Input.SaveTrigger action)
{
Transaction.Commit();
}
void Handle(Input.NewOfficeTrigger action)
{
new Office()
{
Corporation = this.Data as Corporation,
Address = new Address(),
Trend = 0,
Name = this.NewOfficeName
};
this.NewOfficeName = "";
}
}
}
|
Apply SerializableAttribute to custom exception | using System;
namespace Silverpop.Client
{
public class TransactClientException : Exception
{
public TransactClientException()
{
}
public TransactClientException(string message)
: base(message)
{
}
public TransactClientException(string message, Exception innerException)
: base(message, innerException)
{
}
}
} | using System;
namespace Silverpop.Client
{
[Serializable]
public class TransactClientException : Exception
{
public TransactClientException()
{
}
public TransactClientException(string message)
: base(message)
{
}
public TransactClientException(string message, Exception innerException)
: base(message, innerException)
{
}
}
} |
Use NDes.options for binarycache test executable | using System;
using System.Diagnostics;
using Dependencies.ClrPh;
namespace Dependencies
{
namespace Test
{
class Program
{
static void Main(string[] args)
{
// always the first call to make
Phlib.InitializePhLib();
// Redirect debug log to the console
Debug.Listeners.Add(new TextWriterTraceListener(Console.Out));
Debug.AutoFlush = true;
BinaryCache.Instance.Load();
foreach ( var peFilePath in args )
{
PE Pe = BinaryCache.LoadPe(peFilePath);
}
BinaryCache.Instance.Unload();
}
}
}
}
| using System;
using System.Diagnostics;
using System.Collections.Generic;
using Dependencies.ClrPh;
using NDesk.Options;
namespace Dependencies
{
namespace Test
{
class Program
{
static void ShowHelp(OptionSet p)
{
Console.WriteLine("Usage: binarycache [options] <FILES_TO_LOAD>");
Console.WriteLine();
Console.WriteLine("Options:");
p.WriteOptionDescriptions(Console.Out);
}
static void Main(string[] args)
{
bool is_verbose = false;
bool show_help = false;
OptionSet opts = new OptionSet() {
{ "v|verbose", "redirect debug traces to console", v => is_verbose = v != null },
{ "h|help", "show this message and exit", v => show_help = v != null },
};
List<string> eps = opts.Parse(args);
if (show_help)
{
ShowHelp(opts);
return;
}
if (is_verbose)
{
// Redirect debug log to the console
Debug.Listeners.Add(new TextWriterTraceListener(Console.Out));
Debug.AutoFlush = true;
}
// always the first call to make
Phlib.InitializePhLib();
BinaryCache.Instance.Load();
foreach ( var peFilePath in eps)
{
PE Pe = BinaryCache.LoadPe(peFilePath);
Console.WriteLine("Loaded PE file : {0:s}", Pe.Filepath);
}
BinaryCache.Instance.Unload();
}
}
}
}
|
Make sure multi-line output works when invoked with <<...>> output templates. | using System.Collections.Generic;
using CuttingEdge.Conditions;
namespace ZimmerBot.Core
{
public class Request
{
public enum EventEnum { Welcome }
public string Input { get; set; }
public Dictionary<string, string> State { get; set; }
public string SessionId { get; set; }
public string UserId { get; set; }
public string RuleId { get; set; }
public string RuleLabel { get; set; }
public EventEnum? EventType { get; set; }
public string BotId { get; set; }
public Request()
: this("default", "default")
{
}
public Request(string sessionId, string userId)
{
Condition.Requires(sessionId, nameof(sessionId)).IsNotNullOrEmpty();
Condition.Requires(userId, nameof(userId)).IsNotNullOrEmpty();
SessionId = sessionId;
UserId = userId;
}
public Request(Request src, string input)
{
Input = input;
State = src.State;
SessionId = src.SessionId;
UserId = src.UserId;
State = src.State;
RuleId = src.RuleId;
RuleLabel = src.RuleLabel;
}
}
}
| using System.Collections.Generic;
using CuttingEdge.Conditions;
namespace ZimmerBot.Core
{
public class Request
{
public enum EventEnum { Welcome }
public string Input { get; set; }
public Dictionary<string, string> State { get; set; }
public string SessionId { get; set; }
public string UserId { get; set; }
public string RuleId { get; set; }
public string RuleLabel { get; set; }
public EventEnum? EventType { get; set; }
public string BotId { get; set; }
public Request()
: this("default", "default")
{
}
public Request(string sessionId, string userId)
{
Condition.Requires(sessionId, nameof(sessionId)).IsNotNullOrEmpty();
Condition.Requires(userId, nameof(userId)).IsNotNullOrEmpty();
SessionId = sessionId;
UserId = userId;
}
public Request(Request src, string input)
{
Input = input;
State = src.State;
SessionId = src.SessionId;
UserId = src.UserId;
RuleId = src.RuleId;
RuleLabel = src.RuleLabel;
EventType = src.EventType;
BotId = src.BotId;
}
}
}
|
Fix : Un-Stealth rogues for this quest otherwise the mobs arent aggroed. | WoWUnit unit = ObjectManager.GetNearestWoWUnit(ObjectManager.GetWoWUnitByEntry(questObjective.Entry, questObjective.IsDead), questObjective.IgnoreNotSelectable, questObjective.IgnoreBlackList,
questObjective.AllowPlayerControlled);
if (unit.IsValid && unit.Position.DistanceTo(questObjective.Position) <=8)
{
MovementManager.Face(unit);
Interact.InteractWith(unit.GetBaseAddress);
nManager.Wow.Helpers.Fight.StartFight(unit.Guid);
}
else
{
List<Point> liste = new List<Point>();
liste.Add(ObjectManager.Me.Position);
liste.Add(questObjective.Position);
MovementManager.Go(liste);
}
| WoWUnit unit = ObjectManager.GetNearestWoWUnit(ObjectManager.GetWoWUnitByEntry(questObjective.Entry, questObjective.IsDead), questObjective.IgnoreNotSelectable, questObjective.IgnoreBlackList,
questObjective.AllowPlayerControlled);
ObjectManager.Me.UnitAura(115191).TryCancel(); //Remove Stealth from rogue
if (unit.IsValid && unit.Position.DistanceTo(questObjective.Position) <=8)
{
MovementManager.Face(unit);
Interact.InteractWith(unit.GetBaseAddress);
nManager.Wow.Helpers.Fight.StartFight(unit.Guid);
}
else
{
List<Point> liste = new List<Point>();
liste.Add(ObjectManager.Me.Position);
liste.Add(questObjective.Position);
MovementManager.Go(liste);
}
|
Change indent to 2 spaces | 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);
var table = new Table(
Console.WindowWidth, // width
2 // spacing
);
var 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);
var table = new Table(
Console.WindowWidth, // width
2 // spacing
);
var output = table.Draw();
Console.WriteLine(output);
}
}
}
|
Add conditional business rule execution based on successful validation rule execution | using Peasy;
using Peasy.Core;
using Orders.com.BLL.DataProxy;
namespace Orders.com.BLL.Services
{
public abstract class OrdersDotComServiceBase<T> : BusinessServiceBase<T, long> where T : IDomainObject<long>, new()
{
public OrdersDotComServiceBase(IOrdersDotComDataProxy<T> dataProxy) : base(dataProxy)
{
}
}
}
| using Peasy;
using Peasy.Core;
using Orders.com.BLL.DataProxy;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Orders.com.BLL.Services
{
public abstract class OrdersDotComServiceBase<T> : BusinessServiceBase<T, long> where T : IDomainObject<long>, new()
{
public OrdersDotComServiceBase(IOrdersDotComDataProxy<T> dataProxy) : base(dataProxy)
{
}
protected override IEnumerable<ValidationResult> GetAllErrorsForInsert(T entity, ExecutionContext<T> context)
{
var validationErrors = GetValidationResultsForInsert(entity, context);
if (!validationErrors.Any())
{
var businessRuleErrors = GetBusinessRulesForInsert(entity, context).GetValidationResults();
validationErrors.Concat(businessRuleErrors);
}
return validationErrors;
}
protected override async Task<IEnumerable<ValidationResult>> GetAllErrorsForInsertAsync(T entity, ExecutionContext<T> context)
{
var validationErrors = GetValidationResultsForInsert(entity, context);
if (!validationErrors.Any())
{
var businessRuleErrors = await GetBusinessRulesForInsertAsync(entity, context);
validationErrors.Concat(await businessRuleErrors.GetValidationResultsAsync());
}
return validationErrors;
}
protected override IEnumerable<ValidationResult> GetAllErrorsForUpdate(T entity, ExecutionContext<T> context)
{
var validationErrors = GetValidationResultsForUpdate(entity, context);
if (!validationErrors.Any())
{
var businessRuleErrors = GetBusinessRulesForUpdate(entity, context).GetValidationResults();
validationErrors.Concat(businessRuleErrors);
}
return validationErrors;
}
protected override async Task<IEnumerable<ValidationResult>> GetAllErrorsForUpdateAsync(T entity, ExecutionContext<T> context)
{
var validationErrors = GetValidationResultsForUpdate(entity, context);
if (!validationErrors.Any())
{
var businessRuleErrors = await GetBusinessRulesForUpdateAsync(entity, context);
validationErrors.Concat(await businessRuleErrors.GetValidationResultsAsync());
}
return validationErrors;
}
}
}
|
Remove trailing slashes when creating LZMAs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.DotNet.Archive;
namespace RepoTasks
{
public class CreateLzma : Task
{
[Required]
public string OutputPath { get; set; }
[Required]
public string[] Sources { get; set; }
public override bool Execute()
{
var progress = new ConsoleProgressReport();
using (var archive = new IndexedArchive())
{
foreach (var source in Sources)
{
if (Directory.Exists(source))
{
Log.LogMessage(MessageImportance.High, $"Adding directory: {source}");
archive.AddDirectory(source, progress);
}
else
{
Log.LogMessage(MessageImportance.High, $"Adding file: {source}");
archive.AddFile(source, Path.GetFileName(source));
}
}
archive.Save(OutputPath, progress);
}
return true;
}
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.DotNet.Archive;
namespace RepoTasks
{
public class CreateLzma : Task
{
[Required]
public string OutputPath { get; set; }
[Required]
public string[] Sources { get; set; }
public override bool Execute()
{
var progress = new ConsoleProgressReport();
using (var archive = new IndexedArchive())
{
foreach (var source in Sources)
{
if (Directory.Exists(source))
{
var trimmedSource = source.TrimEnd(new []{ '\\', '/' });
Log.LogMessage(MessageImportance.High, $"Adding directory: {trimmedSource}");
archive.AddDirectory(trimmedSource, progress);
}
else
{
Log.LogMessage(MessageImportance.High, $"Adding file: {source}");
archive.AddFile(source, Path.GetFileName(source));
}
}
archive.Save(OutputPath, progress);
}
return true;
}
}
}
|
Put custom uploaders in same dir as other plugins | using System;
using System.Diagnostics;
using System.IO;
namespace HolzShots.IO
{
public static class HolzShotsPaths
{
private static readonly string SystemAppDataDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
private static readonly string UserPicturesDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
private static readonly string AppDataDirectory = Path.Combine(SystemAppDataDirectory, LibraryInformation.Name);
public static string SystemPath { get; } = Environment.GetFolderPath(Environment.SpecialFolder.System);
public static string PluginDirectory { get; } = Path.Combine(AppDataDirectory, "Plugin");
public static string CustomUploadersDirectory { get; } = Path.Combine(AppDataDirectory, "CustomUploaders");
public static string UserSettingsFilePath { get; } = Path.Combine(AppDataDirectory, "settings.json");
public static string DefaultScreenshotSavePath { get; } = Path.Combine(UserPicturesDirectory, LibraryInformation.Name);
/// <summary>
/// We are doing this synchronously, assuming the application is not located on a network drive.
/// See: https://stackoverflow.com/a/20596865
/// </summary>
/// <exception cref="System.UnauthorizedAccessException" />
/// <exception cref="System.IO.PathTooLongException" />
public static void EnsureDirectory(string directory)
{
Debug.Assert(directory != null);
DirectoryEx.EnsureDirectory(directory);
}
}
}
| using System;
using System.Diagnostics;
using System.IO;
namespace HolzShots.IO
{
public static class HolzShotsPaths
{
private static readonly string SystemAppDataDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
private static readonly string UserPicturesDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
private static readonly string AppDataDirectory = Path.Combine(SystemAppDataDirectory, LibraryInformation.Name);
public static string SystemPath { get; } = Environment.GetFolderPath(Environment.SpecialFolder.System);
public static string PluginDirectory { get; } = Path.Combine(AppDataDirectory, "Plugin");
public static string CustomUploadersDirectory { get; } = PluginDirectory;
public static string UserSettingsFilePath { get; } = Path.Combine(AppDataDirectory, "settings.json");
public static string DefaultScreenshotSavePath { get; } = Path.Combine(UserPicturesDirectory, LibraryInformation.Name);
/// <summary>
/// We are doing this synchronously, assuming the application is not located on a network drive.
/// See: https://stackoverflow.com/a/20596865
/// </summary>
/// <exception cref="System.UnauthorizedAccessException" />
/// <exception cref="System.IO.PathTooLongException" />
public static void EnsureDirectory(string directory)
{
Debug.Assert(directory != null);
DirectoryEx.EnsureDirectory(directory);
}
}
}
|
Check isLocal using Uri.TryCreate. It is possible in case we have only absolute url. | namespace Nancy.Extensions
{
using System;
using System.Linq;
/// <summary>
/// Containing extensions for the <see cref="Request"/> object
/// </summary>
public static class RequestExtensions
{
/// <summary>
/// An extension method making it easy to check if the reqeuest was done using ajax
/// </summary>
/// <param name="request">The request made by client</param>
/// <returns><see langword="true" /> if the request was done using ajax, otherwise <see langword="false"/>.</returns>
public static bool IsAjaxRequest(this Request request)
{
const string ajaxRequestHeaderKey = "X-Requested-With";
const string ajaxRequestHeaderValue = "XMLHttpRequest";
return request.Headers[ajaxRequestHeaderKey].Contains(ajaxRequestHeaderValue);
}
/// <summary>
/// Gets a value indicating whether the request is local.
/// </summary>
/// <param name="request">The request made by client</param>
/// <returns><see langword="true" /> if the request is local, otherwise <see langword="false"/>.</returns>
public static bool IsLocal(this Request request)
{
if (string.IsNullOrEmpty(request.UserHostAddress) || string.IsNullOrEmpty(request.Url))
{
return false;
}
try
{
var uri = new Uri(request.Url);
return uri.IsLoopback;
}
catch (Exception)
{
// Invalid Request.Url string
return false;
}
}
}
}
| namespace Nancy.Extensions
{
using System;
using System.Linq;
/// <summary>
/// Containing extensions for the <see cref="Request"/> object
/// </summary>
public static class RequestExtensions
{
/// <summary>
/// An extension method making it easy to check if the reqeuest was done using ajax
/// </summary>
/// <param name="request">The request made by client</param>
/// <returns><see langword="true" /> if the request was done using ajax, otherwise <see langword="false"/>.</returns>
public static bool IsAjaxRequest(this Request request)
{
const string ajaxRequestHeaderKey = "X-Requested-With";
const string ajaxRequestHeaderValue = "XMLHttpRequest";
return request.Headers[ajaxRequestHeaderKey].Contains(ajaxRequestHeaderValue);
}
/// <summary>
/// Gets a value indicating whether the request is local.
/// </summary>
/// <param name="request">The request made by client</param>
/// <returns><see langword="true" /> if the request is local, otherwise <see langword="false"/>.</returns>
public static bool IsLocal(this Request request)
{
if (string.IsNullOrEmpty(request.UserHostAddress) || string.IsNullOrEmpty(request.Url))
{
return false;
}
Uri uri = null;
if (Uri.TryCreate(request.Url, UriKind.Absolute, out uri))
{
return uri.IsLoopback;
}
else
{
// Invalid or relative Request.Url string
return false;
}
}
}
}
|
Fix a dumb bug in the interface generator | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Refit.Generator
{
class Program
{
static void Main(string[] args)
{
var generator = new InterfaceStubGenerator();
var target = new FileInfo(args[0]);
var files = args[1].Split(';').Select(x => new FileInfo(x)).ToArray();
var template = generator.GenerateInterfaceStubs(files.Select(x => x.FullName).ToArray());
File.WriteAllText(target.FullName, template);
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Refit.Generator
{
class Program
{
static void Main(string[] args)
{
// NB: @Compile passes us a list of files relative to the project
// directory - we're going to assume that the target is always in
// the same directory as the project file
var generator = new InterfaceStubGenerator();
var target = new FileInfo(args[0]);
var targetDir = target.DirectoryName;
var files = args[1].Split(';')
.Select(x => new FileInfo(Path.Combine(targetDir, x)))
.ToArray();
var template = generator.GenerateInterfaceStubs(files.Select(x => x.FullName).ToArray());
File.WriteAllText(target.FullName, template);
}
}
}
|
Implement humanize test localization for current culture. | using System.Globalization;
using Abp.Configuration.Startup;
using Abp.Extensions;
using Abp.Logging;
namespace Abp.Localization
{
public static class LocalizationSourceHelper
{
public static string ReturnGivenNameOrThrowException(ILocalizationConfiguration configuration, string sourceName, string name, CultureInfo culture)
{
var exceptionMessage = $"Can not find '{name}' in localization source '{sourceName}'!";
if (!configuration.ReturnGivenTextIfNotFound)
{
throw new AbpException(exceptionMessage);
}
LogHelper.Logger.Warn(exceptionMessage);
#if NET46
var notFoundText = configuration.HumanizeTextIfNotFound
? name.ToSentenceCase(culture)
: name;
#else
var notFoundText = configuration.HumanizeTextIfNotFound
? name.ToSentenceCase() //TODO: Removed culture since it's not supported by netstandard
: name;
#endif
return configuration.WrapGivenTextIfNotFound
? $"[{notFoundText}]"
: notFoundText;
}
}
}
| using System.Globalization;
using Abp.Configuration.Startup;
using Abp.Extensions;
using Abp.Logging;
namespace Abp.Localization
{
public static class LocalizationSourceHelper
{
public static string ReturnGivenNameOrThrowException(ILocalizationConfiguration configuration, string sourceName, string name, CultureInfo culture)
{
var exceptionMessage = $"Can not find '{name}' in localization source '{sourceName}'!";
if (!configuration.ReturnGivenTextIfNotFound)
{
throw new AbpException(exceptionMessage);
}
LogHelper.Logger.Warn(exceptionMessage);
string notFoundText;
#if NET46
notFoundText = configuration.HumanizeTextIfNotFound
? name.ToSentenceCase(culture)
: name;
#else
using (CultureInfoHelper.Use(culture))
{
notFoundText = configuration.HumanizeTextIfNotFound
? name.ToSentenceCase()
: name;
}
#endif
return configuration.WrapGivenTextIfNotFound
? $"[{notFoundText}]"
: notFoundText;
}
}
}
|
Include id and title on package version history items. | using System;
using AspNet.WebApi.HtmlMicrodataFormatter;
namespace NuGet.Lucene.Web.Models
{
public class PackageVersionSummary
{
private readonly StrictSemanticVersion version;
private readonly DateTimeOffset lastUpdated;
private readonly int versionDownloadCount;
private readonly Link link;
public StrictSemanticVersion Version
{
get { return version; }
}
public DateTimeOffset LastUpdated
{
get { return lastUpdated; }
}
public int VersionDownloadCount
{
get { return versionDownloadCount; }
}
public Link Link
{
get { return link; }
}
public PackageVersionSummary(LucenePackage package, Link link)
: this(package.Version, package.LastUpdated, package.VersionDownloadCount, link)
{
}
public PackageVersionSummary(StrictSemanticVersion version, DateTimeOffset lastUpdated, int versionDownloadCount, Link link)
{
this.version = version;
this.lastUpdated = lastUpdated;
this.versionDownloadCount = versionDownloadCount;
this.link = link;
}
}
} | using System;
using AspNet.WebApi.HtmlMicrodataFormatter;
namespace NuGet.Lucene.Web.Models
{
public class PackageVersionSummary
{
private readonly string id;
private readonly string title;
private readonly StrictSemanticVersion version;
private readonly DateTimeOffset lastUpdated;
private readonly int versionDownloadCount;
private readonly Link link;
public string Id
{
get { return id; }
}
public string Title
{
get { return title; }
}
public StrictSemanticVersion Version
{
get { return version; }
}
public DateTimeOffset LastUpdated
{
get { return lastUpdated; }
}
public int VersionDownloadCount
{
get { return versionDownloadCount; }
}
public Link Link
{
get { return link; }
}
public PackageVersionSummary(LucenePackage package, Link link)
: this(package.Id, package.Title, package.Version, package.LastUpdated, package.VersionDownloadCount, link)
{
}
public PackageVersionSummary(string id, string title, StrictSemanticVersion version, DateTimeOffset lastUpdated, int versionDownloadCount, Link link)
{
this.id = id;
this.title = title;
this.version = version;
this.lastUpdated = lastUpdated;
this.versionDownloadCount = versionDownloadCount;
this.link = link;
}
}
} |
Create private and public key when saving a new product | using System;
using System.Linq;
using System.IO;
using System.IO.IsolatedStorage;
using System.Collections.Generic;
using Microsoft.LightSwitch;
using Microsoft.LightSwitch.Framework.Client;
using Microsoft.LightSwitch.Presentation;
using Microsoft.LightSwitch.Presentation.Extensions;
namespace LightSwitchApplication
{
public partial class CreateNewProduct
{
partial void CreateNewProduct_InitializeDataWorkspace(global::System.Collections.Generic.List<global::Microsoft.LightSwitch.IDataService> saveChangesTo)
{
// Write your code here.
this.ProductProperty = new Product();
}
partial void CreateNewProduct_Saved()
{
// Write your code here.
this.Close(false);
Application.Current.ShowDefaultScreen(this.ProductProperty);
}
}
} | using System;
using System.Linq;
using System.IO;
using System.IO.IsolatedStorage;
using System.Collections.Generic;
using Microsoft.LightSwitch;
using Microsoft.LightSwitch.Framework.Client;
using Microsoft.LightSwitch.Presentation;
using Microsoft.LightSwitch.Presentation.Extensions;
namespace LightSwitchApplication
{
public partial class CreateNewProduct
{
partial void CreateNewProduct_InitializeDataWorkspace(global::System.Collections.Generic.List<global::Microsoft.LightSwitch.IDataService> saveChangesTo)
{
// Write your code here.
this.ProductProperty = new Product();
}
partial void CreateNewProduct_Saved()
{
// Write your code here.
this.Close(false);
Application.Current.ShowDefaultScreen(this.ProductProperty);
}
partial void CreateNewProduct_Saving(ref bool handled)
{
if (ProductProperty.KeyPair != null)
return;
ProductProperty.KeyPair = new KeyPair();
if (!string.IsNullOrWhiteSpace(ProductProperty.KeyPair.PrivateKey))
return;
var passPhrase = this.ShowInputBox("Please enter the pass phrase to encrypt the private key.",
"Private Key Generator");
if (string.IsNullOrWhiteSpace(passPhrase))
{
this.ShowMessageBox("Invalid pass phrase!", "Private Key Generator", MessageBoxOption.Ok);
handled = false;
return;
}
var keyPair = Portable.Licensing.Security.Cryptography.KeyGenerator.Create().GenerateKeyPair();
ProductProperty.KeyPair.PrivateKey = keyPair.ToEncryptedPrivateKeyString(passPhrase);
ProductProperty.KeyPair.PublicKey = keyPair.ToPublicKeyString();
}
}
} |
Fix web request failing if password is 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.Net.Http;
using osu.Framework.IO.Network;
using osu.Game.Online.API;
namespace osu.Game.Online.Rooms
{
public class JoinRoomRequest : APIRequest
{
public readonly Room Room;
public readonly string Password;
public JoinRoomRequest(Room room, string password)
{
Room = room;
Password = password;
}
protected override WebRequest CreateWebRequest()
{
var req = base.CreateWebRequest();
req.Method = HttpMethod.Put;
req.AddParameter("password", Password);
return req;
}
protected override string Target => $"rooms/{Room.RoomID.Value}/users/{User.Id}";
}
}
| // 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.Net.Http;
using osu.Framework.IO.Network;
using osu.Game.Online.API;
namespace osu.Game.Online.Rooms
{
public class JoinRoomRequest : APIRequest
{
public readonly Room Room;
public readonly string Password;
public JoinRoomRequest(Room room, string password)
{
Room = room;
Password = password;
}
protected override WebRequest CreateWebRequest()
{
var req = base.CreateWebRequest();
req.Method = HttpMethod.Put;
if (!string.IsNullOrEmpty(Password))
req.AddParameter("password", Password);
return req;
}
protected override string Target => $"rooms/{Room.RoomID.Value}/users/{User.Id}";
}
}
|
Fix fleet ship list not update | using DynamicData;
using DynamicData.Aggregation;
using ReactiveUI;
using Sakuno.ING.Game.Models;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
namespace Sakuno.ING.ViewModels.Homeport
{
public sealed class FleetViewModel : ReactiveObject, IHomeportTabViewModel
{
public PlayerFleet Model { get; }
public IReadOnlyCollection<ShipViewModel> Ships { get; }
private readonly ObservableAsPropertyHelper<int> _totalLevel;
public int TotalLevel => _totalLevel.Value;
private readonly ObservableAsPropertyHelper<int> _speed;
public ShipSpeed Speed => (ShipSpeed)_speed.Value;
private bool _isSelected;
public bool IsSelected
{
get => _isSelected;
set => this.RaiseAndSetIfChanged(ref _isSelected, value);
}
public FleetViewModel(PlayerFleet fleet)
{
Model = fleet;
var ships = fleet.Ships.AsObservableChangeSet();
Ships = ships.Transform(r => new ShipViewModel(r)).Bind();
_totalLevel = ships.Sum(r => r.Leveling.Level).ObserveOn(RxApp.MainThreadScheduler).ToProperty(this, nameof(TotalLevel), deferSubscription: true);
_speed = ships.Minimum(r => (int)r.Speed).ObserveOn(RxApp.MainThreadScheduler).ToProperty(this, nameof(ShipSpeed));
}
}
}
| using DynamicData;
using DynamicData.Aggregation;
using DynamicData.Binding;
using ReactiveUI;
using Sakuno.ING.Game.Models;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
namespace Sakuno.ING.ViewModels.Homeport
{
public sealed class FleetViewModel : ReactiveObject, IHomeportTabViewModel
{
public PlayerFleet Model { get; }
public IReadOnlyCollection<ShipViewModel> Ships { get; }
private readonly ObservableAsPropertyHelper<int> _totalLevel;
public int TotalLevel => _totalLevel.Value;
private readonly ObservableAsPropertyHelper<int> _speed;
public ShipSpeed Speed => (ShipSpeed)_speed.Value;
private bool _isSelected;
public bool IsSelected
{
get => _isSelected;
set => this.RaiseAndSetIfChanged(ref _isSelected, value);
}
public FleetViewModel(PlayerFleet fleet)
{
Model = fleet;
var ships = fleet.Ships.ToObservableChangeSet();
Ships = ships.Transform(r => new ShipViewModel(r)).Bind();
_totalLevel = ships.Sum(r => r.Leveling.Level).ObserveOn(RxApp.MainThreadScheduler).ToProperty(this, nameof(TotalLevel), deferSubscription: true);
_speed = ships.Minimum(r => (int)r.Speed).ObserveOn(RxApp.MainThreadScheduler).ToProperty(this, nameof(ShipSpeed));
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.