Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Remove random xml comment from file header | //-----------------------------------------------------------------------
// <copyright file="DataPortalMethodCache.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>Gets a reference to the DataPortal_Create method for</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using Csla.Reflection;
namespace Csla.Server
{
internal static class DataPortalMethodCache
{
private static Dictionary<MethodCacheKey, DataPortalMethodInfo> _cache =
new Dictionary<MethodCacheKey, DataPortalMethodInfo>();
public static DataPortalMethodInfo GetMethodInfo(Type objectType, string methodName, params object[] parameters)
{
var key = new MethodCacheKey(objectType.FullName, methodName, MethodCaller.GetParameterTypes(parameters));
DataPortalMethodInfo result = null;
var found = false;
try
{
found = _cache.TryGetValue(key, out result);
}
catch
{ /* failure will drop into !found block */ }
if (!found)
{
lock (_cache)
{
if (!_cache.TryGetValue(key, out result))
{
result = new DataPortalMethodInfo(MethodCaller.GetMethod(objectType, methodName, parameters));
_cache.Add(key, result);
}
}
}
return result;
}
}
} | //-----------------------------------------------------------------------
// <copyright file="DataPortalMethodCache.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using Csla.Reflection;
namespace Csla.Server
{
internal static class DataPortalMethodCache
{
private static Dictionary<MethodCacheKey, DataPortalMethodInfo> _cache =
new Dictionary<MethodCacheKey, DataPortalMethodInfo>();
public static DataPortalMethodInfo GetMethodInfo(Type objectType, string methodName, params object[] parameters)
{
var key = new MethodCacheKey(objectType.FullName, methodName, MethodCaller.GetParameterTypes(parameters));
DataPortalMethodInfo result = null;
var found = false;
try
{
found = _cache.TryGetValue(key, out result);
}
catch
{ /* failure will drop into !found block */ }
if (!found)
{
lock (_cache)
{
if (!_cache.TryGetValue(key, out result))
{
result = new DataPortalMethodInfo(MethodCaller.GetMethod(objectType, methodName, parameters));
_cache.Add(key, result);
}
}
}
return result;
}
}
} |
Change buried cards to screen bar in search page | /*
Copyright (C) 2016 Anki Universal Team <ankiuniversal@outlook.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Media;
namespace AnkiU.UIUtilities.DataBindingConverters
{
public class CardStateToSolidBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var number = (int)value;
if (number < 0)
return Application.Current.Resources["ButtonBackGroundCompliment"];
else
return new SolidColorBrush(Windows.UI.Colors.Transparent);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
}
| /*
Copyright (C) 2016 Anki Universal Team <ankiuniversal@outlook.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Media;
namespace AnkiU.UIUtilities.DataBindingConverters
{
public class CardStateToSolidBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var number = (int)value;
if (number >= 0)
return new SolidColorBrush(Windows.UI.Colors.Transparent);
else if (number == -1)
return Application.Current.Resources["ButtonBackGroundCompliment"];
else
return Application.Current.Resources["ButtonBackGroundAnalogousRight"];
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
}
|
Improve readability of DbContextOptions code | using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using System;
using System.Configuration;
using System.Linq;
namespace CycleSales.CycleSalesModel
{
public class CycleSalesContext : DbContext
{
public CycleSalesContext()
{ }
public CycleSalesContext(DbContextOptions options)
: base(options)
{ }
public DbSet<Bike> Bikes { get; set; }
protected override void OnConfiguring(DbContextOptions options)
{
// TODO: This check is so that we can pass in external options from tests
// Need to come up with a better way to handle this scenario
if (!((IDbContextOptionsExtensions)options).Extensions.Any())
{
// TODO: Connection string in code rather than config file because of temporary limitation with Migrations
options.UseSqlServer(@"Server=(localdb)\v11.0;Database=CycleSales;integrated security=True;");
}
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Bike>()
.Key(b => b.Bike_Id);
builder.Entity<Bike>()
.ForRelational()
.Table("Bikes");
}
}
}
| using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using System;
using System.Configuration;
using System.Linq;
namespace CycleSales.CycleSalesModel
{
public class CycleSalesContext : DbContext
{
public CycleSalesContext()
{ }
public CycleSalesContext(DbContextOptions options)
: base(options)
{ }
public DbSet<Bike> Bikes { get; set; }
protected override void OnConfiguring(DbContextOptions options)
{
if (!options.IsAlreadyConfigured())
{
options.UseSqlServer(@"Server=(localdb)\v11.0;Database=CycleSales;integrated security=True;");
}
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Bike>()
.Key(b => b.Bike_Id);
builder.Entity<Bike>()
.ForRelational()
.Table("Bikes");
}
}
public static class DbOptionsExtensions
{
public static bool IsAlreadyConfigured(this DbContextOptions options)
{
return ((IDbContextOptionsExtensions)options).Extensions.Any();
}
}
}
|
Use ConcurrentDictionary for collector registry | using System;
using System.Collections.Generic;
using System.Linq;
using Prometheus.Advanced.DataContracts;
namespace Prometheus.Advanced
{
public class DefaultCollectorRegistry : ICollectorRegistry
{
public readonly static DefaultCollectorRegistry Instance = new DefaultCollectorRegistry();
/// <summary>
/// a list with copy-on-write semantics implemented in-place below. This is to avoid any locks on the read side (ie, CollectAll())
/// </summary>
private List<ICollector> _collectors = new List<ICollector>();
public void RegisterStandardPerfCounters()
{
var perfCounterCollector = new PerfCounterCollector();
Register(perfCounterCollector);
perfCounterCollector.RegisterStandardPerfCounters();
}
public IEnumerable<MetricFamily> CollectAll()
{
//return _collectors.Select(value => value.Collect()).Where(c=>c != null);
//replaced LINQ with code to avoid extra allocations
foreach (ICollector value in _collectors)
{
MetricFamily c = value.Collect();
if (c != null) yield return c;
}
}
public void Clear()
{
lock (_collectors)
{
_collectors = new List<ICollector>();
}
}
public void Register(ICollector collector)
{
if (_collectors.Any(c => c.Name == collector.Name))
{
throw new InvalidOperationException(string.Format("A collector with name '{0}' has already been registered!", collector.Name));
}
lock (_collectors)
{
var newList = new List<ICollector>(_collectors);
newList.Add(collector);
_collectors = newList;
}
}
public bool Remove(ICollector collector)
{
lock (_collectors)
{
var newList = new List<ICollector>(_collectors);
bool removed = newList.Remove(collector);
_collectors = newList;
return removed;
}
}
}
} | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using Prometheus.Advanced.DataContracts;
namespace Prometheus.Advanced
{
public class DefaultCollectorRegistry : ICollectorRegistry
{
public readonly static DefaultCollectorRegistry Instance = new DefaultCollectorRegistry();
private readonly ConcurrentDictionary<string, ICollector> _collectors = new ConcurrentDictionary<string, ICollector>();
public void RegisterStandardPerfCounters()
{
var perfCounterCollector = new PerfCounterCollector();
Register(perfCounterCollector);
perfCounterCollector.RegisterStandardPerfCounters();
}
public IEnumerable<MetricFamily> CollectAll()
{
//return _collectors.Select(value => value.Collect()).Where(c=>c != null);
//replaced LINQ with code to avoid extra allocations
foreach (var value in _collectors.Values)
{
var c = value.Collect();
if (c != null) yield return c;
}
}
public void Clear()
{
_collectors.Clear();
}
public void Register(ICollector collector)
{
if (!_collectors.TryAdd(collector.Name, collector))
throw new InvalidOperationException(string.Format("A collector with name '{0}' has already been registered!", collector.Name));
}
public bool Remove(ICollector collector)
{
ICollector dummy;
return _collectors.TryRemove(collector.Name, out dummy);
}
}
} |
Make debug log store work in release builds | using System;
using System.Threading.Tasks;
using Bit.Core.Contracts;
using Bit.Core.Models;
using System.Diagnostics;
namespace Bit.Owin.Implementations
{
public class DebugLogStore : ILogStore
{
private readonly IContentFormatter _formatter;
public DebugLogStore(IContentFormatter formatter)
{
_formatter = formatter;
}
#if DEBUG
protected DebugLogStore()
{
}
#endif
public virtual void SaveLog(LogEntry logEntry)
{
Debug.WriteLine(_formatter.Serialize(logEntry) + Environment.NewLine);
}
public virtual async Task SaveLogAsync(LogEntry logEntry)
{
Debug.WriteLine(_formatter.Serialize(logEntry) + Environment.NewLine);
}
}
}
| #define DEBUG
using System;
using System.Threading.Tasks;
using Bit.Core.Contracts;
using Bit.Core.Models;
using System.Diagnostics;
namespace Bit.Owin.Implementations
{
public class DebugLogStore : ILogStore
{
private readonly IContentFormatter _formatter;
public DebugLogStore(IContentFormatter formatter)
{
_formatter = formatter;
}
protected DebugLogStore()
{
}
public virtual void SaveLog(LogEntry logEntry)
{
Debug.WriteLine(_formatter.Serialize(logEntry) + Environment.NewLine);
}
public virtual async Task SaveLogAsync(LogEntry logEntry)
{
Debug.WriteLine(_formatter.Serialize(logEntry) + Environment.NewLine);
}
}
}
|
Enable package search by default (in master). | // 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 Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.Shared.Options
{
/// <summary>
/// options to indicate whether a certain component in Roslyn is enabled or not
/// </summary>
internal static class ServiceComponentOnOffOptions
{
public const string OptionName = "FeatureManager/Components";
public static readonly Option<bool> DiagnosticProvider = new Option<bool>(OptionName, "Diagnostic Provider", defaultValue: true);
public static readonly Option<bool> PackageSearch = new Option<bool>(OptionName, nameof(PackageSearch), defaultValue: false);
}
}
| // 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 Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.Shared.Options
{
/// <summary>
/// options to indicate whether a certain component in Roslyn is enabled or not
/// </summary>
internal static class ServiceComponentOnOffOptions
{
public const string OptionName = "FeatureManager/Components";
public static readonly Option<bool> DiagnosticProvider = new Option<bool>(OptionName, "Diagnostic Provider", defaultValue: true);
public static readonly Option<bool> PackageSearch = new Option<bool>(OptionName, nameof(PackageSearch), defaultValue: true);
}
}
|
Fix U4-8532 - No built in Active Directory authentication in Umbraco 7.3+ | using System.Configuration;
using System.DirectoryServices.AccountManagement;
using System.Threading.Tasks;
using Umbraco.Core.Models.Identity;
namespace Umbraco.Core.Security
{
public class ActiveDirectoryBackOfficeUserPasswordChecker : IBackOfficeUserPasswordChecker
{
public Task<BackOfficeUserPasswordCheckerResult> CheckPasswordAsync(BackOfficeIdentityUser user, string password)
{
bool isValid;
using (var pc = new PrincipalContext(ContextType.Domain, ConfigurationManager.AppSettings["ActiveDirectoryDomain"]))
{
isValid = pc.ValidateCredentials(user.UserName, password);
}
var result = isValid
? BackOfficeUserPasswordCheckerResult.ValidCredentials
: BackOfficeUserPasswordCheckerResult.InvalidCredentials;
return Task.FromResult(result);
}
}
}
| using System.Configuration;
using System.DirectoryServices.AccountManagement;
using System.Threading.Tasks;
using Umbraco.Core.Models.Identity;
namespace Umbraco.Core.Security
{
public class ActiveDirectoryBackOfficeUserPasswordChecker : IBackOfficeUserPasswordChecker
{
public virtual string ActiveDirectoryDomain {
get {
return ConfigurationManager.AppSettings["ActiveDirectoryDomain"];
}
}
public Task<BackOfficeUserPasswordCheckerResult> CheckPasswordAsync(BackOfficeIdentityUser user, string password)
{
bool isValid;
using (var pc = new PrincipalContext(ContextType.Domain, ActiveDirectoryDomain))
{
isValid = pc.ValidateCredentials(user.UserName, password);
}
var result = isValid
? BackOfficeUserPasswordCheckerResult.ValidCredentials
: BackOfficeUserPasswordCheckerResult.InvalidCredentials;
return Task.FromResult(result);
}
}
}
|
Add tryremove/add to in memory store | using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using Abp.Data;
namespace Abp.RealTime
{
public class InMemoryOnlineClientStore : IOnlineClientStore
{
/// <summary>
/// Online clients.
/// </summary>
protected ConcurrentDictionary<string, IOnlineClient> Clients { get; }
public InMemoryOnlineClientStore()
{
Clients = new ConcurrentDictionary<string, IOnlineClient>();
}
public void Add(IOnlineClient client)
{
Clients.AddOrUpdate(client.ConnectionId, client, (s, o) => client);
}
public ConditionalValue<IOnlineClient> Remove(string connectionId)
{
return Clients.TryRemove(connectionId, out IOnlineClient removed) ? new ConditionalValue<IOnlineClient>(true, removed) : new ConditionalValue<IOnlineClient>(false, null);
}
public ConditionalValue<IOnlineClient> Get(string connectionId)
{
return Clients.TryGetValue(connectionId, out IOnlineClient found) ? new ConditionalValue<IOnlineClient>(true, found) : new ConditionalValue<IOnlineClient>(false, null);
}
public bool Contains(string connectionId)
{
return Clients.ContainsKey(connectionId);
}
public IReadOnlyList<IOnlineClient> GetAll()
{
return Clients.Values.ToImmutableList();
}
}
}
| using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using Abp.Data;
namespace Abp.RealTime
{
public class InMemoryOnlineClientStore : IOnlineClientStore
{
/// <summary>
/// Online clients.
/// </summary>
protected ConcurrentDictionary<string, IOnlineClient> Clients { get; }
public InMemoryOnlineClientStore()
{
Clients = new ConcurrentDictionary<string, IOnlineClient>();
}
public void Add(IOnlineClient client)
{
Clients.AddOrUpdate(client.ConnectionId, client, (s, o) => client);
}
public bool Remove(string connectionId)
{
return TryRemove(connectionId, out IOnlineClient removed);
}
public bool TryRemove(string connectionId, out IOnlineClient client)
{
return Clients.TryRemove(connectionId, out client);
}
public bool TryGet(string connectionId, out IOnlineClient client)
{
return Clients.TryGetValue(connectionId, out client);
}
public bool Contains(string connectionId)
{
return Clients.ContainsKey(connectionId);
}
public IReadOnlyList<IOnlineClient> GetAll()
{
return Clients.Values.ToImmutableList();
}
}
}
|
Add another keyframe to UT | using System.Linq;
using Avalonia.Data;
using Avalonia.Styling;
using Avalonia.UnitTests;
using Xunit;
namespace Avalonia.Markup.Xaml.UnitTests
{
public class SetterTests : XamlTestBase
{
[Fact]
public void Setter_Should_Work_Outside_Of_Style_With_SetterTargetType_Attribute()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Animation xmlns='https://github.com/avaloniaui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' x:SetterTargetType='Avalonia.Controls.Button'>
<KeyFrame>
<Setter Property='Content' Value='{Binding}'/>
</KeyFrame>
</Animation>";
var animation = (Animation.Animation)AvaloniaRuntimeXamlLoader.Load(xaml);
var setter = (Setter)animation.Children[0].Setters[0];
Assert.IsType<Binding>(setter.Value);
}
}
}
}
| using System.Linq;
using Avalonia.Data;
using Avalonia.Styling;
using Avalonia.UnitTests;
using Xunit;
namespace Avalonia.Markup.Xaml.UnitTests
{
public class SetterTests : XamlTestBase
{
[Fact]
public void Setter_Should_Work_Outside_Of_Style_With_SetterTargetType_Attribute()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Animation xmlns='https://github.com/avaloniaui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' x:SetterTargetType='Avalonia.Controls.Button'>
<KeyFrame>
<Setter Property='Content' Value='{Binding}'/>
</KeyFrame>
<KeyFrame>
<Setter Property='Content' Value='{Binding}'/>
</KeyFrame>
</Animation>";
var animation = (Animation.Animation)AvaloniaRuntimeXamlLoader.Load(xaml);
var setter = (Setter)animation.Children[0].Setters[0];
Assert.IsType<Binding>(setter.Value);
}
}
}
}
|
Revert "Change ProcessorInfo to CPU" | using IL2CPU.API;
using IL2CPU.API.Attribs;
using System;
using System.Diagnostics;
using Cosmos.Core;
namespace Cosmos.Core_Plugs.System.Diagnostics
{
[Plug(Target = typeof(global::System.Diagnostics.Stopwatch))]
public class StopwatchImpl
{
public static long GetTimestamp()
{
if (Stopwatch.IsHighResolution)
// see https://msdn.microsoft.com/en-us/library/windows/desktop/dn553408(v=vs.85).aspx for more details
return (long)(CPU.GetCPUUptime() / (double)CPU.GetCPUCycleSpeed() * 1000000d);
else
return DateTime.UtcNow.Ticks;
}
}
}
| using IL2CPU.API;
using IL2CPU.API.Attribs;
using System;
using System.Diagnostics;
using Cosmos.Core;
namespace Cosmos.Core_Plugs.System.Diagnostics
{
[Plug(Target = typeof(global::System.Diagnostics.Stopwatch))]
public class StopwatchImpl
{
public static long GetTimestamp()
{
if (Stopwatch.IsHighResolution)
// see https://msdn.microsoft.com/en-us/library/windows/desktop/dn553408(v=vs.85).aspx for more details
return (long)(ProcessorInformation.GetCycleCount() / (double)ProcessorInformation.GetCycleRate() * 1000000d);
else
return DateTime.UtcNow.Ticks;
}
}
}
|
Add hashrate data to MyRentalsRecord class | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MiningRigRentalsApi.Converters;
using Newtonsoft.Json;
namespace MiningRigRentalsApi.ObjectModel
{
public class MyRentals
{
public MyRentalsRecords[] records;
}
public class MyRentalsRecords
{
public int id;
public int rigid;
public string name;
public string type;
public int online;
public double price;
[JsonProperty("start_time")]
[JsonConverter(typeof(PhpDateTimeConverter))]
public DateTime starttime;
public string status;
public double vailable_in_hours;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MiningRigRentalsApi.Converters;
using Newtonsoft.Json;
namespace MiningRigRentalsApi.ObjectModel
{
public class MyRentals
{
public MyRentalsRecords[] records;
}
public class MyRentalsRecords
{
public int id;
public int rigid;
public string name;
public string type;
public int online;
public double price;
[JsonProperty("start_time")]
[JsonConverter(typeof(PhpDateTimeConverter))]
public DateTime starttime;
public string status;
public double vailable_in_hours;
public MyRentalsHashrateAdvertised advertised;
public MyRentalsHashrateCurrent current;
public MyRentalsHashrateAverage average;
}
public class MyRentalsHashrateAdvertised
{
public string hashrate_nice;
public ulong hashrate;
}
public class MyRentalsHashrateCurrent
{
public double hash_5m;
public string hash_5m_nice;
public double hash_30m;
public string hash_30m_nice;
public double hash_1h;
public string hash_1h_nice;
}
public class MyRentalsHashrateAverage
{
public double hashrate;
public string hashrate_nice;
public double percent;
}
}
|
Add method to return Department object by it's identifier | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Diploms.Core;
namespace Diploms.WebUI.Controllers
{
[Route("api/[controller]")]
public class DepartmentsController : Controller
{
private readonly IRepository<Department> _repository;
public DepartmentsController(IRepository<Department> repository)
{
_repository = repository ?? throw new ArgumentNullException(nameof(repository));
}
[HttpGet("")]
public async Task<IActionResult> GetDepartments()
{
return Ok(await _repository.Get());
}
[HttpPut("add")]
public async Task<IActionResult> AddDepartment([FromBody] DepartmentAddDto model)
{
var department = new Department
{
Name = model.Name,
ShortName = model.ShortName,
CreateDate = DateTime.UtcNow
};
try
{
_repository.Add(department);
await _repository.SaveChanges();
return Ok();
}
catch
{
return BadRequest();
}
}
}
public class DepartmentAddDto
{
public string Name { get; set; }
public string ShortName { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Diploms.Core;
namespace Diploms.WebUI.Controllers
{
[Route("api/[controller]")]
public class DepartmentsController : Controller
{
private readonly IRepository<Department> _repository;
public DepartmentsController(IRepository<Department> repository)
{
_repository = repository ?? throw new ArgumentNullException(nameof(repository));
}
[HttpGet("")]
public async Task<IActionResult> GetDepartments()
{
return Ok(await _repository.Get());
}
[HttpGet("{id:int}")]
public async Task<IActionResult> GetDepartment(int id)
{
var result = await _repository.Get(id);
if (result != null)
{
return Ok(result);
}
return NotFound();
}
[HttpPut("add")]
public async Task<IActionResult> AddDepartment([FromBody] DepartmentAddDto model)
{
var department = new Department
{
Name = model.Name,
ShortName = model.ShortName,
CreateDate = DateTime.UtcNow
};
try
{
_repository.Add(department);
await _repository.SaveChanges();
return Ok();
}
catch
{
return BadRequest();
}
}
}
public class DepartmentAddDto
{
public string Name { get; set; }
public string ShortName { get; set; }
}
}
|
Add background video for showcase scene (Tournament Client) | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
namespace osu.Game.Tournament.Screens.Showcase
{
public class ShowcaseScreen : BeatmapInfoScreen
{
[BackgroundDependencyLoader]
private void load()
{
AddInternal(new TournamentLogo());
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Tournament.Components;
namespace osu.Game.Tournament.Screens.Showcase
{
public class ShowcaseScreen : BeatmapInfoScreen
{
[BackgroundDependencyLoader]
private void load()
{
AddRangeInternal(new Drawable[] {
new TournamentLogo(),
new TourneyVideo("showcase")
{
Loop = true,
RelativeSizeAxes = Axes.Both,
}
});
}
}
}
|
Update to reuse existing window, if it exists | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.Utilities.Editor;
using System;
using UnityEditor;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Editor
{
internal class MRTKVersionPopup : EditorWindow
{
private static MRTKVersionPopup window;
private static readonly Version MRTKVersion = typeof(MixedRealityToolkit).Assembly.GetName().Version;
private static readonly Vector2 WindowSize = new Vector2(300, 150);
private static readonly GUIContent Title = new GUIContent("Mixed Reality Toolkit");
[MenuItem("Mixed Reality/Toolkit/Show version...")]
private static void Init()
{
if (window != null)
{
window.Close();
}
window = CreateInstance<MRTKVersionPopup>();
window.titleContent = Title;
window.maxSize = WindowSize;
window.minSize = WindowSize;
window.ShowUtility();
}
private void OnGUI()
{
using (new EditorGUILayout.VerticalScope())
{
MixedRealityInspectorUtility.RenderMixedRealityToolkitLogo();
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.FlexibleSpace();
EditorGUILayout.LabelField($"Version {MRTKVersion}", EditorStyles.wordWrappedLabel);
GUILayout.FlexibleSpace();
}
}
}
}
}
| // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.Utilities.Editor;
using System;
using UnityEditor;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Editor
{
internal class MRTKVersionPopup : EditorWindow
{
private static MRTKVersionPopup window;
private static readonly Version MRTKVersion = typeof(MixedRealityToolkit).Assembly.GetName().Version;
private static readonly Vector2 WindowSize = new Vector2(300, 150);
private static readonly GUIContent Title = new GUIContent("Mixed Reality Toolkit");
[MenuItem("Mixed Reality/Toolkit/Show version...")]
private static void Init()
{
if (window != null)
{
window.ShowUtility();
return;
}
window = CreateInstance<MRTKVersionPopup>();
window.titleContent = Title;
window.maxSize = WindowSize;
window.minSize = WindowSize;
window.ShowUtility();
}
private void OnGUI()
{
using (new EditorGUILayout.VerticalScope())
{
MixedRealityInspectorUtility.RenderMixedRealityToolkitLogo();
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.FlexibleSpace();
EditorGUILayout.LabelField($"Version {MRTKVersion}", EditorStyles.wordWrappedLabel);
GUILayout.FlexibleSpace();
}
}
}
}
}
|
Fix migration sql to be run in transaction block | using SimpleMigrations;
namespace Migrations
{
[Migration(5, "Add source track plays index")]
public class AddSourceTrackPlaysIndex : Migration
{
protected override void Up()
{
Execute(@"
CREATE INDEX IF NOT EXISTS idx_source_track_plays_id_btree ON source_track_plays(id);
CREATE INDEX CONCURRENTLY ON setlist_shows (artist_id);
");
}
protected override void Down()
{
throw new System.NotImplementedException();
}
}
} | using SimpleMigrations;
namespace Migrations
{
[Migration(5, "Add source track plays index")]
public class AddSourceTrackPlaysIndex : Migration
{
protected override void Up()
{
Execute(@"
CREATE INDEX IF NOT EXISTS idx_source_track_plays_id_btree ON source_track_plays(id);
CREATE INDEX IF NOT EXISTS idx_setlist_shows_artist_id ON setlist_shows (artist_id);
");
}
protected override void Down()
{
throw new System.NotImplementedException();
}
}
} |
Create PermanentTestRunner rather than direct TestTree | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Reflection;
namespace EnumerableTest.Runner.Wpf
{
/// <summary>
/// TestTreeView.xaml の相互作用ロジック
/// </summary>
public partial class TestTreeView : UserControl
{
readonly TestTree testTree = new TestTree();
IEnumerable<FileInfo> AssemblyFiles
{
get
{
var thisFile = new FileInfo(Assembly.GetExecutingAssembly().Location);
return FileSystemInfo.getTestAssemblies(thisFile).Concat(AppArgumentModule.files);
}
}
public TestTreeView()
{
InitializeComponent();
foreach (var assemblyFile in AssemblyFiles)
{
testTree.LoadFile(assemblyFile);
}
DataContext = testTree;
Unloaded += (sender, e) => testTree.Dispose();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Reflection;
namespace EnumerableTest.Runner.Wpf
{
/// <summary>
/// TestTreeView.xaml の相互作用ロジック
/// </summary>
public partial class TestTreeView : UserControl
{
readonly PermanentTestRunner runner = new PermanentTestRunner();
IEnumerable<FileInfo> AssemblyFiles
{
get
{
var thisFile = new FileInfo(Assembly.GetExecutingAssembly().Location);
return FileSystemInfo.getTestAssemblies(thisFile).Concat(AppArgumentModule.files);
}
}
public TestTreeView()
{
InitializeComponent();
foreach (var assemblyFile in AssemblyFiles)
{
runner.LoadFile(assemblyFile);
}
Unloaded += (sender, e) => runner.Dispose();
DataContext = runner.TestTree;
}
}
}
|
Add comments to a new class. | using Microsoft.AspNetCore.Mvc;
namespace LtiLibrary.AspNet.Outcomes.v1
{
public class ImsxXmlMediaTypeResult : ObjectResult
{
public ImsxXmlMediaTypeResult(object value) : base(value)
{
Formatters.Add(new ImsxXmlMediaTypeOutputFormatter());
}
}
}
| using Microsoft.AspNetCore.Mvc;
namespace LtiLibrary.AspNet.Outcomes.v1
{
/// <summary>
/// Use to attach a specific XML formatter to controller results. For example,
/// <code>public ImsxXmlMediaTypeResult Post([ModelBinder(BinderType = typeof(ImsxXmlMediaTypeModelBinder))] imsx_POXEnvelopeType request)</code>
/// </summary>
public class ImsxXmlMediaTypeResult : ObjectResult
{
public ImsxXmlMediaTypeResult(object value) : base(value)
{
// This formatter produces an imsx_POXEnvelopeType with an imsx_POXEnvelopeResponse
Formatters.Add(new ImsxXmlMediaTypeOutputFormatter());
}
}
}
|
Fix mono bug in the FontHelper class | using System;
using System.Drawing;
using System.Linq;
using NUnit.Framework;
using Palaso.UI.WindowsForms;
namespace PalasoUIWindowsForms.Tests.FontTests
{
[TestFixture]
public class FontHelperTests
{
[SetUp]
public void SetUp()
{
// setup code goes here
}
[TearDown]
public void TearDown()
{
// tear down code goes here
}
[Test]
public void MakeFont_FontName_ValidFont()
{
Font sourceFont = SystemFonts.DefaultFont;
Font returnFont = FontHelper.MakeFont(sourceFont.FontFamily.Name);
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
}
[Test]
public void MakeFont_FontNameAndStyle_ValidFont()
{
// use Times New Roman
foreach (var family in FontFamily.Families.Where(family => family.Name == "Times New Roman"))
{
Font sourceFont = new Font(family, 10f, FontStyle.Regular);
Font returnFont = FontHelper.MakeFont(sourceFont, FontStyle.Bold);
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
Assert.AreEqual(FontStyle.Bold, returnFont.Style & FontStyle.Bold);
break;
}
Assert.IsTrue(true);
}
}
}
| using System;
using System.Drawing;
using NUnit.Framework;
using Palaso.UI.WindowsForms;
namespace PalasoUIWindowsForms.Tests.FontTests
{
[TestFixture]
public class FontHelperTests
{
[SetUp]
public void SetUp()
{
// setup code goes here
}
[TearDown]
public void TearDown()
{
// tear down code goes here
}
[Test]
public void MakeFont_FontName_ValidFont()
{
Font sourceFont = SystemFonts.DefaultFont;
Font returnFont = FontHelper.MakeFont(sourceFont.FontFamily.Name);
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
}
}
}
|
Fix exception that can occur when a PropertyEditor DLL no longer exists | using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using Census.Core;
using Census.Core.Interfaces;
using Census.UmbracoObject;
using umbraco.cms.businesslogic.datatype;
using umbraco.cms.businesslogic.web;
using umbraco.interfaces;
namespace Census.UmbracoObjectRelations
{
public class DataTypeToPropertyEditor : IRelation
{
public object From
{
get { return typeof(UmbracoObject.DataType); }
}
public object To
{
get { return typeof(UmbracoObject.PropertyEditor); }
}
public DataTable GetRelations(object id)
{
var dataType = DataTypeDefinition.GetDataTypeDefinition((int)id);
var propertyEditorGuid = dataType.DataType.Id;
var usages = DataTypeDefinition.GetAll().Where(d => d.DataType.Id == propertyEditorGuid);
return PropertyEditor.ToDataTable(usages);
}
public string Description
{
get { return "Property Editors (aka Render Controls) used by this Datatype"; }
}
}
} | using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using Census.Core;
using Census.Core.Interfaces;
using Census.UmbracoObject;
using umbraco.cms.businesslogic.datatype;
using umbraco.cms.businesslogic.web;
using umbraco.interfaces;
namespace Census.UmbracoObjectRelations
{
public class DataTypeToPropertyEditor : IRelation
{
public object From
{
get { return typeof(UmbracoObject.DataType); }
}
public object To
{
get { return typeof(UmbracoObject.PropertyEditor); }
}
public DataTable GetRelations(object id)
{
var dataType = DataTypeDefinition.GetDataTypeDefinition((int)id);
if (dataType == null || dataType.DataType == null)
return new DataTable(); // PropertyEditor DLL no longer exists
var propertyEditorGuid = dataType.DataType.Id;
var usages = DataTypeDefinition.GetAll().Where(d => d.DataType != null && d.DataType.Id == propertyEditorGuid);
return PropertyEditor.ToDataTable(usages);
}
public string Description
{
get { return "Property Editors (aka Render Controls) used by this Datatype"; }
}
}
} |
Fix OrderRecursivelyAsync bug with OrderByDescending | using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using ChessVariantsTraining.DbRepositories;
namespace ChessVariantsTraining.ViewModels
{
public class CommentSorter
{
ICommentVoteRepository voteRepo;
IUserRepository userRepo;
public CommentSorter(ICommentVoteRepository _voteRepo, IUserRepository _userRepo)
{
voteRepo = _voteRepo;
userRepo = _userRepo;
}
public async Task<ReadOnlyCollection<Comment>> OrderAsync(List<Models.Comment> list)
{
return new ReadOnlyCollection<Comment>(await OrderRecursivelyAsync(list, null, 0));
}
async Task<List<Comment>> OrderRecursivelyAsync(List<Models.Comment> list, int? parent, int indentLevel)
{
List<Comment> result = new List<Comment>();
IEnumerable<Task<Comment>> currentTopLevel = list.Where(x => x.ParentID == parent)
.Select(async x => new Comment(x, indentLevel, await voteRepo.GetScoreForCommentAsync(x.ID), x.Deleted, (await userRepo.FindByIdAsync(x.Author)).Username))
.OrderByDescending(async x => (await x).Score);
foreach (Task<Comment> commentTask in currentTopLevel)
{
Comment comment = await commentTask;
result.Add(comment);
result.AddRange(await OrderRecursivelyAsync(list, comment.ID, indentLevel + 1));
}
return result;
}
}
}
| using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using ChessVariantsTraining.DbRepositories;
namespace ChessVariantsTraining.ViewModels
{
public class CommentSorter
{
ICommentVoteRepository voteRepo;
IUserRepository userRepo;
public CommentSorter(ICommentVoteRepository _voteRepo, IUserRepository _userRepo)
{
voteRepo = _voteRepo;
userRepo = _userRepo;
}
public async Task<ReadOnlyCollection<Comment>> OrderAsync(List<Models.Comment> list)
{
return new ReadOnlyCollection<Comment>(await OrderRecursivelyAsync(list, null, 0));
}
async Task<List<Comment>> OrderRecursivelyAsync(List<Models.Comment> list, int? parent, int indentLevel)
{
List<Comment> result = new List<Comment>();
IEnumerable<Task<Comment>> currentTopLevelTask = list.Where(x => x.ParentID == parent)
.Select(async x => new Comment(x, indentLevel, await voteRepo.GetScoreForCommentAsync(x.ID), x.Deleted, (await userRepo.FindByIdAsync(x.Author)).Username));
IEnumerable<Comment> currentTopLevel = await Task.WhenAll(currentTopLevelTask);
currentTopLevel = currentTopLevel.OrderByDescending(x => x.Score);
foreach (Comment comment in currentTopLevel)
{
result.Add(comment);
result.AddRange(await OrderRecursivelyAsync(list, comment.ID, indentLevel + 1));
}
return result;
}
}
}
|
Update property group type enum | namespace Umbraco.Core.Models
{
/// <summary>
/// Represents the type of a property group.
/// </summary>
public enum PropertyGroupType : short
{
/// <summary>
/// Display as a group (using a header).
/// </summary>
Group = 0,
/// <summary>
/// Display as an app (using a name and icon).
/// </summary>
App = 1,
//Tab = 2,
//Fieldset = 3
}
}
| namespace Umbraco.Core.Models
{
/// <summary>
/// Represents the type of a property group.
/// </summary>
public enum PropertyGroupType : short
{
/// <summary>
/// Display property types in a group.
/// </summary>
Group = 0,
/// <summary>
/// Display property types in a tab.
/// </summary>
Tab = 1
}
}
|
Check for collision with balls only. | using UnityEngine;
using UnityEngine.Events;
public class World : Planet {
private UnityEvent onPlanetHit = new UnityEvent();
private Lives lives;
private void Awake() {
lives = GetComponent<Lives>();
}
private void OnCollisionEnter( Collision other ) {
onPlanetHit.Invoke();
}
public void AddHitListener( UnityAction call ) {
onPlanetHit.AddListener( call );
}
public void AddOutOfLivesListener( UnityAction<int> call ) {
lives.AddOutOfLivesListener( call );
}
public void AddLivesChangedListener( UnityAction<int> call ) {
lives.AddLivesChangedListener( call );
}
}
| using UnityEngine;
using UnityEngine.Events;
public class World : Planet {
private UnityEvent onPlanetHit = new UnityEvent();
private Lives lives;
private void Awake() {
lives = GetComponent<Lives>();
}
private void OnCollisionEnter( Collision other ) {
if( other.transform.GetComponent<Ball>() ) {
onPlanetHit.Invoke();
}
}
public void AddHitListener( UnityAction call ) {
onPlanetHit.AddListener( call );
}
public void AddOutOfLivesListener( UnityAction<int> call ) {
lives.AddOutOfLivesListener( call );
}
public void AddLivesChangedListener( UnityAction<int> call ) {
lives.AddLivesChangedListener( call );
}
}
|
Disable plot buttons until plot is available | using System;
using System.Diagnostics;
using Microsoft.Languages.Editor;
using Microsoft.Languages.Editor.Controller;
namespace Microsoft.VisualStudio.R.Package.Plots {
internal sealed class PlotWindowCommandController : ICommandTarget {
private PlotWindowPane _pane;
public PlotWindowCommandController(PlotWindowPane pane) {
Debug.Assert(pane != null);
_pane = pane;
}
public CommandResult Invoke(Guid group, int id, object inputArg, ref object outputArg) {
RPlotWindowContainer container = _pane.GetIVsWindowPane() as RPlotWindowContainer;
Debug.Assert(container != null);
container.Menu.Execute(id);
return CommandResult.Executed;
}
public void PostProcessInvoke(CommandResult result, Guid group, int id, object inputArg, ref object outputArg) {
}
public CommandStatus Status(Guid group, int id) {
return CommandStatus.SupportedAndEnabled;
}
}
}
| using System;
using System.Diagnostics;
using Microsoft.Languages.Editor;
using Microsoft.Languages.Editor.Controller;
namespace Microsoft.VisualStudio.R.Package.Plots {
internal sealed class PlotWindowCommandController : ICommandTarget {
private PlotWindowPane _pane;
public PlotWindowCommandController(PlotWindowPane pane) {
Debug.Assert(pane != null);
_pane = pane;
}
public CommandResult Invoke(Guid group, int id, object inputArg, ref object outputArg) {
RPlotWindowContainer container = _pane.GetIVsWindowPane() as RPlotWindowContainer;
Debug.Assert(container != null);
if (container.Menu != null) {
container.Menu.Execute(id);
}
return CommandResult.Executed;
}
public void PostProcessInvoke(CommandResult result, Guid group, int id, object inputArg, ref object outputArg) {
}
public CommandStatus Status(Guid group, int id) {
RPlotWindowContainer container = _pane.GetIVsWindowPane() as RPlotWindowContainer;
return (container != null && container.Menu != null) ? CommandStatus.SupportedAndEnabled : CommandStatus.Supported;
}
}
}
|
Remove LSP base from Xaml content type definition to avoid regressing rps | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.LanguageServer.Client;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Xaml
{
public static class XamlStaticTypeDefinitions
{
/// <summary>
/// Definition of the XAML content type.
/// </summary>
[Export]
[Name(ContentTypeNames.XamlContentType)]
[BaseDefinition(CodeRemoteContentDefinition.CodeRemoteContentTypeName)]
internal static readonly ContentTypeDefinition XamlContentType;
// Associate .xaml as the Xaml content type.
[Export]
[FileExtension(StringConstants.XamlFileExtension)]
[ContentType(ContentTypeNames.XamlContentType)]
internal static readonly FileExtensionToContentTypeDefinition XamlFileExtension;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.LanguageServer.Client;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Xaml
{
public static class XamlStaticTypeDefinitions
{
/// <summary>
/// Definition of the XAML content type.
/// </summary>
[Export]
[Name(ContentTypeNames.XamlContentType)]
[BaseDefinition("code")]
internal static readonly ContentTypeDefinition XamlContentType;
// Associate .xaml as the Xaml content type.
[Export]
[FileExtension(StringConstants.XamlFileExtension)]
[ContentType(ContentTypeNames.XamlContentType)]
internal static readonly FileExtensionToContentTypeDefinition XamlFileExtension;
}
}
|
Add documentation for string extensions. | namespace TraktApiSharp.Extensions
{
using System;
using System.Linq;
public static class StringExtensions
{
private static readonly char[] DelimiterChars = { ' ', ',', '.', ':', ';', '\n', '\t' };
public static string FirstToUpper(this string value)
{
if (string.IsNullOrEmpty(value))
throw new ArgumentException("value not valid", nameof(value));
var trimmedValue = value.Trim();
if (trimmedValue.Length > 1)
return char.ToUpper(trimmedValue[0]) + trimmedValue.Substring(1).ToLower();
return trimmedValue.ToUpper();
}
public static int WordCount(this string value)
{
if (string.IsNullOrEmpty(value))
return 0;
var words = value.Split(DelimiterChars);
var filteredWords = words.Where(s => !string.IsNullOrEmpty(s));
return filteredWords.Count();
}
public static bool ContainsSpace(this string value)
{
return value.Contains(" ");
}
}
}
| namespace TraktApiSharp.Extensions
{
using System;
using System.Linq;
/// <summary>Provides helper methods for strings.</summary>
public static class StringExtensions
{
private static readonly char[] DelimiterChars = { ' ', ',', '.', ':', ';', '\n', '\t' };
/// <summary>Converts the given string to a string, in which only the first letter is capitalized.</summary>
/// <param name="value">The string, in which only the first letter should be capitalized.</param>
/// <returns>A string, in which only the first letter is capitalized.</returns>
/// <exception cref="ArgumentException">Thrown, if the given string is null or empty.</exception>
public static string FirstToUpper(this string value)
{
if (string.IsNullOrEmpty(value))
throw new ArgumentException("value not valid", nameof(value));
var trimmedValue = value.Trim();
if (trimmedValue.Length > 1)
return char.ToUpper(trimmedValue[0]) + trimmedValue.Substring(1).ToLower();
return trimmedValue.ToUpper();
}
/// <summary>Counts the words in a string.</summary>
/// <param name="value">The string, for which the words should be counted.</param>
/// <returns>The number of words in the given string or zero, if the given string is null or empty.</returns>
public static int WordCount(this string value)
{
if (string.IsNullOrEmpty(value))
return 0;
var words = value.Split(DelimiterChars);
var filteredWords = words.Where(s => !string.IsNullOrEmpty(s));
return filteredWords.Count();
}
/// <summary>Returns, whether the given string contains any spaces.</summary>
/// <param name="value">The string, which should be checked.</param>
/// <returns>True, if the given string contains any spaces, otherwise false.</returns>
public static bool ContainsSpace(this string value)
{
return value.Contains(" ");
}
}
}
|
Fix typo in NetCoreNUnit_SignIn_WithInvalidPassword test comment | using Atata;
using NUnit.Framework;
namespace AtataSamples.NetCore.NUnit
{
public class SignInTests : UITestFixture
{
[Test]
public void NetCoreNUnit_SignIn()
{
Go.To<SignInPage>().
Email.Set("admin@mail.com").
Password.Set("abc123").
SignIn.ClickAndGo().
Heading.Should.Equal("Users"); // Verify that we are navigated to "Users" page.
}
[Test]
public void NetCoreNUnit_SignIn_WithInvalidPassword()
{
Go.To<SignInPage>().
Email.Set("admin@mail.com").
Password.Set("WRONGPASSWORD").
SignIn.Click().
Heading.Should.Equal("Sign In"). // Verify that we are still on "Sing In" page.
Content.Should.Contain("Password or Email is invalid"); // Verify validation message.
}
}
}
| using Atata;
using NUnit.Framework;
namespace AtataSamples.NetCore.NUnit
{
public class SignInTests : UITestFixture
{
[Test]
public void NetCoreNUnit_SignIn()
{
Go.To<SignInPage>().
Email.Set("admin@mail.com").
Password.Set("abc123").
SignIn.ClickAndGo().
Heading.Should.Equal("Users"); // Verify that we are navigated to "Users" page.
}
[Test]
public void NetCoreNUnit_SignIn_WithInvalidPassword()
{
Go.To<SignInPage>().
Email.Set("admin@mail.com").
Password.Set("WRONGPASSWORD").
SignIn.Click().
Heading.Should.Equal("Sign In"). // Verify that we are still on "Sign In" page.
Content.Should.Contain("Password or Email is invalid"); // Verify validation message.
}
}
}
|
Add tests for PascalCaseToSpacedString extensions | using System;
using NUnit.Framework;
using Entelect.Extensions;
namespace Entelect.Tests.Strings
{
[TestFixture]
public class StringExtensionsTests
{
[Test]
public void ContainsIgnoringCase()
{
var doesContain = "asd".Contains("S",StringComparison.OrdinalIgnoreCase);
Assert.True(doesContain);
}
[Test]
public void ListContainsIgnoringCase()
{
var list = new[] {"asd", "qwe", "zxc"};
var doesContain = list.Contains("ASD", StringComparison.OrdinalIgnoreCase);
Assert.True(doesContain);
}
}
} | using System;
using NUnit.Framework;
using Entelect.Extensions;
namespace Entelect.Tests.Strings
{
[TestFixture]
public class StringExtensionsTests
{
[Test]
public void ContainsIgnoringCase()
{
var doesContain = "asd".Contains("S",StringComparison.OrdinalIgnoreCase);
Assert.True(doesContain);
}
[Test]
public void ListContainsIgnoringCase()
{
var list = new[] {"asd", "qwe", "zxc"};
var doesContain = list.Contains("ASD", StringComparison.OrdinalIgnoreCase);
Assert.True(doesContain);
}
[Test]
public void PascalCaseToSpacedString()
{
const string input = "SomePascalCasedString";
const string expectedOutput = "Some Pascal Cased String";
var actualOutput = input.PascalToSpacedString();
Assert.AreEqual(expectedOutput, actualOutput);
}
[Test]
public void PascalCaseToSpacedStringArray()
{
const string input = "SomePascalCasedString";
var expectedOutput = new []{"Some", "Pascal", "Cased","String"};
var actualOutput = input.PascalToSpacedStringArray();
Assert.That(expectedOutput, Is.EquivalentTo(actualOutput));
}
}
} |
Return DisposableAction.Noop for the null profiler instead of creating new objects for every step. | using System;
using Kudu.Contracts;
using Kudu.Core.Infrastructure;
namespace Kudu.Core.Performance
{
public class NullProfiler : IProfiler
{
public static IProfiler Instance = new NullProfiler();
private NullProfiler()
{
}
public IDisposable Step(string value)
{
return new DisposableAction(() => { });
}
}
}
| using System;
using Kudu.Contracts;
using Kudu.Core.Infrastructure;
namespace Kudu.Core.Performance
{
public class NullProfiler : IProfiler
{
public static IProfiler Instance = new NullProfiler();
private NullProfiler()
{
}
public IDisposable Step(string value)
{
return DisposableAction.Noop;
}
}
}
|
Split out extensions for Entity Framework, Azure Storage, and Mongo. These are now separate projects (and NuGet packages) that all reference the Tables project (which again references the core service project). New NuGet packages are creates and references added. | using Microsoft.WindowsAzure.Mobile.Service;
namespace ZUMOAPPNAMEService.DataObjects
{
public class TodoItem : TableData
{
public string Text { get; set; }
public bool Complete { get; set; }
}
} | using Microsoft.WindowsAzure.Mobile.Service;
namespace ZUMOAPPNAMEService.DataObjects
{
public class TodoItem : EntityData
{
public string Text { get; set; }
public bool Complete { get; set; }
}
} |
Move feature ideas to GitHub issue tracker | using System;
namespace ChatRelay
{
class Program
{
private static readonly Relay relay = new Relay();
static void Main()
{
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
Run();
}
public static void Run()
{
relay.Stop();
try
{
relay.Start();
}
catch (Exception ex) when (ex.GetType() == typeof(RelayConfigurationException))
{
Console.WriteLine($"ERROR: {ex.Message}");
return;
}
while (true)
{
char command = Console.ReadKey(true).KeyChar;
if (command == 'q')
{
Console.WriteLine("Quitting...");
relay.Stop();
return;
}
if (command == 'r')
{
Console.WriteLine("Restarting...");
relay.Stop();
relay.Start();
}
}
}
private static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine($"EXCEPTION: {e.ExceptionObject}");
Run();
}
}
}
// TODO: The adapters use a Connect() Disconnect() naming convention,
// but right now they don't support reconnecting as Disconnect() is treated as more of a Dispose.
// Should probably change the naming structure or code layout to fix this. Maybe Connect/Open and Dispose?
// Alternatively, actually support disconnecting and reconnecting though more error handling is required.
// TODO: Relay emotes.
// TODO: Bot commands.
// Request that the bot tell you who is in the room in another service (reply via DM).
// Request information on the other services, mainly URL.
// Tell you how many people are on the other services (status?).
// TODO: Test on Mono.
// TODO: Logging. Would be good to basically have two log providers, rotating file on disk and console output.
// Ex, replace Console.WriteLine calls with logging calls.
// TODO: Connection monitoring. Heartbeat? IRC has Ping/Pong.
// TODO: Really think through error handling and resiliency in terms of disconnects/reconnects.
// May have to look for an alternative to the Slack API library we're using as it doesn't handling things like this well.
| using System;
namespace ChatRelay
{
class Program
{
private static readonly Relay relay = new Relay();
static void Main()
{
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
Run();
}
public static void Run()
{
relay.Stop();
try
{
relay.Start();
}
catch (Exception ex) when (ex.GetType() == typeof(RelayConfigurationException))
{
Console.WriteLine($"ERROR: {ex.Message}");
return;
}
while (true)
{
char command = Console.ReadKey(true).KeyChar;
if (command == 'q')
{
Console.WriteLine("Quitting...");
relay.Stop();
return;
}
if (command == 'r')
{
Console.WriteLine("Restarting...");
relay.Stop();
relay.Start();
}
}
}
private static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine($"EXCEPTION: {e.ExceptionObject}");
Run();
}
}
}
|
Update Store.SqlServer connection string constructor | using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using Store.Models;
using Store.Storage.Data;
namespace Store.Storage.SqlServer {
public class Client {
public Client(DBContext _dbContext) {
var fac = new Factory<SqlConnection>();
dbConnection = fac.Get(_dbContext);
}
protected string tryCatch(Action act) { try { act(); } catch (Exception e) { return e.Message; } return OperatonResult.Succeeded.ToString("F"); }
internal string runSql(string sql) {
return tryCatch(() => { var runner = new CommandRunner(dbConnection); runner.Transact(new DbCommand[] { runner.BuildCommand(sql, null) }); });
}
internal IEnumerable<dynamic> runSqlDynamic(string sql) {
var runner = new CommandRunner(dbConnection); return runner.ExecuteDynamic(sql, null);
}
protected DbConnection dbConnection;
protected DBContext dbContext;
protected enum OperatonResult { Succeeded = 1, Failed = 0 };
}
}
| using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using Store.Models;
using Store.Storage.Data;
namespace Store.Storage.SqlServer {
public class Client {
public Client(DBContext _dbContext) {
var fac = new Factory<SqlConnection>();
Func<DBContext, string> func = (DBContext _db) => _db.userId.Length == 0 || _db.password.Length == 0 ? string.Format("Data Source={0};Initial Catalog={1};Integrated Security=SSPI;", _db.server, _db.database) : string.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3};", _db.server, _db.database, _db.userId, _db.password);
dbConnection = fac.Get(_dbContext, func);
}
protected string tryCatch(Action act) { try { act(); } catch (Exception e) { return e.Message; } return OperatonResult.Succeeded.ToString("F"); }
public string runSql(string sql) {
return tryCatch(() => { var runner = new CommandRunner(dbConnection); runner.Transact(new DbCommand[] { runner.BuildCommand(sql, null) }); });
}
public IEnumerable<dynamic> runSqlDynamic(string sql) {
var runner = new CommandRunner(dbConnection); return runner.ExecuteDynamic(sql, null);
}
protected DbConnection dbConnection;
protected DBContext dbContext;
protected enum OperatonResult { Succeeded = 1, Failed = 0 };
}
}
|
Add exception (only difference from default template) | using System;
using AppKit;
using Foundation;
namespace UselessExceptions
{
public partial class ViewController : NSViewController
{
public ViewController (IntPtr handle) : base (handle)
{
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Do any additional setup after loading the view.
}
public override NSObject RepresentedObject {
get {
return base.RepresentedObject;
}
set {
base.RepresentedObject = value;
// Update the view, if already loaded.
}
}
}
}
| using System;
using AppKit;
using Foundation;
namespace UselessExceptions
{
public partial class ViewController : NSViewController
{
public ViewController (IntPtr handle) : base (handle)
{
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
throw new Exception ("USELESS");
// Do any additional setup after loading the view.
}
public override NSObject RepresentedObject {
get {
return base.RepresentedObject;
}
set {
base.RepresentedObject = value;
// Update the view, if already loaded.
}
}
}
}
|
Fix conversion bug in out dir provider | /*
Copyright 2014 Daniel Cazzulino
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
*/
namespace OctoFlow
{
using CLAP;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class OutDirProvider : DefaultProvider
{
public override object GetDefault(VerbExecutionContext context)
{
var gitRoot = GitRepo.Find(".");
if (string.IsNullOrEmpty(gitRoot))
return new DirectoryInfo(".");
return gitRoot;
}
public override string Description
{
get { return "git repo root or current dir"; }
}
}
}
| /*
Copyright 2014 Daniel Cazzulino
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
*/
namespace OctoFlow
{
using CLAP;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class OutDirProvider : DefaultProvider
{
public override object GetDefault(VerbExecutionContext context)
{
var gitRoot = GitRepo.Find(".");
if (string.IsNullOrEmpty(gitRoot))
return new DirectoryInfo(".").FullName;
return gitRoot;
}
public override string Description
{
get { return "git repo root or current dir"; }
}
}
}
|
Fix for SOS2 calculator (for one element in array). | using System;
using System.Linq;
using MilpManager.Abstraction;
namespace MilpManager.Implementation.CompositeConstraints
{
public class SOS2Calculator : ICompositeConstraintCalculator
{
public IVariable Set(IMilpManager milpManager, CompositeConstraintType type, ICompositeConstraintParameters parameters,
IVariable leftVariable, params IVariable[] rightVariable)
{
var zero = milpManager.FromConstant(0);
var one = milpManager.FromConstant(1);
var nonZeroes = new [] {leftVariable}.Concat(rightVariable).Select(v => v.Operation(OperationType.IsNotEqual, zero)).ToArray();
var nonZeroPairs = nonZeroes.Zip(nonZeroes.Skip(1), Tuple.Create).Select(pair => pair.Item1.Operation(OperationType.Conjunction, pair.Item2)).ToArray();
var nonZeroesCount = milpManager.Operation(OperationType.Addition, nonZeroes);
milpManager.Set(
ConstraintType.Equal,
milpManager.Operation(
OperationType.Disjunction,
nonZeroesCount.Operation(OperationType.IsEqual, zero),
nonZeroesCount.Operation(OperationType.IsEqual, one),
milpManager.Operation(OperationType.Conjunction,
nonZeroesCount.Operation(OperationType.IsEqual, milpManager.FromConstant(2)),
milpManager.Operation(OperationType.Addition, nonZeroPairs).Operation(OperationType.IsEqual, one)
)
),
one
);
return leftVariable;
}
}
} | using System;
using System.Linq;
using MilpManager.Abstraction;
namespace MilpManager.Implementation.CompositeConstraints
{
public class SOS2Calculator : ICompositeConstraintCalculator
{
public IVariable Set(IMilpManager milpManager, CompositeConstraintType type, ICompositeConstraintParameters parameters,
IVariable leftVariable, params IVariable[] rightVariable)
{
var zero = milpManager.FromConstant(0);
var one = milpManager.FromConstant(1);
var nonZeroes = new [] {leftVariable}.Concat(rightVariable).Select(v => v.Operation(OperationType.IsNotEqual, zero)).ToArray();
var nonZeroPairs = nonZeroes.Zip(nonZeroes.Skip(1), Tuple.Create).Select(pair => pair.Item1.Operation(OperationType.Conjunction, pair.Item2)).ToArray();
if (!nonZeroPairs.Any())
{
nonZeroPairs = new[] {milpManager.FromConstant(0)};
}
var nonZeroesCount = milpManager.Operation(OperationType.Addition, nonZeroes);
milpManager.Set(
ConstraintType.Equal,
milpManager.Operation(
OperationType.Disjunction,
nonZeroesCount.Operation(OperationType.IsEqual, zero),
nonZeroesCount.Operation(OperationType.IsEqual, one),
milpManager.Operation(OperationType.Conjunction,
nonZeroesCount.Operation(OperationType.IsEqual, milpManager.FromConstant(2)),
milpManager.Operation(OperationType.Addition, nonZeroPairs).Operation(OperationType.IsEqual, one)
)
),
one
);
return leftVariable;
}
}
} |
Increase Cassandra delay after startup | using System;
namespace Evolve.Test.Utilities
{
public class CassandraDockerContainer
{
private DockerContainer _container;
public string Id => _container.Id;
public string ExposedPort => "9042";
public string HostPort => "9042";
public string ClusterName => "evolve";
public string DataCenter => "dc1";
public TimeSpan DelayAfterStartup => TimeSpan.FromSeconds(45);
public bool Start(bool fromScratch = false)
{
_container = new DockerContainerBuilder(new DockerContainerBuilderOptions
{
FromImage = "cassandra",
Tag = "latest",
Name = "cassandra-evolve",
Env = new[] { $"CASSANDRA_CLUSTER_NAME={ClusterName}", $"CASSANDRA_DC={DataCenter}", "CASSANDRA_RACK=rack1" },
ExposedPort = $"{ExposedPort}/tcp",
HostPort = HostPort,
DelayAfterStartup = DelayAfterStartup,
RemovePreviousContainer = fromScratch
}).Build();
return _container.Start();
}
public void Remove() => _container.Remove();
public bool Stop() => _container.Stop();
public void Dispose() => _container?.Dispose();
}
}
| using System;
namespace Evolve.Test.Utilities
{
public class CassandraDockerContainer
{
private DockerContainer _container;
public string Id => _container.Id;
public string ExposedPort => "9042";
public string HostPort => "9042";
public string ClusterName => "evolve";
public string DataCenter => "dc1";
public TimeSpan DelayAfterStartup => TimeSpan.FromMinutes(1);
public bool Start(bool fromScratch = false)
{
_container = new DockerContainerBuilder(new DockerContainerBuilderOptions
{
FromImage = "cassandra",
Tag = "latest",
Name = "cassandra-evolve",
Env = new[] { $"CASSANDRA_CLUSTER_NAME={ClusterName}", $"CASSANDRA_DC={DataCenter}", "CASSANDRA_RACK=rack1" },
ExposedPort = $"{ExposedPort}/tcp",
HostPort = HostPort,
DelayAfterStartup = DelayAfterStartup,
RemovePreviousContainer = fromScratch
}).Build();
return _container.Start();
}
public void Remove() => _container.Remove();
public bool Stop() => _container.Stop();
public void Dispose() => _container?.Dispose();
}
}
|
Remove help box from the folders settings list | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
using Borodar.ReorderableList;
using UnityEditor;
namespace Borodar.RainbowFolders.Editor.Settings
{
[CustomEditor(typeof (RainbowFoldersSettings))]
public class RainbowFoldersSettingsEditor : UnityEditor.Editor
{
private const string PROP_NAME_FOLDERS = "Folders";
private SerializedProperty _foldersProperty;
protected void OnEnable()
{
_foldersProperty = serializedObject.FindProperty(PROP_NAME_FOLDERS);
}
public override void OnInspectorGUI()
{
EditorGUILayout.HelpBox("Please set your custom folder icons by specifying:\n\n" +
"- Folder Name\n" +
"Icon will be applied to all folders with the same name\n\n" +
"- Folder Path\n" +
"Icon will be applied to a single folder. The path format: Assets/SomeFolder/YourFolder", MessageType.Info);
serializedObject.Update();
ReorderableListGUI.Title("Rainbow Folders");
ReorderableListGUI.ListField(_foldersProperty);
serializedObject.ApplyModifiedProperties();
}
}
} | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
using Borodar.ReorderableList;
using UnityEditor;
namespace Borodar.RainbowFolders.Editor.Settings
{
[CustomEditor(typeof (RainbowFoldersSettings))]
public class RainbowFoldersSettingsEditor : UnityEditor.Editor
{
private const string PROP_NAME_FOLDERS = "Folders";
private SerializedProperty _foldersProperty;
protected void OnEnable()
{
_foldersProperty = serializedObject.FindProperty(PROP_NAME_FOLDERS);
}
public override void OnInspectorGUI()
{
serializedObject.Update();
ReorderableListGUI.Title("Rainbow Folders");
ReorderableListGUI.ListField(_foldersProperty);
serializedObject.ApplyModifiedProperties();
}
}
} |
Add Trello provider (not yet working) | namespace Xamarin.Forms.OAuth.Providers
{
public sealed class TrelloOAuthProvider : OAuthProvider
{
private const string _redirectUrl = "https://trelloResponse.com";
public TrelloOAuthProvider(string clientId, string clientSecret, params string[] scopes)
: base(new OAuthProviderDefinition(
"Trello",
"https://trello.com/1/authorize",
"https://trello.com/1/OAuthGetAccessToken",
"https://api.trello.com/1/members/me",
clientId,
clientSecret,
_redirectUrl,
scopes)
{
RequiresCode = true,
})
{ }
internal override string GetAuthorizationUrl()
{
return base.GetAuthorizationUrl();
}
}
}
| using System.Collections.Generic;
namespace Xamarin.Forms.OAuth.Providers
{
public sealed class TrelloOAuthProvider : OAuthProvider
{
private const string _redirectUrl = "https://trelloResponse.com";
public TrelloOAuthProvider(string clientId, string clientSecret, params string[] scopes)
: base(new OAuthProviderDefinition(
"Trello",
"https://trello.com/1/authorize",
"https://trello.com/1/OAuthGetAccessToken",
"https://api.trello.com/1/members/me",
clientId,
clientSecret,
_redirectUrl,
scopes)
{
RequiresCode = true,
})
{ }
internal override string GetAuthorizationUrl()
{
return BuildUrl(Definition.AuthorizeUrl, new KeyValuePair<string, string>[] { });
}
}
}
|
Add input event to dotnetcore2.0 example function | // Compile with:
// docker run --rm -v "$PWD":/var/task lambci/lambda:build-dotnetcore2.0 dotnet publish -c Release -o pub
// Run with:
// docker run --rm -v "$PWD"/pub:/var/task lambci/lambda:dotnetcore2.0 test::test.Function::FunctionHandler "some"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
using System.IO;
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace test
{
public class Function
{
public string FunctionHandler(Stream stream, ILambdaContext context)
{
context.Logger.Log("Log Hello world");
return "Hallo world!";
}
}
}
| // Compile with:
// docker run --rm -v "$PWD":/var/task lambci/lambda:build-dotnetcore2.0 dotnet publish -c Release -o pub
// Run with:
// docker run --rm -v "$PWD"/pub:/var/task lambci/lambda:dotnetcore2.0 test::test.Function::FunctionHandler "some"
using Amazon.Lambda.Core;
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace test
{
public class Function
{
public string FunctionHandler(object inputEvent, ILambdaContext context)
{
context.Logger.Log($"inputEvent: {inputEvent}");
return "Hello World!";
}
}
}
|
Update to MD5 hash PR. | using System;
using System.Text;
using System.Security.Cryptography;
namespace Gibe.DittoProcessors.Processors
{
public class StringToMd5HashAttribute : TestableDittoProcessorAttribute
{
public override object ProcessValue()
{
if (Value == null) throw new NullReferenceException();
var stringValue = Value as string;
// byte array representation of that string
byte[] encodedValue = new UTF8Encoding().GetBytes(stringValue);
// need MD5 to calculate the hash
byte[] hashValue = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(encodedValue);
// string representation (similar to UNIX format)
return BitConverter.ToString(hashValue).Replace("-", string.Empty).ToLower();
}
}
}
| using System;
using System.Text;
using System.Security.Cryptography;
namespace Gibe.DittoProcessors.Processors
{
public class StringToMd5HashAttribute : TestableDittoProcessorAttribute
{
public override object ProcessValue()
{
if (Value == null) throw new NullReferenceException();
var stringValue = Value as string;
byte[] encodedValue = new UTF8Encoding().GetBytes(stringValue);
byte[] hashValue = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(encodedValue);
// string representation (similar to UNIX format)
return BitConverter.ToString(hashValue).Replace("-", string.Empty).ToLower();
}
}
}
|
Update for .NET 6 rc2 | #pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: global::Android.Runtime.ResourceDesignerAttribute("Csla.Axml.Resource", IsApplication=false)]
namespace Csla.Axml
{
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "12.1.0.10")]
public partial class Resource
{
static Resource()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
public partial class Attribute
{
static Attribute()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Attribute()
{
}
}
public partial class String
{
// aapt resource value: 0x7F010000
public static int ApplicationName = 2130771968;
static String()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private String()
{
}
}
}
}
#pragma warning restore 1591
| #pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: global::Android.Runtime.ResourceDesignerAttribute("Csla.Axml.Resource", IsApplication=false)]
namespace Csla.Axml
{
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "12.1.0.11")]
public partial class Resource
{
static Resource()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
public partial class Attribute
{
static Attribute()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Attribute()
{
}
}
public partial class String
{
// aapt resource value: 0x7F010000
public static int ApplicationName = 2130771968;
static String()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private String()
{
}
}
}
}
#pragma warning restore 1591
|
Add container for sprite sheet prototypes | /*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/
using System.Collections.Generic;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Audio;
namespace ShiftDrive {
/// <summary>
/// A simple static container, for holding game assets like textures and meshes.
/// </summary>
internal static class Assets {
public static SpriteFont
fontDefault,
fontBold;
public static readonly Dictionary<string, Texture2D>
textures = new Dictionary<string, Texture2D>();
public static Model
mdlSkybox;
public static Effect
fxUnlit;
public static SoundEffect
sndUIConfirm,
sndUICancel,
sndUIAppear1,
sndUIAppear2,
sndUIAppear3,
sndUIAppear4;
public static Texture2D GetTexture(string name) {
if (!textures.ContainsKey(name.ToLowerInvariant()))
throw new KeyNotFoundException($"Texture '{name}' was not found.");
return textures[name.ToLowerInvariant()];
}
}
}
| /*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/
using System.Collections.Generic;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Audio;
namespace ShiftDrive {
/// <summary>
/// A simple static container, for holding game assets like textures and meshes.
/// </summary>
internal static class Assets {
public static SpriteFont
fontDefault,
fontBold;
public static readonly Dictionary<string, Texture2D>
textures = new Dictionary<string, Texture2D>();
public static readonly Dictionary<string, SpriteSheet>
sprites = new Dictionary<string, SpriteSheet>();
public static Model
mdlSkybox;
public static Effect
fxUnlit;
public static SoundEffect
sndUIConfirm,
sndUICancel,
sndUIAppear1,
sndUIAppear2,
sndUIAppear3,
sndUIAppear4;
public static Texture2D GetTexture(string name) {
if (!textures.ContainsKey(name.ToLowerInvariant()))
throw new KeyNotFoundException($"Texture '{name}' was not found.");
return textures[name.ToLowerInvariant()];
}
public static SpriteSheet GetSprite(string name) {
if (!sprites.ContainsKey(name.ToLowerInvariant()))
throw new KeyNotFoundException($"Sprite '{name}' was not found.");
return sprites[name.ToLowerInvariant()];
}
}
}
|
Use Section instead of Paragraph for quote blocks. | // Copyright (c) 2016 Nicolas Musset. All rights reserved.
// This file is licensed under the MIT license.
// See the LICENSE.md file in the project root for more information.
using Markdig.Syntax;
namespace Markdig.Renderers.Xaml
{
/// <summary>
/// A XAML renderer for a <see cref="QuoteBlock"/>.
/// </summary>
/// <seealso cref="Xaml.XamlObjectRenderer{T}" />
public class QuoteBlockRenderer : XamlObjectRenderer<QuoteBlock>
{
protected override void Write(XamlRenderer renderer, QuoteBlock obj)
{
renderer.EnsureLine();
// TODO: apply quote block styling
renderer.Write("<Paragraph>");
renderer.WriteChildren(obj);
renderer.WriteLine("</Paragraph>");
}
}
}
| // Copyright (c) 2016 Nicolas Musset. All rights reserved.
// This file is licensed under the MIT license.
// See the LICENSE.md file in the project root for more information.
using Markdig.Syntax;
namespace Markdig.Renderers.Xaml
{
/// <summary>
/// A XAML renderer for a <see cref="QuoteBlock"/>.
/// </summary>
/// <seealso cref="Xaml.XamlObjectRenderer{T}" />
public class QuoteBlockRenderer : XamlObjectRenderer<QuoteBlock>
{
protected override void Write(XamlRenderer renderer, QuoteBlock obj)
{
renderer.EnsureLine();
// TODO: apply quote block styling
renderer.Write("<Section>");
renderer.WriteChildren(obj);
renderer.WriteLine("</Section>");
}
}
}
|
Introduce a Protocol class for better encapsulation | namespace OpcMockTests
{
internal class OpcMockProtocol
{
}
} | using System;
using System.Collections.Generic;
namespace OpcMock
{
public class OpcMockProtocol
{
private List<ProtocolLine> lines;
public OpcMockProtocol()
{
lines = new List<ProtocolLine>();
}
public List<ProtocolLine> Lines
{
get{ return lines; }
}
public void Append(ProtocolLine protocolLine)
{
lines.Add(protocolLine);
}
}
} |
Fix Record Graph Type Query | using System;
using System.Collections.Generic;
using System.Text;
using GraphQL.Types;
using Snowflake.Model.Game.LibraryExtensions;
namespace Snowflake.Support.Remoting.GraphQL.Types.Model
{
public class GameFileExtensionGraphType : ObjectGraphType<IGameFileExtension>
{
public GameFileExtensionGraphType()
{
Name = "GameFiles";
Description = "The files of a game";
Field<FileRecordGraphType>("files",
description: "The files for which have metadata and are installed, not all files.",
resolve: context => context.Source.Files);
Field<ListGraphType<FileGraphType>>("programFiles",
description: "The files for which have metadata and are installed ",
arguments: new QueryArguments(new QueryArgument<BooleanGraphType>
{Name = "recursive", DefaultValue = false,}),
resolve: context => context.GetArgument("recursive", false)
? context.Source.ProgramRoot.EnumerateFilesRecursive()
: context.Source.ProgramRoot.EnumerateFiles());
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using GraphQL.Types;
using Snowflake.Model.Game.LibraryExtensions;
namespace Snowflake.Support.Remoting.GraphQL.Types.Model
{
public class GameFileExtensionGraphType : ObjectGraphType<IGameFileExtension>
{
public GameFileExtensionGraphType()
{
Name = "GameFiles";
Description = "The files of a game";
Field<ListGraphType<FileRecordGraphType>>("fileRecords",
description: "The files for which have metadata and are installed, not all files.",
resolve: context => context.Source.Files);
Field<ListGraphType<FileGraphType>>("programFiles",
description: "All files inside the program files folder for this game.",
arguments: new QueryArguments(new QueryArgument<BooleanGraphType>
{Name = "recursive", DefaultValue = false,}),
resolve: context => context.GetArgument("recursive", false)
? context.Source.ProgramRoot.EnumerateFilesRecursive()
: context.Source.ProgramRoot.EnumerateFiles());
}
}
}
|
Change order of OWIN handlers so static file handler does not preempt NuGet client redirect handler. | using Autofac;
using Microsoft.Owin.FileSystems;
using Microsoft.Owin.StaticFiles;
using NuGet.Lucene.Web;
using NuGet.Lucene.Web.Formatters;
using Owin;
namespace Klondike.SelfHost
{
class SelfHostStartup : Klondike.Startup
{
private readonly SelfHostSettings selfHostSettings;
public SelfHostStartup(SelfHostSettings selfHostSettings)
{
this.selfHostSettings = selfHostSettings;
}
protected override string MapPath(string virtualPath)
{
return selfHostSettings.MapPath(virtualPath);
}
protected override INuGetWebApiSettings CreateSettings()
{
return selfHostSettings;
}
protected override NuGetHtmlMicrodataFormatter CreateMicrodataFormatter()
{
return new NuGetHtmlMicrodataFormatter();
}
protected override void Start(IAppBuilder app, IContainer container)
{
var fileServerOptions = new FileServerOptions
{
FileSystem = new PhysicalFileSystem(selfHostSettings.BaseDirectory),
EnableDefaultFiles = true,
};
fileServerOptions.DefaultFilesOptions.DefaultFileNames = new[] {"index.html"};
app.UseFileServer(fileServerOptions);
base.Start(app, container);
}
}
}
| using Autofac;
using Microsoft.Owin.FileSystems;
using Microsoft.Owin.StaticFiles;
using NuGet.Lucene.Web;
using NuGet.Lucene.Web.Formatters;
using Owin;
namespace Klondike.SelfHost
{
class SelfHostStartup : Klondike.Startup
{
private readonly SelfHostSettings selfHostSettings;
public SelfHostStartup(SelfHostSettings selfHostSettings)
{
this.selfHostSettings = selfHostSettings;
}
protected override string MapPath(string virtualPath)
{
return selfHostSettings.MapPath(virtualPath);
}
protected override INuGetWebApiSettings CreateSettings()
{
return selfHostSettings;
}
protected override NuGetHtmlMicrodataFormatter CreateMicrodataFormatter()
{
return new NuGetHtmlMicrodataFormatter();
}
protected override void Start(IAppBuilder app, IContainer container)
{
base.Start(app, container);
var fileServerOptions = new FileServerOptions
{
FileSystem = new PhysicalFileSystem(selfHostSettings.BaseDirectory),
EnableDefaultFiles = true,
};
fileServerOptions.DefaultFilesOptions.DefaultFileNames = new[] {"index.html"};
app.UseFileServer(fileServerOptions);
}
}
}
|
Add an option to enable handling of help on empty invocations | using System;
namespace Konsola.Parser
{
/// <summary>
/// Configures the options when parsing args and binding them to a context.
/// </summary>
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public class ContextOptionsAttribute : Attribute
{
/// <summary>
/// Gets or sets the program's description.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to invoke the special methods after parsing.
/// </summary>
public bool InvokeMethods { get; set; }
}
} | using System;
namespace Konsola.Parser
{
/// <summary>
/// Configures the options when parsing args and binding them to a context.
/// </summary>
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public class ContextOptionsAttribute : Attribute
{
/// <summary>
/// Gets or sets the program's description.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to handle empty program invocations as help.
/// </summary>
public bool HandleEmptyInvocationAsHelp { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to invoke the special methods after parsing.
/// </summary>
public bool InvokeMethods { get; set; }
}
} |
Add a safety check for when Authors is null, which shouldn't happen in the first place. Work items: 1727, 1728 | using System;
using System.Collections.Generic;
using System.Windows.Data;
namespace NuGet.Dialog.PackageManagerUI
{
public class StringCollectionsToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (targetType == typeof(string))
{
string stringValue = value as string;
if (stringValue != null)
{
return stringValue;
}
else
{
IEnumerable<string> parts = (IEnumerable<string>)value;
return String.Join(", ", parts);
}
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| using System;
using System.Collections.Generic;
using System.Windows.Data;
namespace NuGet.Dialog.PackageManagerUI
{
public class StringCollectionsToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (targetType == typeof(string))
{
string stringValue = value as string;
if (stringValue != null)
{
return stringValue;
}
else if (value == null)
{
return String.Empty;
}
{
IEnumerable<string> parts = (IEnumerable<string>)value;
return String.Join(", ", parts);
}
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|
Change ModelBuilder to use old EntityFrameworkCore RC1 naming conventions | using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace Dangl.WebDocumentation.Models
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions options) : base(options) { }
public DbSet<DocumentationProject> DocumentationProjects { get; set; }
public DbSet<UserProjectAccess> UserProjects { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Make the Name unique so it can be used as a single identifier for a project ( -> Urls may contain the project name instead of the Guid)
builder.Entity<DocumentationProject>()
.HasIndex(Entity => Entity.Name)
.IsUnique();
// Make the ApiKey unique so it can be used as a single identifier for a project
builder.Entity<DocumentationProject>()
.HasIndex(Entity => Entity.ApiKey)
.IsUnique();
// Composite key for UserProject Access
builder.Entity<UserProjectAccess>()
.HasKey(Entity => new {Entity.ProjectId, Entity.UserId});
builder.Entity<UserProjectAccess>()
.HasOne(Entity => Entity.Project)
.WithMany(Project => Project.UserAccess)
.OnDelete(DeleteBehavior.Cascade);
}
}
} | using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
namespace Dangl.WebDocumentation.Models
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions options) : base(options) { }
public DbSet<DocumentationProject> DocumentationProjects { get; set; }
public DbSet<UserProjectAccess> UserProjects { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
foreach (var entity in builder.Model.GetEntityTypes())
{
entity.Relational().TableName = entity.DisplayName();
}
base.OnModelCreating(builder);
// Make the Name unique so it can be used as a single identifier for a project ( -> Urls may contain the project name instead of the Guid)
builder.Entity<DocumentationProject>()
.HasIndex(Entity => Entity.Name)
.IsUnique();
// Make the ApiKey unique so it can be used as a single identifier for a project
builder.Entity<DocumentationProject>()
.HasIndex(Entity => Entity.ApiKey)
.IsUnique();
// Composite key for UserProject Access
builder.Entity<UserProjectAccess>()
.HasKey(Entity => new {Entity.ProjectId, Entity.UserId});
builder.Entity<UserProjectAccess>()
.HasOne(Entity => Entity.Project)
.WithMany(Project => Project.UserAccess)
.OnDelete(DeleteBehavior.Cascade);
}
}
} |
Add test for generic name collision on frontend | using System.Web.Http;
using Newtonsoft.Json;
namespace WebApiTestApplication.Controllers
{
public class MegaClass : AnotherClass
{
public int Something { get; set; }
}
public class Chain1<T1, T2>
{
public T1 Value11 { get; set; }
public T2 Value12 { get; set; }
}
public class Chain2<TValue> : Chain1<TValue, int>
{
public TValue Value2 { get; set; }
}
public class Chain3 : Chain2<MegaClass>
{
public object Value3 { get; set; }
}
[RoutePrefix("api/thingy")]
public class ThingyController : ApiController
{
[HttpGet]
[Route("")]
public string GetAll()
{
return $"values";
}
[HttpGet]
[Route("{id}")]
public string Get(int? id, string x, [FromUri]MegaClass c)
{
var valueJson = JsonConvert.SerializeObject(c);
return $"value {id} {x} {valueJson}";
}
[HttpGet]
[Route("")]
public string Getty(string x, int y)
{
return $"value {x} {y}";
}
[HttpPost]
[Route("")]
public string Post(MegaClass value)
{
var valueJson = JsonConvert.SerializeObject(value);
return $"thanks for the {valueJson} in the ace!";
}
}
} | using System.Web.Http;
using Newtonsoft.Json;
namespace WebApiTestApplication.Controllers
{
public class MegaClass : AnotherClass
{
public int Something { get; set; }
}
public class Chain1<T>
{
public T Value { get; set; }
}
public class Chain1<T1, T2>
{
public T1 Value11 { get; set; }
public T2 Value12 { get; set; }
}
public class Chain2<TValue> : Chain1<TValue, int>
{
public TValue Value2 { get; set; }
}
public class Chain3 : Chain2<MegaClass>
{
public object Value3 { get; set; }
}
[RoutePrefix("api/thingy")]
public class ThingyController : ApiController
{
[HttpGet]
[Route("")]
public string GetAll()
{
return $"values";
}
[HttpGet]
[Route("{id}")]
public string Get(int? id, string x, [FromUri]MegaClass c)
{
var valueJson = JsonConvert.SerializeObject(c);
return $"value {id} {x} {valueJson}";
}
[HttpGet]
[Route("")]
public string Getty(string x, int y)
{
return $"value {x} {y}";
}
[HttpPost]
[Route("")]
public string Post(MegaClass value)
{
var valueJson = JsonConvert.SerializeObject(value);
return $"thanks for the {valueJson} in the ace!";
}
}
} |
Fix supported enum check in type extentions. | using System;
using System.Collections.Generic;
using System.Reflection;
namespace WindowsAzure.Table.Extensions
{
internal static class TypeExtentions
{
private static readonly HashSet<Type> _supportedEntityPropertyTypes = new HashSet<Type>
{
typeof(long),
typeof(int),
typeof(Guid),
typeof(double),
typeof(string),
typeof(bool),
typeof(DateTime),
typeof(DateTimeOffset),
typeof(byte[]),
};
public static bool IsSupportedEntityPropertyType(this Type type)
{
if (type.GetTypeInfo().IsEnum)
{
return _supportedEntityPropertyTypes.Contains(type);
}
return _supportedEntityPropertyTypes.Contains(type)
|| _supportedEntityPropertyTypes.Contains(Nullable.GetUnderlyingType(type));
}
}
}
| using System;
using System.Collections.Generic;
using System.Reflection;
namespace WindowsAzure.Table.Extensions
{
internal static class TypeExtentions
{
private static readonly HashSet<Type> _supportedEntityPropertyTypes = new HashSet<Type>
{
typeof(long),
typeof(int),
typeof(Guid),
typeof(double),
typeof(string),
typeof(bool),
typeof(DateTime),
typeof(DateTimeOffset),
typeof(byte[]),
};
public static bool IsSupportedEntityPropertyType(this Type type)
{
if (type.GetTypeInfo().IsEnum)
{
return _supportedEntityPropertyTypes.Contains(Enum.GetUnderlyingType(type));
}
return _supportedEntityPropertyTypes.Contains(type)
|| _supportedEntityPropertyTypes.Contains(Nullable.GetUnderlyingType(type));
}
}
}
|
Fix annotations loader for tests | using System;
using System.Collections.Generic;
using JetBrains.Application;
using JetBrains.Metadata.Utils;
using JetBrains.ReSharper.Psi.ExtensionsAPI.ExternalAnnotations;
using JetBrains.TestFramework.Utils;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Unity.Tests
{
[ShellComponent]
public class AnnotationsLoader : IExternalAnnotationsFileProvider
{
private readonly OneToSetMap<string, FileSystemPath> myAnnotations;
public AnnotationsLoader()
{
myAnnotations = new OneToSetMap<string, FileSystemPath>(StringComparer.OrdinalIgnoreCase);
var testDataPathBase = TestUtil.GetTestDataPathBase(GetType().Assembly);
var annotationsPath = testDataPathBase.Parent.Parent / "src" / "resharper-unity" / "annotations";
Assertion.Assert(annotationsPath.ExistsDirectory, $"Cannot find annotations: {annotationsPath}");
var annotationFiles = annotationsPath.GetChildFiles();
foreach (var annotationFile in annotationFiles)
{
myAnnotations.Add(annotationFile.NameWithoutExtension, annotationFile);
}
}
public IEnumerable<FileSystemPath> GetAnnotationsFiles(AssemblyNameInfo assemblyName = null, FileSystemPath assemblyLocation = null)
{
if (assemblyName == null)
return myAnnotations.Values;
return myAnnotations[assemblyName.Name];
}
}
} | using System;
using System.Collections.Generic;
using JetBrains.Application;
using JetBrains.Metadata.Utils;
using JetBrains.ReSharper.Psi.ExtensionsAPI.ExternalAnnotations;
using JetBrains.TestFramework.Utils;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Unity.Tests
{
[ShellComponent]
public class AnnotationsLoader : IExternalAnnotationsFileProvider
{
private readonly OneToSetMap<string, FileSystemPath> myAnnotations;
public AnnotationsLoader()
{
myAnnotations = new OneToSetMap<string, FileSystemPath>(StringComparer.OrdinalIgnoreCase);
var testDataPathBase = TestUtil.GetTestDataPathBase(GetType().Assembly);
var annotationsPath = testDataPathBase.Parent.Parent / "src" / "annotations";
Assertion.Assert(annotationsPath.ExistsDirectory, $"Cannot find annotations: {annotationsPath}");
var annotationFiles = annotationsPath.GetChildFiles();
foreach (var annotationFile in annotationFiles)
{
myAnnotations.Add(annotationFile.NameWithoutExtension, annotationFile);
}
}
public IEnumerable<FileSystemPath> GetAnnotationsFiles(AssemblyNameInfo assemblyName = null, FileSystemPath assemblyLocation = null)
{
if (assemblyName == null)
return myAnnotations.Values;
return myAnnotations[assemblyName.Name];
}
}
} |
Add description for roles scope | using System.Collections.Generic;
using System.Linq;
using Thinktecture.IdentityServer.Core;
using Thinktecture.IdentityServer.Core.Models;
namespace Thinktecture.IdentityServer.Host.Config
{
public class Scopes
{
public static IEnumerable<Scope> Get()
{
return new[]
{
Scope.OpenId,
Scope.Profile,
Scope.Email,
Scope.OfflineAccess,
new Scope
{
Name = "roles",
DisplayName = "Roles",
Type = ScopeType.Identity,
Claims = new[]
{
new ScopeClaim("role")
}
},
new Scope
{
Name = "read",
DisplayName = "Read data",
Type = ScopeType.Resource,
Emphasize = false,
},
new Scope
{
Name = "write",
DisplayName = "Write data",
Type = ScopeType.Resource,
Emphasize = true,
},
new Scope
{
Name = "idmgr",
DisplayName = "IdentityManager",
Type = ScopeType.Resource,
Emphasize = true,
Claims = new List<ScopeClaim>
{
new ScopeClaim("name"),
new ScopeClaim("role")
}
}
};
}
}
} | using System.Collections.Generic;
using System.Linq;
using Thinktecture.IdentityServer.Core;
using Thinktecture.IdentityServer.Core.Models;
namespace Thinktecture.IdentityServer.Host.Config
{
public class Scopes
{
public static IEnumerable<Scope> Get()
{
return new[]
{
Scope.OpenId,
Scope.Profile,
Scope.Email,
Scope.OfflineAccess,
new Scope
{
Name = "roles",
DisplayName = "Roles",
Description = "Your organizational roles",
Type = ScopeType.Identity,
Claims = new[]
{
new ScopeClaim("role")
}
},
new Scope
{
Name = "read",
DisplayName = "Read data",
Type = ScopeType.Resource,
Emphasize = false,
},
new Scope
{
Name = "write",
DisplayName = "Write data",
Type = ScopeType.Resource,
Emphasize = true,
},
new Scope
{
Name = "idmgr",
DisplayName = "IdentityManager",
Type = ScopeType.Resource,
Emphasize = true,
Claims = new List<ScopeClaim>
{
new ScopeClaim("name"),
new ScopeClaim("role")
}
}
};
}
}
} |
Revert "Use dot instead of dash to separate build metadata" | public class BuildVersion
{
public GitVersion GitVersion { get; private set; }
public string Version { get; private set; }
public string Milestone { get; private set; }
public string SemVersion { get; private set; }
public string GemVersion { get; private set; }
public string VsixVersion { get; private set; }
public static BuildVersion Calculate(ICakeContext context, BuildParameters parameters, GitVersion gitVersion)
{
var version = gitVersion.MajorMinorPatch;
var semVersion = gitVersion.LegacySemVer;
var vsixVersion = gitVersion.MajorMinorPatch;
if (!string.IsNullOrWhiteSpace(gitVersion.BuildMetaData)) {
semVersion += "." + gitVersion.BuildMetaData;
vsixVersion += "." + DateTime.UtcNow.ToString("yyMMddHH");
}
return new BuildVersion
{
GitVersion = gitVersion,
Milestone = version,
Version = version,
SemVersion = semVersion,
GemVersion = semVersion.Replace("-", "."),
VsixVersion = vsixVersion,
};
}
}
| public class BuildVersion
{
public GitVersion GitVersion { get; private set; }
public string Version { get; private set; }
public string Milestone { get; private set; }
public string SemVersion { get; private set; }
public string GemVersion { get; private set; }
public string VsixVersion { get; private set; }
public static BuildVersion Calculate(ICakeContext context, BuildParameters parameters, GitVersion gitVersion)
{
var version = gitVersion.MajorMinorPatch;
var semVersion = gitVersion.LegacySemVer;
var vsixVersion = gitVersion.MajorMinorPatch;
if (!string.IsNullOrWhiteSpace(gitVersion.BuildMetaData)) {
semVersion += "-" + gitVersion.BuildMetaData;
vsixVersion += "." + DateTime.UtcNow.ToString("yyMMddHH");
}
return new BuildVersion
{
GitVersion = gitVersion,
Milestone = version,
Version = version,
SemVersion = semVersion,
GemVersion = semVersion.Replace("-", "."),
VsixVersion = vsixVersion,
};
}
}
|
Add test that aggregate exception is last | using System.Linq;
using System.Threading.Tasks;
using Bugsnag.Payload;
using Xunit;
namespace Bugsnag.Tests.Payload
{
public class ExceptionTests
{
[Fact]
public void CorrectNumberOfExceptions()
{
var exception = new System.Exception("oh noes!");
var exceptions = new Exceptions(exception, 5);
Assert.Single(exceptions);
}
[Fact]
public void IncludeInnerExceptions()
{
var innerException = new System.Exception();
var exception = new System.Exception("oh noes!", innerException);
var exceptions = new Exceptions(exception, 5);
Assert.Equal(2, exceptions.Count());
}
[Fact]
public void HandleAggregateExceptions()
{
Exceptions exceptions = null;
var exceptionsToThrow = new[] { new System.Exception(), new System.DllNotFoundException() };
var tasks = exceptionsToThrow.Select(e => Task.Run(() => { throw e; })).ToArray();
try
{
Task.WaitAll(tasks);
}
catch (System.Exception exception)
{
exceptions = new Exceptions(exception, 0);
}
var results = exceptions.ToArray();
Assert.Contains(results, exception => exception.ErrorClass == "System.DllNotFoundException");
Assert.Contains(results, exception => exception.ErrorClass == "System.Exception");
Assert.Contains(results, exception => exception.ErrorClass == "System.AggregateException");
}
}
}
| using System.Linq;
using System.Threading.Tasks;
using Bugsnag.Payload;
using Xunit;
namespace Bugsnag.Tests.Payload
{
public class ExceptionTests
{
[Fact]
public void CorrectNumberOfExceptions()
{
var exception = new System.Exception("oh noes!");
var exceptions = new Exceptions(exception, 5);
Assert.Single(exceptions);
}
[Fact]
public void IncludeInnerExceptions()
{
var innerException = new System.Exception();
var exception = new System.Exception("oh noes!", innerException);
var exceptions = new Exceptions(exception, 5);
Assert.Equal(2, exceptions.Count());
}
public class AggregateExceptions
{
Exception[] exceptions;
public AggregateExceptions()
{
Exceptions exceptions = null;
var exceptionsToThrow = new[] { new System.Exception(), new System.DllNotFoundException() };
var tasks = exceptionsToThrow.Select(e => Task.Run(() => { throw e; })).ToArray();
try
{
Task.WaitAll(tasks);
}
catch (System.Exception exception)
{
exceptions = new Exceptions(exception, 0);
}
this.exceptions = exceptions.ToArray();
}
[Fact]
public void ContainsDllNotFoundException()
{
Assert.Contains(exceptions, exception => exception.ErrorClass == "System.DllNotFoundException");
}
[Fact]
public void ContainsException()
{
Assert.Contains(exceptions, exception => exception.ErrorClass == "System.Exception");
}
[Fact]
public void AggregateExceptionIsLast()
{
var lastException = exceptions.Last();
Assert.Equal("System.AggregateException", lastException.ErrorClass);
}
}
}
}
|
Remove closing bracket from arguments | namespace AngleSharp.Css.ValueConverters
{
using System;
using System.Collections.Generic;
using System.Linq;
using AngleSharp.Dom.Css;
using AngleSharp.Parser.Css;
sealed class FunctionValueConverter<T> : IValueConverter<T>
{
readonly String _name;
readonly IValueConverter<T> _arguments;
public FunctionValueConverter(String name, IValueConverter<T> arguments)
{
_name = name;
_arguments = arguments;
}
public Boolean TryConvert(IEnumerable<CssToken> value, Action<T> setResult)
{
var args = ExtractArguments(value);
return args != null && _arguments.TryConvert(args, setResult);
}
public Boolean Validate(IEnumerable<CssToken> value)
{
var args = ExtractArguments(value);
return args != null && _arguments.Validate(args);
}
List<CssToken> ExtractArguments(IEnumerable<CssToken> value)
{
var iter = value.GetEnumerator();
if (iter.MoveNext() && IsFunction(iter.Current))
{
var tokens = new List<CssToken>();
while (iter.MoveNext())
{
tokens.Add(iter.Current);
}
if (tokens.Count > 0 && tokens[tokens.Count - 1].Type == CssTokenType.RoundBracketClose)
{
return tokens;
}
}
return null;
}
Boolean IsFunction(CssToken value)
{
return value.Type == CssTokenType.Function && value.Data.Equals(_name, StringComparison.OrdinalIgnoreCase);
}
}
}
| namespace AngleSharp.Css.ValueConverters
{
using System;
using System.Collections.Generic;
using System.Linq;
using AngleSharp.Dom.Css;
using AngleSharp.Parser.Css;
sealed class FunctionValueConverter<T> : IValueConverter<T>
{
readonly String _name;
readonly IValueConverter<T> _arguments;
public FunctionValueConverter(String name, IValueConverter<T> arguments)
{
_name = name;
_arguments = arguments;
}
public Boolean TryConvert(IEnumerable<CssToken> value, Action<T> setResult)
{
var args = ExtractArguments(value);
return args != null && _arguments.TryConvert(args, setResult);
}
public Boolean Validate(IEnumerable<CssToken> value)
{
var args = ExtractArguments(value);
return args != null && _arguments.Validate(args);
}
List<CssToken> ExtractArguments(IEnumerable<CssToken> value)
{
var iter = value.GetEnumerator();
if (iter.MoveNext() && IsFunction(iter.Current))
{
var tokens = new List<CssToken>();
while (iter.MoveNext())
{
tokens.Add(iter.Current);
}
if (tokens.Count > 0 && tokens[tokens.Count - 1].Type == CssTokenType.RoundBracketClose)
{
tokens.RemoveAt(tokens.Count - 1);
return tokens;
}
}
return null;
}
Boolean IsFunction(CssToken value)
{
return value.Type == CssTokenType.Function && value.Data.Equals(_name, StringComparison.OrdinalIgnoreCase);
}
}
}
|
Adjust version number to match DokanNet | using System;
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("DokanNet.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DokanNet.Tests")]
[assembly: AssemblyCopyright("Copyright © 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)]
// 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")]
[assembly: CLSCompliant(true)] | using System;
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("DokanNet.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DokanNet.Tests")]
[assembly: AssemblyCopyright("Copyright © 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)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.8.0.0")]
[assembly: AssemblyFileVersion("0.8.0.0")]
[assembly: CLSCompliant(true)] |
Update the length once during construction | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Linq;
using osu.Framework.Audio.Track;
using osu.Game.Rulesets.Objects.Types;
namespace osu.Game.Beatmaps
{
public partial class WorkingBeatmap
{
private class VirtualBeatmapTrack : TrackVirtual
{
private readonly IBeatmap beatmap;
public VirtualBeatmapTrack(IBeatmap beatmap)
{
this.beatmap = beatmap;
}
protected override void UpdateState()
{
updateVirtualLength();
base.UpdateState();
}
private void updateVirtualLength()
{
var lastObject = beatmap.HitObjects.LastOrDefault();
switch (lastObject)
{
case null:
Length = 1000;
break;
case IHasEndTime endTime:
Length = endTime.EndTime + 1000;
break;
default:
Length = lastObject.StartTime + 1000;
break;
}
}
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Linq;
using osu.Framework.Audio.Track;
using osu.Game.Rulesets.Objects.Types;
namespace osu.Game.Beatmaps
{
public partial class WorkingBeatmap
{
/// <summary>
/// A type of <see cref="TrackVirtual"/> which provides a valid length based on the <see cref="HitObject"/>s of an <see cref="IBeatmap"/>.
/// </summary>
private class VirtualBeatmapTrack : TrackVirtual
{
private readonly IBeatmap beatmap;
public VirtualBeatmapTrack(IBeatmap beatmap)
{
this.beatmap = beatmap;
updateVirtualLength();
}
protected override void UpdateState()
{
updateVirtualLength();
base.UpdateState();
}
private void updateVirtualLength()
{
var lastObject = beatmap.HitObjects.LastOrDefault();
switch (lastObject)
{
case null:
Length = 1000;
break;
case IHasEndTime endTime:
Length = endTime.EndTime + 1000;
break;
default:
Length = lastObject.StartTime + 1000;
break;
}
}
}
}
}
|
Revert CrytoConfiguration to using Credential implementation | using System.Collections.Generic;
namespace RockLib.Encryption.Symmetric
{
/// <summary>
/// Defines an xml-serializable object that contains the information needed to configure an
/// instance of <see cref="SymmetricCrypto"/>.
/// </summary>
public class CryptoConfiguration
{
/// <summary>
/// Gets the collection of credentials that will be available for encryption or
/// decryption operations.
/// </summary>
public List<ICredential> Credentials { get; set; } = new List<ICredential>();
}
} | using System.Collections.Generic;
namespace RockLib.Encryption.Symmetric
{
/// <summary>
/// Defines an xml-serializable object that contains the information needed to configure an
/// instance of <see cref="SymmetricCrypto"/>.
/// </summary>
public class CryptoConfiguration
{
/// <summary>
/// Gets the collection of credentials that will be available for encryption or
/// decryption operations.
/// </summary>
public List<Credential> Credentials { get; set; } = new List<Credential>();
}
} |
Add frame counter to give DrawVis a bit more activity. | //Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
//Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Drawables;
using osu.Framework.Graphics.Sprites;
using OpenTK;
using OpenTK.Graphics;
namespace osu.Framework.VisualTests
{
class VisualTestGame : Game
{
public override void Load()
{
base.Load();
Host.Size = new Vector2(1366, 768);
SampleGame test = new SampleGame();
DrawVisualiser drawVis;
Add(test);
Add(drawVis = new DrawVisualiser(test));
Add(new CursorContainer());
}
class SampleGame : LargeContainer
{
SpriteText text;
int num = 0;
public override void Load()
{
base.Load();
Box box;
Add(box = new Box()
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(150, 150),
Colour = Color4.Tomato
});
Add(text = new SpriteText());
box.RotateTo(360 * 10, 60000);
}
protected override void Update()
{
text.Text = (num++).ToString();
base.Update();
}
}
}
}
| //Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
//Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Drawables;
using osu.Framework.Graphics.Sprites;
using OpenTK;
using OpenTK.Graphics;
namespace osu.Framework.VisualTests
{
class VisualTestGame : Game
{
public override void Load()
{
base.Load();
Host.Size = new Vector2(1366, 768);
SampleGame test = new SampleGame();
DrawVisualiser drawVis;
Add(test);
Add(drawVis = new DrawVisualiser(test));
Add(new CursorContainer());
}
class SampleGame : LargeContainer
{
SpriteText text;
int num = 0;
public override void Load()
{
base.Load();
Box box;
Add(box = new Box()
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(150, 150),
Colour = Color4.Tomato
});
Add(text = new SpriteText()
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
});
box.RotateTo(360 * 10, 60000);
}
protected override void Update()
{
base.Update();
text.Text = $@"frame count: {num++}";
}
}
}
}
|
Add 10K mod to incompatibility list | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Mania.Beatmaps;
using osu.Game.Rulesets.Mods;
namespace osu.Game.Rulesets.Mania.Mods
{
public abstract class ManiaKeyMod : Mod, IApplicableToBeatmapConverter
{
public override string Acronym => Name;
public abstract int KeyCount { get; }
public override ModType Type => ModType.Conversion;
public override double ScoreMultiplier => 1; // TODO: Implement the mania key mod score multiplier
public override bool Ranked => true;
public void ApplyToBeatmapConverter(IBeatmapConverter beatmapConverter)
{
var mbc = (ManiaBeatmapConverter)beatmapConverter;
// Although this can work, for now let's not allow keymods for mania-specific beatmaps
if (mbc.IsForCurrentRuleset)
return;
mbc.TargetColumns = KeyCount;
}
public override Type[] IncompatibleMods => new[]
{
typeof(ManiaModKey1),
typeof(ManiaModKey2),
typeof(ManiaModKey3),
typeof(ManiaModKey4),
typeof(ManiaModKey5),
typeof(ManiaModKey6),
typeof(ManiaModKey7),
typeof(ManiaModKey8),
typeof(ManiaModKey9),
}.Except(new[] { GetType() }).ToArray();
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Mania.Beatmaps;
using osu.Game.Rulesets.Mods;
namespace osu.Game.Rulesets.Mania.Mods
{
public abstract class ManiaKeyMod : Mod, IApplicableToBeatmapConverter
{
public override string Acronym => Name;
public abstract int KeyCount { get; }
public override ModType Type => ModType.Conversion;
public override double ScoreMultiplier => 1; // TODO: Implement the mania key mod score multiplier
public override bool Ranked => true;
public void ApplyToBeatmapConverter(IBeatmapConverter beatmapConverter)
{
var mbc = (ManiaBeatmapConverter)beatmapConverter;
// Although this can work, for now let's not allow keymods for mania-specific beatmaps
if (mbc.IsForCurrentRuleset)
return;
mbc.TargetColumns = KeyCount;
}
public override Type[] IncompatibleMods => new[]
{
typeof(ManiaModKey1),
typeof(ManiaModKey2),
typeof(ManiaModKey3),
typeof(ManiaModKey4),
typeof(ManiaModKey5),
typeof(ManiaModKey6),
typeof(ManiaModKey7),
typeof(ManiaModKey8),
typeof(ManiaModKey9),
typeof(ManiaModKey10),
}.Except(new[] { GetType() }).ToArray();
}
}
|
Revert "Fix issue with API header binding when running under a subdirectory" | using System;
using System.Web.Mvc;
namespace NuGetGallery
{
public class HttpHeaderValueProviderFactory : ValueProviderFactory
{
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
var request = controllerContext.RequestContext.HttpContext.Request;
// Use this value provider only if a route is located under "API"
if (request.Path.Contains("/api/"))
return new HttpHeaderValueProvider(request, "ApiKey");
return null;
}
}
} | using System;
using System.Web.Mvc;
namespace NuGetGallery
{
public class HttpHeaderValueProviderFactory : ValueProviderFactory
{
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
var request = controllerContext.RequestContext.HttpContext.Request;
// Use this value provider only if a route is located under "API"
if (request.Path.TrimStart('/').StartsWith("api", StringComparison.OrdinalIgnoreCase))
return new HttpHeaderValueProvider(request, "ApiKey");
return null;
}
}
} |
Check if eventargs is null | namespace Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing
{
using System;
#if !NET40
using System.Diagnostics.Tracing;
#endif
using System.Linq;
#if NET40
using Microsoft.Diagnostics.Tracing;
#endif
internal class DiagnosticsEventListener : EventListener
{
private const long AllKeyword = -1;
private readonly EventLevel logLevel;
private readonly DiagnosticsListener listener;
public DiagnosticsEventListener(DiagnosticsListener listener, EventLevel logLevel)
{
this.listener = listener;
this.logLevel = logLevel;
}
protected override void OnEventWritten(EventWrittenEventArgs eventSourceEvent)
{
var metadata = new EventMetaData
{
Keywords = (long)eventSourceEvent.Keywords,
MessageFormat = eventSourceEvent.Message,
EventId = eventSourceEvent.EventId,
Level = eventSourceEvent.Level
};
var traceEvent = new TraceEvent
{
MetaData = metadata,
Payload = eventSourceEvent.Payload != null ? eventSourceEvent.Payload.ToArray() : null
};
this.listener.WriteEvent(traceEvent);
}
protected override void OnEventSourceCreated(EventSource eventSource)
{
if (eventSource.Name.StartsWith("Microsoft-ApplicationInsights-", StringComparison.Ordinal))
{
this.EnableEvents(eventSource, this.logLevel, (EventKeywords)AllKeyword);
}
base.OnEventSourceCreated(eventSource);
}
}
} | namespace Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing
{
using System;
#if !NET40
using System.Diagnostics.Tracing;
#endif
using System.Linq;
#if NET40
using Microsoft.Diagnostics.Tracing;
#endif
internal class DiagnosticsEventListener : EventListener
{
private const long AllKeyword = -1;
private readonly EventLevel logLevel;
private readonly DiagnosticsListener listener;
public DiagnosticsEventListener(DiagnosticsListener listener, EventLevel logLevel)
{
this.listener = listener;
this.logLevel = logLevel;
}
protected override void OnEventWritten(EventWrittenEventArgs eventSourceEvent)
{
if (eventSourceEvent == null)
{
return;
}
var metadata = new EventMetaData
{
Keywords = (long)eventSourceEvent.Keywords,
MessageFormat = eventSourceEvent.Message,
EventId = eventSourceEvent.EventId,
Level = eventSourceEvent.Level
};
var traceEvent = new TraceEvent
{
MetaData = metadata,
Payload = eventSourceEvent.Payload != null ? eventSourceEvent.Payload.ToArray() : null
};
this.listener.WriteEvent(traceEvent);
}
protected override void OnEventSourceCreated(EventSource eventSource)
{
if (eventSource.Name.StartsWith("Microsoft-ApplicationInsights-", StringComparison.Ordinal))
{
this.EnableEvents(eventSource, this.logLevel, (EventKeywords)AllKeyword);
}
base.OnEventSourceCreated(eventSource);
}
}
} |
Add method to get current power source. | // Copyright (C) 2017, The Duplicati Team
// http://www.duplicati.com, info@duplicati.com
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace Duplicati.Library.Utility.Power
{
public static class PowerSupply
{
public enum Source
{
AC,
Battery,
Unknown
}
}
}
| // Copyright (C) 2017, The Duplicati Team
// http://www.duplicati.com, info@duplicati.com
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace Duplicati.Library.Utility.Power
{
public static class PowerSupply
{
public enum Source
{
AC,
Battery,
Unknown
}
public static Source GetSource()
{
IPowerSupplyState state;
// Since IsClientLinux returns true when on Mac OS X, we need to check IsClientOSX first.
if (Utility.IsClientOSX)
{
state = new DefaultPowerSupplyState();
}
else if (Utility.IsClientLinux)
{
state = new LinuxPowerSupplyState();
}
else
{
state = new DefaultPowerSupplyState();
}
return state.GetSource();
}
}
}
|
Change datatype for OpeningBalance and OpeningRate | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace com.techphernalia.MyPersonalAccounts.Model.Inventory
{
public class StockItem
{
public int StockItemId { get; set; }
public string StockItemName { get; set; }
public int StockGroupId { get; set; }
public int StockUnitId { get; set; }
public decimal OpeningBalance { get; set; }
public decimal OpeningRate { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace com.techphernalia.MyPersonalAccounts.Model.Inventory
{
public class StockItem
{
public int StockItemId { get; set; }
public string StockItemName { get; set; }
public int StockGroupId { get; set; }
public int StockUnitId { get; set; }
public double OpeningBalance { get; set; }
public double OpeningRate { get; set; }
}
}
|
Add token issuspended to view model | using Foundatio.Repositories.Models;
namespace Exceptionless.Web.Models;
public class ViewToken : IIdentity, IHaveDates {
public string Id { get; set; }
public string OrganizationId { get; set; }
public string ProjectId { get; set; }
public string UserId { get; set; }
public string DefaultProjectId { get; set; }
public HashSet<string> Scopes { get; set; }
public DateTime? ExpiresUtc { get; set; }
public string Notes { get; set; }
public bool IsDisabled { get; set; }
public DateTime CreatedUtc { get; set; }
public DateTime UpdatedUtc { get; set; }
}
| using Foundatio.Repositories.Models;
namespace Exceptionless.Web.Models;
public class ViewToken : IIdentity, IHaveDates {
public string Id { get; set; }
public string OrganizationId { get; set; }
public string ProjectId { get; set; }
public string UserId { get; set; }
public string DefaultProjectId { get; set; }
public HashSet<string> Scopes { get; set; }
public DateTime? ExpiresUtc { get; set; }
public string Notes { get; set; }
public bool IsDisabled { get; set; }
public bool IsSuspended { get; set; }
public DateTime CreatedUtc { get; set; }
public DateTime UpdatedUtc { get; set; }
}
|
Fix failing test on Linux | using System;
using Newtonsoft.Json;
using Oocx.ACME.Jose;
using Oocx.ACME.Protocol;
using Xunit;
namespace Oocx.ACME.Tests
{
public class RegistrationTests
{
[Fact]
public void Can_serialize()
{
var request = new NewRegistrationRequest
{
Contact = new[]
{
"mailto:cert-admin@example.com",
"tel:+12025551212"
},
Key = new JsonWebKey
{
Algorithm = "none"
},
Agreement = "https://example.com/acme/terms",
Authorizations = "https://example.com/acme/reg/1/authz",
Certificates = "https://example.com/acme/reg/1/cert",
};
var json = JsonConvert.SerializeObject(request, Formatting.Indented, new JsonSerializerSettings {
DefaultValueHandling = DefaultValueHandling.Ignore
});
Assert.Equal(@"{
""resource"": ""new-reg"",
""jwk"": {
""alg"": ""none""
},
""contact"": [
""mailto:cert-admin@example.com"",
""tel:+12025551212""
],
""agreement"": ""https://example.com/acme/terms"",
""authorizations"": ""https://example.com/acme/reg/1/authz"",
""certificates"": ""https://example.com/acme/reg/1/cert""
}", json);
}
}
}
| using System;
using Newtonsoft.Json;
using Oocx.ACME.Jose;
using Oocx.ACME.Protocol;
using Xunit;
namespace Oocx.ACME.Tests
{
public class RegistrationTests
{
[Fact]
public void Can_serialize()
{
var request = new NewRegistrationRequest
{
Contact = new[]
{
"mailto:cert-admin@example.com",
"tel:+12025551212"
},
Key = new JsonWebKey
{
Algorithm = "none"
},
Agreement = "https://example.com/acme/terms",
Authorizations = "https://example.com/acme/reg/1/authz",
Certificates = "https://example.com/acme/reg/1/cert",
};
var json = JsonConvert.SerializeObject(request, Formatting.Indented, new JsonSerializerSettings {
DefaultValueHandling = DefaultValueHandling.Ignore
});
Assert.Equal(@"{
""resource"": ""new-reg"",
""jwk"": {
""alg"": ""none""
},
""contact"": [
""mailto:cert-admin@example.com"",
""tel:+12025551212""
],
""agreement"": ""https://example.com/acme/terms"",
""authorizations"": ""https://example.com/acme/reg/1/authz"",
""certificates"": ""https://example.com/acme/reg/1/cert""
}".Replace("\r\n", "\n"), json.Replace("\r\n", "\n"));
}
}
}
|
Add Method to Get Device | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Devices.I2c;
namespace AM2320Demo
{
public struct AM2320Data
{
public double Temperature;
public double Humidity;
}
public class AM2320 : IDisposable
{
private I2cDevice sensor;
private const byte AM2320_ADDR = 0x5C;
/// <summary>
/// Initialize
/// </summary>
public async Task InitializeAsync()
{
var settings = new I2cConnectionSettings(AM2320_ADDR);
settings.BusSpeed = I2cBusSpeed.StandardMode;
var controller = await I2cController.GetDefaultAsync();
sensor = controller.GetDevice(settings);
}
public AM2320Data Read()
{
byte[] readBuf = new byte[4];
sensor.WriteRead(new byte[] { 0x03, 0x00, 0x04 }, readBuf);
double rawH = BitConverter.ToInt16(readBuf, 0);
double rawT = BitConverter.ToInt16(readBuf, 2);
AM2320Data data = new AM2320Data
{
Temperature = rawT / 10.0,
Humidity = rawH / 10.0
};
return data;
}
public void Dispose()
{
sensor.Dispose();
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Devices.I2c;
namespace AM2320Demo
{
public struct AM2320Data
{
public double Temperature;
public double Humidity;
}
public class AM2320 : IDisposable
{
private I2cDevice sensor;
private const byte AM2320_ADDR = 0x5C;
/// <summary>
/// Initialize
/// </summary>
public async Task InitializeAsync()
{
var settings = new I2cConnectionSettings(AM2320_ADDR);
settings.BusSpeed = I2cBusSpeed.StandardMode;
var controller = await I2cController.GetDefaultAsync();
sensor = controller.GetDevice(settings);
}
public AM2320Data Read()
{
byte[] readBuf = new byte[4];
sensor.WriteRead(new byte[] { 0x03, 0x00, 0x04 }, readBuf);
double rawH = BitConverter.ToInt16(readBuf, 0);
double rawT = BitConverter.ToInt16(readBuf, 2);
AM2320Data data = new AM2320Data
{
Temperature = rawT / 10.0,
Humidity = rawH / 10.0
};
return data;
}
public I2cDevice GetDevice()
{
return sensor;
}
public void Dispose()
{
sensor.Dispose();
}
}
}
|
Fix for the wrong updateBuildNumber behavior | using System;
using System.Collections.Generic;
using GitVersion.Logging;
using GitVersion.OutputVariables;
namespace GitVersion
{
public abstract class BuildAgentBase : ICurrentBuildAgent
{
protected readonly ILog Log;
protected IEnvironment Environment { get; }
protected BuildAgentBase(IEnvironment environment, ILog log)
{
Log = log;
Environment = environment;
}
protected abstract string EnvironmentVariable { get; }
public abstract string GenerateSetVersionMessage(VersionVariables variables);
public abstract string[] GenerateSetParameterMessage(string name, string value);
public virtual bool CanApplyToCurrentContext() => !string.IsNullOrEmpty(Environment.GetEnvironmentVariable(EnvironmentVariable));
public virtual string GetCurrentBranch(bool usingDynamicRepos) => null;
public virtual bool PreventFetch() => true;
public virtual bool ShouldCleanUpRemotes() => false;
public virtual void WriteIntegration(Action<string> writer, VersionVariables variables, bool updateBuildNumber = true)
{
if (writer == null || !updateBuildNumber)
{
return;
}
writer($"Executing GenerateSetVersionMessage for '{GetType().Name}'.");
writer(GenerateSetVersionMessage(variables));
writer($"Executing GenerateBuildLogOutput for '{GetType().Name}'.");
foreach (var buildParameter in GenerateBuildLogOutput(variables))
{
writer(buildParameter);
}
}
protected IEnumerable<string> GenerateBuildLogOutput(VersionVariables variables)
{
var output = new List<string>();
foreach (var variable in variables)
{
output.AddRange(GenerateSetParameterMessage(variable.Key, variable.Value));
}
return output;
}
}
}
| using System;
using System.Collections.Generic;
using GitVersion.Logging;
using GitVersion.OutputVariables;
namespace GitVersion
{
public abstract class BuildAgentBase : ICurrentBuildAgent
{
protected readonly ILog Log;
protected IEnvironment Environment { get; }
protected BuildAgentBase(IEnvironment environment, ILog log)
{
Log = log;
Environment = environment;
}
protected abstract string EnvironmentVariable { get; }
public abstract string GenerateSetVersionMessage(VersionVariables variables);
public abstract string[] GenerateSetParameterMessage(string name, string value);
public virtual bool CanApplyToCurrentContext() => !string.IsNullOrEmpty(Environment.GetEnvironmentVariable(EnvironmentVariable));
public virtual string GetCurrentBranch(bool usingDynamicRepos) => null;
public virtual bool PreventFetch() => true;
public virtual bool ShouldCleanUpRemotes() => false;
public virtual void WriteIntegration(Action<string> writer, VersionVariables variables, bool updateBuildNumber = true)
{
if (writer == null)
{
return;
}
if (updateBuildNumber)
{
writer($"Executing GenerateSetVersionMessage for '{GetType().Name}'.");
writer(GenerateSetVersionMessage(variables));
}
writer($"Executing GenerateBuildLogOutput for '{GetType().Name}'.");
foreach (var buildParameter in GenerateBuildLogOutput(variables))
{
writer(buildParameter);
}
}
protected IEnumerable<string> GenerateBuildLogOutput(VersionVariables variables)
{
var output = new List<string>();
foreach (var variable in variables)
{
output.AddRange(GenerateSetParameterMessage(variable.Key, variable.Value));
}
return output;
}
}
}
|
Allow word boundary delimiter to be set by user | using System;
namespace FluentConsole.Library
{
/// <summary>
/// Optionial configuration for FluentConsole
/// </summary>
public class FluentConsoleSettings
{
/// <summary>
/// Gets or sets a value indicating how long lines of text should be displayed in the console window.
/// </summary>
public static LineWrapOption LineWrapOption { get; set; } = LineWrapOption.Auto;
/// <summary>
/// Gets or sets the line width used for wrapping long lines of text. Note: This value is ignored
/// unless 'LineWrapOption' is set to 'Manual'. The default width is the value of the
/// 'Console.BufferWidth' property.
/// </summary>
public static int LineWrapWidth { get; set; } = ConsoleWrapper.BufferWidth;
}
} | using System;
namespace FluentConsole.Library
{
/// <summary>
/// Optionial configuration for FluentConsole
/// </summary>
public class FluentConsoleSettings
{
/// <summary>
/// Gets or sets a value indicating how long lines of text should be displayed in the console window.
/// </summary>
public static LineWrapOption LineWrapOption { get; set; } = LineWrapOption.Auto;
/// <summary>
/// Gets or sets the line width used for wrapping long lines of text. Note: This value is ignored
/// unless 'LineWrapOption' is set to 'Manual'. The default width is the value of the
/// 'Console.BufferWidth' property.
/// </summary>
public static int LineWrapWidth { get; set; } = ConsoleWrapper.BufferWidth;
/// <summary>
/// Gets or sets the delimter used when wrapping long lines of text. The default is a space character. Note: This value is ignored if
/// 'LineWrapOption' is set to 'Off'.
/// </summary>
public static char WordDelimiter { get; set; } = ' ';
}
} |
Add comments to public methods | using System;
using System.Diagnostics;
using System.Threading.Tasks;
namespace ConsoleWritePrettyOneDay
{
public static class Spinner
{
private static char[] _chars = new[] { '|', '/', '-', '\\', '|', '/', '-', '\\' };
public static void Wait(Action action, string message = null)
{
Wait(Task.Run(action), message);
}
public static void Wait(Task task, string message = null)
{
WaitAsync(task, message).Wait();
}
public static async Task WaitAsync(Task task, string message = null)
{
int index = 0;
int max = _chars.Length;
if (!string.IsNullOrWhiteSpace(message) && !message.EndsWith(" "))
{
message += " ";
}
var timer = new Stopwatch();
timer.Start();
while (!task.IsCompleted)
{
await Task.Delay(35);
index = ++index % max;
Console.Write($"\r{message}{_chars[index]}");
}
timer.Stop();
Console.WriteLine($"\r{message}[{(timer.ElapsedMilliseconds / 1000m).ToString("0.0##")}s]");
}
}
}
| using System;
using System.Diagnostics;
using System.Threading.Tasks;
namespace ConsoleWritePrettyOneDay
{
public static class Spinner
{
private static char[] _chars = new[] { '|', '/', '-', '\\', '|', '/', '-', '\\' };
/// <summary>
/// Displays a spinner while the provided <paramref name="action"/> is performed.
/// If provided, <paramref name="message"/> will be displayed along with the elapsed time in milliseconds.
/// </summary>
public static void Wait(Action action, string message = null)
{
Wait(Task.Run(action), message);
}
/// <summary>
/// Displays a spinner while the provided <paramref name="task"/> is executed.
/// If provided, <paramref name="message"/> will be displayed along with the elapsed time in milliseconds.
/// </summary>
public static void Wait(Task task, string message = null)
{
WaitAsync(task, message).Wait();
}
/// <summary>
/// Displays a spinner while the provided <paramref name="task"/> is executed.
/// If provided, <paramref name="message"/> will be displayed along with the elapsed time in milliseconds.
/// </summary>
/// <returns></returns>
public static async Task WaitAsync(Task task, string message = null)
{
int index = 0;
int max = _chars.Length;
if (!string.IsNullOrWhiteSpace(message) && !message.EndsWith(" "))
{
message += " ";
}
var timer = new Stopwatch();
timer.Start();
while (!task.IsCompleted)
{
await Task.Delay(35);
index = ++index % max;
Console.Write($"\r{message}{_chars[index]}");
}
timer.Stop();
Console.WriteLine($"\r{message}[{(timer.ElapsedMilliseconds / 1000m).ToString("0.0##")}s]");
}
}
}
|
Fix dllimport inconsistency and possibly being broken on windows. | //
// Copyright (c) 2017-2019 the rbfx project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
namespace Urho3DNet
{
[System.Security.SuppressUnmanagedCodeSecurity]
public partial class Urho3D
{
[DllImport("libUrho3D", EntryPoint="Urho3D_ParseArguments")]
public static extern void ParseArguments(int argc,
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr)]string[] argv);
}
}
| //
// Copyright (c) 2017-2019 the rbfx project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
namespace Urho3DNet
{
[System.Security.SuppressUnmanagedCodeSecurity]
public partial class Urho3D
{
[DllImport("Urho3D", EntryPoint="Urho3D_ParseArguments")]
public static extern void ParseArguments(int argc,
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr)]string[] argv);
}
}
|
Add ResolveByName attribute to TargetControl property | using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Xaml.Interactivity;
namespace Avalonia.Xaml.Interactions.Custom;
/// <summary>
/// A behavior that allows to show control on double tapped event.
/// </summary>
public class ShowOnDoubleTappedBehavior : Behavior<Control>
{
/// <summary>
/// Identifies the <seealso cref="TargetControl"/> avalonia property.
/// </summary>
public static readonly StyledProperty<Control?> TargetControlProperty =
AvaloniaProperty.Register<ShowOnDoubleTappedBehavior, Control?>(nameof(TargetControl));
/// <summary>
/// Gets or sets the target control. This is a avalonia property.
/// </summary>
public Control? TargetControl
{
get => GetValue(TargetControlProperty);
set => SetValue(TargetControlProperty, value);
}
/// <inheritdoc />
protected override void OnAttachedToVisualTree()
{
AssociatedObject?.AddHandler(Gestures.DoubleTappedEvent, AssociatedObject_DoubleTapped, RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
}
/// <inheritdoc />
protected override void OnDetachedFromVisualTree()
{
AssociatedObject?.RemoveHandler(Gestures.DoubleTappedEvent, AssociatedObject_DoubleTapped);
}
private void AssociatedObject_DoubleTapped(object? sender, RoutedEventArgs e)
{
if (TargetControl is { IsVisible: false })
{
TargetControl.IsVisible = true;
TargetControl.Focus();
}
}
}
| using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Xaml.Interactivity;
namespace Avalonia.Xaml.Interactions.Custom;
/// <summary>
/// A behavior that allows to show control on double tapped event.
/// </summary>
public class ShowOnDoubleTappedBehavior : Behavior<Control>
{
/// <summary>
/// Identifies the <seealso cref="TargetControl"/> avalonia property.
/// </summary>
public static readonly StyledProperty<Control?> TargetControlProperty =
AvaloniaProperty.Register<ShowOnDoubleTappedBehavior, Control?>(nameof(TargetControl));
/// <summary>
/// Gets or sets the target control. This is a avalonia property.
/// </summary>
[ResolveByName]
public Control? TargetControl
{
get => GetValue(TargetControlProperty);
set => SetValue(TargetControlProperty, value);
}
/// <inheritdoc />
protected override void OnAttachedToVisualTree()
{
AssociatedObject?.AddHandler(Gestures.DoubleTappedEvent, AssociatedObject_DoubleTapped, RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
}
/// <inheritdoc />
protected override void OnDetachedFromVisualTree()
{
AssociatedObject?.RemoveHandler(Gestures.DoubleTappedEvent, AssociatedObject_DoubleTapped);
}
private void AssociatedObject_DoubleTapped(object? sender, RoutedEventArgs e)
{
if (TargetControl is { IsVisible: false })
{
TargetControl.IsVisible = true;
TargetControl.Focus();
}
}
}
|
Fix ring glow lookup being incorrect | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces
{
public class GlowPiece : Container
{
public GlowPiece()
{
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
RelativeSizeAxes = Axes.Both;
}
[BackgroundDependencyLoader]
private void load(TextureStore textures)
{
Child = new Sprite
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Texture = textures.Get("ring-glow"),
Blending = BlendingParameters.Additive,
Alpha = 0.5f
};
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces
{
public class GlowPiece : Container
{
public GlowPiece()
{
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
RelativeSizeAxes = Axes.Both;
}
[BackgroundDependencyLoader]
private void load(TextureStore textures)
{
Child = new Sprite
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Texture = textures.Get("Gameplay/osu/ring-glow"),
Blending = BlendingParameters.Additive,
Alpha = 0.5f
};
}
}
}
|
Change number of cells. ( 9 => 7 ) | using System;
namespace XamarinLifeGameXAML.Logic
{
public class CellUtils
{
public static int GetIndex(Tuple<int, int> point)
{
return GetIndex(point.Item1, point.Item2);
}
public static int GetIndex(int x, int y)
{
return (y + x * CellSize);
}
public static Tuple<int, int> GetPoint(int index)
{
var y = index % CellSize;
var x = (index - y) / CellSize;
return Tuple.Create(x, y);
}
public static int CellSize => 9;
public static int ArraySize => CellSize * CellSize;
}
} | using System;
namespace XamarinLifeGameXAML.Logic
{
public class CellUtils
{
public static int GetIndex(Tuple<int, int> point)
{
return GetIndex(point.Item1, point.Item2);
}
public static int GetIndex(int x, int y)
{
return (y + x * CellSize);
}
public static Tuple<int, int> GetPoint(int index)
{
var y = index % CellSize;
var x = (index - y) / CellSize;
return Tuple.Create(x, y);
}
public static int CellSize => 7;
public static int ArraySize => CellSize * CellSize;
}
} |
Return added disposable from `DisposeWith` | using System;
using System.Collections.Generic;
using System.Reactive.Disposables;
using System.Text;
namespace SolidworksAddinFramework
{
public static class DisposableExtensions
{
public static IDisposable ToCompositeDisposable(this IEnumerable<IDisposable> d)
{
return new CompositeDisposable(d);
}
public static void DisposeWith(this IDisposable disposable, CompositeDisposable container)
{
container.Add(disposable);
}
}
}
| using System;
using System.Collections.Generic;
using System.Reactive.Disposables;
using System.Text;
namespace SolidworksAddinFramework
{
public static class DisposableExtensions
{
public static IDisposable ToCompositeDisposable(this IEnumerable<IDisposable> d)
{
return new CompositeDisposable(d);
}
public static T DisposeWith<T>(this T disposable, CompositeDisposable container)
where T : IDisposable
{
container.Add(disposable);
return disposable;
}
}
}
|
Introduce variables to avoid multiple type casting | using System.Collections.Generic;
namespace Ploeh.AutoFixture.Xunit
{
internal class CustomizeAttributeComparer : Comparer<CustomizeAttribute>
{
public override int Compare(CustomizeAttribute x, CustomizeAttribute y)
{
if (x is FrozenAttribute && !(y is FrozenAttribute))
{
return 1;
}
if (y is FrozenAttribute && !(x is FrozenAttribute))
{
return -1;
}
return 0;
}
}
} | using System.Collections.Generic;
namespace Ploeh.AutoFixture.Xunit
{
internal class CustomizeAttributeComparer : Comparer<CustomizeAttribute>
{
public override int Compare(CustomizeAttribute x, CustomizeAttribute y)
{
var xfrozen = x is FrozenAttribute;
var yfrozen = y is FrozenAttribute;
if (xfrozen && !yfrozen)
{
return 1;
}
if (yfrozen && !xfrozen)
{
return -1;
}
return 0;
}
}
} |
Fix project name in assembly info | 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("TOTD.Mailer.Html")]
[assembly: AssemblyDescription("")]
[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)]
| 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("TOTD.Mailer.Templates")]
[assembly: AssemblyDescription("")]
[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)]
|
Add test skipping for 0.5.2 | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Consul.Test
{
[TestClass]
public class CoordinateTest
{
[TestMethod]
public void TestCoordinate_Datacenters()
{
var client = new Client();
var datacenters = client.Coordinate.Datacenters();
Assert.IsNotNull(datacenters.Response);
Assert.IsTrue(datacenters.Response.Length > 0);
}
[TestMethod]
public void TestCoordinate_Nodes()
{
var client = new Client();
var nodes = client.Coordinate.Nodes();
Assert.IsNotNull(nodes.Response);
Assert.IsTrue(nodes.Response.Length > 0);
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Consul.Test
{
[TestClass]
public class CoordinateTest
{
[TestMethod]
public void TestCoordinate_Datacenters()
{
var client = new Client();
var info = client.Agent.Self();
if (!info.Response.ContainsKey("Coord"))
{
Assert.Inconclusive("This version of Consul does not support the coordinate API");
}
var datacenters = client.Coordinate.Datacenters();
Assert.IsNotNull(datacenters.Response);
Assert.IsTrue(datacenters.Response.Length > 0);
}
[TestMethod]
public void TestCoordinate_Nodes()
{
var client = new Client();
var info = client.Agent.Self();
if (!info.Response.ContainsKey("Coord"))
{
Assert.Inconclusive("This version of Consul does not support the coordinate API");
}
var nodes = client.Coordinate.Nodes();
Assert.IsNotNull(nodes.Response);
Assert.IsTrue(nodes.Response.Length > 0);
}
}
}
|
Implement the read/write xml data | // XMLDataSaver.cs
// <copyright file="XMLDataSaver.cs"> This code is protected under the MIT License. </copyright>
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
namespace Todo_List
{
/// <summary>
/// A static class for reading and writing to XML files.
/// </summary>
public static class XMLDataSaver
{
/// <summary>
/// Reads the xml file of information from the save location.
/// </summary>
public static void ReadXMLFile()
{
}
/// <summary>
/// Saves the xml file of information to the save location.
/// </summary>
public static void SaveXMLFile()
{
}
}
}
| // XMLDataSaver.cs
// <copyright file="XMLDataSaver.cs"> This code is protected under the MIT License. </copyright>
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
namespace Todo_List
{
/// <summary>
/// A static class for reading and writing to XML files.
/// </summary>
public static class XMLDataSaver
{
/// <summary>
/// Reads the xml file of information from the save location.
/// </summary>
public static void ReadXMLFile()
{
try
{
using (TextReader tr = new StreamReader("TodoListData.xml"))
{
XmlSerializer xs = new XmlSerializer(typeof(List<Note>));
NoteSorter.Notes = (List<Note>)xs.Deserialize(tr);
}
}
catch (FileNotFoundException)
{
// File not found so don't read anything
}
}
/// <summary>
/// Saves the xml file of information to the save location.
/// </summary>
public static void SaveXMLFile()
{
using (TextWriter tw = new StreamWriter("TodoListData.xml"))
{
XmlSerializer xs = new XmlSerializer(typeof(List<Note>));
xs.Serialize(tw, NoteSorter.Notes);
}
}
}
}
|
Add bing map keys with fake default | namespace TestAppUWP.Samples.Map
{
public class MapServiceSettings
{
public static string Token="Pippo";
}
} | namespace TestAppUWP.Samples.Map
{
public class MapServiceSettings
{
public static string Token = string.Empty;
}
} |
Remove obsolete Linux build architectures on 2019.2+ | using UnityEditor;
namespace SuperSystems.UnityBuild
{
[System.Serializable]
public class BuildLinux : BuildPlatform
{
#region Constants
private const string _name = "Linux";
private const string _dataDirNameFormat = "{0}_Data";
private const BuildTargetGroup _targetGroup = BuildTargetGroup.Standalone;
#endregion
public BuildLinux()
{
enabled = false;
Init();
}
public override void Init()
{
platformName = _name;
dataDirNameFormat = _dataDirNameFormat;
targetGroup = _targetGroup;
if (architectures == null || architectures.Length == 0)
{
architectures = new BuildArchitecture[] {
new BuildArchitecture(BuildTarget.StandaloneLinuxUniversal, "Linux Universal", true, "{0}"),
new BuildArchitecture(BuildTarget.StandaloneLinux, "Linux x86", false, "{0}.x86"),
new BuildArchitecture(BuildTarget.StandaloneLinux64, "Linux x64", false, "{0}.x86_64")
};
#if UNITY_2018_3_OR_NEWER
architectures[0].enabled = false;
architectures[2].enabled = true;
#endif
}
}
}
} | using UnityEditor;
namespace SuperSystems.UnityBuild
{
[System.Serializable]
public class BuildLinux : BuildPlatform
{
#region Constants
private const string _name = "Linux";
private const string _dataDirNameFormat = "{0}_Data";
private const BuildTargetGroup _targetGroup = BuildTargetGroup.Standalone;
#endregion
public BuildLinux()
{
enabled = false;
Init();
}
public override void Init()
{
platformName = _name;
dataDirNameFormat = _dataDirNameFormat;
targetGroup = _targetGroup;
if (architectures == null || architectures.Length == 0)
{
architectures = new BuildArchitecture[] {
new BuildArchitecture(BuildTarget.StandaloneLinux64, "Linux x64", false, "{0}.x86_64"),
#if !UNITY_2019_2_OR_NEWER
new BuildArchitecture(BuildTarget.StandaloneLinuxUniversal, "Linux Universal", true, "{0}"),
new BuildArchitecture(BuildTarget.StandaloneLinux, "Linux x86", false, "{0}.x86"),
#endif
};
#if UNITY_2018_3_OR_NEWER
architectures[0].enabled = true;
#endif
#if UNITY_2018_3_OR_NEWER && !UNITY_2019_2_OR_NEWER
architectures[1].enabled = false;
#endif
}
}
}
}
|
Use CombineLatest instead of Zip | #region Usings
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
using ReactiveUI;
#endregion
namespace UI.WPF.Modules.Installation.ViewModels.Installation
{
public class InstallationItemParent : InstallationItem
{
public InstallationItemParent(string title, IEnumerable<InstallationItem> children)
{
Title = title;
Children = children.ToList();
Children.Select(x => x.ProgressObservable).Zip().Select(list => list.Average()).BindTo(this, x => x.Progress);
Children.Select(x => x.IndeterminateObservable).Zip().Select(list => list.All(b => b)).BindTo(this, x => x.Indeterminate);
OperationMessage = null;
CancellationTokenSource = new CancellationTokenSource();
CancellationTokenSource.Token.Register(() =>
{
foreach (var installationItem in Children.Where(installationItem => !installationItem.CancellationTokenSource.IsCancellationRequested)
)
{
installationItem.CancellationTokenSource.Cancel();
}
});
}
public IEnumerable<InstallationItem> Children { get; private set; }
#region Overrides of InstallationItem
public override Task Install()
{
return Task.WhenAll(Children.Select(x => x.Install()));
}
#endregion
}
}
| #region Usings
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
using ReactiveUI;
#endregion
namespace UI.WPF.Modules.Installation.ViewModels.Installation
{
public class InstallationItemParent : InstallationItem
{
public InstallationItemParent(string title, IEnumerable<InstallationItem> children)
{
Title = title;
Children = children.ToList();
Children.Select(x => x.ProgressObservable).CombineLatest().Select(list => list.Average()).BindTo(this, x => x.Progress);
Children.Select(x => x.IndeterminateObservable).CombineLatest().Select(list => list.All(b => b)).BindTo(this, x => x.Indeterminate);
OperationMessage = null;
CancellationTokenSource = new CancellationTokenSource();
CancellationTokenSource.Token.Register(() =>
{
foreach (var installationItem in Children.Where(installationItem => !installationItem.CancellationTokenSource.IsCancellationRequested)
)
{
installationItem.CancellationTokenSource.Cancel();
}
});
}
public IEnumerable<InstallationItem> Children { get; private set; }
#region Overrides of InstallationItem
public override Task Install()
{
return Task.WhenAll(Children.Select(x => x.Install()));
}
#endregion
}
}
|
Adjust tests to MySqlConnector 1.4.0-beta.4. | using Microsoft.EntityFrameworkCore;
using Pomelo.EntityFrameworkCore.MySql.FunctionalTests.TestUtilities;
using Pomelo.EntityFrameworkCore.MySql.Tests;
using Xunit;
namespace Pomelo.EntityFrameworkCore.MySql.FunctionalTests
{
public class TwoDatabasesMySqlTest : TwoDatabasesTestBase, IClassFixture<MySqlFixture>
{
public TwoDatabasesMySqlTest(MySqlFixture fixture)
: base(fixture)
{
}
protected new MySqlFixture Fixture
=> (MySqlFixture)base.Fixture;
protected override DbContextOptionsBuilder CreateTestOptions(
DbContextOptionsBuilder optionsBuilder, bool withConnectionString = false)
=> withConnectionString
? optionsBuilder.UseMySql(DummyConnectionString, AppConfig.ServerVersion)
: optionsBuilder.UseMySql(AppConfig.ServerVersion);
protected override TwoDatabasesWithDataContext CreateBackingContext(string databaseName)
=> new TwoDatabasesWithDataContext(Fixture.CreateOptions(MySqlTestStore.Create(databaseName)));
protected override string DummyConnectionString { get; } = "Server=localhost;Database=DoesNotExist;AllowUserVariables=True;Use Affected Rows=False";
}
}
| using Microsoft.EntityFrameworkCore;
using Pomelo.EntityFrameworkCore.MySql.FunctionalTests.TestUtilities;
using Pomelo.EntityFrameworkCore.MySql.Tests;
using Xunit;
namespace Pomelo.EntityFrameworkCore.MySql.FunctionalTests
{
public class TwoDatabasesMySqlTest : TwoDatabasesTestBase, IClassFixture<MySqlFixture>
{
public TwoDatabasesMySqlTest(MySqlFixture fixture)
: base(fixture)
{
}
protected new MySqlFixture Fixture
=> (MySqlFixture)base.Fixture;
protected override DbContextOptionsBuilder CreateTestOptions(
DbContextOptionsBuilder optionsBuilder, bool withConnectionString = false)
=> withConnectionString
? optionsBuilder.UseMySql(DummyConnectionString, AppConfig.ServerVersion)
: optionsBuilder.UseMySql(AppConfig.ServerVersion);
protected override TwoDatabasesWithDataContext CreateBackingContext(string databaseName)
=> new TwoDatabasesWithDataContext(Fixture.CreateOptions(MySqlTestStore.Create(databaseName)));
protected override string DummyConnectionString { get; } = "Server=localhost;Database=DoesNotExist;Allow User Variables=True;Use Affected Rows=False";
}
}
|
Fix cross plattform issue with drive info method | using System;
using System.IO;
using Arkivverket.Arkade.Core.Base;
namespace Arkivverket.Arkade.Core.Util
{
public static class SystemInfo
{
public static long GetAvailableDiskSpaceInBytes()
{
return GetAvailableDiskSpaceInBytes(ArkadeProcessingArea.RootDirectory.FullName);
}
public static long GetTotalDiskSpaceInBytes()
{
return GetTotalDiskSpaceInBytes(ArkadeProcessingArea.RootDirectory.FullName);
}
public static long GetAvailableDiskSpaceInBytes(string directory)
{
return GetDirectoryDriveInfo(directory).AvailableFreeSpace;
}
public static long GetTotalDiskSpaceInBytes(string directory)
{
return GetDirectoryDriveInfo(directory).TotalSize;
}
public static string GetDotNetClrVersion()
{
return Environment.Version.ToString();
}
private static DriveInfo GetDirectoryDriveInfo(string directory)
{
string fullyQualifiedPath = Path.GetFullPath(directory);
// TODO: Use below line when on .NET Standard 2.1 (reducing IO)
//string fullyQualifiedPath = Path.IsPathFullyQualified(directory) ? directory : Path.GetFullPath(directory);
string directoryPathRoot = Path.GetPathRoot(fullyQualifiedPath);
return new DriveInfo(directoryPathRoot);
}
}
}
| using System;
using System.IO;
using System.Linq;
using Arkivverket.Arkade.Core.Base;
namespace Arkivverket.Arkade.Core.Util
{
public static class SystemInfo
{
public static long GetAvailableDiskSpaceInBytes()
{
return GetAvailableDiskSpaceInBytes(ArkadeProcessingArea.RootDirectory.FullName);
}
public static long GetTotalDiskSpaceInBytes()
{
return GetTotalDiskSpaceInBytes(ArkadeProcessingArea.RootDirectory.FullName);
}
public static long GetAvailableDiskSpaceInBytes(string directory)
{
return GetDirectoryDriveInfo(directory).AvailableFreeSpace;
}
public static long GetTotalDiskSpaceInBytes(string directory)
{
return GetDirectoryDriveInfo(directory).TotalSize;
}
public static string GetDotNetClrVersion()
{
return Environment.Version.ToString();
}
private static DriveInfo GetDirectoryDriveInfo(string directory)
{
string fullyQualifiedDirectoryPath = // TODO: Uncomment below line when on .NET Standard 2.1 (reducing IO)
/*Path.IsPathFullyQualified(directory) ? directory :*/ Path.GetFullPath(directory);
DriveInfo directoryDrive = DriveInfo.GetDrives()
.OrderByDescending(drive => drive.Name.Length)
.First(drive => fullyQualifiedDirectoryPath.StartsWith(drive.Name));
return directoryDrive;
}
}
}
|
Allow all characters for password fields | namespace SFA.DAS.EmployerUsers.Web.Models
{
public class RegisterViewModel :ViewModelBase
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
public bool HasAcceptedTermsAndConditions { get; set; }
public string ReturnUrl { get; set; }
public string GeneralError => GetErrorMessage("");
public string FirstNameError => GetErrorMessage(nameof(FirstName));
public string LastNameError => GetErrorMessage(nameof(LastName));
public string EmailError => GetErrorMessage(nameof(Email));
public string PasswordError => GetErrorMessage(nameof(Password));
public string ConfirmPasswordError => GetErrorMessage(nameof(ConfirmPassword));
public string HasAcceptedTermsAndConditionsError => GetErrorMessage(nameof(HasAcceptedTermsAndConditions));
}
} | using System.Web.Mvc;
namespace SFA.DAS.EmployerUsers.Web.Models
{
public class RegisterViewModel :ViewModelBase
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
[AllowHtml]
public string Password { get; set; }
[AllowHtml]
public string ConfirmPassword { get; set; }
public bool HasAcceptedTermsAndConditions { get; set; }
public string ReturnUrl { get; set; }
public string GeneralError => GetErrorMessage("");
public string FirstNameError => GetErrorMessage(nameof(FirstName));
public string LastNameError => GetErrorMessage(nameof(LastName));
public string EmailError => GetErrorMessage(nameof(Email));
public string PasswordError => GetErrorMessage(nameof(Password));
public string ConfirmPasswordError => GetErrorMessage(nameof(ConfirmPassword));
public string HasAcceptedTermsAndConditionsError => GetErrorMessage(nameof(HasAcceptedTermsAndConditions));
}
} |
Load levels with SceneManager instead of Application for Unity 5.3+ | using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class LoadTest : MonoBehaviour
{
public void SignInButtonClicked()
{
GameJolt.UI.Manager.Instance.ShowSignIn((bool success) => {
if (success)
{
Debug.Log("Logged In");
}
else
{
Debug.Log("Dismissed");
}
});
}
public void IsSignedInButtonClicked() {
bool isSignedIn = GameJolt.API.Manager.Instance.CurrentUser != null;
if (isSignedIn) {
Debug.Log("Signed In");
}
else {
Debug.Log("Not Signed In");
}
}
public void LoadSceneButtonClicked(string sceneName) {
Debug.Log("Loading Scene " + sceneName);
Application.LoadLevel(sceneName);
}
}
| using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class LoadTest : MonoBehaviour
{
public void SignInButtonClicked()
{
GameJolt.UI.Manager.Instance.ShowSignIn((bool success) => {
if (success)
{
Debug.Log("Logged In");
}
else
{
Debug.Log("Dismissed");
}
});
}
public void IsSignedInButtonClicked() {
bool isSignedIn = GameJolt.API.Manager.Instance.CurrentUser != null;
if (isSignedIn) {
Debug.Log("Signed In");
}
else {
Debug.Log("Not Signed In");
}
}
public void LoadSceneButtonClicked(string sceneName) {
Debug.Log("Loading Scene " + sceneName);
#if UNITY_5_0 || UNITY_5_1 || UNITY_5_2
Application.LoadLevel(sceneName);
#else
UnityEngine.SceneManagement.SceneManager.LoadScene(sceneName);
#endif
}
}
|
Fix namespace so that external access wrapper type can be accessed from UT. | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.Serialization;
using Microsoft.CodeAnalysis.Remote;
namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting
{
[DataContract]
internal readonly struct UnitTestingPinnedSolutionInfoWrapper
{
[DataMember(Order = 0)]
internal readonly PinnedSolutionInfo UnderlyingObject;
public UnitTestingPinnedSolutionInfoWrapper(PinnedSolutionInfo underlyingObject)
=> UnderlyingObject = underlyingObject;
public static implicit operator UnitTestingPinnedSolutionInfoWrapper(PinnedSolutionInfo info)
=> new(info);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.Serialization;
using Microsoft.CodeAnalysis.Remote;
namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api
{
[DataContract]
internal readonly struct UnitTestingPinnedSolutionInfoWrapper
{
[DataMember(Order = 0)]
internal readonly PinnedSolutionInfo UnderlyingObject;
public UnitTestingPinnedSolutionInfoWrapper(PinnedSolutionInfo underlyingObject)
=> UnderlyingObject = underlyingObject;
public static implicit operator UnitTestingPinnedSolutionInfoWrapper(PinnedSolutionInfo info)
=> new(info);
}
}
|
Add email validity check to change email command | using System.Threading.Tasks;
using SFA.DAS.EmployerUsers.Application.Validation;
namespace SFA.DAS.EmployerUsers.Application.Commands.RequestChangeEmail
{
public class RequestChangeEmailCommandValidator : IValidator<RequestChangeEmailCommand>
{
public Task<ValidationResult> ValidateAsync(RequestChangeEmailCommand item)
{
var result = new ValidationResult();
if (string.IsNullOrEmpty(item.UserId))
{
result.AddError(nameof(item.UserId));
}
if (string.IsNullOrEmpty(item.NewEmailAddress))
{
result.AddError(nameof(item.NewEmailAddress), "Enter a valid email address");
}
if (string.IsNullOrEmpty(item.ConfirmEmailAddress))
{
result.AddError(nameof(item.ConfirmEmailAddress), "Re-type email address");
}
if (!result.IsValid())
{
return Task.FromResult(result);
}
if (!item.NewEmailAddress.Equals(item.ConfirmEmailAddress, System.StringComparison.CurrentCultureIgnoreCase))
{
result.AddError(nameof(item.ConfirmEmailAddress), "Emails don't match");
}
return Task.FromResult(result);
}
}
} | using System.Threading.Tasks;
using SFA.DAS.EmployerUsers.Application.Validation;
namespace SFA.DAS.EmployerUsers.Application.Commands.RequestChangeEmail
{
public class RequestChangeEmailCommandValidator : BaseValidator, IValidator<RequestChangeEmailCommand>
{
public Task<ValidationResult> ValidateAsync(RequestChangeEmailCommand item)
{
var result = new ValidationResult();
if (string.IsNullOrEmpty(item.UserId))
{
result.AddError(nameof(item.UserId));
}
if (string.IsNullOrEmpty(item.NewEmailAddress) || !IsEmailValid(item.NewEmailAddress))
{
result.AddError(nameof(item.NewEmailAddress), "Enter a valid email address");
}
if (string.IsNullOrEmpty(item.ConfirmEmailAddress) || !IsEmailValid(item.ConfirmEmailAddress))
{
result.AddError(nameof(item.ConfirmEmailAddress), "Re-type email address");
}
if (!result.IsValid())
{
return Task.FromResult(result);
}
if (!item.NewEmailAddress.Equals(item.ConfirmEmailAddress, System.StringComparison.CurrentCultureIgnoreCase))
{
result.AddError(nameof(item.ConfirmEmailAddress), "Emails don't match");
}
return Task.FromResult(result);
}
}
} |
Use acknowledgement callback to indicate whether createTopic event was successful | using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Quobject.SocketIoClientDotNet.Client;
namespace KafkaHttp.Net
{
public interface IKafkaProducer
{
Task CreateTopic(string name);
void Publish(params Message<string>[] payload);
}
public class KafkaProducer : IKafkaProducer
{
private readonly Socket _socket;
private readonly Json _json;
public KafkaProducer(Socket socket)
{
_socket = socket;
_json = new Json();
}
public Task CreateTopic(string name)
{
Trace.TraceInformation("Creating topic...");
var waitHandle = new AutoResetEvent(false);
_socket.On("topicCreated", o => waitHandle.Set());
_socket.Emit("createTopic", name);
return waitHandle.ToTask($"Failed to create topic {name}.", $"Created topic {name}.");
}
public void Publish(params Message<string>[] payload)
{
_socket.Emit("publish", _json.Serialize(payload));
}
}
}
| using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Quobject.SocketIoClientDotNet.Client;
namespace KafkaHttp.Net
{
public interface IKafkaProducer
{
Task CreateTopic(string name);
void Publish(params Message<string>[] payload);
}
public class KafkaProducer : IKafkaProducer
{
private readonly Socket _socket;
private readonly Json _json;
public KafkaProducer(Socket socket)
{
_socket = socket;
_json = new Json();
}
public Task CreateTopic(string name)
{
Trace.TraceInformation($"Creating topic {name}...");
var tcs = new TaskCompletionSource<object>();
_socket.Emit(
"createTopic",
(e, d) =>
{
if (e != null)
{
Trace.TraceError(e.ToString());
tcs.SetException(new Exception(e.ToString()));
return;
}
Trace.TraceInformation($"Topic {name} created.");
tcs.SetResult(true);
}
, name);
return tcs.Task;
}
public void Publish(params Message<string>[] payload)
{
_socket.Emit("publish", _json.Serialize(payload));
}
}
}
|
Fix typo in VersionNavigation class name | // 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 Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace osu.Game.Online.API.Requests.Responses
{
public class APIChangelogBuild : IEquatable<APIChangelogBuild>
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("version")]
public string Version { get; set; }
[JsonProperty("display_version")]
public string DisplayVersion { get; set; }
[JsonProperty("users")]
public long Users { get; set; }
[JsonProperty("created_at")]
public DateTimeOffset CreatedAt { get; set; }
[JsonProperty("update_stream")]
public APIUpdateStream UpdateStream { get; set; }
[JsonProperty("changelog_entries")]
public List<APIChangelogEntry> ChangelogEntries { get; set; }
[JsonProperty("versions")]
public VersionNatigation Versions { get; set; }
public class VersionNatigation
{
[JsonProperty("next")]
public APIChangelogBuild Next { get; set; }
[JsonProperty("previous")]
public APIChangelogBuild Previous { get; set; }
}
public bool Equals(APIChangelogBuild other) => Id == other?.Id;
public override string ToString() => $"{UpdateStream.DisplayName} {DisplayVersion}";
}
}
| // 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 Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace osu.Game.Online.API.Requests.Responses
{
public class APIChangelogBuild : IEquatable<APIChangelogBuild>
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("version")]
public string Version { get; set; }
[JsonProperty("display_version")]
public string DisplayVersion { get; set; }
[JsonProperty("users")]
public long Users { get; set; }
[JsonProperty("created_at")]
public DateTimeOffset CreatedAt { get; set; }
[JsonProperty("update_stream")]
public APIUpdateStream UpdateStream { get; set; }
[JsonProperty("changelog_entries")]
public List<APIChangelogEntry> ChangelogEntries { get; set; }
[JsonProperty("versions")]
public VersionNavigation Versions { get; set; }
public class VersionNavigation
{
[JsonProperty("next")]
public APIChangelogBuild Next { get; set; }
[JsonProperty("previous")]
public APIChangelogBuild Previous { get; set; }
}
public bool Equals(APIChangelogBuild other) => Id == other?.Id;
public override string ToString() => $"{UpdateStream.DisplayName} {DisplayVersion}";
}
}
|
Allow using `ToLocalisableString` without a format string | // 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;
#nullable enable
namespace osu.Framework.Localisation
{
public static class LocalisableStringExtensions
{
/// <summary>
/// Returns a <see cref="LocalisableFormattableString"/> formatting the given <paramref name="value"/> with the specified <paramref name="format"/>.
/// </summary>
/// <param name="value">The value to format.</param>
/// <param name="format">The format string.</param>
public static LocalisableFormattableString ToLocalisableString(this IFormattable value, string? format)
=> new LocalisableFormattableString(value, format);
}
}
| // 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;
#nullable enable
namespace osu.Framework.Localisation
{
public static class LocalisableStringExtensions
{
/// <summary>
/// Returns a <see cref="LocalisableFormattableString"/> formatting the given <paramref name="value"/> to a string, along with an optional <paramref name="format"/> string.
/// </summary>
/// <param name="value">The value to format.</param>
/// <param name="format">The format string.</param>
public static LocalisableFormattableString ToLocalisableString(this IFormattable value, string? format = null)
=> new LocalisableFormattableString(value, format);
}
}
|
Add EF extensions for identity columns and index column order | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.ModelConfiguration.Configuration;
using System.Linq;
namespace TOTD.EntityFramework
{
public static class ConfigurationExtensions
{
public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration configuration)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute()));
}
public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration configuration, string name)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name)));
}
public static PrimitivePropertyConfiguration HasUniqueIndex(this PrimitivePropertyConfiguration configuration)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute()
{
IsUnique = true
}));
}
public static PrimitivePropertyConfiguration HasUniqueIndex(this PrimitivePropertyConfiguration configuration, string name)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name)
{
IsUnique = true
}));
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.ModelConfiguration.Configuration;
using System.Linq;
namespace TOTD.EntityFramework
{
public static class ConfigurationExtensions
{
public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration configuration)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute()));
}
public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration configuration, string name)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name)));
}
public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration configuration, string name, int order)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name, order)));
}
public static PrimitivePropertyConfiguration HasUniqueIndex(this PrimitivePropertyConfiguration configuration)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute()
{
IsUnique = true
}));
}
public static PrimitivePropertyConfiguration HasUniqueIndex(this PrimitivePropertyConfiguration configuration, string name)
{
return configuration.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute(name)
{
IsUnique = true
}));
}
public static PrimitivePropertyConfiguration IsIdentity(this PrimitivePropertyConfiguration configuration)
{
return configuration.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}
}
|
Fix changelog header staying dimmed after build show | // 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.Online.API.Requests.Responses;
namespace osu.Game.Overlays.Changelog
{
public class ChangelogUpdateStreamControl : OverlayStreamControl<APIUpdateStream>
{
protected override OverlayStreamItem<APIUpdateStream> CreateStreamItem(APIUpdateStream value) => new ChangelogUpdateStreamItem(value);
protected override void LoadComplete()
{
// suppress base logic of immediately selecting first item if one exists
// (we always want to start with no stream selected).
}
}
}
| // 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.Online.API.Requests.Responses;
namespace osu.Game.Overlays.Changelog
{
public class ChangelogUpdateStreamControl : OverlayStreamControl<APIUpdateStream>
{
public ChangelogUpdateStreamControl()
{
SelectFirstTabByDefault = false;
}
protected override OverlayStreamItem<APIUpdateStream> CreateStreamItem(APIUpdateStream value) => new ChangelogUpdateStreamItem(value);
}
}
|
Extend the extension methods test case again | using System;
using System.Collections.Generic;
using System.Linq;
public class Herp
{
public Herp(int X)
{
this.X = X;
}
public int X { get; private set; }
}
public static class HerpExtensions
{
public static void PrintX(this Herp Value)
{
Console.WriteLine(Value.X);
}
}
public static class Program
{
public static void Main()
{
var herp = new Herp(20);
herp.PrintX();
var items = new List<int>();
items.Add(10);
items.Add(20);
items.Add(30);
// Note that ToArray<int> is actually a generic extension method:
// Enumerable.ToArray<T>.
foreach (var x in items.ToArray<int>())
{
Console.WriteLine(x);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
public class Herp
{
public Herp(int X)
{
this.X = X;
}
public int X { get; private set; }
}
public static class HerpExtensions
{
public static void PrintX(this Herp Value)
{
Console.WriteLine(Value.X);
}
}
public static class Program
{
public static void Main()
{
var herp = new Herp(20);
herp.PrintX();
var items = new List<int>();
items.Add(10);
items.Add(20);
items.Add(30);
// Note that ToArray<int> is actually a generic extension method:
// Enumerable.ToArray<T>.
foreach (var x in items.ToArray<int>())
{
Console.WriteLine(x);
}
foreach (var x in items.Concat<int>(new int[] { 40, 50 }))
{
Console.WriteLine(x);
}
}
}
|
Move BindValueChanged subscriptions to LoadComplete | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.Online.Multiplayer;
using osu.Game.Screens.OnlinePlay.Match.Components;
namespace osu.Game.Screens.OnlinePlay.Multiplayer
{
public class CreateMultiplayerMatchButton : PurpleTriangleButton
{
private IBindable<bool> isConnected;
private IBindable<bool> operationInProgress;
[Resolved]
private StatefulMultiplayerClient multiplayerClient { get; set; }
[Resolved]
private OngoingOperationTracker ongoingOperationTracker { get; set; }
[BackgroundDependencyLoader]
private void load()
{
Triangles.TriangleScale = 1.5f;
Text = "Create room";
isConnected = multiplayerClient.IsConnected.GetBoundCopy();
isConnected.BindValueChanged(_ => updateState());
operationInProgress = ongoingOperationTracker.InProgress.GetBoundCopy();
operationInProgress.BindValueChanged(_ => updateState(), true);
}
private void updateState() => Enabled.Value = isConnected.Value && !operationInProgress.Value;
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.Online.Multiplayer;
using osu.Game.Screens.OnlinePlay.Match.Components;
namespace osu.Game.Screens.OnlinePlay.Multiplayer
{
public class CreateMultiplayerMatchButton : PurpleTriangleButton
{
private IBindable<bool> isConnected;
private IBindable<bool> operationInProgress;
[Resolved]
private StatefulMultiplayerClient multiplayerClient { get; set; }
[Resolved]
private OngoingOperationTracker ongoingOperationTracker { get; set; }
[BackgroundDependencyLoader]
private void load()
{
Triangles.TriangleScale = 1.5f;
Text = "Create room";
isConnected = multiplayerClient.IsConnected.GetBoundCopy();
operationInProgress = ongoingOperationTracker.InProgress.GetBoundCopy();
}
protected override void LoadComplete()
{
base.LoadComplete();
isConnected.BindValueChanged(_ => updateState());
operationInProgress.BindValueChanged(_ => updateState(), true);
}
private void updateState() => Enabled.Value = isConnected.Value && !operationInProgress.Value;
}
}
|
Change Price type to double | using Newtonsoft.Json;
namespace BitFlyer.Apis
{
public class SendChildOrderParameter
{
[JsonProperty("product_code")]
public ProductCode ProductCode { get; set; }
[JsonProperty("child_order_type")]
public ChildOrderType ChildOrderType { get; set; }
[JsonProperty("side")]
public Side Side { get; set; }
[JsonProperty("price")]
public int Price { get; set; }
[JsonProperty("size")]
public double Size { get; set; }
[JsonProperty("minute_to_expire")]
public int MinuteToExpire { get; set; }
[JsonProperty("time_in_force")]
public TimeInForce TimeInForce { get; set; }
}
}
| using Newtonsoft.Json;
namespace BitFlyer.Apis
{
public class SendChildOrderParameter
{
[JsonProperty("product_code")]
public ProductCode ProductCode { get; set; }
[JsonProperty("child_order_type")]
public ChildOrderType ChildOrderType { get; set; }
[JsonProperty("side")]
public Side Side { get; set; }
[JsonProperty("price")]
public double Price { get; set; }
[JsonProperty("size")]
public double Size { get; set; }
[JsonProperty("minute_to_expire")]
public int MinuteToExpire { get; set; }
[JsonProperty("time_in_force")]
public TimeInForce TimeInForce { get; set; }
}
}
|
Disable login redirect to dbbrowser.aspx forbidding redirects altogether | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Sitecore.Linqpad.Server
{
public class CookieAwareWebClient : WebClient
{
public CookieAwareWebClient(CookieContainer cookies = null)
{
this.Cookies = cookies ?? new CookieContainer();
}
protected override WebRequest GetWebRequest(Uri address)
{
var webRequest = base.GetWebRequest(address);
var request2 = webRequest as HttpWebRequest;
if (request2 != null)
{
request2.CookieContainer = this.Cookies;
}
webRequest.Timeout = 300000;
return webRequest;
}
public CookieContainer Cookies { get; private set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Sitecore.Linqpad.Server
{
public class CookieAwareWebClient : WebClient
{
public CookieAwareWebClient(CookieContainer cookies = null)
{
this.Cookies = cookies ?? new CookieContainer();
}
protected override WebRequest GetWebRequest(Uri address)
{
var webRequest = base.GetWebRequest(address);
var request2 = webRequest as HttpWebRequest;
if (request2 != null)
{
request2.CookieContainer = this.Cookies;
request2.AllowAutoRedirect = false;
}
webRequest.Timeout = 300000;
return webRequest;
}
public CookieContainer Cookies { get; private set; }
}
}
|
Revert "clean code a bit" | using System.Collections.Generic;
namespace Humanizer.Localisation.NumberToWords
{
internal class FrenchNumberToWordsConverter : FrenchNumberToWordsConverterBase
{
protected override void CollectPartsUnderAHundred(ICollection<string> parts, ref int number, GrammaticalGender gender, bool pluralize)
{
if (number == 71)
parts.Add("soixante et onze");
else if (number == 80)
parts.Add("quatre-vingt" + (pluralize ? "s" : string.Empty));
else if (number >= 70)
{
var @base = number < 80 ? 60 : 80;
int units = number - @base;
var tens = @base / 10;
parts.Add($"{GetTens(tens)}-{GetUnits(units, gender)}");
}
else
base.CollectPartsUnderAHundred(parts, ref number, gender, pluralize);
}
protected override string GetTens(int tens) => tens == 8 ? "quatre-vingt" : base.GetTens(tens);
}
}
| using System.Collections.Generic;
namespace Humanizer.Localisation.NumberToWords
{
internal class FrenchNumberToWordsConverter : FrenchNumberToWordsConverterBase
{
protected override void CollectPartsUnderAHundred(ICollection<string> parts, ref int number, GrammaticalGender gender, bool pluralize)
{
if (number == 71)
parts.Add("soixante et onze");
else if (number == 80)
parts.Add(pluralize ? "quatre-vingts" : "quatre-vingt");
else if (number >= 70)
{
var @base = number < 80 ? 60 : 80;
int units = number - @base;
var tens = @base/10;
parts.Add(string.Format("{0}-{1}", GetTens(tens), GetUnits(units, gender)));
}
else
base.CollectPartsUnderAHundred(parts, ref number, gender, pluralize);
}
protected override string GetTens(int tens)
{
if (tens == 8)
return "quatre-vingt";
return base.GetTens(tens);
}
}
} |
Allow redefining already defined symbols | using System.Collections.Generic;
using Squirrel.Nodes;
namespace Squirrel
{
public class Environment
{
private readonly Environment _parent;
private readonly Dictionary<string, INode> _definitions = new Dictionary<string, INode>();
public Environment(Environment parent)
{
_parent = parent;
}
public Environment() : this(null)
{
}
public void Put(string key, INode value) => _definitions.Add(key, value);
public void PutOuter(string key, INode value) => _parent.Put(key, value);
public INode Get(string key)
{
if (_parent == null)
{
return GetShallow(key);
}
return GetShallow(key) ?? _parent.Get(key);
}
private INode GetShallow(string key) => _definitions.ContainsKey(key) ? _definitions[key] : null;
public void Extend(Environment env)
{
foreach (var definition in env._definitions)
{
Put(definition.Key, definition.Value);
}
}
}
}
| using System.Collections.Generic;
using Squirrel.Nodes;
namespace Squirrel
{
public class Environment
{
private readonly Environment _parent;
private readonly Dictionary<string, INode> _definitions = new Dictionary<string, INode>();
public Environment(Environment parent)
{
_parent = parent;
}
public Environment() : this(null)
{
}
public void Put(string key, INode value) => _definitions[key] = value;
public void PutOuter(string key, INode value) => _parent.Put(key, value);
public INode Get(string key)
{
if (_parent == null)
{
return GetShallow(key);
}
return GetShallow(key) ?? _parent.Get(key);
}
private INode GetShallow(string key) => _definitions.ContainsKey(key) ? _definitions[key] : null;
public void Extend(Environment env)
{
foreach (var definition in env._definitions)
{
Put(definition.Key, definition.Value);
}
}
}
}
|
Remove lazy loading of configuration | using System.IO;
using Newtonsoft.Json;
namespace TfsHipChat.Configuration
{
public class ConfigurationProvider : IConfigurationProvider
{
private TfsHipChatConfig _tfsHipChatConfig;
public TfsHipChatConfig Config
{
get
{
if (_tfsHipChatConfig == null)
{
using (var reader = new JsonTextReader(new StreamReader(Properties.Settings.Default.DefaultConfigPath)))
{
_tfsHipChatConfig = (new JsonSerializer()).Deserialize<TfsHipChatConfig>(reader);
}
}
return _tfsHipChatConfig;
}
}
}
}
| using System.IO;
using Newtonsoft.Json;
using TfsHipChat.Properties;
namespace TfsHipChat.Configuration
{
public class ConfigurationProvider : IConfigurationProvider
{
public ConfigurationProvider()
{
using (var reader = new JsonTextReader(new StreamReader(Settings.Default.DefaultConfigPath)))
{
Config = (new JsonSerializer()).Deserialize<TfsHipChatConfig>(reader);
}
}
public TfsHipChatConfig Config { get; private set; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.