Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Annotate return value for consumers | // 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
using System.Diagnostics;
namespace osu.Framework.Extensions.ObjectExtensions
{
/// <summary>
/// Extensions that apply to all objects.
/// </summary>
public static class ObjectExtensions
{
/// <summary>
/// Coerces a nullable object as non-nullable. This is an alternative to the C# 8 null-forgiving operator "<c>!</c>".
/// </summary>
/// <remarks>
/// This should only be used when an assertion or other handling is not a reasonable alternative.
/// </remarks>
/// <param name="obj">The nullable object.</param>
/// <typeparam name="T">The type of the object.</typeparam>
/// <returns>The non-nullable object corresponding to <paramref name="obj"/>.</returns>
public static T AsNonNull<T>(this T? obj)
where T : class
{
Debug.Assert(obj != null);
return obj;
}
/// <summary>
/// If the given object is null.
/// </summary>
public static bool IsNull<T>(this T obj) => ReferenceEquals(obj, null);
/// <summary>
/// <c>true</c> if the given object is not null, <c>false</c> otherwise.
/// </summary>
public static bool IsNotNull<T>(this T obj) => !ReferenceEquals(obj, null);
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace osu.Framework.Extensions.ObjectExtensions
{
/// <summary>
/// Extensions that apply to all objects.
/// </summary>
public static class ObjectExtensions
{
/// <summary>
/// Coerces a nullable object as non-nullable. This is an alternative to the C# 8 null-forgiving operator "<c>!</c>".
/// </summary>
/// <remarks>
/// This should only be used when an assertion or other handling is not a reasonable alternative.
/// </remarks>
/// <param name="obj">The nullable object.</param>
/// <typeparam name="T">The type of the object.</typeparam>
/// <returns>The non-nullable object corresponding to <paramref name="obj"/>.</returns>
public static T AsNonNull<T>(this T? obj)
where T : class
{
Debug.Assert(obj != null);
return obj;
}
/// <summary>
/// If the given object is null.
/// </summary>
public static bool IsNull<T>([NotNullWhen(false)] this T obj) => ReferenceEquals(obj, null);
/// <summary>
/// <c>true</c> if the given object is not null, <c>false</c> otherwise.
/// </summary>
public static bool IsNotNull<T>([NotNullWhen(true)] this T obj) => !ReferenceEquals(obj, null);
}
}
|
Correct error message for missing test connection string | using System;
using Baseline;
namespace Marten.Testing
{
public class ConnectionSource : ConnectionFactory
{
public static readonly string ConnectionString = Environment.GetEnvironmentVariable("marten_testing_database");
static ConnectionSource()
{
if (ConnectionString.IsEmpty())
throw new Exception(
"You need to set the connection string for your local Postgresql database in the environment variable 'marten-testing-database'");
}
public ConnectionSource() : base(ConnectionString)
{
}
}
} | using System;
namespace Marten.Testing
{
public class ConnectionSource : ConnectionFactory
{
public static readonly string ConnectionString = Environment.GetEnvironmentVariable("marten_testing_database");
static ConnectionSource()
{
if (ConnectionString.IsEmpty())
throw new Exception(
"You need to set the connection string for your local Postgresql database in the environment variable 'marten_testing_database'");
}
public ConnectionSource() : base(ConnectionString)
{
}
}
} |
Fix find vessels landed at | using Harmony;
using LunaClient.Systems.Lock;
using LunaCommon.Enums;
using System.Collections.Generic;
// ReSharper disable All
namespace LunaClient.Harmony
{
/// <summary>
/// This harmony patch is intended to override the "FindVesselsLandedAt" that sometimes is called to check if there are vessels in a launch site
/// We just remove the other controlled vessels from that check and set them correctly
/// </summary>
[HarmonyPatch(typeof(ShipConstruction))]
[HarmonyPatch("FindVesselsLandedAt")]
[HarmonyPatch(new[] { typeof(FlightState), typeof(string) })]
public class ShipConstruction_FindVesselsLandedAt
{
private static readonly List<ProtoVessel> ProtoVesselsToRemove = new List<ProtoVessel>();
[HarmonyPostfix]
private static void PostfixFindVesselsLandedAt(List<ProtoVessel> __result)
{
if (MainSystem.NetworkState < ClientState.Connected) return;
ProtoVesselsToRemove.Clear();
foreach (var pv in __result)
{
if (!LockSystem.LockQuery.ControlLockExists(pv.vesselID))
ProtoVesselsToRemove.Add(pv);
}
foreach (var pv in ProtoVesselsToRemove)
{
__result.Remove(pv);
}
}
}
}
| using Harmony;
using LunaClient.Systems.Lock;
using LunaCommon.Enums;
using System.Collections.Generic;
// ReSharper disable All
namespace LunaClient.Harmony
{
/// <summary>
/// This harmony patch is intended to override the "FindVesselsLandedAt" that sometimes is called to check if there are vessels in a launch site
/// We just remove the other controlled vessels from that check and set them correctly
/// </summary>
[HarmonyPatch(typeof(ShipConstruction))]
[HarmonyPatch("FindVesselsLandedAt")]
[HarmonyPatch(new[] { typeof(FlightState), typeof(string) })]
public class ShipConstruction_FindVesselsLandedAt
{
private static readonly List<ProtoVessel> ProtoVesselsToRemove = new List<ProtoVessel>();
[HarmonyPostfix]
private static void PostfixFindVesselsLandedAt(List<ProtoVessel> __result)
{
if (MainSystem.NetworkState < ClientState.Connected) return;
ProtoVesselsToRemove.Clear();
foreach (var pv in __result)
{
if (LockSystem.LockQuery.ControlLockExists(pv.vesselID))
ProtoVesselsToRemove.Add(pv);
}
foreach (var pv in ProtoVesselsToRemove)
{
__result.Remove(pv);
}
}
}
}
|
Mark IsDirty property as internal | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace Draw2D.Core
{
public abstract class ObservableObject : INotifyPropertyChanged
{
public bool IsDirty { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public void Notify([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public bool Update<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
if (!Equals(field, value))
{
field = value;
IsDirty = true;
Notify(propertyName);
return true;
}
return false;
}
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace Draw2D.Core
{
public abstract class ObservableObject : INotifyPropertyChanged
{
internal bool IsDirty { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public void Notify([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public bool Update<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
if (!Equals(field, value))
{
field = value;
IsDirty = true;
Notify(propertyName);
return true;
}
return false;
}
}
}
|
Change back to use the default database name. | using System.Data.Entity;
namespace food_tracker {
public class TrackerContext : DbContext {
public TrackerContext() : base("name=NutritionTrackerContext") {
Configuration.LazyLoadingEnabled = false;
this.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
}
public DbSet<WholeDay> Days { get; set; }
public DbSet<NutritionItem> Nutrition { get; set; }
}
}
| using System.Data.Entity;
namespace food_tracker {
public class TrackerContext : DbContext {
public TrackerContext() : base() {
Configuration.LazyLoadingEnabled = false;
this.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
}
public DbSet<WholeDay> Days { get; set; }
public DbSet<NutritionItem> Nutrition { get; set; }
}
}
|
Update tests re: process builder, etc. | namespace Bakery.Processes
{
using Specification.Builder;
using System;
using System.Text;
using System.Threading.Tasks;
using Xunit;
public class SystemDiagnosticsProcessTests
{
[Fact]
public async Task EchoWithCombinedOutput()
{
var processSpecification =
ProcessSpecificationBuilder.Create()
.WithProgram(@"echo")
.WithArguments("a", "b", "c")
.WithEnvironment()
.WithCombinedOutput()
.Build();
var processFactory = new ProcessFactory();
var process = processFactory.Start(processSpecification);
var stringBuilder = new StringBuilder();
await process.WaitForExit(TimeSpan.FromSeconds(5));
while (true)
{
var output = await process.TryReadAsync(TimeSpan.FromSeconds(1));
if (output == null)
break;
stringBuilder.Append(output.Text);
}
var totalOutput = stringBuilder.ToString();
Assert.Equal("a b c", totalOutput);
}
}
}
| namespace Bakery.Processes
{
using System;
using System.Text;
using System.Threading.Tasks;
using Xunit;
public class SystemDiagnosticsProcessTests
{
[Fact]
public async Task EchoWithCombinedOutput()
{
var process = await new ProcessFactory().RunAsync(builder =>
{
return builder
.WithProgram("echo")
.WithArguments("a", "b", "c")
.WithEnvironment()
.WithCombinedOutput()
.Build();
});
var stringBuilder = new StringBuilder();
while (true)
{
var output = await process.TryReadAsync(TimeSpan.FromSeconds(1));
if (output == null)
break;
stringBuilder.Append(output.Text);
}
var totalOutput = stringBuilder.ToString();
Assert.Equal("a b c", totalOutput);
}
}
}
|
Add invariant IFormatterProvider to avoid issues based on user local | using System;
using System.Collections.Generic;
using Cake.Core.Diagnostics;
namespace Cake.Arguments
{
/// <summary>
/// Responsible for parsing <see cref="Verbosity"/>.
/// </summary>
internal sealed class VerbosityParser
{
private readonly Dictionary<string, Verbosity> _lookup;
/// <summary>
/// Initializes a new instance of the <see cref="VerbosityParser"/> class.
/// </summary>
public VerbosityParser()
{
_lookup = new Dictionary<string, Verbosity>(StringComparer.OrdinalIgnoreCase)
{
{ "q", Verbosity.Quiet },
{ "quiet", Verbosity.Quiet },
{ "m", Verbosity.Minimal },
{ "minimal", Verbosity.Minimal },
{ "n", Verbosity.Normal },
{ "normal", Verbosity.Normal },
{ "v", Verbosity.Verbose },
{ "verbose", Verbosity.Verbose },
{ "d", Verbosity.Diagnostic },
{ "diagnostic", Verbosity.Diagnostic }
};
}
/// <summary>
/// Parses the provided string to a <see cref="Verbosity"/>.
/// </summary>
/// <param name="value">The string to parse.</param>
/// <returns>The verbosity.</returns>
public Verbosity Parse(string value)
{
Verbosity verbosity;
if (_lookup.TryGetValue(value, out verbosity))
{
return verbosity;
}
const string format = "The value '{0}' is not a valid verbosity.";
var message = string.Format(format, value ?? string.Empty);
throw new InvalidOperationException(message);
}
}
} | using System;
using System.Collections.Generic;
using System.Globalization;
using Cake.Core.Diagnostics;
namespace Cake.Arguments
{
/// <summary>
/// Responsible for parsing <see cref="Verbosity"/>.
/// </summary>
internal sealed class VerbosityParser
{
private readonly Dictionary<string, Verbosity> _lookup;
/// <summary>
/// Initializes a new instance of the <see cref="VerbosityParser"/> class.
/// </summary>
public VerbosityParser()
{
_lookup = new Dictionary<string, Verbosity>(StringComparer.OrdinalIgnoreCase)
{
{ "q", Verbosity.Quiet },
{ "quiet", Verbosity.Quiet },
{ "m", Verbosity.Minimal },
{ "minimal", Verbosity.Minimal },
{ "n", Verbosity.Normal },
{ "normal", Verbosity.Normal },
{ "v", Verbosity.Verbose },
{ "verbose", Verbosity.Verbose },
{ "d", Verbosity.Diagnostic },
{ "diagnostic", Verbosity.Diagnostic }
};
}
/// <summary>
/// Parses the provided string to a <see cref="Verbosity"/>.
/// </summary>
/// <param name="value">The string to parse.</param>
/// <returns>The verbosity.</returns>
public Verbosity Parse(string value)
{
Verbosity verbosity;
if (_lookup.TryGetValue(value, out verbosity))
{
return verbosity;
}
const string format = "The value '{0}' is not a valid verbosity.";
var message = string.Format(CultureInfo.InvariantCulture, format, value);
throw new InvalidOperationException(message);
}
}
} |
Add implementation for serializing TraktAuthorization. | namespace TraktApiSharp.Services
{
using Authentication;
using System;
/// <summary>Provides helper methods for serializing and deserializing Trakt objects.</summary>
public static class TraktSerializationService
{
public static string Serialize(TraktAuthorization authorization)
{
if (authorization == null)
throw new ArgumentNullException(nameof(authorization), "authorization must not be null");
return string.Empty;
}
public static TraktAuthorization Deserialize(string authorization)
{
return null;
}
}
}
| namespace TraktApiSharp.Services
{
using Authentication;
using Extensions;
using System;
using Utils;
/// <summary>Provides helper methods for serializing and deserializing Trakt objects.</summary>
public static class TraktSerializationService
{
/// <summary>Serializes an <see cref="TraktAuthorization" /> instance to a Json string.</summary>
/// <param name="authorization">The authorization information, which should be serialized.</param>
/// <returns>A Json string, containing all properties of the given authorization.</returns>
/// <exception cref="ArgumentNullException">Thrown, if the given authorization is null.</exception>
public static string Serialize(TraktAuthorization authorization)
{
if (authorization == null)
throw new ArgumentNullException(nameof(authorization), "authorization must not be null");
var anonymousAuthorization = new
{
AccessToken = authorization.AccessToken,
RefreshToken = authorization.RefreshToken,
ExpiresIn = authorization.ExpiresIn,
Scope = authorization.AccessScope.ObjectName,
TokenType = authorization.TokenType.ObjectName,
CreatedAt = authorization.Created.ToTraktLongDateTimeString(),
IgnoreExpiration = authorization.IgnoreExpiration
};
return Json.Serialize(anonymousAuthorization);
}
public static TraktAuthorization Deserialize(string authorization)
{
return null;
}
}
}
|
Remove not needed IoC registrations | using IIUWr.Fereol.Common;
using IIUWr.Fereol.Interface;
using IIUWr.ViewModels.Fereol;
using LionCub.Patterns.DependencyInjection;
using System;
using HTMLParsing = IIUWr.Fereol.HTMLParsing;
namespace IIUWr
{
public static class ConfigureIoC
{
public static void All()
{
#if DEBUG
IoC.AsInstance(new Uri(@"http://192.168.1.150:8002/"));
#else
IoC.AsInstance(new Uri(@"https://zapisy.ii.uni.wroc.pl/"));
#endif
ViewModels();
Fereol.Common();
Fereol.HTMLParsing();
}
public static void ViewModels()
{
IoC.AsSingleton<SemestersViewModel>();
IoC.PerRequest<SemesterViewModel>();
IoC.PerRequest<CourseViewModel>();
IoC.PerRequest<TutorialViewModel>();
}
public static class Fereol
{
public static void Common()
{
IoC.AsSingleton<ICredentialsManager, CredentialsManager>();
IoC.AsSingleton<ISessionManager, CredentialsManager>();
}
public static void HTMLParsing()
{
IoC.AsSingleton<IConnection, HTMLParsing.Connection>();
IoC.AsSingleton<HTMLParsing.Interface.IHTTPConnection, HTMLParsing.Connection>();
IoC.AsSingleton<ICoursesService, HTMLParsing.CoursesService>();
}
}
}
}
| using IIUWr.Fereol.Common;
using IIUWr.Fereol.Interface;
using IIUWr.ViewModels.Fereol;
using LionCub.Patterns.DependencyInjection;
using System;
using HTMLParsing = IIUWr.Fereol.HTMLParsing;
namespace IIUWr
{
public static class ConfigureIoC
{
public static void All()
{
#if DEBUG
IoC.AsInstance(new Uri(@"http://192.168.1.150:8002/"));
#else
IoC.AsInstance(new Uri(@"https://zapisy.ii.uni.wroc.pl/"));
#endif
ViewModels();
Fereol.Common();
Fereol.HTMLParsing();
}
public static void ViewModels()
{
IoC.AsSingleton<SemestersViewModel>();
}
public static class Fereol
{
public static void Common()
{
IoC.AsSingleton<ICredentialsManager, CredentialsManager>();
IoC.AsSingleton<ISessionManager, CredentialsManager>();
}
public static void HTMLParsing()
{
IoC.AsSingleton<IConnection, HTMLParsing.Connection>();
IoC.AsSingleton<HTMLParsing.Interface.IHTTPConnection, HTMLParsing.Connection>();
IoC.AsSingleton<ICoursesService, HTMLParsing.CoursesService>();
}
}
}
}
|
Fix category for a test about tabular structure | using NBi.Core.Structure;
using NBi.Core.Structure.Olap;
using NBi.Core.Structure.Relational;
using NBi.Core.Structure.Tabular;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace NBi.Testing.Integration.Core.Structure
{
public class StructureDiscoveryFactoryProviderTest
{
private class FakeStructureDiscoveryFactoryProvider : StructureDiscoveryFactoryProvider
{
public new string InquireFurtherAnalysisService(string connectionString)
{
return base.InquireFurtherAnalysisService(connectionString);
}
}
[Test]
[Category("Olap")]
public void InquireFurtherAnalysisService_Multidimensional_ReturnCorrectServerMode()
{
var connectionString = ConnectionStringReader.GetAdomd();
var provider = new FakeStructureDiscoveryFactoryProvider();
var serverMode = provider.InquireFurtherAnalysisService(connectionString);
Assert.That(serverMode, Is.EqualTo("olap"));
}
[Test]
[Category("Tabular")]
public void InquireFurtherAnalysisService_Tabular_ReturnCorrectServerMode()
{
var connectionString = ConnectionStringReader.GetAdomdTabular();
var provider = new FakeStructureDiscoveryFactoryProvider();
var serverMode = provider.InquireFurtherAnalysisService(connectionString);
Assert.That(serverMode, Is.EqualTo("tabular"));
}
}
}
| using NBi.Core.Structure;
using NBi.Core.Structure.Olap;
using NBi.Core.Structure.Relational;
using NBi.Core.Structure.Tabular;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace NBi.Testing.Integration.Core.Structure
{
public class StructureDiscoveryFactoryProviderTest
{
private class FakeStructureDiscoveryFactoryProvider : StructureDiscoveryFactoryProvider
{
public new string InquireFurtherAnalysisService(string connectionString)
{
return base.InquireFurtherAnalysisService(connectionString);
}
}
[Test]
[Category("Olap")]
public void InquireFurtherAnalysisService_Multidimensional_ReturnCorrectServerMode()
{
var connectionString = ConnectionStringReader.GetAdomd();
var provider = new FakeStructureDiscoveryFactoryProvider();
var serverMode = provider.InquireFurtherAnalysisService(connectionString);
Assert.That(serverMode, Is.EqualTo("olap"));
}
[Test]
[Category("Olap")]
public void InquireFurtherAnalysisService_Tabular_ReturnCorrectServerMode()
{
var connectionString = ConnectionStringReader.GetAdomdTabular();
var provider = new FakeStructureDiscoveryFactoryProvider();
var serverMode = provider.InquireFurtherAnalysisService(connectionString);
Assert.That(serverMode, Is.EqualTo("tabular"));
}
}
}
|
Change user accounts view model to use the new viewmodel for displaying SuccessMessage | using SFA.DAS.EmployerApprenticeshipsService.Domain.Entities.Account;
namespace SFA.DAS.EmployerApprenticeshipsService.Web.Models
{
public class UserAccountsViewModel
{
public Accounts Accounts;
public int Invitations;
public string SuccessMessage;
}
} | using SFA.DAS.EmployerApprenticeshipsService.Domain.Entities.Account;
namespace SFA.DAS.EmployerApprenticeshipsService.Web.Models
{
public class UserAccountsViewModel
{
public Accounts Accounts;
public int Invitations;
public SuccessMessageViewModel SuccessMessage;
}
} |
Fix to dispose when the specified object is Icon. | /* ------------------------------------------------------------------------- */
//
// Copyright (c) 2010 CubeSoft, 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.
//
/* ------------------------------------------------------------------------- */
using Cube.Mixin.Drawing;
namespace Cube.Xui.Converters
{
/* --------------------------------------------------------------------- */
///
/// ImageConverter
///
/// <summary>
/// Provides functionality to convert from an Image object to
/// a BitmapImage object.
/// </summary>
///
/* --------------------------------------------------------------------- */
public class ImageConverter : SimplexConverter
{
/* ----------------------------------------------------------------- */
///
/// ImageValueConverter
///
/// <summary>
/// Initializes a new instance of the ImageConverter class.
/// </summary>
///
/* ----------------------------------------------------------------- */
public ImageConverter() : base(e =>
{
var src = e is System.Drawing.Image image ? image :
e is System.Drawing.Icon icon ? icon.ToBitmap() :
null;
return src.ToBitmapImage();
}) { }
}
}
| /* ------------------------------------------------------------------------- */
//
// Copyright (c) 2010 CubeSoft, 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.
//
/* ------------------------------------------------------------------------- */
using Cube.Mixin.Drawing;
namespace Cube.Xui.Converters
{
/* --------------------------------------------------------------------- */
///
/// ImageConverter
///
/// <summary>
/// Provides functionality to convert from an Image object to
/// a BitmapImage object.
/// </summary>
///
/* --------------------------------------------------------------------- */
public class ImageConverter : SimplexConverter
{
/* ----------------------------------------------------------------- */
///
/// ImageValueConverter
///
/// <summary>
/// Initializes a new instance of the ImageConverter class.
/// </summary>
///
/* ----------------------------------------------------------------- */
public ImageConverter() : base(e =>
{
if (e is System.Drawing.Image i0) return i0.ToBitmapImage(false);
if (e is System.Drawing.Icon i1) return i1.ToBitmap().ToBitmapImage(true);
return null;
}) { }
}
}
|
Change the order Loaders are disposed | using System;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using MuffinFramework.Muffin;
using MuffinFramework.Platform;
using MuffinFramework.Service;
namespace MuffinFramework
{
public class MuffinClient : IDisposable
{
private readonly object _lockObj = new object();
public bool IsStarted { get; private set; }
public AggregateCatalog Catalog { get; private set; }
public PlatformLoader PlatformLoader { get; private set; }
public ServiceLoader ServiceLoader { get; private set; }
public MuffinLoader MuffinLoader { get; private set; }
public MuffinClient()
{
Catalog = new AggregateCatalog();
Catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetCallingAssembly()));
PlatformLoader = new PlatformLoader();
ServiceLoader = new ServiceLoader();
MuffinLoader = new MuffinLoader();
}
public void Start()
{
lock (_lockObj)
{
if (IsStarted)
throw new InvalidOperationException("MuffinClient has already been started.");
IsStarted = true;
}
PlatformLoader.Enable(Catalog, new PlatformArgs(PlatformLoader));
ServiceLoader.Enable(Catalog, new ServiceArgs(PlatformLoader, ServiceLoader));
MuffinLoader.Enable(Catalog, new MuffinArgs(PlatformLoader, ServiceLoader, MuffinLoader));
}
public virtual void Dispose()
{
Catalog.Dispose();
PlatformLoader.Dispose();
ServiceLoader.Dispose();
MuffinLoader.Dispose();
}
}
} | using System;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using MuffinFramework.Muffin;
using MuffinFramework.Platform;
using MuffinFramework.Service;
namespace MuffinFramework
{
public class MuffinClient : IDisposable
{
private readonly object _lockObj = new object();
public bool IsStarted { get; private set; }
public AggregateCatalog Catalog { get; private set; }
public PlatformLoader PlatformLoader { get; private set; }
public ServiceLoader ServiceLoader { get; private set; }
public MuffinLoader MuffinLoader { get; private set; }
public MuffinClient()
{
Catalog = new AggregateCatalog();
Catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetCallingAssembly()));
PlatformLoader = new PlatformLoader();
ServiceLoader = new ServiceLoader();
MuffinLoader = new MuffinLoader();
}
public void Start()
{
lock (_lockObj)
{
if (IsStarted)
throw new InvalidOperationException("MuffinClient has already been started.");
IsStarted = true;
}
PlatformLoader.Enable(Catalog, new PlatformArgs(PlatformLoader));
ServiceLoader.Enable(Catalog, new ServiceArgs(PlatformLoader, ServiceLoader));
MuffinLoader.Enable(Catalog, new MuffinArgs(PlatformLoader, ServiceLoader, MuffinLoader));
}
public virtual void Dispose()
{
MuffinLoader.Dispose();
ServiceLoader.Dispose();
PlatformLoader.Dispose();
Catalog.Dispose();
}
}
} |
Fix timeline sizes being updated potentially before the track has a length | // 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;
using OpenTK;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
namespace osu.Game.Screens.Edit.Components.Timelines.Summary.Parts
{
/// <summary>
/// Represents a part of the summary timeline..
/// </summary>
internal abstract class TimelinePart : CompositeDrawable
{
public Bindable<WorkingBeatmap> Beatmap = new Bindable<WorkingBeatmap>();
private readonly Container timeline;
protected TimelinePart()
{
AddInternal(timeline = new Container { RelativeSizeAxes = Axes.Both });
Beatmap.ValueChanged += b =>
{
timeline.RelativeChildSize = new Vector2((float)Math.Max(1, b.Track.Length), 1);
LoadBeatmap(b);
};
}
protected void Add(Drawable visualisation) => timeline.Add(visualisation);
protected virtual void LoadBeatmap(WorkingBeatmap beatmap)
{
timeline.Clear();
}
}
}
| // 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;
using OpenTK;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
namespace osu.Game.Screens.Edit.Components.Timelines.Summary.Parts
{
/// <summary>
/// Represents a part of the summary timeline..
/// </summary>
internal abstract class TimelinePart : CompositeDrawable
{
public Bindable<WorkingBeatmap> Beatmap = new Bindable<WorkingBeatmap>();
private readonly Container timeline;
protected TimelinePart()
{
AddInternal(timeline = new Container { RelativeSizeAxes = Axes.Both });
Beatmap.ValueChanged += b =>
{
updateRelativeChildSize();
LoadBeatmap(b);
};
}
private void updateRelativeChildSize()
{
if (!Beatmap.Value.TrackLoaded)
{
timeline.RelativeChildSize = Vector2.One;
return;
}
var track = Beatmap.Value.Track;
if (!track.IsLoaded)
{
// the track may not be loaded completely (only has a length once it is).
Schedule(updateRelativeChildSize);
return;
}
timeline.RelativeChildSize = new Vector2((float)Math.Max(1, track.Length), 1);
}
protected void Add(Drawable visualisation) => timeline.Add(visualisation);
protected virtual void LoadBeatmap(WorkingBeatmap beatmap)
{
timeline.Clear();
}
}
}
|
Fix failing test due to project rename | using System;
using Xunit;
namespace DnxFlash.Test
{
public class MessageTest
{
private Message sut;
public class Constructor : MessageTest
{
[Fact]
public void Should_set_message()
{
sut = new Message("test message");
Assert.Equal("test message", sut.Text);
}
[Theory,
InlineData(null),
InlineData("")]
public void Should_throw_exception_if_message_is_not_valid(string message)
{
var exception = Assert.Throws<ArgumentNullException>(() => new Message(message));
Assert.Equal("message", exception.ParamName);
}
[Fact]
public void Should_set_title()
{
sut = new Message(
text: "test message",
title: "test");
Assert.Equal("test", sut.Title);
}
[Fact]
public void Should_set_type()
{
sut = new Message(
text: "test message",
type: "test");
Assert.Equal("test", sut.Type);
}
}
}
}
| using System;
using Xunit;
namespace DnxFlash.Test
{
public class MessageTest
{
private Message sut;
public class Constructor : MessageTest
{
[Fact]
public void Should_set_message()
{
sut = new Message("test message");
Assert.Equal("test message", sut.Text);
}
[Theory,
InlineData(null),
InlineData("")]
public void Should_throw_exception_if_message_is_not_valid(string text)
{
var exception = Assert.Throws<ArgumentNullException>(() => new Message(text));
Assert.Equal("text", exception.ParamName);
}
[Fact]
public void Should_set_title()
{
sut = new Message(
text: "test message",
title: "test");
Assert.Equal("test", sut.Title);
}
[Fact]
public void Should_set_type()
{
sut = new Message(
text: "test message",
type: "test");
Assert.Equal("test", sut.Type);
}
}
}
}
|
Adjust mania scoring to be 95% based on accuracy | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Mania.Scoring
{
internal class ManiaScoreProcessor : ScoreProcessor
{
protected override double DefaultAccuracyPortion => 0.8;
protected override double DefaultComboPortion => 0.2;
public override HitWindows CreateHitWindows() => new ManiaHitWindows();
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Mania.Scoring
{
internal class ManiaScoreProcessor : ScoreProcessor
{
protected override double DefaultAccuracyPortion => 0.95;
protected override double DefaultComboPortion => 0.05;
public override HitWindows CreateHitWindows() => new ManiaHitWindows();
}
}
|
Add description at top of new template | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace NewAnalyzerTemplate
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class NewAnalyzerTemplateAnalyzer : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
throw new NotImplementedException();
}
}
public override void Initialize(AnalysisContext context)
{
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
/*This tutorial is going to guide you to write a diagnostic analyzer that enforces the placement of one space between the if keyword of an if statement and the
open parenthesis of the condition.
For more information, please reference the ReadMe.
Before you begin, got to Tools->Extensions and Updates->Online, and install:
- .NET Compiler SDK
- Roslyn Syntax Visualizer
*/
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace NewAnalyzerTemplate
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class NewAnalyzerTemplateAnalyzer : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
throw new NotImplementedException();
}
}
public override void Initialize(AnalysisContext context)
{
}
}
}
|
Update assemblyinfo & strong name version to 4.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.
#if DNX
[assembly: AssemblyTitle("NLog.Web.ASPNET5")]
[assembly: AssemblyProduct("NLog.Web for ASP.NET5")]
#else
[assembly: AssemblyTitle("NLog.Web")]
[assembly: AssemblyProduct("NLog.Web")]
#endif
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright © NLog 2015-2016")]
[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("74d5915b-bea9-404c-b4d0-b663164def37")]
| 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.
#if DNX
[assembly: AssemblyTitle("NLog.Web.ASPNET5")]
[assembly: AssemblyProduct("NLog.Web for ASP.NET Core")]
#else
[assembly: AssemblyTitle("NLog.Web")]
[assembly: AssemblyProduct("NLog.Web")]
#endif
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright © NLog 2015-2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("4.0.0.0")] //fixed
// 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("74d5915b-bea9-404c-b4d0-b663164def37")]
|
Fix test in Release mode. | // Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using Perspex.Markup.Data;
using Xunit;
namespace Perspex.Markup.UnitTests.Binding
{
public class ExpressionObserverTests_PerspexProperty
{
[Fact]
public async void Should_Get_Simple_Property_Value()
{
var data = new Class1();
var target = new ExpressionObserver(data, "Foo");
var result = await target.Take(1);
Assert.Equal("foo", result);
}
[Fact]
public void Should_Track_Simple_Property_Value()
{
var data = new Class1();
var target = new ExpressionObserver(data, "Foo");
var result = new List<object>();
var sub = target.Subscribe(x => result.Add(x));
data.SetValue(Class1.FooProperty, "bar");
Assert.Equal(new[] { "foo", "bar" }, result);
sub.Dispose();
}
private class Class1 : PerspexObject
{
public static readonly PerspexProperty<string> FooProperty =
PerspexProperty.Register<Class1, string>("Foo", defaultValue: "foo");
}
}
}
| // Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using Perspex.Markup.Data;
using Xunit;
namespace Perspex.Markup.UnitTests.Binding
{
public class ExpressionObserverTests_PerspexProperty
{
public ExpressionObserverTests_PerspexProperty()
{
var foo = Class1.FooProperty;
}
[Fact]
public async void Should_Get_Simple_Property_Value()
{
var data = new Class1();
var target = new ExpressionObserver(data, "Foo");
var result = await target.Take(1);
Assert.Equal("foo", result);
}
[Fact]
public void Should_Track_Simple_Property_Value()
{
var data = new Class1();
var target = new ExpressionObserver(data, "Foo");
var result = new List<object>();
var sub = target.Subscribe(x => result.Add(x));
data.SetValue(Class1.FooProperty, "bar");
Assert.Equal(new[] { "foo", "bar" }, result);
sub.Dispose();
}
private class Class1 : PerspexObject
{
public static readonly PerspexProperty<string> FooProperty =
PerspexProperty.Register<Class1, string>("Foo", defaultValue: "foo");
}
}
}
|
Fix wrong timescale being forced on win/loss | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class YoumuSlashTimingEffectsController : MonoBehaviour
{
[SerializeField]
private AudioSource musicSource;
[SerializeField]
private float pitchMult = 1f;
[SerializeField]
private float timeScaleMult = 1f;
[SerializeField]
private float volumeMult = 1f;
bool failed = false;
bool ended = false;
float initialTimeScale;
float initialVolume;
void Start ()
{
YoumuSlashPlayerController.onFail += onFail;
YoumuSlashPlayerController.onGameplayEnd += onGameplayEnd;
initialTimeScale = Time.timeScale;
initialVolume = musicSource.volume;
}
void onGameplayEnd()
{
ended = true;
}
void onFail()
{
failed = true;
}
private void LateUpdate()
{
if (MicrogameController.instance.getVictoryDetermined())
Time.timeScale = initialVolume;
else if (ended)
Time.timeScale = timeScaleMult * initialTimeScale;
if (failed)
musicSource.pitch = Time.timeScale * pitchMult;
musicSource.volume = volumeMult * initialVolume;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class YoumuSlashTimingEffectsController : MonoBehaviour
{
[SerializeField]
private AudioSource musicSource;
[SerializeField]
private float pitchMult = 1f;
[SerializeField]
private float timeScaleMult = 1f;
[SerializeField]
private float volumeMult = 1f;
bool failed = false;
bool ended = false;
float initialTimeScale;
float initialVolume;
void Start ()
{
YoumuSlashPlayerController.onFail += onFail;
YoumuSlashPlayerController.onGameplayEnd += onGameplayEnd;
initialTimeScale = Time.timeScale;
initialVolume = musicSource.volume;
}
void onGameplayEnd()
{
ended = true;
}
void onFail()
{
failed = true;
}
private void LateUpdate()
{
if (MicrogameController.instance.getVictoryDetermined())
Time.timeScale = initialTimeScale;
else if (ended)
Time.timeScale = timeScaleMult * initialTimeScale;
if (failed)
musicSource.pitch = Time.timeScale * pitchMult;
musicSource.volume = volumeMult * initialVolume;
}
}
|
Change type in error from of to or | #load "LogHelper.csx"
using System.Configuration;
public static class AppSettingsHelper
{
public static string GetAppSetting(string SettingName, bool LogValue = true )
{
string SettingValue = "";
try
{
SettingValue = ConfigurationManager.AppSettings[SettingName].ToString();
if ((!String.IsNullOrEmpty(SettingValue)) && LogValue)
{
LogHelper.Info($"Retreived AppSetting {SettingName} with a value of {SettingValue}");
}
else if((!String.IsNullOrEmpty(SettingValue)) && !LogValue)
{
LogHelper.Info($"Retreived AppSetting {SettingName} but logging value was turned off");
}
else if(!String.IsNullOrEmpty(SettingValue))
{
LogHelper.Info($"AppSetting {SettingName} was null of empty");
}
}
catch (ConfigurationErrorsException ex)
{
LogHelper.Error($"Unable to find AppSetting {SettingName} with exception of {ex.Message}");
}
catch (System.Exception ex)
{
LogHelper.Error($"Looking for AppSetting {SettingName} caused an exception of {ex.Message}");
}
return SettingValue;
}
} | #load "LogHelper.csx"
using System.Configuration;
public static class AppSettingsHelper
{
public static string GetAppSetting(string SettingName, bool LogValue = true )
{
string SettingValue = "";
try
{
SettingValue = ConfigurationManager.AppSettings[SettingName].ToString();
if ((!String.IsNullOrEmpty(SettingValue)) && LogValue)
{
LogHelper.Info($"Retreived AppSetting {SettingName} with a value of {SettingValue}");
}
else if((!String.IsNullOrEmpty(SettingValue)) && !LogValue)
{
LogHelper.Info($"Retreived AppSetting {SettingName} but logging value was turned off");
}
else if(!String.IsNullOrEmpty(SettingValue))
{
LogHelper.Info($"AppSetting {SettingName} was null or empty");
}
}
catch (ConfigurationErrorsException ex)
{
LogHelper.Error($"Unable to find AppSetting {SettingName} with exception of {ex.Message}");
}
catch (System.Exception ex)
{
LogHelper.Error($"Looking for AppSetting {SettingName} caused an exception of {ex.Message}");
}
return SettingValue;
}
} |
Update copyright data and assembly description. | using System.Reflection;
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("ServerHost")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jorgen Thelin")]
[assembly: AssemblyProduct("ServerHost")]
[assembly: AssemblyCopyright("Copyright © Jorgen Thelin 2015")]
[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("e9fff8d5-f4c0-483d-aee6-5ff82afd434f")]
// 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.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("ServerHost")]
[assembly: AssemblyDescription("ServerHost - A .NET Server Hosting utility library, including in-process server host testing.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jorgen Thelin")]
[assembly: AssemblyProduct("ServerHost")]
[assembly: AssemblyCopyright("Copyright © Jorgen Thelin 2015-2016")]
[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("e9fff8d5-f4c0-483d-aee6-5ff82afd434f")]
// 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")]
|
Fix so that SPARQL query test works | using System;
using System.Collections.Generic;
using System.Text;
using BrightstarDB.EntityFramework;
namespace BrightstarDB.PerformanceBenchmarks.Models
{
[Entity("http://xmlns.com/foaf/0.1/Person")]
public interface IFoafPerson
{
string Id { get; }
[PropertyType("http://xmlns.com/foaf/0.1/name")]
string Name { get; set; }
[PropertyType("http://xmlns.com/foaf/0.1/givenName")]
string GivenName { get; set; }
[PropertyType("http://xmlns.com/foaf/0.1/familyName")]
string FamilyName { get; set; }
[PropertyType("http://xmlns.com/foaf/0.1/age")]
int Age { get; set; }
[PropertyType("http://xmlns.com/foaf/0.1/organization")]
string Organisation { get; set; }
[PropertyType("http://xmlns.com/foaf/0.1/knows")]
ICollection<IFoafPerson> Knows { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using BrightstarDB.EntityFramework;
namespace BrightstarDB.PerformanceBenchmarks.Models
{
[Entity("http://xmlns.com/foaf/0.1/Person")]
public interface IFoafPerson
{
[Identifier("http://www.brightstardb.com/people/")]
string Id { get; }
[PropertyType("http://xmlns.com/foaf/0.1/name")]
string Name { get; set; }
[PropertyType("http://xmlns.com/foaf/0.1/givenName")]
string GivenName { get; set; }
[PropertyType("http://xmlns.com/foaf/0.1/familyName")]
string FamilyName { get; set; }
[PropertyType("http://xmlns.com/foaf/0.1/age")]
int Age { get; set; }
[PropertyType("http://xmlns.com/foaf/0.1/organization")]
string Organisation { get; set; }
[PropertyType("http://xmlns.com/foaf/0.1/knows")]
ICollection<IFoafPerson> Knows { get; set; }
}
}
|
Implement TypeConverter CanConvertTo() and ConvertTo() methods for Uuid. | namespace Bakery
{
using System;
using System.ComponentModel;
using System.Globalization;
public class UuidTypeConverter
: TypeConverter
{
public override Boolean CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(String);
}
public override Object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
{
return new Uuid(Guid.Parse((String)value));
}
}
}
| namespace Bakery
{
using System;
using System.ComponentModel;
using System.Globalization;
public class UuidTypeConverter
: TypeConverter
{
public override Boolean CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(String);
}
public override Boolean CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(String);
}
public override Object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
{
return new Uuid(Guid.Parse((String)value));
}
public override Object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, Object value, Type destinationType)
{
if (value == null)
return null;
return value.ToString();
}
}
}
|
Fix start of week calculation | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumModels
{
public static class Helpers
{
public static DateTimeOffset GetStartOfWeek(string date)
{
var dt = DateTimeOffset.Now;
if (!String.IsNullOrEmpty(date))
{
dt = DateTimeOffset.Parse(date);
}
dt = dt.ToLocalTime();
var dayOfWeekLocal = (int)dt.DayOfWeek;
// +1 because we want to start the week on Monday and not Sunday (local time)
return dt.Date.AddDays(-dayOfWeekLocal + 1);
}
public static string GetDataFileNameFromDate(DateTimeOffset startOfPeriod)
{
return startOfPeriod.ToString("yyyy-MM-dd") + ".json";
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumModels
{
public static class Helpers
{
public static DateTimeOffset GetStartOfWeek(string date)
{
var dt = DateTimeOffset.Now;
if (!String.IsNullOrEmpty(date))
{
dt = DateTimeOffset.Parse(date);
}
dt = dt.ToLocalTime();
var dayOfWeekLocal = (int)dt.DayOfWeek;
// Adjust it so the week starts Monday instead of Sunday
dayOfWeekLocal = (dayOfWeekLocal + 6) % 7;
// Go back to the start of the current week
return dt.Date.AddDays(-dayOfWeekLocal);
}
public static string GetDataFileNameFromDate(DateTimeOffset startOfPeriod)
{
return startOfPeriod.ToString("yyyy-MM-dd") + ".json";
}
}
}
|
Make use of asynchronous methods | using System;
using System.Net.Http;
using Newtonsoft.Json;
namespace PexelsNet
{
public class PexelsClient
{
private readonly string _apiKey;
private const string BaseUrl = "http://api.pexels.com/v1/";
public PexelsClient(string apiKey)
{
_apiKey = apiKey;
}
private HttpClient InitHttpClient()
{
var client = new HttpClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", _apiKey);
return client;
}
public Page Search(string query, int page = 1, int perPage = 15)
{
var client = InitHttpClient();
HttpResponseMessage response = client.GetAsync(BaseUrl + "search?query=" + Uri.EscapeDataString(query) + "&per_page="+ perPage + "&page=" + page).Result;
return GetResult(response);
}
public Page Popular(int page = 1, int perPage = 15)
{
var client = InitHttpClient();
HttpResponseMessage response = client.GetAsync(BaseUrl + "popular?per_page=" + perPage + "&page=" + page).Result;
return GetResult(response);
}
private static Page GetResult(HttpResponseMessage response)
{
var body = response.Content.ReadAsStringAsync().Result;
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<Page>(body);
}
throw new PexelsNetException(response.StatusCode, body);
}
}
}
| using System;
using System.Net.Http;
using Newtonsoft.Json;
using System.Threading.Tasks;
namespace PexelsNet
{
public class PexelsClient
{
private readonly string _apiKey;
private const string BaseUrl = "http://api.pexels.com/v1/";
public PexelsClient(string apiKey)
{
_apiKey = apiKey;
}
private HttpClient InitHttpClient()
{
var client = new HttpClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", _apiKey);
return client;
}
public async Task<Page> SearchAsync(string query, int page = 1, int perPage = 15)
{
var client = InitHttpClient();
HttpResponseMessage response = await client.GetAsync(BaseUrl + "search?query=" + Uri.EscapeDataString(query) + "&per_page=" + perPage + "&page=" + page);
return await GetResultAsync(response);
}
public async Task<Page> PopularAsync(int page = 1, int perPage = 15)
{
var client = InitHttpClient();
HttpResponseMessage response = await client.GetAsync(BaseUrl + "popular?per_page=" + perPage + "&page=" + page);
return await GetResultAsync(response);
}
private static async Task<Page> GetResultAsync(HttpResponseMessage response)
{
var body = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<Page>(body);
}
throw new PexelsNetException(response.StatusCode, body);
}
}
}
|
Disable test debug logging in appveyor. | using System.Collections.Generic;
using System.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Slp.Evi.Storage;
using Slp.Evi.Storage.Bootstrap;
using Slp.Evi.Storage.Database;
using Slp.Evi.Storage.Database.Vendor.MsSql;
namespace Slp.Evi.Test.System.SPARQL.SPARQL_TestSuite.Db
{
[TestClass]
public class MSSQLDb : TestSuite
{
private static Dictionary<string, EviQueryableStorage> _storages;
[ClassInitialize]
public static void TestSuiteInitialization(TestContext context)
{
_storages = new Dictionary<string, EviQueryableStorage>();
foreach (var dataset in StorageNames)
{
var storage = InitializeDataset(dataset, GetSqlDb(), GetStorageFactory());
_storages.Add(dataset, storage);
}
}
private static ISqlDatabase GetSqlDb()
{
var connectionString = ConfigurationManager.ConnectionStrings["mssql_connection"].ConnectionString;
return (new MsSqlDbFactory()).CreateSqlDb(connectionString);
}
private static IEviQueryableStorageFactory GetStorageFactory()
{
var loggerFactory = new LoggerFactory();
loggerFactory.AddConsole(LogLevel.Trace);
loggerFactory.AddDebug(LogLevel.Trace);
return new DefaultEviQueryableStorageFactory(loggerFactory);
}
protected override EviQueryableStorage GetStorage(string storageName)
{
return _storages[storageName];
}
}
}
| using System;
using System.Collections.Generic;
using System.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Slp.Evi.Storage;
using Slp.Evi.Storage.Bootstrap;
using Slp.Evi.Storage.Database;
using Slp.Evi.Storage.Database.Vendor.MsSql;
namespace Slp.Evi.Test.System.SPARQL.SPARQL_TestSuite.Db
{
[TestClass]
public class MSSQLDb : TestSuite
{
private static Dictionary<string, EviQueryableStorage> _storages;
[ClassInitialize]
public static void TestSuiteInitialization(TestContext context)
{
_storages = new Dictionary<string, EviQueryableStorage>();
foreach (var dataset in StorageNames)
{
var storage = InitializeDataset(dataset, GetSqlDb(), GetStorageFactory());
_storages.Add(dataset, storage);
}
}
private static ISqlDatabase GetSqlDb()
{
var connectionString = ConfigurationManager.ConnectionStrings["mssql_connection"].ConnectionString;
return (new MsSqlDbFactory()).CreateSqlDb(connectionString);
}
private static IEviQueryableStorageFactory GetStorageFactory()
{
var loggerFactory = new LoggerFactory();
loggerFactory.AddConsole(LogLevel.Trace);
if (Environment.GetEnvironmentVariable("APPVEYOR") != "True")
{
loggerFactory.AddDebug(LogLevel.Trace);
}
return new DefaultEviQueryableStorageFactory(loggerFactory);
}
protected override EviQueryableStorage GetStorage(string storageName)
{
return _storages[storageName];
}
}
}
|
Add one more unit test | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="DiffbotClientTest.cs" company="KriaSoft LLC">
// Copyright © 2014 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Diffbot.Client.Tests
{
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class DiffbotClientTest
{
private const string ValidApiKey = "<your api key>";
private const string InvalidApiKey = "b2571e7c9108ac25ef31cdd30ef83194";
[TestMethod, TestCategory("Integration")]
public async Task DiffbotClient_GetArticle_Should_Return_an_Article()
{
// Arrange
var client = new DiffbotClient(ValidApiKey);
// Act
var article = await client.GetArticle(
"http://gigaom.com/cloud/silicon-valley-royalty-pony-up-2m-to-scale-diffbots-visual-learning-robot/");
// Assert
Assert.IsNotNull(article);
Assert.AreEqual("Silicon Valley stars pony up $2M to scale Diffbot’s visual learning robot", article.Title);
}
}
}
| // --------------------------------------------------------------------------------------------------------------------
// <copyright file="DiffbotClientTest.cs" company="KriaSoft LLC">
// Copyright © 2014 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Diffbot.Client.Tests
{
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class DiffbotClientTest
{
private const string ValidApiKey = "<your api key>";
private const string InvalidApiKey = "b2571e7c9108ac25ef31cdd30ef83194";
private const string WebPageUrl1 =
"http://gigaom.com/cloud/silicon-valley-royalty-pony-up-2m-to-scale-diffbots-visual-learning-robot/";
[TestMethod, TestCategory("Integration")]
public async Task DiffbotClient_GetArticle_Should_Return_an_Article()
{
// Arrange
var client = new DiffbotClient(ValidApiKey);
// Act
var article = await client.GetArticle(WebPageUrl1);
// Assert
Assert.IsNotNull(article);
Assert.AreEqual("Silicon Valley stars pony up $2M to scale Diffbot’s visual learning robot", article.Title);
}
[TestMethod, TestCategory("Integration"), ExpectedException(typeof(HttpRequestException))]
public async Task DiffbotClient_GetArticle_Should_Throw_an_Exception()
{
// Arrange
var client = new DiffbotClient(InvalidApiKey);
// Act
await client.GetArticle(WebPageUrl1);
}
}
}
|
Support all particle vector providers that have m_vLiteralValue | using System;
using System.Numerics;
using ValveResourceFormat.Serialization;
namespace GUI.Types.ParticleRenderer
{
public interface IVectorProvider
{
Vector3 NextVector();
}
public class LiteralVectorProvider : IVectorProvider
{
private readonly Vector3 value;
public LiteralVectorProvider(Vector3 value)
{
this.value = value;
}
public LiteralVectorProvider(double[] value)
{
this.value = new Vector3((float)value[0], (float)value[1], (float)value[2]);
}
public Vector3 NextVector() => value;
}
public static class IVectorProviderExtensions
{
public static IVectorProvider GetVectorProvider(this IKeyValueCollection keyValues, string propertyName)
{
var property = keyValues.GetProperty<object>(propertyName);
if (property is IKeyValueCollection numberProviderParameters && numberProviderParameters.ContainsKey("m_nType"))
{
var type = numberProviderParameters.GetProperty<string>("m_nType");
switch (type)
{
case "PVEC_TYPE_LITERAL":
return new LiteralVectorProvider(numberProviderParameters.GetArray<double>("m_vLiteralValue"));
default:
throw new InvalidCastException($"Could not create vector provider of type {type}.");
}
}
return new LiteralVectorProvider(keyValues.GetArray<double>(propertyName));
}
}
}
| using System;
using System.Numerics;
using ValveResourceFormat.Serialization;
namespace GUI.Types.ParticleRenderer
{
public interface IVectorProvider
{
Vector3 NextVector();
}
public class LiteralVectorProvider : IVectorProvider
{
private readonly Vector3 value;
public LiteralVectorProvider(Vector3 value)
{
this.value = value;
}
public LiteralVectorProvider(double[] value)
{
this.value = new Vector3((float)value[0], (float)value[1], (float)value[2]);
}
public Vector3 NextVector() => value;
}
public static class IVectorProviderExtensions
{
public static IVectorProvider GetVectorProvider(this IKeyValueCollection keyValues, string propertyName)
{
var property = keyValues.GetProperty<object>(propertyName);
if (property is IKeyValueCollection numberProviderParameters && numberProviderParameters.ContainsKey("m_nType"))
{
var type = numberProviderParameters.GetProperty<string>("m_nType");
switch (type)
{
case "PVEC_TYPE_LITERAL":
return new LiteralVectorProvider(numberProviderParameters.GetArray<double>("m_vLiteralValue"));
default:
if (numberProviderParameters.ContainsKey("m_vLiteralValue"))
{
Console.Error.WriteLine($"Vector provider of type {type} is not directly supported, but it has m_vLiteralValue.");
return new LiteralVectorProvider(numberProviderParameters.GetArray<double>("m_vLiteralValue"));
}
throw new InvalidCastException($"Could not create vector provider of type {type}.");
}
}
return new LiteralVectorProvider(keyValues.GetArray<double>(propertyName));
}
}
}
|
Fix bug where drawn objects are also transparent, and add pen variable. | using System;
using System.Drawing;
using System.Windows.Forms;
namespace vuwall_motion {
public partial class TransparentForm : Form {
public TransparentForm() {
InitializeComponent();
DoubleBuffered = true;
ShowInTaskbar = false;
}
private void TransparentForm_Load(object sender, EventArgs e)
{
int wl = TransparentWindowAPI.GetWindowLong(this.Handle, TransparentWindowAPI.GWL.ExStyle);
wl = wl | 0x80000 | 0x20;
TransparentWindowAPI.SetWindowLong(this.Handle, TransparentWindowAPI.GWL.ExStyle, wl);
TransparentWindowAPI.SetLayeredWindowAttributes(this.Handle, 0, 128, TransparentWindowAPI.LWA.Alpha);
Invalidate();
}
private void TransparentForm_Paint(object sender, PaintEventArgs e) {
e.Graphics.DrawEllipse(Pens.Red, 250, 250, 20, 20);
}
// TODO: Method to get an event from MYO to get x & y positions, used to invalidate
}
}
| using System;
using System.Drawing;
using System.Windows.Forms;
namespace vuwall_motion {
public partial class TransparentForm : Form {
private Pen pen = new Pen(Color.Red, 5);
public TransparentForm() {
InitializeComponent();
DoubleBuffered = true;
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
TransparencyKey = BackColor;
ShowInTaskbar = false;
}
private void TransparentForm_Load(object sender, EventArgs e)
{
int wl = TransparentWindowAPI.GetWindowLong(this.Handle, TransparentWindowAPI.GWL.ExStyle);
wl = wl | 0x80000 | 0x20;
TransparentWindowAPI.SetLayeredWindowAttributes(this.Handle, 0, 128, TransparentWindowAPI.LWA.Alpha);
Invalidate();
}
private void TransparentForm_Paint(object sender, PaintEventArgs e) {
e.Graphics.DrawEllipse(pen, 250, 250, 20, 20);
}
// TODO: Method to get an event from MYO to get x & y positions, used to invalidate
}
}
|
Add journals and self relations. | using System.ComponentModel.DataAnnotations;
namespace LibrarySystem.Models
{
public class Subject
{
public int Id { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
}
} | // <copyright file="Subject.cs" company="YAGNI">
// All rights reserved.
// </copyright>
// <summary>Holds implementation of Book model.</summary>
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace LibrarySystem.Models
{
/// <summary>
/// Represent a <see cref="Subject"/> entity model.
/// </summary>
public class Subject
{
/// <summary>
/// Child nodes of the <see cref="Subject"/> entity.
/// </summary>
private ICollection<Subject> subSubjects;
/// <summary>
/// Journal of the <see cref="Subject"/> entity.
/// </summary>
private ICollection<Journal> journals;
/// <summary>
/// Initializes a new instance of the <see cref="Subject"/> class.
/// </summary>
public Subject()
{
this.subSubjects = new HashSet<Subject>();
this.journals = new HashSet<Journal>();
}
/// <summary>
/// Gets or sets the primary key of the <see cref="Subject"/> entity.
/// </summary>
/// <value>Primary key of the <see cref="Subject"/> entity.</value>
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
/// <summary>
/// Gets or sets the name of the <see cref="Subject"/> entity.
/// </summary>
/// <value>Name of the <see cref="Subject"/> entity.</value>
[Required]
[StringLength(50, ErrorMessage = "Subject Name Invalid Length", MinimumLength = 1)]
public string Name { get; set; }
/// <summary>
/// Gets or sets foreign key of the parent node of the <see cref="Subject"/> entity.
/// </summary>
/// <value>Primary key of the parent node of the <see cref="Subject"/> entity.</value>
public int? SuperSubjectId { get; set; }
/// <summary>
/// Gets or sets the parent node of the <see cref="Subject"/> entity.
/// </summary>
/// <value>Parent node of the <see cref="Subject"/> entity.</value>
public virtual Subject SuperSubject { get; set; }
/// <summary>
/// Gets or sets the child nodes of the <see cref="Subject"/> entity.
/// </summary>
/// <value>Initial collection of child nodes of the <see cref="Subject"/> entity.</value>
public virtual ICollection<Subject> SubSubjects
{
get
{
return this.subSubjects;
}
set
{
this.subSubjects = value;
}
}
/// <summary>
/// Gets or sets the journals related to the <see cref="Subject"/> entity.
/// </summary>
/// <value>Initial collection of journals related to the <see cref="Subject"/> entity.</value>
public virtual ICollection<Journal> Journals
{
get
{
return this.journals;
}
set
{
this.journals = value;
}
}
}
} |
Fix bug in IQuickInfoModelProvider for SELECT column aliases | using System;
using System.ComponentModel.Composition;
using NQuery.Syntax;
namespace NQuery.Authoring.QuickInfo
{
[Export(typeof(IQuickInfoModelProvider))]
internal sealed class ExpressionSelectColumnQuickInfoModelProvider : QuickInfoModelProvider<ExpressionSelectColumnSyntax>
{
protected override QuickInfoModel CreateModel(SemanticModel semanticModel, int position, ExpressionSelectColumnSyntax node)
{
if (node.Alias == null)
return null;
var symbol = semanticModel.GetDeclaredSymbol(node);
return symbol == null
? null
: QuickInfoModel.ForSymbol(semanticModel, node.Alias.Identifier.Span, symbol);
}
}
}
| using System;
using System.ComponentModel.Composition;
using NQuery.Syntax;
namespace NQuery.Authoring.QuickInfo
{
[Export(typeof(IQuickInfoModelProvider))]
internal sealed class ExpressionSelectColumnQuickInfoModelProvider : QuickInfoModelProvider<ExpressionSelectColumnSyntax>
{
protected override QuickInfoModel CreateModel(SemanticModel semanticModel, int position, ExpressionSelectColumnSyntax node)
{
if (node.Alias == null || !node.Alias.Span.Contains(position))
return null;
var symbol = semanticModel.GetDeclaredSymbol(node);
return symbol == null
? null
: QuickInfoModel.ForSymbol(semanticModel, node.Alias.Identifier.Span, symbol);
}
}
}
|
Update test suite for latest changes | using System;
using System.Globalization;
namespace MultiMiner.Win.Extensions
{
public static class DateTimeExtensions
{
public static string ToReallyShortDateString(this DateTime dateTime)
{
//short date no year
string shortDateString = dateTime.ToShortDateString();
//year could be at beginning (JP) or end (EN)
string dateSeparator = CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator;
string value1 = dateTime.Year + dateSeparator;
string value2 = dateSeparator + dateTime.Year;
return shortDateString.Replace(value1, String.Empty).Replace(value2, String.Empty);
}
public static string ToReallyShortDateTimeString(this DateTime dateTime)
{
return String.Format("{0} {1}", dateTime.ToReallyShortDateString(), dateTime.ToShortTimeString());
}
}
}
| using System;
using System.Globalization;
namespace MultiMiner.Win.Extensions
{
public static class DateTimeExtensions
{
private static string ToReallyShortDateString(this DateTime dateTime)
{
//short date no year
string shortDateString = dateTime.ToShortDateString();
//year could be at beginning (JP) or end (EN)
string dateSeparator = CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator;
string value1 = dateTime.Year + dateSeparator;
string value2 = dateSeparator + dateTime.Year;
return shortDateString.Replace(value1, String.Empty).Replace(value2, String.Empty);
}
public static string ToReallyShortDateTimeString(this DateTime dateTime)
{
return String.Format("{0} {1}", dateTime.ToReallyShortDateString(), dateTime.ToShortTimeString());
}
}
}
|
Remove dead line from autocomplete | using WootzJs.Web;
namespace WootzJs.Mvc.Views
{
public class AutocompleteTextBox<T> : Control
{
private Control content;
private Control overlay;
private Element contentNode;
private Element overlayContainer;
private DropDownAlignment alignment;
private T selectedItem;
protected override Element CreateNode()
{
contentNode = Browser.Document.CreateElement("input");
contentNode.SetAttribute("type", "text");
contentNode.Style.Height = "100%";
var dropdown = Browser.Document.CreateElement("");
overlayContainer = Browser.Document.CreateElement("div");
overlayContainer.Style.Position = "absolute";
overlayContainer.Style.Display = "none";
overlayContainer.AppendChild(overlay.Node);
Add(overlay);
var overlayAnchor = Browser.Document.CreateElement("div");
overlayAnchor.Style.Position = "relative";
overlayAnchor.AppendChild(overlayContainer);
var result = Browser.Document.CreateElement("div");
result.AppendChild(contentNode);
result.AppendChild(overlayAnchor);
return result;
}
}
} | using WootzJs.Web;
namespace WootzJs.Mvc.Views
{
public class AutocompleteTextBox<T> : Control
{
private Control content;
private Control overlay;
private Element contentNode;
private Element overlayContainer;
private DropDownAlignment alignment;
private T selectedItem;
protected override Element CreateNode()
{
contentNode = Browser.Document.CreateElement("input");
contentNode.SetAttribute("type", "text");
contentNode.Style.Height = "100%";
overlayContainer = Browser.Document.CreateElement("div");
overlayContainer.Style.Position = "absolute";
overlayContainer.Style.Display = "none";
overlayContainer.AppendChild(overlay.Node);
Add(overlay);
var overlayAnchor = Browser.Document.CreateElement("div");
overlayAnchor.Style.Position = "relative";
overlayAnchor.AppendChild(overlayContainer);
var result = Browser.Document.CreateElement("div");
result.AppendChild(contentNode);
result.AppendChild(overlayAnchor);
return result;
}
}
} |
Fix app always showing the login page after orientation change | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Disposables;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Support.V4.App;
using Android.Views;
using Android.Widget;
using ReactiveUI.Routing.Android;
using ReactiveUI.Routing.Presentation;
using ReactiveUI.Routing.UseCases.Common.ViewModels;
using Splat;
namespace ReactiveUI.Routing.UseCases.Android
{
[Activity(Label = "ReactiveUI.Routing.UseCases.Android", MainLauncher = true)]
public class MainActivity : FragmentActivity, IActivatable
{
protected override void OnCreate(Bundle savedInstanceState)
{
Locator.CurrentMutable.InitializeRoutingAndroid(this);
this.WhenActivated(d =>
{
Locator.Current.GetService<FragmentActivationForViewFetcher>().SetFragmentManager(SupportFragmentManager);
PagePresenter.RegisterHost(SupportFragmentManager, Resource.Id.Container)
.DisposeWith(d);
Locator.Current.GetService<IAppPresenter>()
.PresentPage(new LoginViewModel())
.Subscribe()
.DisposeWith(d);
});
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Disposables;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Support.V4.App;
using Android.Views;
using Android.Widget;
using ReactiveUI.Routing.Android;
using ReactiveUI.Routing.Presentation;
using ReactiveUI.Routing.UseCases.Common.ViewModels;
using Splat;
namespace ReactiveUI.Routing.UseCases.Android
{
[Activity(Label = "ReactiveUI.Routing.UseCases.Android", MainLauncher = true)]
public class MainActivity : FragmentActivity, IActivatable
{
protected override void OnCreate(Bundle savedInstanceState)
{
Locator.CurrentMutable.InitializeRoutingAndroid(this);
this.WhenActivated(d =>
{
Locator.Current.GetService<FragmentActivationForViewFetcher>().SetFragmentManager(SupportFragmentManager);
PagePresenter.RegisterHost(SupportFragmentManager, Resource.Id.Container)
.DisposeWith(d);
var presenter = Locator.Current.GetService<IAppPresenter>();
if (!presenter.ActiveViews.Any())
{
presenter.PresentPage(new LoginViewModel())
.Subscribe()
.DisposeWith(d);
}
});
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
}
}
} |
Add filter property to popular movies request. | namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common
{
using Base.Get;
using Objects.Basic;
using Objects.Get.Movies;
internal class TraktMoviesPopularRequest : TraktGetRequest<TraktPaginationListResult<TraktMovie>, TraktMovie>
{
internal TraktMoviesPopularRequest(TraktClient client) : base(client) { }
protected override string UriTemplate => "movies/popular{?extended,page,limit}";
protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;
protected override bool SupportsPagination => true;
protected override bool IsListResult => true;
}
}
| namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common
{
using Base;
using Base.Get;
using Objects.Basic;
using Objects.Get.Movies;
internal class TraktMoviesPopularRequest : TraktGetRequest<TraktPaginationListResult<TraktMovie>, TraktMovie>
{
internal TraktMoviesPopularRequest(TraktClient client) : base(client) { }
protected override string UriTemplate => "movies/popular{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications}";
protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;
internet TraktMovieFilter Filter { get; set; }
protected override bool SupportsPagination => true;
protected override bool IsListResult => true;
}
}
|
Fix exception if Keys is null | using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Radosgw.AdminAPI
{
public class User
{
[JsonProperty(PropertyName = "display_name")]
public string DisplayName { get; set; }
[JsonProperty(PropertyName = "user_id")]
public string UserId { get; set; }
[JsonProperty(PropertyName = "tenant")]
public string Tenant { get; set; }
[JsonProperty(PropertyName = "email")]
public string Email { get; set; }
[JsonProperty(PropertyName = "max_buckets")]
public uint MaxBuckets { get; set; }
[JsonConverter(typeof(BoolConverter))]
[JsonProperty(PropertyName = "suspended")]
public bool Suspended { get; set; }
[JsonProperty(PropertyName="keys")]
public List<Key> Keys { get; set; }
public override string ToString()
{
return string.Format("[User: DisplayName={0}, UserId={1}, Tenant={2}, Email={3}, MaxBuckets={4}, Suspended={5}, Keys={6}]",
DisplayName, UserId, Tenant, Email, MaxBuckets, Suspended, string.Format("[{0}]", string.Join(",", Keys)));
}
public User()
{
}
}
}
| using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Radosgw.AdminAPI
{
public class User
{
[JsonProperty(PropertyName = "display_name")]
public string DisplayName { get; set; }
[JsonProperty(PropertyName = "user_id")]
public string UserId { get; set; }
[JsonProperty(PropertyName = "tenant")]
public string Tenant { get; set; }
[JsonProperty(PropertyName = "email")]
public string Email { get; set; }
[JsonProperty(PropertyName = "max_buckets")]
public uint MaxBuckets { get; set; }
[JsonConverter(typeof(BoolConverter))]
[JsonProperty(PropertyName = "suspended")]
public bool Suspended { get; set; }
[JsonProperty(PropertyName="keys")]
public List<Key> Keys { get; set; }
public override string ToString()
{
return string.Format("[User: DisplayName={0}, UserId={1}, Tenant={2}, Email={3}, MaxBuckets={4}, Suspended={5}, Keys={6}]",
DisplayName, UserId, Tenant, Email, MaxBuckets, Suspended, string.Format("[{0}]", string.Join(",", Keys ?? new List<Key>())));
}
public User()
{
}
}
}
|
Add comment that design time data does not work with {x:Bind} | using Jbe.NewsReader.Applications.ViewModels;
using Jbe.NewsReader.Applications.Views;
namespace Jbe.NewsReader.Presentation.DesignData
{
public class SampleFeedItemListViewModel : FeedItemListViewModel
{
public SampleFeedItemListViewModel() : base(new MockFeedItemListView(), null)
{
}
private class MockFeedItemListView : IFeedItemListView
{
public object DataContext { get; set; }
}
}
}
| using Jbe.NewsReader.Applications.ViewModels;
using Jbe.NewsReader.Applications.Views;
namespace Jbe.NewsReader.Presentation.DesignData
{
public class SampleFeedItemListViewModel : FeedItemListViewModel
{
public SampleFeedItemListViewModel() : base(new MockFeedItemListView(), null)
{
// Note: Design time data does not work with {x:Bind}
}
private class MockFeedItemListView : IFeedItemListView
{
public object DataContext { get; set; }
}
}
}
|
Fix follow point transforms not working after rewind | // 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 osuTK;
using osuTK.Graphics;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Effects;
using osu.Framework.Graphics.Shapes;
using osu.Game.Skinning;
namespace osu.Game.Rulesets.Osu.Objects.Drawables.Connections
{
public class FollowPoint : Container
{
private const float width = 8;
public override bool RemoveWhenNotAlive => false;
public FollowPoint()
{
Origin = Anchor.Centre;
Child = new SkinnableDrawable(new OsuSkinComponent(OsuSkinComponents.FollowPoint), _ => new Container
{
Masking = true,
AutoSizeAxes = Axes.Both,
CornerRadius = width / 2,
EdgeEffect = new EdgeEffectParameters
{
Type = EdgeEffectType.Glow,
Colour = Color4.White.Opacity(0.2f),
Radius = 4,
},
Child = new Box
{
Size = new Vector2(width),
Blending = BlendingParameters.Additive,
Origin = Anchor.Centre,
Anchor = Anchor.Centre,
Alpha = 0.5f,
}
}, confineMode: ConfineMode.NoScaling);
}
}
}
| // 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 osuTK;
using osuTK.Graphics;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Effects;
using osu.Framework.Graphics.Shapes;
using osu.Game.Skinning;
namespace osu.Game.Rulesets.Osu.Objects.Drawables.Connections
{
public class FollowPoint : Container
{
private const float width = 8;
public override bool RemoveWhenNotAlive => false;
public override bool RemoveCompletedTransforms => false;
public FollowPoint()
{
Origin = Anchor.Centre;
Child = new SkinnableDrawable(new OsuSkinComponent(OsuSkinComponents.FollowPoint), _ => new Container
{
Masking = true,
AutoSizeAxes = Axes.Both,
CornerRadius = width / 2,
EdgeEffect = new EdgeEffectParameters
{
Type = EdgeEffectType.Glow,
Colour = Color4.White.Opacity(0.2f),
Radius = 4,
},
Child = new Box
{
Size = new Vector2(width),
Blending = BlendingParameters.Additive,
Origin = Anchor.Centre,
Anchor = Anchor.Centre,
Alpha = 0.5f,
}
}, confineMode: ConfineMode.NoScaling);
}
}
}
|
Add registration to the serive | using Glimpse;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using System.Collections.Generic;
namespace Glimpse
{
public class GlimpseServices
{
public static IEnumerable<IServiceDescriptor> GetDefaultServices()
{
return GetDefaultServices(new Configuration());
}
public static IEnumerable<IServiceDescriptor> GetDefaultServices(IConfiguration configuration)
{
var describe = new ServiceDescriber(configuration);
//
// Discovery & Reflection.
//
yield return describe.Transient<ITypeActivator, DefaultTypeActivator>();
yield return describe.Transient<ITypeSelector, DefaultTypeSelector>();
yield return describe.Transient<IAssemblyProvider, DefaultAssemblyProvider>();
yield return describe.Transient<ITypeService, DefaultTypeService>();
yield return describe.Transient(typeof(IDiscoverableCollection<>), typeof(ReflectionDiscoverableCollection<>));
}
}
} | using Glimpse;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using System.Collections.Generic;
namespace Glimpse
{
public class GlimpseServices
{
public static IEnumerable<IServiceDescriptor> GetDefaultServices()
{
return GetDefaultServices(new Configuration());
}
public static IEnumerable<IServiceDescriptor> GetDefaultServices(IConfiguration configuration)
{
var describe = new ServiceDescriber(configuration);
//
// Discovery & Reflection.
//
yield return describe.Transient<ITypeActivator, DefaultTypeActivator>();
yield return describe.Transient<ITypeSelector, DefaultTypeSelector>();
yield return describe.Transient<IAssemblyProvider, DefaultAssemblyProvider>();
yield return describe.Transient<ITypeService, DefaultTypeService>();
yield return describe.Transient(typeof(IDiscoverableCollection<>), typeof(ReflectionDiscoverableCollection<>));
//
// Broker
//
yield return describe.Singleton<IMessageBus, DefaultMessageBus>();
}
}
} |
Remove reference to old library name. | using ArduinoUploader;
namespace ArduinoSketchUploader
{
/// <summary>
/// The ArduinoLibCSharp SketchUploader can upload a compiled (Intel) HEX file directly to an attached Arduino.
/// </summary>
internal class Program
{
private static void Main(string[] args)
{
var commandLineOptions = new CommandLineOptions();
if (!CommandLine.Parser.Default.ParseArguments(args, commandLineOptions)) return;
var options = new ArduinoSketchUploaderOptions
{
PortName = commandLineOptions.PortName,
FileName = commandLineOptions.FileName,
ArduinoModel = commandLineOptions.ArduinoModel
};
var uploader = new ArduinoUploader.ArduinoSketchUploader(options);
uploader.UploadSketch();
}
}
}
| using ArduinoUploader;
namespace ArduinoSketchUploader
{
/// <summary>
/// The ArduinoSketchUploader can upload a compiled (Intel) HEX file directly to an attached Arduino.
/// </summary>
internal class Program
{
private static void Main(string[] args)
{
var commandLineOptions = new CommandLineOptions();
if (!CommandLine.Parser.Default.ParseArguments(args, commandLineOptions)) return;
var options = new ArduinoSketchUploaderOptions
{
PortName = commandLineOptions.PortName,
FileName = commandLineOptions.FileName,
ArduinoModel = commandLineOptions.ArduinoModel
};
var uploader = new ArduinoUploader.ArduinoSketchUploader(options);
uploader.UploadSketch();
}
}
}
|
Add flag 0x20 to PacketFlags | using System;
using System.Runtime.InteropServices;
using PolarisServer.Models;
namespace PolarisServer.Models
{
public struct PacketHeader
{
public UInt32 Size;
public byte Type;
public byte Subtype;
public byte Flags1;
public byte Flags2;
public PacketHeader(int size, byte type, byte subtype, byte flags1, byte flags2)
{
this.Size = (uint)size;
this.Type = type;
this.Subtype = subtype;
this.Flags1 = flags1;
this.Flags2 = flags2;
}
public PacketHeader(byte type, byte subtype) : this(type, subtype, (byte)0)
{
}
public PacketHeader(byte type, byte subtype, byte flags1) : this(0, type, subtype, flags1, 0)
{
}
public PacketHeader(byte type, byte subtype, PacketFlags packetFlags) : this(type, subtype, (byte)packetFlags)
{
}
}
[Flags]
public enum PacketFlags : byte
{
NONE,
STREAM_PACKED = 0x4,
FLAG_10 = 0x10,
ENTITY_HEADER = 0x40
}
}
| using System;
using System.Runtime.InteropServices;
using PolarisServer.Models;
namespace PolarisServer.Models
{
public struct PacketHeader
{
public UInt32 Size;
public byte Type;
public byte Subtype;
public byte Flags1;
public byte Flags2;
public PacketHeader(int size, byte type, byte subtype, byte flags1, byte flags2)
{
this.Size = (uint)size;
this.Type = type;
this.Subtype = subtype;
this.Flags1 = flags1;
this.Flags2 = flags2;
}
public PacketHeader(byte type, byte subtype) : this(type, subtype, (byte)0)
{
}
public PacketHeader(byte type, byte subtype, byte flags1) : this(0, type, subtype, flags1, 0)
{
}
public PacketHeader(byte type, byte subtype, PacketFlags packetFlags) : this(type, subtype, (byte)packetFlags)
{
}
}
[Flags]
public enum PacketFlags : byte
{
NONE,
STREAM_PACKED = 0x4,
FLAG_10 = 0x10,
FULL_MOVEMENT = 0x20,
ENTITY_HEADER = 0x40
}
}
|
Remove EN-us culture from assembly attributes. | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Provision.AspNet.Identity.PlainSql")]
[assembly: AssemblyDescription("ASP.NET Identity provider for SQL databases")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Provision Data Systems Inc.")]
[assembly: AssemblyProduct("Provision.AspNet.Identity.PlainSql")]
[assembly: AssemblyCopyright("Copyright © 2016 Provision Data Systems Inc.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("EN-us")]
[assembly: ComVisible(false)]
[assembly: Guid("9248deff-4947-481f-ba7c-09e9925e62d2")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Provision.AspNet.Identity.PlainSql")]
[assembly: AssemblyDescription("ASP.NET Identity provider for SQL databases")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Provision Data Systems Inc.")]
[assembly: AssemblyProduct("Provision.AspNet.Identity.PlainSql")]
[assembly: AssemblyCopyright("Copyright © 2016 Provision Data Systems Inc.")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("9248deff-4947-481f-ba7c-09e9925e62d2")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
|
Rework extension to spend less time on UI thread | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#if WINDOWS_UWP
using Microsoft.MixedReality.Toolkit.Windows.Utilities;
using System;
using System.Collections.Generic;
using UnityEngine.XR.WSA.Input;
using Windows.Foundation;
using Windows.Perception;
using Windows.Storage.Streams;
using Windows.UI.Input.Spatial;
#endif
namespace Microsoft.MixedReality.Toolkit.Windows.Input
{
/// <summary>
/// Extensions for the InteractionSource class to expose the renderable model.
/// </summary>
public static class InteractionSourceExtensions
{
#if WINDOWS_UWP
public static IAsyncOperation<IRandomAccessStreamWithContentType> TryGetRenderableModelAsync(this InteractionSource interactionSource)
{
IAsyncOperation<IRandomAccessStreamWithContentType> returnValue = null;
if (WindowsApiChecker.UniversalApiContractV5_IsAvailable)
{
UnityEngine.WSA.Application.InvokeOnUIThread(() =>
{
IReadOnlyList<SpatialInteractionSourceState> sources = SpatialInteractionManager.GetForCurrentView()?.GetDetectedSourcesAtTimestamp(PerceptionTimestampHelper.FromHistoricalTargetTime(DateTimeOffset.Now));
for (var i = 0; i < sources.Count; i++)
{
if (sources[i].Source.Id.Equals(interactionSource.id))
{
returnValue = sources[i].Source.Controller.TryGetRenderableModelAsync();
}
}
}, true);
}
return returnValue;
}
#endif // WINDOWS_UWP
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#if WINDOWS_UWP
using Microsoft.MixedReality.Toolkit.Windows.Utilities;
using System;
using System.Collections.Generic;
using UnityEngine.XR.WSA.Input;
using Windows.Foundation;
using Windows.Perception;
using Windows.Storage.Streams;
using Windows.UI.Input.Spatial;
#endif
namespace Microsoft.MixedReality.Toolkit.Windows.Input
{
/// <summary>
/// Extensions for the InteractionSource class to expose the renderable model.
/// </summary>
public static class InteractionSourceExtensions
{
#if WINDOWS_UWP
public static IAsyncOperation<IRandomAccessStreamWithContentType> TryGetRenderableModelAsync(this InteractionSource interactionSource)
{
IAsyncOperation<IRandomAccessStreamWithContentType> returnValue = null;
if (WindowsApiChecker.UniversalApiContractV5_IsAvailable)
{
IReadOnlyList<SpatialInteractionSourceState> sources = null;
UnityEngine.WSA.Application.InvokeOnUIThread(() =>
{
sources = SpatialInteractionManager.GetForCurrentView()?.GetDetectedSourcesAtTimestamp(PerceptionTimestampHelper.FromHistoricalTargetTime(DateTimeOffset.Now));
}, true);
for (var i = 0; i < sources?.Count; i++)
{
if (sources[i].Source.Id.Equals(interactionSource.id))
{
returnValue = sources[i].Source.Controller.TryGetRenderableModelAsync();
}
}
}
return returnValue;
}
#endif // WINDOWS_UWP
}
}
|
Make sure Issues are at correct index | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hl7.Fhir.Model;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Spark.Engine.Extensions;
namespace Spark.Engine.Test.Extensions
{
[TestClass]
public class OperationOutcomeInnerErrorsTest
{
[TestMethod]
public void AddAllInnerErrorsTest()
{
OperationOutcome outcome;
try
{
try
{
try
{
throw new Exception("Third error level");
}
catch (Exception e3)
{
throw new Exception("Second error level", e3);
}
}
catch (Exception e2)
{
throw new Exception("First error level", e2);
}
}
catch (Exception e1)
{
outcome = new OperationOutcome().AddAllInnerErrors(e1);
}
Assert.IsFalse(!outcome.Issue.Any(i => i.Diagnostics.Equals("Exception: First error level")), "No info about first error");
Assert.IsFalse(!outcome.Issue.Any(i => i.Diagnostics.Equals("Exception: Second error level")), "No info about second error");
Assert.IsFalse(!outcome.Issue.Any(i => i.Diagnostics.Equals("Exception: Third error level")), "No info about third error");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hl7.Fhir.Model;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Spark.Engine.Extensions;
namespace Spark.Engine.Test.Extensions
{
[TestClass]
public class OperationOutcomeInnerErrorsTest
{
[TestMethod]
public void AddAllInnerErrorsTest()
{
OperationOutcome outcome;
try
{
try
{
try
{
throw new Exception("Third error level");
}
catch (Exception e3)
{
throw new Exception("Second error level", e3);
}
}
catch (Exception e2)
{
throw new Exception("First error level", e2);
}
}
catch (Exception e1)
{
outcome = new OperationOutcome().AddAllInnerErrors(e1);
}
Assert.IsTrue(outcome.Issue.FindIndex(i => i.Diagnostics.Equals("Exception: First error level")) == 0, "First error level should be at index 0");
Assert.IsTrue(outcome.Issue.FindIndex(i => i.Diagnostics.Equals("Exception: Second error level")) == 1, "Second error level should be at index 1");
Assert.IsTrue(outcome.Issue.FindIndex(i => i.Diagnostics.Equals("Exception: Third error level")) == 2, "Third error level should be at index 2");
}
}
}
|
Use TryParseExact instead of ParseExact. Better performance. | using System;
using System.Collections.Generic;
using System.Globalization;
namespace Arkivverket.Arkade.Core.Addml.Definitions.DataTypes
{
public class DateDataType : DataType
{
private readonly string _dateTimeFormat;
private readonly string _fieldFormat;
public DateDataType(string fieldFormat) : this(fieldFormat, null)
{
}
public DateDataType(string fieldFormat, List<string> nullValues) : base(nullValues)
{
_fieldFormat = fieldFormat;
_dateTimeFormat = ConvertToDateTimeFormat(_fieldFormat);
}
public DateDataType()
{
throw new NotImplementedException();
}
private string ConvertToDateTimeFormat(string fieldFormat)
{
// TODO: Do we have to convert ADDML data fieldFormat til .NET format?
return fieldFormat;
}
public DateTimeOffset Parse(string dateTimeString)
{
DateTimeOffset dto = DateTimeOffset.ParseExact
(dateTimeString, _dateTimeFormat, CultureInfo.InvariantCulture);
return dto;
}
protected bool Equals(DateDataType other)
{
return string.Equals(_fieldFormat, other._fieldFormat);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((DateDataType) obj);
}
public override int GetHashCode()
{
return _fieldFormat?.GetHashCode() ?? 0;
}
public override bool IsValid(string s)
{
try
{
Parse(s);
return true;
}
catch (FormatException e)
{
return false;
}
}
}
} | using System;
using System.Collections.Generic;
using System.Globalization;
namespace Arkivverket.Arkade.Core.Addml.Definitions.DataTypes
{
public class DateDataType : DataType
{
private readonly string _dateTimeFormat;
private readonly string _fieldFormat;
public DateDataType(string fieldFormat) : this(fieldFormat, null)
{
}
public DateDataType(string fieldFormat, List<string> nullValues) : base(nullValues)
{
_fieldFormat = fieldFormat;
_dateTimeFormat = ConvertToDateTimeFormat(_fieldFormat);
}
private string ConvertToDateTimeFormat(string fieldFormat)
{
return fieldFormat;
}
public DateTimeOffset Parse(string dateTimeString)
{
DateTimeOffset dto = DateTimeOffset.ParseExact
(dateTimeString, _dateTimeFormat, CultureInfo.InvariantCulture);
return dto;
}
protected bool Equals(DateDataType other)
{
return string.Equals(_fieldFormat, other._fieldFormat);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((DateDataType) obj);
}
public override int GetHashCode()
{
return _fieldFormat?.GetHashCode() ?? 0;
}
public override bool IsValid(string s)
{
DateTimeOffset res;
return DateTimeOffset.TryParseExact(s, _dateTimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out res);
}
}
} |
Fix fallback to default combo colours not working | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Textures;
using osu.Game.Audio;
namespace osu.Game.Skinning
{
public class DefaultSkin : Skin
{
public DefaultSkin()
: base(SkinInfo.Default)
{
Configuration = new DefaultSkinConfiguration();
}
public override Drawable GetDrawableComponent(ISkinComponent component) => null;
public override Texture GetTexture(string componentName) => null;
public override SampleChannel GetSample(ISampleInfo sampleInfo) => null;
public override IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup) => 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.Collections.Generic;
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Textures;
using osu.Game.Audio;
using osuTK.Graphics;
namespace osu.Game.Skinning
{
public class DefaultSkin : Skin
{
public DefaultSkin()
: base(SkinInfo.Default)
{
Configuration = new DefaultSkinConfiguration();
}
public override Drawable GetDrawableComponent(ISkinComponent component) => null;
public override Texture GetTexture(string componentName) => null;
public override SampleChannel GetSample(ISampleInfo sampleInfo) => null;
public override IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup)
{
switch (lookup)
{
case GlobalSkinConfiguration global:
switch (global)
{
case GlobalSkinConfiguration.ComboColours:
return SkinUtils.As<TValue>(new Bindable<List<Color4>>(Configuration.ComboColours));
}
break;
}
return null;
}
}
}
|
Add a HTML title to error view | @model AtomicChessPuzzles.HttpErrors.HttpError
<h1>@Model.StatusCode - @Model.StatusText</h1>
<p>@Model.Description</p> | @model AtomicChessPuzzles.HttpErrors.HttpError
@section Title{@Model.StatusCode @Model.StatusText}
<h1>@Model.StatusCode - @Model.StatusText</h1>
<p>@Model.Description</p> |
Modify case handling of entry types | using System;
using System.IO;
namespace Flirper
{
public class ImageListEntry
{
public string uri;
public string title;
public string author;
public string extraInfo;
public ImageListEntry (string uri, string title, string author, string extraInfo)
{
this.uri = uri;
this.title = title;
this.author = author;
this.extraInfo = extraInfo;
}
public bool isHTTP {
get {
return this.uri.ToLower ().StartsWith ("http:") || this.uri.ToLower ().StartsWith ("https:");
}
}
public bool isFile {
get {
if (isHTTP || isLatestSaveGame)
return false;
return !System.IO.Directory.Exists(@uri) && System.IO.File.Exists(@uri);
}
}
public bool isDirectory {
get {
if (isHTTP || isLatestSaveGame || isFile)
return false;
FileAttributes attr = System.IO.File.GetAttributes (@uri);
return (attr & FileAttributes.Directory) == FileAttributes.Directory;
}
}
public bool isLatestSaveGame {
get {
return this.uri.ToLower ().StartsWith ("savegame");
}
}
public bool isValidPath {
get {
if(isHTTP || isLatestSaveGame)
return true;
try {
FileInfo fi = new System.IO.FileInfo(@uri);
FileAttributes attr = System.IO.File.GetAttributes (@uri);
} catch (Exception ex) {
ex.ToString();
return false;
}
return true;
}
}
}
} | using System;
using System.IO;
namespace Flirper
{
public class ImageListEntry
{
public string uri;
public string title;
public string author;
public string extraInfo;
public ImageListEntry (string uri, string title, string author, string extraInfo)
{
this.uri = uri;
this.title = title;
this.author = author;
this.extraInfo = extraInfo;
}
public bool isHTTP {
get {
return this.uri.ToLower ().StartsWith ("http:") || this.uri.ToLower ().StartsWith ("https:");
}
}
public bool isFile {
get {
return isLocal && !System.IO.Directory.Exists(@uri) && System.IO.File.Exists(@uri);
}
}
public bool isDirectory {
get {
if (!isLocal || isFile)
return false;
FileAttributes attr = System.IO.File.GetAttributes (@uri);
return (attr & FileAttributes.Directory) == FileAttributes.Directory;
}
}
public bool isLatestSaveGame {
get {
return this.uri.ToLower ().StartsWith ("savegame");
}
}
private bool isLocal {
get {
return !(isHTTP || isLatestSaveGame);
}
}
public bool isValidPath {
get {
if(!isLocal)
return true;
try {
FileInfo fi = new System.IO.FileInfo(@uri);
FileAttributes attr = System.IO.File.GetAttributes (@uri);
} catch (Exception ex) {
ex.ToString();
return false;
}
return true;
}
}
}
} |
Add Bigsby Gates was here | using System;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World, I was created by my father, Bigsby, in an unidentified evironment!");
}
}
}
| using System;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World, I was created by my father, Bigsby, in an unidentified evironment!");
Console.WriteLine("Bigsby Gates was here!");
}
}
}
|
Return 400 instead of 500 if no login/password | using System.Data.Entity;
using System.Threading.Tasks;
using JoinRpg.Web.Helpers;
using Microsoft.Owin.Security.OAuth;
namespace JoinRpg.Web
{
internal class ApiSignInProvider : OAuthAuthorizationServerProvider
{
private ApplicationUserManager Manager { get; }
public ApiSignInProvider(ApplicationUserManager manager)
{
Manager = manager;
}
/// <inheritdoc />
public override Task ValidateClientAuthentication(
OAuthValidateClientAuthenticationContext context)
{
context.Validated();
return Task.FromResult(0);
}
public override async Task GrantResourceOwnerCredentials(
OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"});
var user = await Manager.FindByEmailAsync(context.UserName);
if (!await Manager.CheckPasswordAsync(user, context.Password))
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
var x = await user.GenerateUserIdentityAsync(Manager, context.Options.AuthenticationType);
context.Validated(x);
}
}
} | using System.Threading.Tasks;
using JoinRpg.Web.Helpers;
using Microsoft.Owin.Security.OAuth;
namespace JoinRpg.Web
{
internal class ApiSignInProvider : OAuthAuthorizationServerProvider
{
private ApplicationUserManager Manager { get; }
public ApiSignInProvider(ApplicationUserManager manager)
{
Manager = manager;
}
/// <inheritdoc />
public override Task ValidateClientAuthentication(
OAuthValidateClientAuthenticationContext context)
{
context.Validated();
return Task.FromResult(0);
}
public override async Task GrantResourceOwnerCredentials(
OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"});
if (string.IsNullOrWhiteSpace(context.UserName) ||
string.IsNullOrWhiteSpace(context.Password))
{
context.SetError("invalid_grant", "Please supply susername and password.");
return;
}
var user = await Manager.FindByEmailAsync(context.UserName);
if (!await Manager.CheckPasswordAsync(user, context.Password))
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
var x = await user.GenerateUserIdentityAsync(Manager, context.Options.AuthenticationType);
context.Validated(x);
}
}
} |
Fix The GlowWindow in the taskmanager | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Interactivity;
using MahApps.Metro.Controls;
namespace MahApps.Metro.Behaviours
{
public class GlowWindowBehavior : Behavior<Window>
{
private GlowWindow left, right, top, bottom;
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.Loaded += (sender, e) =>
{
left = new GlowWindow(this.AssociatedObject, GlowDirection.Left);
right = new GlowWindow(this.AssociatedObject, GlowDirection.Right);
top = new GlowWindow(this.AssociatedObject, GlowDirection.Top);
bottom = new GlowWindow(this.AssociatedObject, GlowDirection.Bottom);
Show();
left.Update();
right.Update();
top.Update();
bottom.Update();
};
this.AssociatedObject.Closed += (sender, args) =>
{
if (left != null) left.Close();
if (right != null) right.Close();
if (top != null) top.Close();
if (bottom != null) bottom.Close();
};
}
public void Hide()
{
left.Hide();
right.Hide();
bottom.Hide();
top.Hide();
}
public void Show()
{
left.Show();
right.Show();
top.Show();
bottom.Show();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Interactivity;
using MahApps.Metro.Controls;
namespace MahApps.Metro.Behaviours
{
public class GlowWindowBehavior : Behavior<Window>
{
private GlowWindow left, right, top, bottom;
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.Loaded += (sender, e) =>
{
left = new GlowWindow(this.AssociatedObject, GlowDirection.Left);
right = new GlowWindow(this.AssociatedObject, GlowDirection.Right);
top = new GlowWindow(this.AssociatedObject, GlowDirection.Top);
bottom = new GlowWindow(this.AssociatedObject, GlowDirection.Bottom);
left.Owner = (MetroWindow)sender;
right.Owner = (MetroWindow)sender;
top.Owner = (MetroWindow)sender;
bottom.Owner = (MetroWindow)sender;
Show();
left.Update();
right.Update();
top.Update();
bottom.Update();
};
this.AssociatedObject.Closed += (sender, args) =>
{
if (left != null) left.Close();
if (right != null) right.Close();
if (top != null) top.Close();
if (bottom != null) bottom.Close();
};
}
public void Hide()
{
left.Hide();
right.Hide();
bottom.Hide();
top.Hide();
}
public void Show()
{
left.Show();
right.Show();
top.Show();
bottom.Show();
}
}
}
|
Fix broken redirect when restoring game on mobile | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
namespace WebPlayer.Mobile
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string origUrl = Request.QueryString.Get("origUrl");
int queryPos = origUrl.IndexOf("Play.aspx?");
if (queryPos != -1)
{
var origUrlValues = HttpUtility.ParseQueryString(origUrl.Substring(origUrl.IndexOf("?")));
string id = origUrlValues.Get("id");
Response.Redirect("Play.aspx?id=" + id);
return;
}
Response.Clear();
Response.StatusCode = 404;
Response.End();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
namespace WebPlayer.Mobile
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string origUrl = Request.QueryString.Get("origUrl");
int queryPos = origUrl.IndexOf("Play.aspx?");
if (queryPos != -1)
{
var origUrlValues = HttpUtility.ParseQueryString(origUrl.Substring(origUrl.IndexOf("?")));
string id = origUrlValues.Get("id");
if (!string.IsNullOrEmpty(id))
{
Response.Redirect("Play.aspx?id=" + id);
return;
}
string load = origUrlValues.Get("load");
if (!string.IsNullOrEmpty(load))
{
Response.Redirect("Play.aspx?load=" + load);
return;
}
}
Response.Clear();
Response.StatusCode = 404;
Response.End();
}
}
} |
Revert "Revert "LoginTest is completed"" | using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Support.UI;
using NUnit.Framework;
namespace SeleniumTasksProject1._1
{
[TestFixture]
public class InternetExplorer
{
private IWebDriver driver;
private WebDriverWait wait;
[SetUp]
public void start()
{
driver = new InternetExplorerDriver();
wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
}
[Test]
public void LoginTestInInternetExplorer()
{
driver.Url = "http://localhost:8082/litecart/admin/";
}
[TearDown]
public void stop()
{
driver.Quit();
driver = null;
}
}
}
| using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Support.UI;
using NUnit.Framework;
namespace SeleniumTasksProject1._1
{
[TestFixture]
public class InternetExplorer
{
private IWebDriver driver;
private WebDriverWait wait;
[SetUp]
public void start()
{
driver = new InternetExplorerDriver();
wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
}
[Test]
public void LoginTestInInternetExplorer()
{
driver.Url = "http://localhost:8082/litecart/admin/";
driver.FindElement(By.Name("username")).SendKeys("admin");
driver.FindElement(By.Name("password")).SendKeys("admin");
driver.FindElement(By.Name("login")).Click();
//wait.Until(ExpectedConditions.TitleIs("My Store"));
}
[TearDown]
public void stop()
{
driver.Quit();
driver = null;
}
}
}
|
Fix for disposing DataContext object. | /* ------------------------------------------------------------------------- */
//
// Copyright (c) 2010 CubeSoft, 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.
//
/* ------------------------------------------------------------------------- */
using System;
using System.Windows;
using System.Windows.Interactivity;
namespace Cube.Xui.Behaviors
{
/* --------------------------------------------------------------------- */
///
/// DisposeAction
///
/// <summary>
/// DataContext の開放処理を実行する TriggerAction です。
/// </summary>
///
/* --------------------------------------------------------------------- */
public class DisposeAction : TriggerAction<FrameworkElement>
{
/* ----------------------------------------------------------------- */
///
/// Invoke
///
/// <summary>
/// 処理を実行します。
/// </summary>
///
/* ----------------------------------------------------------------- */
protected override void Invoke(object notused)
{
if (AssociatedObject.DataContext is IDisposable dc) dc.Dispose();
AssociatedObject.DataContext = null;
}
}
}
| /* ------------------------------------------------------------------------- */
//
// Copyright (c) 2010 CubeSoft, 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.
//
/* ------------------------------------------------------------------------- */
using System;
using System.Windows;
using System.Windows.Interactivity;
namespace Cube.Xui.Behaviors
{
/* --------------------------------------------------------------------- */
///
/// DisposeAction
///
/// <summary>
/// DataContext の開放処理を実行する TriggerAction です。
/// </summary>
///
/* --------------------------------------------------------------------- */
public class DisposeAction : TriggerAction<FrameworkElement>
{
/* ----------------------------------------------------------------- */
///
/// Invoke
///
/// <summary>
/// 処理を実行します。
/// </summary>
///
/* ----------------------------------------------------------------- */
protected override void Invoke(object notused)
{
var dc = AssociatedObject.DataContext as IDisposable;
AssociatedObject.DataContext = null;
dc?.Dispose();
}
}
}
|
Add missing field to FinishedWarp | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FreecraftCore.Serializer;
namespace Booma.Proxy
{
/// <summary>
/// Payload that tells the server we've finsihed loading/bursting/warping.
/// We should have sent a warp request to the server before this so it should know where we
/// were going.
/// </summary>
[WireDataContract]
[SubCommand60Client(SubCommand60OperationCode.EnterFreshlyWrappedZoneCommand)]
public sealed class Sub60FinishedWarpingBurstingPayload : BlockNetworkCommandEventClientPayload
{
//Packet is empty. Just tells the server we bursted/warped finished.
public Sub60FinishedWarpingBurstingPayload()
{
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FreecraftCore.Serializer;
namespace Booma.Proxy
{
/// <summary>
/// Payload that tells the server we've finsihed loading/bursting/warping.
/// We should have sent a warp request to the server before this so it should know where we
/// were going.
/// </summary>
[WireDataContract]
[SubCommand60Client(SubCommand60OperationCode.EnterFreshlyWrappedZoneCommand)]
public sealed class Sub60FinishedWarpingBurstingPayload : BlockNetworkCommandEventClientPayload
{
//Packet is empty. Just tells the server we bursted/warped finished.
//TODO: Is this client id?
[WireMember(1)]
private short unk { get; }
public Sub60FinishedWarpingBurstingPayload()
{
}
}
}
|
Increase project version number to 0.8 | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Yevgeniy Shunevych")]
[assembly: AssemblyProduct("Atata")]
[assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2016")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.7.0.0")]
[assembly: AssemblyFileVersion("0.7.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Yevgeniy Shunevych")]
[assembly: AssemblyProduct("Atata")]
[assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2016")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.8.0.0")]
[assembly: AssemblyFileVersion("0.8.0.0")]
|
Add a foreach induction variable cast test | using System;
using System.Collections.Generic;
public class Enumerator
{
public Enumerator() { }
public int Current { get; private set; } = 10;
public bool MoveNext()
{
Current--;
return Current > 0;
}
public void Dispose()
{
Console.WriteLine("Hi!");
}
}
public class Enumerable
{
public Enumerable() { }
public Enumerator GetEnumerator()
{
return new Enumerator();
}
}
public static class Program
{
public static Enumerable StaticEnumerable = new Enumerable();
public static void Main(string[] Args)
{
var col = Args;
foreach (var item in col)
Console.WriteLine(item);
foreach (var item in new List<string>(Args))
Console.WriteLine(item);
foreach (var item in StaticEnumerable)
Console.WriteLine(item);
}
}
| using System;
using System.Collections.Generic;
public class Enumerator
{
public Enumerator() { }
public int Current { get; private set; } = 10;
public bool MoveNext()
{
Current--;
return Current > 0;
}
public void Dispose()
{
Console.WriteLine("Hi!");
}
}
public class Enumerable
{
public Enumerable() { }
public Enumerator GetEnumerator()
{
return new Enumerator();
}
}
public static class Program
{
public static Enumerable StaticEnumerable = new Enumerable();
public static void Main(string[] Args)
{
var col = Args;
foreach (var item in col)
Console.WriteLine(item);
foreach (var item in new List<string>(Args))
Console.WriteLine(item);
foreach (var item in StaticEnumerable)
Console.WriteLine(item);
foreach (string item in new List<object>())
Console.WriteLine(item);
}
}
|
Adjust repeat/tail fade in to match stable closer | // 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.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Osu.Objects
{
/// <summary>
/// A hitcircle which is at the end of a slider path (either repeat or final tail).
/// </summary>
public abstract class SliderEndCircle : HitCircle
{
public int RepeatIndex { get; set; }
public double SpanDuration { get; set; }
protected override void ApplyDefaultsToSelf(ControlPointInfo controlPointInfo, BeatmapDifficulty difficulty)
{
base.ApplyDefaultsToSelf(controlPointInfo, difficulty);
// Out preempt should be one span early to give the user ample warning.
TimePreempt += SpanDuration;
// We want to show the first RepeatPoint as the TimePreempt dictates but on short (and possibly fast) sliders
// we may need to cut down this time on following RepeatPoints to only show up to two RepeatPoints at any given time.
if (RepeatIndex > 0)
TimePreempt = Math.Min(SpanDuration * 2, TimePreempt);
}
protected override HitWindows CreateHitWindows() => HitWindows.Empty;
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Osu.Objects
{
/// <summary>
/// A hitcircle which is at the end of a slider path (either repeat or final tail).
/// </summary>
public abstract class SliderEndCircle : HitCircle
{
public int RepeatIndex { get; set; }
public double SpanDuration { get; set; }
protected override void ApplyDefaultsToSelf(ControlPointInfo controlPointInfo, BeatmapDifficulty difficulty)
{
base.ApplyDefaultsToSelf(controlPointInfo, difficulty);
if (RepeatIndex > 0)
{
// Repeat points after the first span should appear behind the still-visible one.
TimeFadeIn = 0;
// The next end circle should appear exactly after the previous circle (on the same end) is hit.
TimePreempt = SpanDuration * 2;
}
}
protected override HitWindows CreateHitWindows() => HitWindows.Empty;
}
}
|
Fix issue with precision in assertions | using System;
using System.Collections.Generic;
using System.Linq;
using SFA.DAS.Payments.AcceptanceTests.Contexts;
using SFA.DAS.Payments.AcceptanceTests.ReferenceDataModels;
using SFA.DAS.Payments.AcceptanceTests.ResultsDataModels;
namespace SFA.DAS.Payments.AcceptanceTests.Assertions.TransactionTypeRules
{
public abstract class TransactionTypeRuleBase
{
public virtual void AssertPeriodValues(IEnumerable<PeriodValue> periodValues, LearnerResults[] submissionResults, EmployerAccountContext employerAccountContext)
{
foreach (var period in periodValues)
{
var payments = FilterPayments(period, submissionResults, employerAccountContext);
var paidInPeriod = payments.Sum(p => p.Amount);
if (period.Value != paidInPeriod)
{
throw new Exception(FormatAssertionFailureMessage(period, paidInPeriod));
}
}
}
protected abstract IEnumerable<PaymentResult> FilterPayments(PeriodValue period, IEnumerable<LearnerResults> submissionResults, EmployerAccountContext employerAccountContext);
protected abstract string FormatAssertionFailureMessage(PeriodValue period, decimal actualPaymentInPeriod);
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using SFA.DAS.Payments.AcceptanceTests.Contexts;
using SFA.DAS.Payments.AcceptanceTests.ReferenceDataModels;
using SFA.DAS.Payments.AcceptanceTests.ResultsDataModels;
namespace SFA.DAS.Payments.AcceptanceTests.Assertions.TransactionTypeRules
{
public abstract class TransactionTypeRuleBase
{
public virtual void AssertPeriodValues(IEnumerable<PeriodValue> periodValues, LearnerResults[] submissionResults, EmployerAccountContext employerAccountContext)
{
foreach (var period in periodValues)
{
var payments = FilterPayments(period, submissionResults, employerAccountContext);
var paidInPeriod = payments.Sum(p => p.Amount);
if(Math.Round(paidInPeriod, 2) != Math.Round(period.Value, 2))
{
throw new Exception(FormatAssertionFailureMessage(period, paidInPeriod));
}
}
}
protected abstract IEnumerable<PaymentResult> FilterPayments(PeriodValue period, IEnumerable<LearnerResults> submissionResults, EmployerAccountContext employerAccountContext);
protected abstract string FormatAssertionFailureMessage(PeriodValue period, decimal actualPaymentInPeriod);
}
}
|
Fix `SynchronizationContext` to match correctly implementation structure | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading;
#nullable enable
namespace osu.Framework.Threading
{
/// <summary>
/// A synchronisation context which posts all continuatiuons to a scheduler instance.
/// </summary>
internal class SchedulerSynchronizationContext : SynchronizationContext
{
private readonly Scheduler scheduler;
public SchedulerSynchronizationContext(Scheduler scheduler)
{
this.scheduler = scheduler;
}
public override void Send(SendOrPostCallback d, object? state) => scheduler.Add(() => d(state), false);
public override void Post(SendOrPostCallback d, object? state) => scheduler.Add(() => d(state), true);
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Diagnostics;
using System.Threading;
#nullable enable
namespace osu.Framework.Threading
{
/// <summary>
/// A synchronisation context which posts all continuatiuons to a scheduler instance.
/// </summary>
internal class SchedulerSynchronizationContext : SynchronizationContext
{
private readonly Scheduler scheduler;
public SchedulerSynchronizationContext(Scheduler scheduler)
{
this.scheduler = scheduler;
}
public override void Send(SendOrPostCallback d, object? state)
{
var del = scheduler.Add(() => d(state));
Debug.Assert(del != null);
while (del.State == ScheduledDelegate.RunState.Waiting)
scheduler.Update();
}
public override void Post(SendOrPostCallback d, object? state) => scheduler.Add(() => d(state));
}
}
|
Add optional dotnet new arguments | namespace Boilerplate.Templates.Test
{
using System;
using System.IO;
using System.Threading.Tasks;
public static class TempDirectoryExtensions
{
public static async Task<Project> DotnetNew(
this TempDirectory tempDirectory,
string templateName,
string name = null,
TimeSpan? timeout = null)
{
await ProcessAssert.AssertStart(tempDirectory.DirectoryPath, "dotnet", $"new {templateName} --name \"{name}\"", timeout ?? TimeSpan.FromSeconds(20));
var projectDirectoryPath = Path.Combine(tempDirectory.DirectoryPath, name);
var projectFilePath = Path.Combine(projectDirectoryPath, name + ".csproj");
var publishDirectoryPath = Path.Combine(projectDirectoryPath, "Publish");
return new Project(name, projectFilePath, projectDirectoryPath, publishDirectoryPath);
}
}
}
| namespace Boilerplate.Templates.Test
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
public static class TempDirectoryExtensions
{
public static async Task<Project> DotnetNew(
this TempDirectory tempDirectory,
string templateName,
string name,
IDictionary<string, string> arguments = null,
TimeSpan? timeout = null)
{
var stringBuilder = new StringBuilder($"new {templateName} --name \"{name}\"");
if (arguments != null)
{
foreach (var argument in arguments)
{
stringBuilder.Append($" --{argument.Key} \"{argument.Value}\"");
}
}
await ProcessAssert.AssertStart(
tempDirectory.DirectoryPath,
"dotnet",
stringBuilder.ToString(),
timeout ?? TimeSpan.FromSeconds(20));
var projectDirectoryPath = Path.Combine(tempDirectory.DirectoryPath, name);
var projectFilePath = Path.Combine(projectDirectoryPath, name + ".csproj");
var publishDirectoryPath = Path.Combine(projectDirectoryPath, "Publish");
return new Project(name, projectFilePath, projectDirectoryPath, publishDirectoryPath);
}
}
}
|
Create only 1 hit file per running process | using System;
using System.IO;
namespace MiniCover.HitServices
{
public static class HitService
{
public static MethodContext EnterMethod(
string hitsPath,
string assemblyName,
string className,
string methodName)
{
return new MethodContext(hitsPath, assemblyName, className, methodName);
}
public class MethodContext : IDisposable
{
private readonly string _hitsPath;
private readonly HitContext _hitContext;
private readonly bool _saveHitContext;
public MethodContext(
string hitsPath,
string assemblyName,
string className,
string methodName)
{
_hitsPath = hitsPath;
if (HitContext.Current == null)
{
_hitContext = new HitContext(assemblyName, className, methodName);
HitContext.Current = _hitContext;
_saveHitContext = true;
}
else
{
_hitContext = HitContext.Current;
}
}
public void HitInstruction(int id)
{
_hitContext.RecordHit(id);
}
public void Dispose()
{
if (_saveHitContext)
{
Directory.CreateDirectory(_hitsPath);
var filePath = Path.Combine(_hitsPath, $"{Guid.NewGuid()}.hits");
using (var fileStream = File.Open(filePath, FileMode.CreateNew))
{
_hitContext.Serialize(fileStream);
fileStream.Flush();
}
HitContext.Current = null;
}
}
}
}
} | using System;
using System.Collections.Concurrent;
using System.IO;
namespace MiniCover.HitServices
{
public static class HitService
{
public static MethodContext EnterMethod(
string hitsPath,
string assemblyName,
string className,
string methodName)
{
return new MethodContext(hitsPath, assemblyName, className, methodName);
}
public class MethodContext : IDisposable
{
private static ConcurrentDictionary<string, Stream> _filesStream = new ConcurrentDictionary<string, Stream>();
private readonly string _hitsPath;
private readonly HitContext _hitContext;
private readonly bool _saveHitContext;
public MethodContext(
string hitsPath,
string assemblyName,
string className,
string methodName)
{
_hitsPath = hitsPath;
if (HitContext.Current == null)
{
_hitContext = new HitContext(assemblyName, className, methodName);
HitContext.Current = _hitContext;
_saveHitContext = true;
}
else
{
_hitContext = HitContext.Current;
}
}
public void HitInstruction(int id)
{
_hitContext.RecordHit(id);
}
public void Dispose()
{
if (_saveHitContext)
{
var fileStream = _filesStream.GetOrAdd(_hitsPath, CreateOutputFile);
lock (fileStream)
{
_hitContext.Serialize(fileStream);
fileStream.Flush();
}
HitContext.Current = null;
}
}
private static FileStream CreateOutputFile(string hitsPath)
{
Directory.CreateDirectory(hitsPath);
var filePath = Path.Combine(hitsPath, $"{Guid.NewGuid()}.hits");
return File.Open(filePath, FileMode.CreateNew);
}
}
}
} |
Add tutorials to blog categories. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CompetitionPlatform.Data.BlogCategory
{
public class BlogCategoriesRepository : IBlogCategoriesRepository
{
public List<string> GetCategories()
{
return new List<string>
{
"News",
"Results",
"Winners",
"Success stories",
"Videos",
"About"
};
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CompetitionPlatform.Data.BlogCategory
{
public class BlogCategoriesRepository : IBlogCategoriesRepository
{
public List<string> GetCategories()
{
return new List<string>
{
"News",
"Results",
"Winners",
"Success stories",
"Videos",
"About",
"Tutorials"
};
}
}
}
|
Replace helper implementation with DateOffset members | using System;
namespace LibGit2Sharp.Core
{
/// <summary>
/// Provides helper methods to help converting between Epoch (unix timestamp) and <see cref="DateTimeOffset"/>.
/// </summary>
internal static class Epoch
{
private static readonly DateTimeOffset epochDateTimeOffset = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
/// <summary>
/// Builds a <see cref="DateTimeOffset"/> from a Unix timestamp and a timezone offset.
/// </summary>
/// <param name="secondsSinceEpoch">The number of seconds since 00:00:00 UTC on 1 January 1970.</param>
/// <param name="timeZoneOffsetInMinutes">The number of minutes from UTC in a timezone.</param>
/// <returns>A <see cref="DateTimeOffset"/> representing this instant.</returns>
public static DateTimeOffset ToDateTimeOffset(long secondsSinceEpoch, int timeZoneOffsetInMinutes)
{
DateTimeOffset utcDateTime = epochDateTimeOffset.AddSeconds(secondsSinceEpoch);
TimeSpan offset = TimeSpan.FromMinutes(timeZoneOffsetInMinutes);
return new DateTimeOffset(utcDateTime.DateTime.Add(offset), offset);
}
/// <summary>
/// Converts the<see cref="DateTimeOffset.UtcDateTime"/> part of a <see cref="DateTimeOffset"/> into a Unix timestamp.
/// </summary>
/// <param name="date">The <see cref="DateTimeOffset"/> to convert.</param>
/// <returns>The number of seconds since 00:00:00 UTC on 1 January 1970.</returns>
public static Int32 ToSecondsSinceEpoch(this DateTimeOffset date)
{
DateTimeOffset utcDate = date.ToUniversalTime();
return (Int32)utcDate.Subtract(epochDateTimeOffset).TotalSeconds;
}
}
}
| using System;
namespace LibGit2Sharp.Core
{
/// <summary>
/// Provides helper methods to help converting between Epoch (unix timestamp) and <see cref="DateTimeOffset"/>.
/// </summary>
internal static class Epoch
{
/// <summary>
/// Builds a <see cref="DateTimeOffset"/> from a Unix timestamp and a timezone offset.
/// </summary>
/// <param name="secondsSinceEpoch">The number of seconds since 00:00:00 UTC on 1 January 1970.</param>
/// <param name="timeZoneOffsetInMinutes">The number of minutes from UTC in a timezone.</param>
/// <returns>A <see cref="DateTimeOffset"/> representing this instant.</returns>
public static DateTimeOffset ToDateTimeOffset(long secondsSinceEpoch, int timeZoneOffsetInMinutes) =>
DateTimeOffset.FromUnixTimeSeconds(secondsSinceEpoch).ToOffset(TimeSpan.FromMinutes(timeZoneOffsetInMinutes));
/// <summary>
/// Converts the<see cref="DateTimeOffset.UtcDateTime"/> part of a <see cref="DateTimeOffset"/> into a Unix timestamp.
/// </summary>
/// <param name="date">The <see cref="DateTimeOffset"/> to convert.</param>
/// <returns>The number of seconds since 00:00:00 UTC on 1 January 1970.</returns>
public static Int32 ToSecondsSinceEpoch(this DateTimeOffset date) => (int)date.ToUnixTimeSeconds();
}
}
|
Fix RadioButtons, need to use Active insted of Activate. | using System;
namespace Views
{
[System.ComponentModel.ToolboxItem(true)]
public partial class BooleanRadioButton : Gtk.Bin, IEditable
{
String[] labels;
bool isEditable;
public BooleanRadioButton ()
{
this.Build ();
}
public String[] Labels {
get { return this.labels; }
set {
labels = value;
radiobutton_true.Label = labels[0];
radiobutton_false.Label = labels[1];
}
}
public bool Value () {
if (radiobutton_true.Active)
return true;
else
return false;
}
public bool IsEditable {
get {
return this.isEditable;
}
set {
isEditable = value;
radiobutton_true.Visible = value;
radiobutton_false.Visible = value;
text.Visible = !value;
text.Text = radiobutton_true.Active ? labels[0] : labels[1];
}
}
public new bool Activate {
get {
return Value ();
}
set {
bool state = value;
if (state)
radiobutton_true.Activate ();
else
radiobutton_false.Activate ();
}
}
}
} | using System;
namespace Views
{
[System.ComponentModel.ToolboxItem(true)]
public partial class BooleanRadioButton : Gtk.Bin, IEditable
{
String[] labels;
bool isEditable;
public BooleanRadioButton ()
{
this.Build ();
}
public String[] Labels {
get { return this.labels; }
set {
labels = value;
radiobutton_true.Label = labels[0];
radiobutton_false.Label = labels[1];
}
}
public bool Value () {
if (radiobutton_true.Active)
return true;
else
return false;
}
public bool IsEditable {
get {
return this.isEditable;
}
set {
isEditable = value;
radiobutton_true.Visible = value;
radiobutton_false.Visible = value;
text.Visible = !value;
text.Text = radiobutton_true.Active ? labels[0] : labels[1];
}
}
public new bool Activate {
get {
return Value ();
}
set {
bool state = value;
if (state) {
radiobutton_true.Active = true;
} else {
radiobutton_false.Active = true;
}
}
}
}
} |
Update server side API for single multiple answer question | using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRespository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var question = _dbContext.SingleMultipleAnswerQuestion.ToList();
return question;
}
/// <summary>
/// Add single multiple answer question into model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption)
{
singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id;
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement);
}
_dbContext.SaveChanges();
}
}
}
| using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRespository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var question = _dbContext.SingleMultipleAnswerQuestion.ToList();
return question;
}
/// <summary>
/// Add single multiple answer question into model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption)
{
singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id;
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement);
}
_dbContext.SaveChanges();
}
}
}
|
Use localized content for cookies disabled message | <article id="cookies-disabled-panel" class="panel-inverse">
<h1>Cookies are disabled</h1>
<section>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
</section>
</br>
</br>
</article>
| <article id="cookies-disabled-panel" class="panel-inverse">
<h1>@Text.Content.CookiesDisabledHeading</h1>
<section>
@Text.Content.CookiesDisabledDetails
</section>
</br>
</br>
</article>
|
Make project comvisible explicitly set to false to meet compliance requirements. | using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Microsoft.ApplicationInsights.AspNetCore.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] | using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: InternalsVisibleTo("Microsoft.ApplicationInsights.AspNetCore.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: ComVisible(false)] |
Support nullable properties on authorization_controls | namespace Stripe.Issuing
{
using System.Collections.Generic;
using Newtonsoft.Json;
public class AuthorizationControls : StripeEntity
{
[JsonProperty("allowed_categories")]
public List<string> AllowedCategories { get; set; }
[JsonProperty("blocked_categories")]
public List<string> BlockedCategories { get; set; }
[JsonProperty("currency")]
public string Currency { get; set; }
[JsonProperty("max_amount")]
public long MaxAmount { get; set; }
[JsonProperty("max_approvals")]
public long MaxApprovals { get; set; }
}
}
| namespace Stripe.Issuing
{
using System.Collections.Generic;
using Newtonsoft.Json;
public class AuthorizationControls : StripeEntity
{
[JsonProperty("allowed_categories")]
public List<string> AllowedCategories { get; set; }
[JsonProperty("blocked_categories")]
public List<string> BlockedCategories { get; set; }
[JsonProperty("currency")]
public string Currency { get; set; }
[JsonProperty("max_amount")]
public long? MaxAmount { get; set; }
[JsonProperty("max_approvals")]
public long? MaxApprovals { get; set; }
}
}
|
Change exception type for null argument to ArgumentNullException. | using System;
using NUnit.Framework;
using DevTyr.Gullap;
namespace DevTyr.Gullap.Tests.With_Converter.For_SetParser
{
[TestFixture]
public class When_argument_is_null
{
[Test]
public void Should_throw_argument_exception ()
{
var converter = new Converter (new ConverterOptions {
SitePath = "any"
});
Assert.Throws<ArgumentException> (() => converter.SetParser (null));
}
[Test]
public void Should_throw_exception_with_proper_message ()
{
var converter = new Converter (new ConverterOptions {
SitePath = "any"
});
Assert.Throws<ArgumentException> (() => converter.SetParser (null), "No valid parser given");
}
}
}
| using System;
using NUnit.Framework;
using DevTyr.Gullap;
namespace DevTyr.Gullap.Tests.With_Converter.For_SetParser
{
[TestFixture]
public class When_argument_is_null
{
[Test]
public void Should_throw_argument_null_exception ()
{
var converter = new Converter (new ConverterOptions {
SitePath = "any"
});
Assert.Throws<ArgumentNullException> (() => converter.SetParser (null));
}
[Test]
public void Should_throw_exception_with_proper_message ()
{
var converter = new Converter (new ConverterOptions {
SitePath = "any"
});
Assert.Throws<ArgumentNullException> (() => converter.SetParser (null), "No valid parser given");
}
}
}
|
Change statusbar errors to yellow | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Avalonia.Data.Converters;
using Avalonia.Media;
using AvalonStudio.Extensibility.Theme;
using WalletWasabi.Models;
namespace WalletWasabi.Gui.Converters
{
public class StatusColorConvertor : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool isTor = Enum.TryParse(value.ToString(), out TorStatus tor);
if (isTor && tor == TorStatus.NotRunning)
{
return Brushes.Red;
}
bool isBackend = Enum.TryParse(value.ToString(), out BackendStatus backend);
if (isBackend && backend == BackendStatus.NotConnected)
{
return Brushes.Red;
}
return ColorTheme.CurrentTheme.Foreground;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
}
| using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Avalonia.Data.Converters;
using Avalonia.Media;
using AvalonStudio.Extensibility.Theme;
using WalletWasabi.Models;
namespace WalletWasabi.Gui.Converters
{
public class StatusColorConvertor : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool isTor = Enum.TryParse(value.ToString(), out TorStatus tor);
if (isTor && tor == TorStatus.NotRunning)
{
return Brushes.Yellow;
}
bool isBackend = Enum.TryParse(value.ToString(), out BackendStatus backend);
if (isBackend && backend == BackendStatus.NotConnected)
{
return Brushes.Yellow;
}
return ColorTheme.CurrentTheme.Foreground;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
}
|
Increase the estinated cost for the text file property store to 10 to avoid fetching all dead properties | // <copyright file="TextFilePropertyStoreOptions.cs" company="Fubar Development Junker">
// Copyright (c) Fubar Development Junker. All rights reserved.
// </copyright>
namespace FubarDev.WebDavServer.Props.Store.TextFile
{
public class TextFilePropertyStoreOptions
{
public int EstimatedCost { get; set; }
public string RootFolder { get; set; }
public bool StoreInTargetFileSystem { get; set; }
}
}
| // <copyright file="TextFilePropertyStoreOptions.cs" company="Fubar Development Junker">
// Copyright (c) Fubar Development Junker. All rights reserved.
// </copyright>
namespace FubarDev.WebDavServer.Props.Store.TextFile
{
public class TextFilePropertyStoreOptions
{
public int EstimatedCost { get; set; } = 10;
public string RootFolder { get; set; }
public bool StoreInTargetFileSystem { get; set; }
}
}
|
Fix decimal property value converter to work on non EN-US cultures | using Umbraco.Core.Models.PublishedContent;
namespace Umbraco.Core.PropertyEditors.ValueConverters
{
[PropertyValueType(typeof(decimal))]
[PropertyValueCache(PropertyCacheValue.All, PropertyCacheLevel.Content)]
public class DecimalValueConverter : PropertyValueConverterBase
{
public override bool IsConverter(PublishedPropertyType propertyType)
{
return Constants.PropertyEditors.DecimalAlias.Equals(propertyType.PropertyEditorAlias);
}
public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview)
{
if (source == null) return 0M;
// in XML a decimal is a string
var sourceString = source as string;
if (sourceString != null)
{
decimal d;
return (decimal.TryParse(sourceString, out d)) ? d : 0M;
}
// in the database an a decimal is an a decimal
// default value is zero
return (source is decimal) ? source : 0M;
}
}
}
| using System.Globalization;
using Umbraco.Core.Models.PublishedContent;
namespace Umbraco.Core.PropertyEditors.ValueConverters
{
[PropertyValueType(typeof(decimal))]
[PropertyValueCache(PropertyCacheValue.All, PropertyCacheLevel.Content)]
public class DecimalValueConverter : PropertyValueConverterBase
{
public override bool IsConverter(PublishedPropertyType propertyType)
{
return Constants.PropertyEditors.DecimalAlias.Equals(propertyType.PropertyEditorAlias);
}
public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview)
{
if (source == null) return 0M;
// in XML a decimal is a string
var sourceString = source as string;
if (sourceString != null)
{
decimal d;
return (decimal.TryParse(sourceString, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out d)) ? d : 0M;
}
// in the database an a decimal is an a decimal
// default value is zero
return (source is decimal) ? source : 0M;
}
}
}
|
Fix bitmap serialization with indexed format bitmaps | namespace TAUtil.Gdi.Bitmap
{
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using TAUtil.Gdi.Palette;
/// <summary>
/// Serializes a 32-bit Bitmap instance into raw 8-bit indexed color data.
/// The mapping from color to index is done according to the given
/// reverse palette lookup.
/// </summary>
public class BitmapSerializer
{
private readonly IPalette palette;
public BitmapSerializer(IPalette palette)
{
this.palette = palette;
}
public byte[] ToBytes(Bitmap bitmap)
{
int length = bitmap.Width * bitmap.Height;
byte[] output = new byte[length];
this.Serialize(new MemoryStream(output, true), bitmap);
return output;
}
public void Serialize(Stream output, Bitmap bitmap)
{
Rectangle r = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
BitmapData data = bitmap.LockBits(r, ImageLockMode.ReadOnly, bitmap.PixelFormat);
int length = bitmap.Width * bitmap.Height;
unsafe
{
int* pointer = (int*)data.Scan0;
for (int i = 0; i < length; i++)
{
Color c = Color.FromArgb(pointer[i]);
output.WriteByte((byte)this.palette.LookUp(c));
}
}
bitmap.UnlockBits(data);
}
}
} | namespace TAUtil.Gdi.Bitmap
{
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using TAUtil.Gdi.Palette;
/// <summary>
/// Serializes a 32-bit Bitmap instance into raw 8-bit indexed color data.
/// The mapping from color to index is done according to the given
/// reverse palette lookup.
/// </summary>
public class BitmapSerializer
{
private readonly IPalette palette;
public BitmapSerializer(IPalette palette)
{
this.palette = palette;
}
public byte[] ToBytes(Bitmap bitmap)
{
int length = bitmap.Width * bitmap.Height;
byte[] output = new byte[length];
this.Serialize(new MemoryStream(output, true), bitmap);
return output;
}
public void Serialize(Stream output, Bitmap bitmap)
{
Rectangle r = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
BitmapData data = bitmap.LockBits(r, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
int length = bitmap.Width * bitmap.Height;
unsafe
{
int* pointer = (int*)data.Scan0;
for (int i = 0; i < length; i++)
{
Color c = Color.FromArgb(pointer[i]);
output.WriteByte((byte)this.palette.LookUp(c));
}
}
bitmap.UnlockBits(data);
}
}
} |
Revert "TEMP: test env vars on prod" | using System;
using System.Threading.Tasks;
using FilterLists.Agent.AppSettings;
using FilterLists.Agent.Extensions;
using FilterLists.Agent.Features.Lists;
using FilterLists.Agent.Features.Urls;
using FilterLists.Agent.Features.Urls.Models.DataFileUrls;
using MediatR;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace FilterLists.Agent
{
public static class Program
{
private static IServiceProvider _serviceProvider;
public static async Task Main()
{
BuildServiceProvider();
var mediator = _serviceProvider.GetService<IOptions<GitHub>>().Value;
Console.WriteLine(mediator.ProductHeaderValue);
//await mediator.Send(new CaptureLists.Command());
//await mediator.Send(new ValidateAllUrls.Command());
}
private static void BuildServiceProvider()
{
var serviceCollection = new ServiceCollection();
serviceCollection.RegisterAgentServices();
_serviceProvider = serviceCollection.BuildServiceProvider();
}
}
} | using System;
using System.Threading.Tasks;
using FilterLists.Agent.Extensions;
using FilterLists.Agent.Features.Lists;
using FilterLists.Agent.Features.Urls;
using MediatR;
using Microsoft.Extensions.DependencyInjection;
namespace FilterLists.Agent
{
public static class Program
{
private static IServiceProvider _serviceProvider;
public static async Task Main()
{
BuildServiceProvider();
var mediator = _serviceProvider.GetService<IMediator>();
await mediator.Send(new CaptureLists.Command());
await mediator.Send(new ValidateAllUrls.Command());
}
private static void BuildServiceProvider()
{
var serviceCollection = new ServiceCollection();
serviceCollection.RegisterAgentServices();
_serviceProvider = serviceCollection.BuildServiceProvider();
}
}
} |
Fix Repository's `createGitHubDeployments` not being returned in API responses | using System.ComponentModel.DataAnnotations;
using Tgstation.Server.Api.Models;
namespace Tgstation.Server.Host.Models
{
/// <inheritdoc />
public sealed class RepositorySettings : Api.Models.Internal.RepositorySettings
{
/// <summary>
/// The row Id
/// </summary>
public long Id { get; set; }
/// <summary>
/// The instance <see cref="EntityId.Id"/>
/// </summary>
public long InstanceId { get; set; }
/// <summary>
/// The parent <see cref="Models.Instance"/>
/// </summary>
[Required]
public Instance Instance { get; set; }
/// <summary>
/// Convert the <see cref="Repository"/> to it's API form
/// </summary>
/// <returns>A new <see cref="Repository"/></returns>
public Repository ToApi() => new Repository
{
// AccessToken = AccessToken, // never show this
AccessUser = AccessUser,
AutoUpdatesKeepTestMerges = AutoUpdatesKeepTestMerges,
AutoUpdatesSynchronize = AutoUpdatesSynchronize,
CommitterEmail = CommitterEmail,
CommitterName = CommitterName,
PushTestMergeCommits = PushTestMergeCommits,
ShowTestMergeCommitters = ShowTestMergeCommitters,
PostTestMergeComment = PostTestMergeComment
// revision information and the rest retrieved by controller
};
}
}
| using System.ComponentModel.DataAnnotations;
using Tgstation.Server.Api.Models;
namespace Tgstation.Server.Host.Models
{
/// <inheritdoc />
public sealed class RepositorySettings : Api.Models.Internal.RepositorySettings
{
/// <summary>
/// The row Id
/// </summary>
public long Id { get; set; }
/// <summary>
/// The instance <see cref="EntityId.Id"/>
/// </summary>
public long InstanceId { get; set; }
/// <summary>
/// The parent <see cref="Models.Instance"/>
/// </summary>
[Required]
public Instance Instance { get; set; }
/// <summary>
/// Convert the <see cref="Repository"/> to it's API form
/// </summary>
/// <returns>A new <see cref="Repository"/></returns>
public Repository ToApi() => new Repository
{
// AccessToken = AccessToken, // never show this
AccessUser = AccessUser,
AutoUpdatesKeepTestMerges = AutoUpdatesKeepTestMerges,
AutoUpdatesSynchronize = AutoUpdatesSynchronize,
CommitterEmail = CommitterEmail,
CommitterName = CommitterName,
PushTestMergeCommits = PushTestMergeCommits,
ShowTestMergeCommitters = ShowTestMergeCommitters,
PostTestMergeComment = PostTestMergeComment,
CreateGitHubDeployments = CreateGitHubDeployments,
// revision information and the rest retrieved by controller
};
}
}
|
Update OData assembly versions to 5.3.1.0 | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
#if !BUILD_GENERATED_VERSION
[assembly: AssemblyCompany("Microsoft Open Technologies, Inc.")]
[assembly: AssemblyCopyright("© Microsoft Open Technologies, Inc. All rights reserved.")]
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
#if !NOT_CLS_COMPLIANT
[assembly: CLSCompliant(true)]
#endif
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyMetadata("Serviceable", "True")]
// ===========================================================================
// DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT.
// Version numbers are automatically generated based on regular expressions.
// ===========================================================================
#if ASPNETODATA
#if !BUILD_GENERATED_VERSION
[assembly: AssemblyVersion("5.3.0.0")] // ASPNETODATA
[assembly: AssemblyFileVersion("5.3.0.0")] // ASPNETODATA
#endif
[assembly: AssemblyProduct("Microsoft ASP.NET Web API OData")]
#endif | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
#if !BUILD_GENERATED_VERSION
[assembly: AssemblyCompany("Microsoft Open Technologies, Inc.")]
[assembly: AssemblyCopyright("© Microsoft Open Technologies, Inc. All rights reserved.")]
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
#if !NOT_CLS_COMPLIANT
[assembly: CLSCompliant(true)]
#endif
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyMetadata("Serviceable", "True")]
// ===========================================================================
// DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT.
// Version numbers are automatically generated based on regular expressions.
// ===========================================================================
#if ASPNETODATA
#if !BUILD_GENERATED_VERSION
[assembly: AssemblyVersion("5.3.1.0")] // ASPNETODATA
[assembly: AssemblyFileVersion("5.3.1.0")] // ASPNETODATA
#endif
[assembly: AssemblyProduct("Microsoft ASP.NET Web API OData")]
#endif |
Write BrightstarDB log output if a log file is specified | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BrightstarDB.ReadWriteBenchmark
{
internal class Program
{
private static void Main(string[] args)
{
var opts = new BenchmarkArgs();
if (CommandLine.Parser.ParseArgumentsWithUsage(args, opts))
{
if (!string.IsNullOrEmpty(opts.LogFilePath))
{
BenchmarkLogging.EnableFileLogging(opts.LogFilePath);
}
}
else
{
var usage = CommandLine.Parser.ArgumentsUsage(typeof (BenchmarkArgs));
Console.WriteLine(usage);
}
var runner = new BenchmarkRunner(opts);
runner.Run();
BenchmarkLogging.Close();
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BrightstarDB.ReadWriteBenchmark
{
internal class Program
{
public static TraceListener BrightstarListener;
private static void Main(string[] args)
{
var opts = new BenchmarkArgs();
if (CommandLine.Parser.ParseArgumentsWithUsage(args, opts))
{
if (!string.IsNullOrEmpty(opts.LogFilePath))
{
BenchmarkLogging.EnableFileLogging(opts.LogFilePath);
var logStream = new FileStream(opts.LogFilePath + ".bslog", FileMode.Create);
BrightstarListener = new TextWriterTraceListener(logStream);
BrightstarDB.Logging.BrightstarTraceSource.Listeners.Add(BrightstarListener);
BrightstarDB.Logging.BrightstarTraceSource.Switch.Level = SourceLevels.All;
}
}
else
{
var usage = CommandLine.Parser.ArgumentsUsage(typeof (BenchmarkArgs));
Console.WriteLine(usage);
}
var runner = new BenchmarkRunner(opts);
runner.Run();
BenchmarkLogging.Close();
BrightstarDB.Logging.BrightstarTraceSource.Close();
}
}
}
|
Revert to method LINQ syntax. | using System;
using System.Linq;
using System.Reflection;
using StructureMap.Graph;
using StructureMap.Pipeline;
namespace StructureMap
{
internal class AspNetConstructorSelector : IConstructorSelector
{
// ASP.NET expects registered services to be considered when selecting a ctor, SM doesn't by default.
public ConstructorInfo Find(Type pluggedType, DependencyCollection dependencies, PluginGraph graph)
{
var constructors = from constructor in pluggedType.GetConstructors()
select new
{
Constructor = constructor,
Parameters = constructor.GetParameters(),
};
var satisfiable = from constructor in constructors
where constructor.Parameters.All(parameter => ParameterIsRegistered(parameter, dependencies, graph))
orderby constructor.Parameters.Length descending
select constructor.Constructor;
return satisfiable.FirstOrDefault();
}
private static bool ParameterIsRegistered(ParameterInfo parameter, DependencyCollection dependencies, PluginGraph graph)
{
return graph.HasFamily(parameter.ParameterType) || dependencies.Any(dependency => dependency.Type == parameter.ParameterType);
}
}
}
| using System;
using System.Linq;
using System.Reflection;
using StructureMap.Graph;
using StructureMap.Pipeline;
namespace StructureMap
{
internal class AspNetConstructorSelector : IConstructorSelector
{
// ASP.NET expects registered services to be considered when selecting a ctor, SM doesn't by default.
public ConstructorInfo Find(Type pluggedType, DependencyCollection dependencies, PluginGraph graph) =>
pluggedType.GetTypeInfo()
.DeclaredConstructors
.Select(ctor => new { Constructor = ctor, Parameters = ctor.GetParameters() })
.Where(x => x.Parameters.All(param => graph.HasFamily(param.ParameterType) || dependencies.Any(dep => dep.Type == param.ParameterType)))
.OrderByDescending(x => x.Parameters.Length)
.Select(x => x.Constructor)
.FirstOrDefault();
}
}
|
Use scriptureforge database to get project data | // Copyright (c) 2015 SIL International
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
using System.Linq;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Core.Clusters;
namespace LfMerge
{
public class LanguageDepotProject
{
public LanguageDepotProject(string lfProjectCode)
{
var client = new MongoClient("mongodb://" + LfMergeSettings.Current.MongoDbHostNameAndPort);
var database = client.GetDatabase("languageforge");
var collection = database.GetCollection<BsonDocument>("projects");
var filter = new BsonDocument("projectCode", lfProjectCode);
var list = collection.Find(filter).ToListAsync();
list.Wait();
var project = list.Result.FirstOrDefault();
if (project == null)
throw new ArgumentException("Can't find project code", "lfProjectCode");
BsonValue value;
if (project.TryGetValue("ldUsername", out value))
Username = value.AsString;
if (project.TryGetValue("ldPassword", out value))
Password = value.AsString;
if (project.TryGetValue("ldProjectCode", out value))
ProjectCode = value.AsString;
}
public string Username { get; private set; }
public string Password { get; private set; }
public string ProjectCode { get; private set; }
}
}
| // Copyright (c) 2015 SIL International
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
using System.Linq;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Core.Clusters;
namespace LfMerge
{
public class LanguageDepotProject
{
public LanguageDepotProject(string lfProjectCode)
{
var client = new MongoClient("mongodb://" + LfMergeSettings.Current.MongoDbHostNameAndPort);
var database = client.GetDatabase("scriptureforge");
var projectCollection = database.GetCollection<BsonDocument>("projects");
//var userCollection = database.GetCollection<BsonDocument>("users");
var projectFilter = new BsonDocument("projectCode", lfProjectCode);
var list = projectCollection.Find(projectFilter).ToListAsync();
list.Wait();
var project = list.Result.FirstOrDefault();
if (project == null)
throw new ArgumentException("Can't find project code", "lfProjectCode");
BsonValue value;
if (project.TryGetValue("ldProjectCode", out value))
ProjectCode = value.AsString;
// TODO: need to get S/R server (language depot public, language depot private, custom, etc).
// TODO: ldUsername and ldPassword should come from the users collection
if (project.TryGetValue("ldUsername", out value))
Username = value.AsString;
if (project.TryGetValue("ldPassword", out value))
Password = value.AsString;
}
public string Username { get; private set; }
public string Password { get; private set; }
public string ProjectCode { get; private set; }
}
}
|
Improve packet sender seralize codes | using LiteNetLib;
using LiteNetLib.Utils;
using LiteNetLibManager;
public static class LiteNetLibPacketSender
{
public static readonly NetDataWriter Writer = new NetDataWriter();
public static void SendPacket(NetDataWriter writer, SendOptions options, NetPeer peer, short msgType, System.Action<NetDataWriter> serializer)
{
writer.Reset();
writer.Put(msgType);
serializer(writer);
peer.Send(writer, options);
}
public static void SendPacket(SendOptions options, NetPeer peer, short msgType, System.Action<NetDataWriter> serializer)
{
SendPacket(Writer, options, peer, msgType, serializer);
}
public static void SendPacket<T>(NetDataWriter writer, SendOptions options, NetPeer peer, short msgType, T messageData) where T : ILiteNetLibMessage
{
SendPacket(writer, options, peer, msgType, messageData.Serialize);
}
public static void SendPacket<T>(SendOptions options, NetPeer peer, short msgType, T messageData) where T : ILiteNetLibMessage
{
SendPacket(Writer, options, peer, msgType, messageData);
}
public static void SendPacket(NetDataWriter writer, SendOptions options, NetPeer peer, short msgType)
{
writer.Reset();
writer.Put(msgType);
peer.Send(writer, options);
}
public static void SendPacket(SendOptions options, NetPeer peer, short msgType)
{
SendPacket(Writer, options, peer, msgType);
}
}
| using LiteNetLib;
using LiteNetLib.Utils;
using LiteNetLibManager;
public static class LiteNetLibPacketSender
{
public static readonly NetDataWriter Writer = new NetDataWriter();
public static void SendPacket(NetDataWriter writer, SendOptions options, NetPeer peer, short msgType, System.Action<NetDataWriter> serializer)
{
writer.Reset();
writer.Put(msgType);
if (serializer != null)
serializer(writer);
peer.Send(writer, options);
}
public static void SendPacket(SendOptions options, NetPeer peer, short msgType, System.Action<NetDataWriter> serializer)
{
SendPacket(Writer, options, peer, msgType, serializer);
}
public static void SendPacket<T>(NetDataWriter writer, SendOptions options, NetPeer peer, short msgType, T messageData) where T : ILiteNetLibMessage
{
SendPacket(writer, options, peer, msgType, messageData.Serialize);
}
public static void SendPacket<T>(SendOptions options, NetPeer peer, short msgType, T messageData) where T : ILiteNetLibMessage
{
SendPacket(Writer, options, peer, msgType, messageData);
}
public static void SendPacket(NetDataWriter writer, SendOptions options, NetPeer peer, short msgType)
{
SendPacket(writer, options, peer, msgType, null);
}
public static void SendPacket(SendOptions options, NetPeer peer, short msgType)
{
SendPacket(Writer, options, peer, msgType);
}
}
|
Make the sandbox example even more complex | using System;
using System.Net;
using System.Net.Http;
using Knapcode.SocketToMe.Http;
using Knapcode.SocketToMe.Socks;
namespace Knapcode.SocketToMe.Sandbox
{
public class Program
{
private static void Main()
{
var endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9150);
var client = new Socks5Client();
var socket = client.ConnectToServer(endpoint);
socket = client.ConnectToDestination(socket, "icanhazip.com", 80);
var httpClient = new HttpClient(new NetworkHandler(socket));
var response = httpClient.GetAsync("http://icanhazip.com/").Result;
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}
}
} | using System;
using System.Net;
using System.Net.Http;
using Knapcode.SocketToMe.Http;
using Knapcode.SocketToMe.Socks;
namespace Knapcode.SocketToMe.Sandbox
{
public class Program
{
private static void Main()
{
var endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9150);
var client = new Socks5Client();
var socket = client.ConnectToServer(endpoint);
socket = client.ConnectToDestination(socket, "icanhazip.com", 443);
var httpClient = new HttpClient(new NetworkHandler(socket));
var response = httpClient.GetAsync("https://icanhazip.com/").Result;
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}
}
} |
Update benchmark and add worst case scenario | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using osu.Framework.Text;
namespace osu.Framework.Benchmarks
{
public class BenchmarkTextBuilder
{
private readonly ITexturedGlyphLookupStore store = new TestStore();
private TextBuilder textBuilder;
[Benchmark]
public void AddCharacters() => initialiseBuilder(false);
[Benchmark]
public void RemoveLastCharacter()
{
initialiseBuilder(false);
textBuilder.RemoveLastCharacter();
}
private void initialiseBuilder(bool allDifferentBaselines)
{
textBuilder = new TextBuilder(store, FontUsage.Default);
char different = 'B';
for (int i = 0; i < 100; i++)
textBuilder.AddCharacter(i % (allDifferentBaselines ? 1 : 10) == 0 ? different++ : 'A');
}
private class TestStore : ITexturedGlyphLookupStore
{
public ITexturedCharacterGlyph Get(string fontName, char character) => new TexturedCharacterGlyph(new CharacterGlyph(character, character, character, character, null), Texture.WhitePixel);
public Task<ITexturedCharacterGlyph> GetAsync(string fontName, char character) => Task.Run(() => Get(fontName, character));
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using osu.Framework.Text;
namespace osu.Framework.Benchmarks
{
public class BenchmarkTextBuilder
{
private readonly ITexturedGlyphLookupStore store = new TestStore();
private TextBuilder textBuilder;
[Benchmark]
public void AddCharacters() => initialiseBuilder(false);
[Benchmark]
public void AddCharactersWithDifferentBaselines() => initialiseBuilder(true);
[Benchmark]
public void RemoveLastCharacter()
{
initialiseBuilder(false);
textBuilder.RemoveLastCharacter();
}
[Benchmark]
public void RemoveLastCharacterWithDifferentBaselines()
{
initialiseBuilder(true);
textBuilder.RemoveLastCharacter();
}
private void initialiseBuilder(bool withDifferentBaselines)
{
textBuilder = new TextBuilder(store, FontUsage.Default);
char different = 'B';
for (int i = 0; i < 100; i++)
textBuilder.AddCharacter(withDifferentBaselines && (i % 10 == 0) ? different++ : 'A');
}
private class TestStore : ITexturedGlyphLookupStore
{
public ITexturedCharacterGlyph Get(string fontName, char character) => new TexturedCharacterGlyph(new CharacterGlyph(character, character, character, character, character, null), Texture.WhitePixel);
public Task<ITexturedCharacterGlyph> GetAsync(string fontName, char character) => Task.Run(() => Get(fontName, character));
}
}
}
|
Change private setter to public. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lezen.Core.Entity
{
public class Document
{
public Document()
{
this.Authors = new HashSet<Author>();
}
public int ID { get; set; }
public string Title { get; set; }
public virtual ICollection<Author> Authors { get; private set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lezen.Core.Entity
{
public class Document
{
public Document()
{
this.Authors = new HashSet<Author>();
}
public int ID { get; set; }
public string Title { get; set; }
public virtual ICollection<Author> Authors { get; set; }
}
}
|
Fix wrong method name, causing a build error | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CardsAgainstIRC3.Game.Bots
{
[Bot("rando")]
public class Rando : IBot
{
public GameManager Manager
{
get;
private set;
}
public GameUser User
{
get;
private set;
}
public Rando(GameManager manager)
{
Manager = manager;
}
public void RegisteredToUser(GameUser user)
{
User = user;
}
public Card[] ResponseToCard(Card blackCard)
{
return Manager.TakeWhiteCards(blackCard.Parts.Length - 1).ToArray();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CardsAgainstIRC3.Game.Bots
{
[Bot("rando")]
public class Rando : IBot
{
public GameManager Manager
{
get;
private set;
}
public GameUser User
{
get;
private set;
}
public Rando(GameManager manager)
{
Manager = manager;
}
public void LinkedToUser(GameUser user)
{
User = user;
}
public Card[] ResponseToCard(Card blackCard)
{
return Manager.TakeWhiteCards(blackCard.Parts.Length - 1).ToArray();
}
}
}
|
Correct default paste behaviour for IMDb textbox | using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace Subtle.UI.Controls
{
public class ImdbTextBox : TextBox
{
// ReSharper disable once InconsistentNaming
private const int WM_PASTE = 0x0302;
private static readonly Regex ImdbRegex = new Regex(@"tt(\d{7})");
/// <summary>
/// Handles paste event and tries to extract IMDb ID.
/// </summary>
/// <param name="m"></param>
protected override void WndProc(ref Message m)
{
if (m.Msg != WM_PASTE)
{
base.WndProc(ref m);
return;
}
var match = ImdbRegex.Match(Clipboard.GetText());
if (match.Success)
{
Text = match.Groups[1].Value;
}
}
}
} | using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace Subtle.UI.Controls
{
public class ImdbTextBox : TextBox
{
// ReSharper disable once InconsistentNaming
private const int WM_PASTE = 0x0302;
private static readonly Regex ImdbRegex = new Regex(@"tt(\d{7})");
/// <summary>
/// Handles paste event and tries to extract IMDb ID.
/// </summary>
/// <param name="m"></param>
protected override void WndProc(ref Message m)
{
if (m.Msg != WM_PASTE)
{
base.WndProc(ref m);
return;
}
var match = ImdbRegex.Match(Clipboard.GetText());
if (match.Success)
{
Text = match.Groups[1].Value;
}
else
{
base.WndProc(ref m);
}
}
}
} |
Remove <br> from select in checkin | @model JoinRpg.Web.Models.CheckIn.CheckInIndexViewModel
@{
ViewBag.Title = "Регистрация";
}
<h2>Регистрация</h2>
@using (Html.BeginForm())
{
@Html.HiddenFor(model => model.ProjectId)
@Html.AntiForgeryToken()
@Html.SearchableDropdownFor(model => model.ClaimId, Model.Claims.Select(
claim =>
new ImprovedSelectListItem()
{
Value = claim.ClaimId.ToString(),
Text = claim.CharacterName,
ExtraSearch = claim.OtherNicks,
Subtext = "<br />" + claim.NickName + " (" + claim.Fullname + " )"
}))
<input type="submit" class="btn btn-success" value="Зарегистрировать"/>
}
<hr/>
@Html.ActionLink("Статистика по регистрации", "Stat", new {Model.ProjectId})
| @model JoinRpg.Web.Models.CheckIn.CheckInIndexViewModel
@{
ViewBag.Title = "Регистрация";
}
<h2>Регистрация</h2>
@using (Html.BeginForm())
{
@Html.HiddenFor(model => model.ProjectId)
@Html.AntiForgeryToken()
@Html.SearchableDropdownFor(model => model.ClaimId, Model.Claims.Select(
claim =>
new ImprovedSelectListItem()
{
Value = claim.ClaimId.ToString(),
Text = claim.CharacterName,
ExtraSearch = claim.OtherNicks,
Subtext = claim.NickName + " (" + claim.Fullname + " )"
}))
<input type="submit" class="btn btn-success" value="Зарегистрировать"/>
}
<hr/>
@Html.ActionLink("Статистика по регистрации", "Stat", new {Model.ProjectId})
|
Improve server wait and disconnect after each msg | using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
namespace Syndll2
{
public class SynelServer : IDisposable
{
private readonly IConnection _connection;
private bool _disposed;
private SynelServer(IConnection connection)
{
_connection = connection;
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
_connection.Dispose();
_disposed = true;
}
public static SynelServer Listen(Action<PushNotification> action)
{
return Listen(3734, action);
}
public static SynelServer Listen(int port, Action<PushNotification> action)
{
var connection = NetworkConnection.Listen(port, (stream, socket) =>
{
var history = new List<string>();
var receiver = new Receiver(stream);
var signal = new SemaphoreSlim(1);
receiver.MessageHandler += message =>
{
if (!history.Contains(message.RawResponse))
{
history.Add(message.RawResponse);
Util.Log(string.Format("Received: {0}", message.RawResponse));
if (message.Response != null)
{
var notification = new PushNotification(stream, message.Response, (IPEndPoint) socket.RemoteEndPoint);
action(notification);
}
}
signal.Release();
};
receiver.WatchStream();
while (stream.CanRead)
signal.Wait();
});
return new SynelServer(connection);
}
}
}
| using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
namespace Syndll2
{
public class SynelServer : IDisposable
{
private readonly IConnection _connection;
private bool _disposed;
private SynelServer(IConnection connection)
{
_connection = connection;
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
_connection.Dispose();
_disposed = true;
}
public static SynelServer Listen(Action<PushNotification> action)
{
return Listen(3734, action);
}
public static SynelServer Listen(int port, Action<PushNotification> action)
{
var connection = NetworkConnection.Listen(port, (stream, socket) =>
{
var history = new List<string>();
var receiver = new Receiver(stream);
var signal = new ManualResetEvent(false);
receiver.MessageHandler = message =>
{
if (!history.Contains(message.RawResponse))
{
history.Add(message.RawResponse);
Util.Log(string.Format("Received: {0}", message.RawResponse));
if (message.Response != null)
{
var notification = new PushNotification(stream, message.Response, (IPEndPoint) socket.RemoteEndPoint);
action(notification);
}
}
signal.Set();
};
receiver.WatchStream();
// Wait until a message is received
while (stream.CanRead && socket.Connected)
if (signal.WaitOne(100))
break;
});
return new SynelServer(connection);
}
}
}
|
Add test to check that Unicode languages work (testing Chinese). | namespace ForecastPCL.Test
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ForecastIOPortable;
using NUnit.Framework;
[TestFixture]
public class LanguageTests
{
[Test]
public void AllLanguagesHaveValues()
{
foreach (Language language in Enum.GetValues(typeof(Language)))
{
Assert.That(() => language.ToValue(), Throws.Nothing);
}
}
}
}
| namespace ForecastPCL.Test
{
using System;
using System.Configuration;
using ForecastIOPortable;
using NUnit.Framework;
[TestFixture]
public class LanguageTests
{
// These coordinates came from the Forecast API documentation,
// and should return forecasts with all blocks.
private const double AlcatrazLatitude = 37.8267;
private const double AlcatrazLongitude = -122.423;
private const double MumbaiLatitude = 18.975;
private const double MumbaiLongitude = 72.825833;
/// <summary>
/// API key to be used for testing. This should be specified in the
/// test project's app.config file.
/// </summary>
private string apiKey;
/// <summary>
/// Sets up all tests by retrieving the API key from app.config.
/// </summary>
[TestFixtureSetUp]
public void SetUp()
{
this.apiKey = ConfigurationManager.AppSettings["ApiKey"];
}
[Test]
public void AllLanguagesHaveValues()
{
foreach (Language language in Enum.GetValues(typeof(Language)))
{
Assert.That(() => language.ToValue(), Throws.Nothing);
}
}
[Test]
public async void UnicodeLanguageIsSupported()
{
var client = new ForecastApi(this.apiKey);
var result = await client.GetWeatherDataAsync(AlcatrazLatitude, AlcatrazLongitude, Unit.Auto, Language.Chinese);
Assert.That(result, Is.Not.Null);
}
}
}
|
Implement Enabled flag to be able to run sorts separately | using System;
using System.Diagnostics;
using Basics.Algorithms.Sorts;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Basics.Algorithms.Tests
{
[TestClass]
public class SortingPerformanceTests
{
private const int size = 10000;
private class SortInfo
{
public string Name { get; set; }
public Action<int[]> Act { get; set; }
}
[TestMethod]
public void SortingPerformanceTest()
{
var stopwatch = new Stopwatch();
var sortedArray = new int[size];
for (int i = 0; i < size; i++)
{
sortedArray[i] = i;
}
var sorts = new SortInfo[]
{
new SortInfo { Name = "Selection Sort", Act = array => Selection.Sort(array) },
new SortInfo { Name = "Insertion Sort", Act = array => Insertion.Sort(array) },
new SortInfo { Name = "Shell Sort", Act = array => Shell.Sort(array) },
new SortInfo { Name = "Mergesort", Act = array => Merge.Sort(array) },
new SortInfo { Name = "Quicksort", Act = array => Quick.Sort(array) }
};
foreach (var sort in sorts)
{
sortedArray.Shuffle();
stopwatch.Restart();
sort.Act(sortedArray);
stopwatch.Stop();
Console.WriteLine("{0}:\t{1}", sort.Name, stopwatch.ElapsedTicks);
}
}
}
}
| using System;
using System.Diagnostics;
using System.Linq;
using Basics.Algorithms.Sorts;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Basics.Algorithms.Tests
{
[TestClass]
public class SortingPerformanceTests
{
private const int size = 1000000;
private class SortInfo
{
public string Name { get; set; }
public Action<int[]> Act { get; set; }
public bool Enabled { get; set; }
}
[TestMethod]
public void SortingPerformanceTest()
{
var stopwatch = new Stopwatch();
var sortedArray = new int[size];
for (int i = 0; i < size; i++)
{
sortedArray[i] = i;
}
var sorts = new SortInfo[]
{
new SortInfo { Name = "Selection Sort", Act = array => Selection.Sort(array), Enabled = false },
new SortInfo { Name = "Insertion Sort", Act = array => Insertion.Sort(array), Enabled = false },
new SortInfo { Name = "Shell Sort", Act = array => Shell.Sort(array), Enabled = false },
new SortInfo { Name = "Mergesort", Act = array => Merge.Sort(array), Enabled = true },
new SortInfo { Name = "Quicksort", Act = array => Quick.Sort(array), Enabled = true }
};
foreach (var sort in sorts.Where(s => s.Enabled))
{
sortedArray.Shuffle();
stopwatch.Restart();
sort.Act(sortedArray);
stopwatch.Stop();
Console.WriteLine("{0}:\t{1}", sort.Name, stopwatch.ElapsedTicks);
}
}
}
}
|
Add continue time entry on recent list view click. | using System;
using System.Linq;
using Android.App;
using Android.OS;
using Android.Views;
using Toggl.Joey.UI.Adapters;
namespace Toggl.Joey.UI.Fragments
{
public class RecentTimeEntriesListFragment : ListFragment
{
public override void OnViewCreated (View view, Bundle savedInstanceState)
{
base.OnViewCreated (view, savedInstanceState);
ListAdapter = new RecentTimeEntriesAdapter ();
}
}
}
| using System;
using System.Linq;
using Android.App;
using Android.OS;
using Android.Views;
using Android.Widget;
using Toggl.Joey.UI.Adapters;
namespace Toggl.Joey.UI.Fragments
{
public class RecentTimeEntriesListFragment : ListFragment
{
public override void OnViewCreated (View view, Bundle savedInstanceState)
{
base.OnViewCreated (view, savedInstanceState);
ListAdapter = new RecentTimeEntriesAdapter ();
}
public override void OnListItemClick (ListView l, View v, int position, long id)
{
var adapter = l.Adapter as RecentTimeEntriesAdapter;
if (adapter == null)
return;
var model = adapter.GetModel (position);
if (model == null)
return;
model.Continue ();
}
}
}
|
Add IsFilterActive; remove unneeded parameters to filter (pass it on ctor) | using System;
using System.Collections.Generic;
namespace PrepareLanding.Filters
{
public enum FilterHeaviness
{
Light = 0,
Medium = 1,
Heavy = 2
}
public interface ITileFilter
{
string SubjectThingDef { get; }
string RunningDescription { get; }
string AttachedProperty { get; }
Action<PrepareLandingUserData, List<int>> FilterAction { get; }
FilterHeaviness Heaviness { get; }
List<int> FilteredTiles { get; }
void Filter(PrepareLandingUserData userData, List<int> inputList);
}
}
| using System;
using System.Collections.Generic;
namespace PrepareLanding.Filters
{
public enum FilterHeaviness
{
Light = 0,
Medium = 1,
Heavy = 2
}
public interface ITileFilter
{
string SubjectThingDef { get; }
string RunningDescription { get; }
string AttachedProperty { get; }
Action<List<int>> FilterAction { get; }
FilterHeaviness Heaviness { get; }
List<int> FilteredTiles { get; }
void Filter(List<int> inputList);
bool IsFilterActive { get; }
}
}
|
Change test code to repro issue in old code and prove new code doesn't crash | using Microsoft.ServiceFabric.Actors;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SoCreate.ServiceFabric.PubSub.Events;
using SoCreate.ServiceFabric.PubSub.State;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace SoCreate.ServiceFabric.PubSub.Tests
{
[TestClass]
public class GivenDefaultBrokerEventsManager
{
[TestMethod]
public async Task WhenInsertingConcurrently_ThenAllCallbacksAreMadeCorrectly()
{
int callCount = 0;
var manager = new DefaultBrokerEventsManager();
manager.Subscribed += (s, e, t) =>
{
lock (manager)
{
callCount++;
}
return Task.CompletedTask;
};
const int attempts = 20;
var tasks = new List<Task>(attempts);
for (int i = 0; i < attempts; i++)
{
var actorReference = new ActorReference{ ActorId = ActorId.CreateRandom() };
tasks.Add(manager.OnSubscribedAsync("Key", new ActorReferenceWrapper(actorReference), "MessageType"));
}
await Task.WhenAll(tasks);
Assert.AreEqual(attempts, callCount);
}
}
}
| using Microsoft.ServiceFabric.Actors;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SoCreate.ServiceFabric.PubSub.Events;
using SoCreate.ServiceFabric.PubSub.State;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace SoCreate.ServiceFabric.PubSub.Tests
{
[TestClass]
public class GivenDefaultBrokerEventsManager
{
[TestMethod]
public void WhenInsertingConcurrently_ThenAllCallbacksAreMadeCorrectly()
{
bool hasCrashed = false;
var manager = new DefaultBrokerEventsManager();
ManualResetEvent mr = new ManualResetEvent(false);
ManualResetEvent mr2 = new ManualResetEvent(false);
manager.Subscribed += (s, e, t) =>
{
mr.WaitOne();
return Task.CompletedTask;
};
const int attempts = 2000;
for (int i = 0; i < attempts; i++)
{
ThreadPool.QueueUserWorkItem(async j =>
{
var actorReference = new ActorReference { ActorId = ActorId.CreateRandom() };
try
{
await manager.OnSubscribedAsync("Key" + (int) j % 5, new ActorReferenceWrapper(actorReference),
"MessageType");
}
catch (NullReferenceException)
{
hasCrashed = true;
}
catch (IndexOutOfRangeException)
{
hasCrashed = true;
}
finally
{
if ((int)j == attempts - 1)
{
mr2.Set();
}
}
}, i);
}
mr.Set();
Assert.IsTrue(mr2.WaitOne(TimeSpan.FromSeconds(10)), "Failed to run within time limits.");
Assert.IsFalse(hasCrashed, "Should not crash.");
}
}
}
|
Make class public and all methods virtual so that it can be used as a base class for interceptors. | using System;
using System.Collections;
using NHibernate.Type;
namespace NHibernate.Cfg
{
[Serializable]
internal class EmptyInterceptor : IInterceptor
{
public EmptyInterceptor()
{
}
public void OnDelete( object entity, object id, object[ ] state, string[ ] propertyNames, IType[ ] types )
{
}
public bool OnFlushDirty( object entity, object id, object[ ] currentState, object[ ] previousState, string[ ] propertyNames, IType[ ] types )
{
return false;
}
public bool OnLoad( object entity, object id, object[ ] state, string[ ] propertyNames, IType[ ] types )
{
return false;
}
public bool OnSave( object entity, object id, object[ ] state, string[ ] propertyNames, IType[ ] types )
{
return false;
}
public void OnPostFlush( object entity, object id, object[ ] currentState, string[ ] propertyNames, IType[ ] types )
{
}
public void PostFlush( ICollection entities )
{
}
public void PreFlush( ICollection entitites )
{
}
public object IsUnsaved( object entity )
{
return null;
}
public object Instantiate( System.Type clazz, object id )
{
return null;
}
public int[ ] FindDirty( object entity, object id, object[ ] currentState, object[ ] previousState, string[ ] propertyNames, IType[ ] types )
{
return null;
}
}
}
| using System;
using System.Collections;
using NHibernate.Type;
namespace NHibernate.Cfg
{
[Serializable]
public class EmptyInterceptor : IInterceptor
{
public virtual void OnDelete( object entity, object id, object[ ] state, string[ ] propertyNames, IType[ ] types )
{
}
public virtual bool OnFlushDirty( object entity, object id, object[ ] currentState, object[ ] previousState, string[ ] propertyNames, IType[ ] types )
{
return false;
}
public virtual bool OnLoad( object entity, object id, object[ ] state, string[ ] propertyNames, IType[ ] types )
{
return false;
}
public virtual bool OnSave( object entity, object id, object[ ] state, string[ ] propertyNames, IType[ ] types )
{
return false;
}
public virtual void PostFlush( ICollection entities )
{
}
public virtual void PreFlush( ICollection entitites )
{
}
public virtual object IsUnsaved( object entity )
{
return null;
}
public virtual object Instantiate( System.Type clazz, object id )
{
return null;
}
public virtual int[] FindDirty( object entity, object id, object[] currentState, object[] previousState, string[] propertyNames, IType[] types )
{
return null;
}
}
}
|
Fix for resend confirmation button | <div ng-app="GVA.Manage" ng-controller="ConfirmRegistrationController">
<div class="manage-area centered">
<h2>
Thank you for registering!
</h2>
<p class="text-centered">
You should receive an Email confirmation shortly.
</p>
<p class="text-centered">
If not, ensure you check any spam filters you may have running.
</p>
<div class="flexbox">
<button class="centered active-btn" ng-click="resendConfirmation()">Resend Confirmation Email"</button>
</div>
</div>
</div> | <div ng-app="GVA.Manage" ng-controller="ConfirmRegistrationController">
<div class="manage-area centered">
<h2>
Thank you for registering!
</h2>
<p class="text-centered">
You should receive an Email confirmation shortly.
</p>
<p class="text-centered">
If not, ensure you check any spam filters you may have running.
</p>
<div class="flexbox">
<button class="centered active-btn" ng-click="resendConfirmation()">Resend Confirmation Email</button>
</div>
</div>
</div> |
Move ordering if types around |
namespace Glimpse.Agent.AspNet.Mvc.Messages
{
public class BeforeActionMessage : IActionRouteFoundMessage
{
public string ActionId { get; set; }
public string DisplayName { get; set; }
public RouteData RouteData { get; set; }
public string ActionName { get; set; }
public string ControllerName { get; set; }
}
} |
namespace Glimpse.Agent.AspNet.Mvc.Messages
{
public class BeforeActionMessage : IActionRouteFoundMessage
{
public string ActionId { get; set; }
public string DisplayName { get; set; }
public string ActionName { get; set; }
public string ControllerName { get; set; }
public RouteData RouteData { get; set; }
}
} |
Cover case-insensitive child component parameter names in E2E test | <h1>Counter</h1>
<p>Current count: <MessageComponent Message=@currentCount.ToString() /></p>
<button @onclick(IncrementCount)>Click me</button>
@functions {
int currentCount = 0;
void IncrementCount()
{
currentCount++;
}
}
| <h1>Counter</h1>
<!-- Note: passing 'Message' parameter with lowercase name to show it's case insensitive -->
<p>Current count: <MessageComponent message=@currentCount.ToString() /></p>
<button @onclick(IncrementCount)>Click me</button>
@functions {
int currentCount = 0;
void IncrementCount()
{
currentCount++;
}
}
|
Add cleandatabase call in global steps | using Moq;
using SFA.DAS.EAS.TestCommon.DbCleanup;
using SFA.DAS.EAS.TestCommon.DependencyResolution;
using SFA.DAS.EAS.Web;
using SFA.DAS.EAS.Web.Authentication;
using SFA.DAS.Messaging;
using StructureMap;
using TechTalk.SpecFlow;
namespace SFA.DAS.EAS.Transactions.AcceptanceTests.Steps.CommonSteps
{
[Binding]
public static class GlobalTestSteps
{
private static Mock<IMessagePublisher> _messagePublisher;
private static Mock<IOwinWrapper> _owinWrapper;
private static Container _container;
private static Mock<ICookieService> _cookieService;
[AfterTestRun()]
public static void Arrange()
{
_messagePublisher = new Mock<IMessagePublisher>();
_owinWrapper = new Mock<IOwinWrapper>();
_cookieService = new Mock<ICookieService>();
_container = IoC.CreateContainer(_messagePublisher, _owinWrapper, _cookieService);
var cleanDownDb = _container.GetInstance<ICleanDatabase>();
cleanDownDb.Execute().Wait();
}
}
}
| using Moq;
using SFA.DAS.EAS.TestCommon.DbCleanup;
using SFA.DAS.EAS.TestCommon.DependencyResolution;
using SFA.DAS.EAS.Web;
using SFA.DAS.EAS.Web.Authentication;
using SFA.DAS.Messaging;
using StructureMap;
using TechTalk.SpecFlow;
namespace SFA.DAS.EAS.Transactions.AcceptanceTests.Steps.CommonSteps
{
[Binding]
public static class GlobalTestSteps
{
private static Mock<IMessagePublisher> _messagePublisher;
private static Mock<IOwinWrapper> _owinWrapper;
private static Container _container;
private static Mock<ICookieService> _cookieService;
[AfterTestRun()]
public static void Arrange()
{
_messagePublisher = new Mock<IMessagePublisher>();
_owinWrapper = new Mock<IOwinWrapper>();
_cookieService = new Mock<ICookieService>();
_container = IoC.CreateContainer(_messagePublisher, _owinWrapper, _cookieService);
var cleanDownDb = _container.GetInstance<ICleanDatabase>();
cleanDownDb.Execute().Wait();
var cleanDownTransactionDb = _container.GetInstance<ICleanTransactionsDatabase>();
cleanDownTransactionDb.Execute().Wait();
}
}
}
|
Add graduate flag as additional property | namespace SEEK.AdPostingApi.Client.Models
{
public enum AdditionalPropertyType
{
ResidentsOnly = 1
}
}
| namespace SEEK.AdPostingApi.Client.Models
{
public enum AdditionalPropertyType
{
ResidentsOnly = 1,
Graduate
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.