Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix custom culture throws ArgumentException on .NET 3.5 unit tests. | #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2017 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System;
using System.Globalization;
namespace MsgPack
{
/// <summary>
/// Custom <see cref="CultureInfo" /> which uses full width hiphen for negative sign.!--
/// </summary>
internal sealed class LegacyJapaneseCultureInfo : CultureInfo
{
public LegacyJapaneseCultureInfo()
: base( "ja-NP" )
{
var numberFormatInfo = CultureInfo.InvariantCulture.NumberFormat.Clone() as NumberFormatInfo;
numberFormatInfo.NegativeSign = "\uFF0D"; // Full width hiphen
this.NumberFormat = NumberFormatInfo.ReadOnly( numberFormatInfo );
}
}
}
| #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2017 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System;
using System.Globalization;
namespace MsgPack
{
/// <summary>
/// Custom <see cref="CultureInfo" /> which uses full width hiphen for negative sign.!--
/// </summary>
internal sealed class LegacyJapaneseCultureInfo : CultureInfo
{
public LegacyJapaneseCultureInfo()
#if NETSTANDARD1_1 || NETSTANDARD1_3 || SILVERLIGHT
: base( "ja-JP" )
#else
: base( "ja-JP", true )
#endif // NETSTANDARD1_1 || NETSTANDARD1_3 || SILVERLIGHT
{
var numberFormatInfo = CultureInfo.InvariantCulture.NumberFormat.Clone() as NumberFormatInfo;
numberFormatInfo.NegativeSign = "\uFF0D"; // Full width hiphen
this.NumberFormat = NumberFormatInfo.ReadOnly( numberFormatInfo );
}
}
}
|
Fix typo on depot data set. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NFleet.Data
{
public class DepotDataSet : IResponseData, IVersioned
{
public static string MIMEType = "application/vnd.jyu.nfleet.depotset";
public static string MIMEVersion = "2.2";
int IVersioned.VersionNumber { get; set; }
public List<VehicleData> Items { get; set; }
public List<Link> Meta { get; set; }
public DepotDataSet()
{
Items = new List<VehicleData>();
Meta = new List<Link>();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NFleet.Data
{
public class DepotDataSet : IResponseData, IVersioned
{
public static string MIMEType = "application/vnd.jyu.nfleet.depotset";
public static string MIMEVersion = "2.2";
int IVersioned.VersionNumber { get; set; }
public List<DepotData> Items { get; set; }
public List<Link> Meta { get; set; }
public DepotDataSet()
{
Items = new List<DepotData>();
Meta = new List<Link>();
}
}
}
|
Add explanatory comment to unclear use of rotation. | //----------------------------------------------------------------------------
// <copyright file="RemotePlayerMarker.cs" company="Delft University of Technology">
// Copyright 2015, Delft University of Technology
//
// This software is licensed under the terms of the MIT License.
// A copy of the license should be included with this software. If not,
// see http://opensource.org/licenses/MIT for the full license.
// </copyright>
//----------------------------------------------------------------------------
namespace Projection
{
using UnityEngine;
/// <summary>
/// Remote marker that represents a player.
/// <para>
/// This <see cref="RemoteMarker"/> subclass treats rotations differently,
/// because the camera rotation is not determined by the <c>ObjectRotation</c>
/// field, but directly by the rotation as provided by the <c>RemotePosition</c>.
/// </para>
/// </summary>
public class RemotePlayerMarker : RemoteMarker
{
/// <summary>
/// Updates the position of this <see cref="RemotePlayerMarker"/>.
/// </summary>
/// <param name="transformMatrix">The transformation matrix.</param>
public override void UpdatePosition(Matrix4x4 transformMatrix)
{
if (this.RemotePosition != null) {
Quaternion rotation = Quaternion.LookRotation(this.RemotePosition.Position, this.RemotePosition.Rotation.eulerAngles);
Matrix4x4 levelProjection = Matrix4x4.TRS(
this.RemotePosition.Position,
rotation,
this.RemotePosition.Scale);
this.transform.SetFromMatrix(transformMatrix * levelProjection);
}
}
}
} | //----------------------------------------------------------------------------
// <copyright file="RemotePlayerMarker.cs" company="Delft University of Technology">
// Copyright 2015, Delft University of Technology
//
// This software is licensed under the terms of the MIT License.
// A copy of the license should be included with this software. If not,
// see http://opensource.org/licenses/MIT for the full license.
// </copyright>
//----------------------------------------------------------------------------
namespace Projection
{
using UnityEngine;
/// <summary>
/// Remote marker that represents a player.
/// <para>
/// This <see cref="RemoteMarker"/> subclass treats rotations differently,
/// because the camera rotation is not determined by the <c>ObjectRotation</c>
/// field, but directly by the rotation as provided by the <c>RemotePosition</c>.
/// </para>
/// </summary>
public class RemotePlayerMarker : RemoteMarker
{
/// <summary>
/// Updates the position of this <see cref="RemotePlayerMarker"/>.
/// </summary>
/// <param name="transformMatrix">The transformation matrix.</param>
public override void UpdatePosition(Matrix4x4 transformMatrix)
{
if (this.RemotePosition != null)
{
// The rotation in the RemotePosition is actually an upwards vector here, so we can use
// Quaternion.LookRotation with the rotation's Euler angles.
Quaternion rotation = Quaternion.LookRotation(this.RemotePosition.Position, this.RemotePosition.Rotation.eulerAngles);
Matrix4x4 levelProjection = Matrix4x4.TRS(
this.RemotePosition.Position,
rotation,
this.RemotePosition.Scale);
this.transform.SetFromMatrix(transformMatrix * levelProjection);
}
}
}
} |
Make the Xmas Tree move randomly on its first pattern. | using System;
using Microsoft.Xna.Framework;
using MonoGame.Extended.Timers;
using XmasHell.BulletML;
namespace XmasHell.Entities.Bosses.XmasTree
{
class XmasTreeBehaviour1 : AbstractBossBehaviour
{
public XmasTreeBehaviour1(Boss boss) : base(boss)
{
InitialBehaviourLife = GameConfig.BossDefaultBehaviourLife * 1.5f;
}
public override void Start()
{
base.Start();
Boss.Speed = GameConfig.BossDefaultSpeed * 2.5f;
Boss.StartShootTimer = true;
Boss.ShootTimerTime = 0.01f;
Boss.ShootTimerFinished += ShootTimerFinished;
Boss.CurrentAnimator.Play("Idle");
}
private void ShootTimerFinished(object sender, float e)
{
if (CurrentBehaviourLife <= InitialBehaviourLife / 1.5f)
Boss.Game.GameManager.MoverManager.TriggerPattern("XmasTree/pattern1.2", BulletType.Type2, false, Boss.Position());
else
Boss.Game.GameManager.MoverManager.TriggerPattern("XmasTree/pattern1.1", BulletType.Type2, false, Boss.Position());
}
public override void Stop()
{
base.Stop();
Boss.StartShootTimer = false;
Boss.ShootTimerFinished -= ShootTimerFinished;
}
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
}
}
} | using System;
using Microsoft.Xna.Framework;
using MonoGame.Extended.Timers;
using XmasHell.BulletML;
namespace XmasHell.Entities.Bosses.XmasTree
{
class XmasTreeBehaviour1 : AbstractBossBehaviour
{
public XmasTreeBehaviour1(Boss boss) : base(boss)
{
InitialBehaviourLife = GameConfig.BossDefaultBehaviourLife * 1.5f;
}
public override void Start()
{
base.Start();
Boss.Speed = GameConfig.BossDefaultSpeed * 2.5f;
Boss.StartShootTimer = true;
Boss.ShootTimerTime = 0.01f;
Boss.ShootTimerFinished += ShootTimerFinished;
Boss.CurrentAnimator.Play("Idle");
Boss.EnableRandomPosition(true);
}
private void ShootTimerFinished(object sender, float e)
{
if (CurrentBehaviourLife <= InitialBehaviourLife / 1.5f)
Boss.Game.GameManager.MoverManager.TriggerPattern("XmasTree/pattern1.2", BulletType.Type2, false, Boss.Position());
else
Boss.Game.GameManager.MoverManager.TriggerPattern("XmasTree/pattern1.1", BulletType.Type2, false, Boss.Position());
}
public override void Stop()
{
base.Stop();
Boss.StartShootTimer = false;
Boss.ShootTimerFinished -= ShootTimerFinished;
}
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
}
}
} |
Fix incorrect current directory that accours on some devices on android. | // 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 Android.App;
using Android.Content.PM;
using Android.OS;
using Android.Views;
using osu.Framework.Android;
namespace osu.Android
{
[Activity(Theme = "@android:style/Theme.NoTitleBar", MainLauncher = true, ScreenOrientation = ScreenOrientation.FullSensor, SupportsPictureInPicture = false, ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, HardwareAccelerated = true)]
public class OsuGameActivity : AndroidGameActivity
{
protected override Framework.Game CreateGame() => new OsuGameAndroid();
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Window.AddFlags(WindowManagerFlags.Fullscreen);
Window.AddFlags(WindowManagerFlags.KeepScreenOn);
}
}
}
| // 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 Android.App;
using Android.Content.PM;
using Android.OS;
using Android.Views;
using osu.Framework.Android;
namespace osu.Android
{
[Activity(Theme = "@android:style/Theme.NoTitleBar", MainLauncher = true, ScreenOrientation = ScreenOrientation.FullSensor, SupportsPictureInPicture = false, ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, HardwareAccelerated = true)]
public class OsuGameActivity : AndroidGameActivity
{
protected override Framework.Game CreateGame() => new OsuGameAndroid();
protected override void OnCreate(Bundle savedInstanceState)
{
// The default current directory on android is '/'.
// On some devices '/' maps to the app data directory. On others it maps to the root of the internal storage.
// In order to have a consitend current directory on all devices the full path of the app data directory is set as the current directory.
System.Environment.CurrentDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
base.OnCreate(savedInstanceState);
Window.AddFlags(WindowManagerFlags.Fullscreen);
Window.AddFlags(WindowManagerFlags.KeepScreenOn);
}
}
}
|
Implement constructor for Leather Backpack (Lettered) | using SimpleInventory.Examples.Common;
namespace SimpleInventory.Examples.InventoryLetters
{
public class LeatherBackpack : InventoryLetterBag<Item>
{
}
} | using SimpleInventory.Examples.Common;
namespace SimpleInventory.Examples.InventoryLetters
{
public class LeatherBackpack : InventoryLetterBag<Item>
{
/// <inheritdoc />
public LeatherBackpack() : base("Leather Backpack (Lettered)", Volumes.Litres(25), Weights.Kilograms(1))
{ }
}
} |
Add H1 back into profiles | @using StockportWebapp.Enums
@using StockportWebapp.Models
@model Profile
@{
ViewData["Title"] = Model.Title;
var articleTitle = Model.Breadcrumbs.LastOrDefault() != null ? Model.Breadcrumbs.LastOrDefault().Title + " - " : string.Empty;
ViewData["og:title"] = articleTitle + Model.Title;
Layout = "../../Shared/_LayoutSemantic.cshtml";
}
@section Breadcrumbs {
<partial name="SemanticBreadcrumb" model='Model.Breadcrumbs' />
}
<article class="page-container">
<p class="lead-paragraph">@Model.Subtitle</p>
<hr class="thick-divider" />
<section>
@Html.Raw(Model.Body)
</section>
@if (Model.TriviaSection?.Count() > 0)
{
<hr class="thick-divider" />
@await Component.InvokeAsync("InformationList", new {
model = Model.TriviaSection,
heading = Model.TriviaSubheading
})
}
</article>
| @using StockportWebapp.Enums
@using StockportWebapp.Models
@model Profile
@{
ViewData["Title"] = Model.Title;
var articleTitle = Model.Breadcrumbs.LastOrDefault() != null ? Model.Breadcrumbs.LastOrDefault().Title + " - " : string.Empty;
ViewData["og:title"] = articleTitle + Model.Title;
Layout = "../../Shared/_LayoutSemantic.cshtml";
}
@section Breadcrumbs {
<partial name="SemanticBreadcrumb" model='Model.Breadcrumbs' />
}
<article class="page-container">
<h1 tabindex="-1">@ViewData["Title"]</h1>
<p class="lead-paragraph">@Model.Subtitle</p>
<hr class="thick-divider" />
<section>
@Html.Raw(Model.Body)
</section>
@if (Model.TriviaSection?.Count() > 0)
{
<hr class="thick-divider" />
@await Component.InvokeAsync("InformationList", new {
model = Model.TriviaSection,
heading = Model.TriviaSubheading
})
}
</article>
|
Fix crash when bruiser monster can see player but can't path. | using System;
using System.Collections.Generic;
using Magecrawl.Utilities;
namespace Magecrawl.GameEngine.Actors
{
internal class BruiserMonster : Monster
{
public BruiserMonster(string name, Point p, int maxHP, int vision, DiceRoll damage, double defense, double evade, double ctIncreaseModifer, double ctMoveCost, double ctActCost, double ctAttackCost)
: base(name, p, maxHP, vision, damage, defense, evade, ctIncreaseModifer, ctMoveCost, ctActCost, ctAttackCost)
{
}
public override void Action(CoreGameEngine engine)
{
if (IsPlayerVisible(engine) && GetPathToPlayer(engine).Count == 1)
{
UpdateKnownPlayerLocation(engine);
if (engine.UseSkill(this, SkillType.DoubleSwing, engine.Player.Position))
return;
}
DefaultAction(engine);
}
}
}
| using System;
using System.Collections.Generic;
using Magecrawl.Utilities;
namespace Magecrawl.GameEngine.Actors
{
internal class BruiserMonster : Monster
{
public BruiserMonster(string name, Point p, int maxHP, int vision, DiceRoll damage, double defense, double evade, double ctIncreaseModifer, double ctMoveCost, double ctActCost, double ctAttackCost)
: base(name, p, maxHP, vision, damage, defense, evade, ctIncreaseModifer, ctMoveCost, ctActCost, ctAttackCost)
{
}
public override void Action(CoreGameEngine engine)
{
if (IsPlayerVisible(engine))
{
UpdateKnownPlayerLocation(engine);
List<Point> pathToPlayer = GetPathToPlayer(engine);
if (pathToPlayer != null && pathToPlayer.Count == 1)
{
if (engine.UseSkill(this, SkillType.DoubleSwing, engine.Player.Position))
return;
}
}
DefaultAction(engine);
}
}
}
|
Add Azure Function that updates the system status avg temp | //using Microsoft.Framework.Configuration;
//using Microsoft.WindowsAzure.Storage;
//using Microsoft.WindowsAzure.Storage.Table;
//using System.Threading.Tasks;
//using LogLevel = Microsoft.Framework.Logging.LogLevel;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using System;
using System.Threading.Tasks;
namespace vunvulea_iot_core
{
public class SystemStatus
{
private const string systemStatysTablename = "systemstatus";
private readonly CloudStorageAccount storageAccount;
private readonly CloudTableClient tableClient;
private readonly CloudTable systemStatusTable;
// Connection string shall never be hardcoded here.
public SystemStatus(string storageConnectionString =
"@@@")
{
storageAccount = CloudStorageAccount.Parse(storageConnectionString);
tableClient = storageAccount.CreateCloudTableClient();
systemStatusTable = tableClient.GetTableReference(systemStatysTablename);
}
public async Task<string> GetCurrentSystemStatusAsync(SystemStatusType systemStatusType)
{
TableOperation retrieveOperation = TableOperation.Retrieve<SystemStatusEntity>(
SystemStatusEntity.PartitionKeyValue,
Enum.GetName(typeof(SystemStatusType), systemStatusType).ToLower());
TableResult retrievedResult = await systemStatusTable.ExecuteAsync(retrieveOperation);
SystemStatusEntity retrivedEntity = (SystemStatusEntity)retrievedResult.Result;
return retrivedEntity.Status;
}
}
}
| //using Microsoft.Framework.Configuration;
//using Microsoft.WindowsAzure.Storage;
//using Microsoft.WindowsAzure.Storage.Table;
//using System.Threading.Tasks;
//using LogLevel = Microsoft.Framework.Logging.LogLevel;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using System;
using System.Threading.Tasks;
namespace vunvulea_iot_core
{
public class SystemStatus
{
private const string systemStatysTablename = "systemstatus";
private readonly CloudStorageAccount storageAccount;
private readonly CloudTableClient tableClient;
private readonly CloudTable systemStatusTable;
public SystemStatus(string storageConnectionString =
"DefaultEndpointsProtocol=https;AccountName=vunvuleariotstorage;AccountKey=GmmafAcfKQBw3O+7l8xtGdtYt5/PnkIGHmJHy7YkD26VYrmQkrvzENGfBzxuudmFrMmyKf1gt7+vXQA80kemKw==;")
{
storageAccount = CloudStorageAccount.Parse(storageConnectionString);
tableClient = storageAccount.CreateCloudTableClient();
systemStatusTable = tableClient.GetTableReference(systemStatysTablename);
}
public async Task<string> GetCurrentSystemStatusAsync(SystemStatusType systemStatusType)
{
TableOperation retrieveOperation = TableOperation.Retrieve<SystemStatusEntity>(
SystemStatusEntity.PartitionKeyValue,
Enum.GetName(typeof(SystemStatusType), systemStatusType).ToLower());
TableResult retrievedResult = await systemStatusTable.ExecuteAsync(retrieveOperation);
SystemStatusEntity retrivedEntity = (SystemStatusEntity)retrievedResult.Result;
return retrivedEntity.Status;
}
}
}
|
Fix reflection type handling of out parameters | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using System.Reflection;
namespace IntelliTect.Coalesce.TypeDefinition.Wrappers
{
internal class ReflectionParameterWrapper : ParameterWrapper
{
public ReflectionParameterWrapper(ParameterInfo info)
{
Info = info;
Type = new TypeViewModel(new ReflectionTypeWrapper(info.ParameterType));
}
public override string Name => Info.Name;
public override object GetAttributeValue<TAttribute>(string valueName)
{
return Info.GetAttributeValue<TAttribute>(valueName);
}
public override bool HasAttribute<TAttribute>()
{
return Info.HasAttribute<TAttribute>();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using System.Reflection;
namespace IntelliTect.Coalesce.TypeDefinition.Wrappers
{
internal class ReflectionParameterWrapper : ParameterWrapper
{
public ReflectionParameterWrapper(ParameterInfo info)
{
Info = info;
if (info.ParameterType.IsByRef)
Type = new TypeViewModel(new ReflectionTypeWrapper(info.ParameterType.GetElementType()));
else
Type = new TypeViewModel(new ReflectionTypeWrapper(info.ParameterType));
}
public override string Name => Info.Name;
public override object GetAttributeValue<TAttribute>(string valueName)
{
return Info.GetAttributeValue<TAttribute>(valueName);
}
public override bool HasAttribute<TAttribute>()
{
return Info.HasAttribute<TAttribute>();
}
}
}
|
Fix breaks to xml docs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNet.Mvc.ApiExplorer
{
/// <summary>
/// Provides metadata information about the response format to an <c>IApiDescriptionProvider</c>.
/// </summary>
/// <remarks>
/// An <see cref="IOutputFormatter"/> should implement this interface to expose metadata information
/// to an <c>IApiDescriptionProvider</c>.
/// </remarks>
public interface IApiResponseFormatMetadataProvider
{
/// <summary>
/// Gets a filtered list of content types which are supported by the <see cref="IOutputFormatter"/>
/// for the <paramref name="declaredType"/> and <paramref name="contentType"/>.
/// </summary>
/// <param name="contentType">
/// The content type for which the supported content types are desired, or <c>null</c> if any content
/// type can be used.
/// </param>
/// <param name="objectType">
/// The <see cref="Type"/> for which the supported content types are desired.
/// </param>
/// <returns>Content types which are supported by the <see cref="IOutputFormatter"/>.</returns>
IReadOnlyList<MediaTypeHeaderValue> GetSupportedContentTypes(
MediaTypeHeaderValue contentType,
Type objectType);
}
} | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNet.Mvc.ApiExplorer
{
/// <summary>
/// Provides metadata information about the response format to an <c>IApiDescriptionProvider</c>.
/// </summary>
/// <remarks>
/// An <see cref="Formatters.IOutputFormatter"/> should implement this interface to expose metadata information
/// to an <c>IApiDescriptionProvider</c>.
/// </remarks>
public interface IApiResponseFormatMetadataProvider
{
/// <summary>
/// Gets a filtered list of content types which are supported by the <see cref="Formatters.IOutputFormatter"/>
/// for the <paramref name="declaredType"/> and <paramref name="contentType"/>.
/// </summary>
/// <param name="contentType">
/// The content type for which the supported content types are desired, or <c>null</c> if any content
/// type can be used.
/// </param>
/// <param name="objectType">
/// The <see cref="Type"/> for which the supported content types are desired.
/// </param>
/// <returns>Content types which are supported by the <see cref="Formatters.IOutputFormatter"/>.</returns>
IReadOnlyList<MediaTypeHeaderValue> GetSupportedContentTypes(
MediaTypeHeaderValue contentType,
Type objectType);
}
} |
Fix some problem with the find bar accepting input too early | using System.Windows;
using UserControl = System.Windows.Controls.UserControl;
namespace anime_downloader.Views.Components
{
/// <summary>
/// Interaction logic for FindViewModel.xaml
/// </summary>
public partial class Find : UserControl
{
public Find()
{
InitializeComponent();
}
private void UIElement_OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (IsVisible)
Textbox.Focus();
}
}
}
| using System.Windows;
using UserControl = System.Windows.Controls.UserControl;
namespace anime_downloader.Views.Components
{
/// <summary>
/// Interaction logic for FindViewModel.xaml
/// </summary>
public partial class Find : UserControl
{
public Find()
{
InitializeComponent();
}
private void UIElement_OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (IsLoaded && IsVisible)
Textbox.Focus();
}
}
}
|
Add delay between attempts to contact the server | using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
namespace Microsoft.DotNet.Tools.Test.Utilities
{
public class NetworkHelper
{
// in milliseconds
private const int Timeout = 20000;
public static string Localhost { get; } = "http://localhost";
public static bool IsServerUp(string url)
{
return SpinWait.SpinUntil(() =>
{
using (var client = new HttpClient())
{
try
{
client.BaseAddress = new Uri(url);
HttpResponseMessage response = client.GetAsync("").Result;
return response.IsSuccessStatusCode;
}
catch (Exception)
{
return false;
}
}
}, Timeout);
}
public static void TestGetRequest(string url, string expectedResponse)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(url);
HttpResponseMessage response = client.GetAsync("").Result;
if (response.IsSuccessStatusCode)
{
var responseString = response.Content.ReadAsStringAsync().Result;
responseString.Should().Contain(expectedResponse);
}
}
}
public static string GetLocalhostUrlWithFreePort()
{
return $"{Localhost}:{PortManager.GetPort()}/";
}
}
}
| using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
namespace Microsoft.DotNet.Tools.Test.Utilities
{
public class NetworkHelper
{
// in milliseconds
private const int Timeout = 20000;
public static string Localhost { get; } = "http://localhost";
public static bool IsServerUp(string url)
{
return SpinWait.SpinUntil(() =>
{
using (var client = new HttpClient())
{
try
{
client.BaseAddress = new Uri(url);
HttpResponseMessage response = client.GetAsync("").Result;
return response.IsSuccessStatusCode;
}
catch (Exception)
{
Thread.Sleep(100);
return false;
}
}
}, Timeout);
}
public static void TestGetRequest(string url, string expectedResponse)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(url);
HttpResponseMessage response = client.GetAsync("").Result;
if (response.IsSuccessStatusCode)
{
var responseString = response.Content.ReadAsStringAsync().Result;
responseString.Should().Contain(expectedResponse);
}
}
}
public static string GetLocalhostUrlWithFreePort()
{
return $"{Localhost}:{PortManager.GetPort()}/";
}
}
}
|
Make WindowsPrincipalIsInRoleNeg pass when a domain client is offline | // 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.Security.Principal;
using Xunit;
public class WindowsPrincipalTests
{
[Fact]
public static void WindowsPrincipalIsInRoleNeg()
{
WindowsIdentity windowsIdentity = WindowsIdentity.GetAnonymous();
WindowsPrincipal windowsPrincipal = new WindowsPrincipal(windowsIdentity);
var ret = windowsPrincipal.IsInRole("FAKEDOMAIN\\nonexist");
Assert.False(ret);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.ComponentModel;
using System.Security.Principal;
using Xunit;
public class WindowsPrincipalTests
{
[Fact]
public static void WindowsPrincipalIsInRoleNeg()
{
WindowsIdentity windowsIdentity = WindowsIdentity.GetAnonymous();
WindowsPrincipal windowsPrincipal = new WindowsPrincipal(windowsIdentity);
try
{
bool ret = windowsPrincipal.IsInRole("FAKEDOMAIN\\nonexist");
Assert.False(ret);
}
catch (SystemException e)
{
// If a domain joined machine can't talk to the domain controller then it
// can't determine if "FAKEDOMAIN" is resolvable within the AD forest, so it
// fails with ERROR_TRUSTED_RELATIONSHIP_FAILURE (resulting in an exception).
const int ERROR_TRUSTED_RELATIONSHIP_FAILURE = 0x6FD;
Win32Exception win32Exception = new Win32Exception(ERROR_TRUSTED_RELATIONSHIP_FAILURE);
// NetFx throws a plain SystemException which has the message built via FormatMessage.
// CoreFx throws a Win32Exception based on the error, which gets the same message value.
Assert.Equal(win32Exception.Message, e.Message);
}
}
}
|
Use interface ICommand instead of MvxCommand | using Android.Widget;
using Cirrious.MvvmCross.ViewModels;
using System;
using System.Windows.Input;
namespace MvvmCrossSpikes.Droid.Bindings
{
public class ButtonCommandBinding : MvxTargetBinding<Button, MvxCommand>
{
private ICommand _command;
public ButtonCommandBinding(Button target)
: base(target)
{
if (target != null)
target.Click += Target_Click;
}
public static string Name { get { return "Command"; } }
public override void SetTypedValue(MvxCommand cmd)
{
if (_command != null)
_command.CanExecuteChanged -= command_CanExecuteChanged;
_command = cmd;
if (_command != null)
{
_command.CanExecuteChanged += command_CanExecuteChanged;
}
command_CanExecuteChanged(this, EventArgs.Empty);
}
protected override void Dispose(bool isDisposing)
{
var button = Target;
if (isDisposing && button != null)
{
button.Click -= Target_Click;
}
base.Dispose(isDisposing);
}
private void command_CanExecuteChanged(object sender, EventArgs e)
{
var cmd = _command;
var parameter = sender;
var target = Target;
if (cmd != null && target != null)
{
target.Enabled = cmd.CanExecute(parameter);
}
}
private void Target_Click(object sender, EventArgs e)
{
var cmd = _command;
var parameter = sender;
if (cmd != null && cmd.CanExecute(parameter))
{
cmd.Execute(parameter);
}
}
}
} | using Android.Widget;
using Cirrious.MvvmCross.ViewModels;
using System;
using System.Windows.Input;
namespace MvvmCrossSpikes.Droid.Bindings
{
public class ButtonCommandBinding : MvxTargetBinding<Button, ICommand>
{
private ICommand _command;
public ButtonCommandBinding(Button target)
: base(target)
{
if (target != null)
target.Click += Target_Click;
}
public static string Name { get { return "Command"; } }
public override void SetTypedValue(ICommand cmd)
{
if (_command != null)
_command.CanExecuteChanged -= command_CanExecuteChanged;
_command = cmd;
if (_command != null)
{
_command.CanExecuteChanged += command_CanExecuteChanged;
}
command_CanExecuteChanged(this, EventArgs.Empty);
}
protected override void Dispose(bool isDisposing)
{
var button = Target;
if (isDisposing && button != null)
{
button.Click -= Target_Click;
}
base.Dispose(isDisposing);
}
private void command_CanExecuteChanged(object sender, EventArgs e)
{
var cmd = _command;
var parameter = sender;
var target = Target;
if (cmd != null && target != null)
{
target.Enabled = cmd.CanExecute(parameter);
}
}
private void Target_Click(object sender, EventArgs e)
{
var cmd = _command;
var parameter = sender;
if (cmd != null && cmd.CanExecute(parameter))
{
cmd.Execute(parameter);
}
}
}
} |
Change SDK name in NewAnalyzerTemplate | /*This tutorial is going to guide you to write a diagnostic analyzer that enforces the placement of a single space between the if keyword of an if statement and the
open parenthesis of the condition.
For more information, please reference the ReadMe.
Before you begin, go to Tools->Extensions and Updates->Online, and install .NET compiler SDK
*/
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace NewAnalyzerTemplate
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class NewAnalyzerTemplateAnalyzer : DiagnosticAnalyzer
{
// The SupportedDiagnostics property stores an ImmutableArray containing any diagnostics that can be reported by this analyzer
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
throw new NotImplementedException();
}
}
// The Initialize method is used to register methods to perform analysis of the Syntax Tree when there is a change to the Syntax Tree
// The AnalysisContext parameter has members, such as RegisterSyntaxNodeAction, that perform the registering mentioned above
public override void Initialize(AnalysisContext context)
{
}
}
}
| /*This tutorial is going to guide you to write a diagnostic analyzer that enforces the placement of a single space between the if keyword of an if statement and the
open parenthesis of the condition.
For more information, please reference the ReadMe.
Before you begin, go to Tools->Extensions and Updates->Online, and install .NET Compiler Platform SDK
*/
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace NewAnalyzerTemplate
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class NewAnalyzerTemplateAnalyzer : DiagnosticAnalyzer
{
// The SupportedDiagnostics property stores an ImmutableArray containing any diagnostics that can be reported by this analyzer
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
throw new NotImplementedException();
}
}
// The Initialize method is used to register methods to perform analysis of the Syntax Tree when there is a change to the Syntax Tree
// The AnalysisContext parameter has members, such as RegisterSyntaxNodeAction, that perform the registering mentioned above
public override void Initialize(AnalysisContext context)
{
}
}
}
|
Support RelationName as dictionary key | using Utf8Json;
namespace Nest
{
internal class RelationNameFormatter : IJsonFormatter<RelationName>
{
public RelationName Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
if (reader.GetCurrentJsonToken() == JsonToken.String)
{
RelationName relationName = reader.ReadString();
return relationName;
}
return null;
}
public void Serialize(ref JsonWriter writer, RelationName value, IJsonFormatterResolver formatterResolver)
{
if (value == null)
{
writer.WriteNull();
return;
}
var settings = formatterResolver.GetConnectionSettings();
writer.WriteString(settings.Inferrer.RelationName(value));
}
}
}
| using Utf8Json;
namespace Nest
{
internal class RelationNameFormatter : IJsonFormatter<RelationName>, IObjectPropertyNameFormatter<RelationName>
{
public RelationName Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
{
if (reader.GetCurrentJsonToken() == JsonToken.String)
{
RelationName relationName = reader.ReadString();
return relationName;
}
return null;
}
public void Serialize(ref JsonWriter writer, RelationName value, IJsonFormatterResolver formatterResolver)
{
if (value == null)
{
writer.WriteNull();
return;
}
var settings = formatterResolver.GetConnectionSettings();
writer.WriteString(settings.Inferrer.RelationName(value));
}
public void SerializeToPropertyName(ref JsonWriter writer, RelationName value, IJsonFormatterResolver formatterResolver) =>
Serialize(ref writer, value, formatterResolver);
public RelationName DeserializeFromPropertyName(ref JsonReader reader, IJsonFormatterResolver formatterResolver) =>
Deserialize(ref reader, formatterResolver);
}
}
|
Fix missing newline at the end of a file | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using Xunit;
namespace System.IO.Tests
{
public static class DirectoryNotFoundExceptionTests
{
[Fact]
public static void Ctor_Empty()
{
var exception = new DirectoryNotFoundException();
ExceptionUtility.ValidateExceptionProperties(exception, hResult: HResults.COR_E_DIRECTORYNOTFOUND, validateMessage: false);
}
[Fact]
public static void Ctor_String()
{
string message = "That page was missing from the directory.";
var exception = new DirectoryNotFoundException(message);
ExceptionUtility.ValidateExceptionProperties(exception, hResult: HResults.COR_E_DIRECTORYNOTFOUND, message: message);
}
[Fact]
public static void Ctor_String_Exception()
{
string message = "That page was missing from the directory.";
var innerException = new Exception("Inner exception");
var exception = new DirectoryNotFoundException(message, innerException);
ExceptionUtility.ValidateExceptionProperties(exception, hResult: HResults.COR_E_DIRECTORYNOTFOUND, innerException: innerException, message: message);
}
}
} | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using Xunit;
namespace System.IO.Tests
{
public static class DirectoryNotFoundExceptionTests
{
[Fact]
public static void Ctor_Empty()
{
var exception = new DirectoryNotFoundException();
ExceptionUtility.ValidateExceptionProperties(exception, hResult: HResults.COR_E_DIRECTORYNOTFOUND, validateMessage: false);
}
[Fact]
public static void Ctor_String()
{
string message = "That page was missing from the directory.";
var exception = new DirectoryNotFoundException(message);
ExceptionUtility.ValidateExceptionProperties(exception, hResult: HResults.COR_E_DIRECTORYNOTFOUND, message: message);
}
[Fact]
public static void Ctor_String_Exception()
{
string message = "That page was missing from the directory.";
var innerException = new Exception("Inner exception");
var exception = new DirectoryNotFoundException(message, innerException);
ExceptionUtility.ValidateExceptionProperties(exception, hResult: HResults.COR_E_DIRECTORYNOTFOUND, innerException: innerException, message: message);
}
}
}
|
Initialize to the route handler of ASP.NET MVC | using System.Web.Mvc;
using System.Web.Routing;
namespace RestfulRouting
{
public abstract class Mapper
{
private readonly IRouteHandler _routeHandler;
protected Route GenerateRoute(string path, string controller, string action, string[] httpMethods)
{
return new Route(path,
new RouteValueDictionary(new { controller, action }),
new RouteValueDictionary(new { httpMethod = new HttpMethodConstraint(httpMethods) }),
new MvcRouteHandler());
}
}
}
| using System.Web.Mvc;
using System.Web.Routing;
namespace RestfulRouting
{
public abstract class Mapper
{
private readonly IRouteHandler _routeHandler;
protected Mapper()
{
_routeHandler = new MvcRouteHandler();
}
protected Route GenerateRoute(string path, string controller, string action, string[] httpMethods)
{
return new Route(path,
new RouteValueDictionary(new { controller, action }),
new RouteValueDictionary(new { httpMethod = new HttpMethodConstraint(httpMethods) }),
new MvcRouteHandler());
}
}
}
|
Set max concurrent deliveries to 10 in demo. | using System;
using Demo.Endpoints.FileSystem;
using Demo.Endpoints.Sharepoint;
using Verdeler;
namespace Demo
{
internal class Program
{
private static void Main(string[] args)
{
//Configure the distributor
var distributor = new Distributor<DistributableFile, Vendor>();
distributor.RegisterEndpointRepository(new FileSystemEndpointRepository());
distributor.RegisterEndpointRepository(new SharepointEndpointRepository());
distributor.RegisterEndpointDeliveryService(new FileSystemDeliveryService());
distributor.RegisterEndpointDeliveryService(new SharepointDeliveryService());
distributor.MaxConcurrentDeliveries = 1;
//Distribute a file to a vendor
var distributionTask = distributor.DistributeAsync(FakeFile, FakeVendor);
Console.WriteLine("All deliveries started.");
distributionTask.Wait();
Console.WriteLine("All deliveries complete.");
Console.ReadLine();
}
private static DistributableFile FakeFile => new DistributableFile
{
Name = @"test.pdf",
Contents = new byte[1024]
};
private static Vendor FakeVendor => new Vendor
{
Name = @"Mark's Pool Supplies"
};
}
}
| using System;
using Demo.Endpoints.FileSystem;
using Demo.Endpoints.Sharepoint;
using Verdeler;
namespace Demo
{
internal class Program
{
private static void Main(string[] args)
{
//Configure the distributor
var distributor = new Distributor<DistributableFile, Vendor>();
distributor.RegisterEndpointRepository(new FileSystemEndpointRepository());
distributor.RegisterEndpointRepository(new SharepointEndpointRepository());
distributor.RegisterEndpointDeliveryService(new FileSystemDeliveryService());
distributor.RegisterEndpointDeliveryService(new SharepointDeliveryService());
distributor.MaxConcurrentDeliveries = 10;
//Distribute a file to a vendor
var distributionTask = distributor.DistributeAsync(FakeFile, FakeVendor);
Console.WriteLine("All deliveries started.");
distributionTask.Wait();
Console.WriteLine("All deliveries complete.");
Console.ReadLine();
}
private static DistributableFile FakeFile => new DistributableFile
{
Name = @"test.pdf",
Contents = new byte[1024]
};
private static Vendor FakeVendor => new Vendor
{
Name = @"Mark's Pool Supplies"
};
}
}
|
Remove milliseconds from date fields in GetLearners Json | using System;
using System.Threading.Tasks;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using SFA.DAS.CommitmentsV2.Api.Types.Responses;
using SFA.DAS.CommitmentsV2.Application.Queries.GetAllLearners;
namespace SFA.DAS.CommitmentsV2.Api.Controllers
{
[ApiController]
[Route("api/learners")]
public class LearnerController : ControllerBase
{
private readonly IMediator _mediator;
public LearnerController(IMediator mediator)
{
_mediator = mediator;
}
[HttpGet]
public async Task<IActionResult> GetAllLearners(DateTime? sinceTime = null, int batch_number = 1, int batch_size = 1000)
{
var result = await _mediator.Send(new GetAllLearnersQuery(sinceTime, batch_number, batch_size));
return Ok(new GetAllLearnersResponse()
{
Learners = result.Learners,
BatchNumber = result.BatchNumber,
BatchSize = result.BatchSize,
TotalNumberOfBatches = result.TotalNumberOfBatches
});
}
}
}
| using System;
using System.Threading.Tasks;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using SFA.DAS.CommitmentsV2.Api.Types.Responses;
using SFA.DAS.CommitmentsV2.Application.Queries.GetAllLearners;
namespace SFA.DAS.CommitmentsV2.Api.Controllers
{
[ApiController]
[Route("api/learners")]
public class LearnerController : ControllerBase
{
private readonly IMediator _mediator;
public LearnerController(IMediator mediator)
{
_mediator = mediator;
}
[HttpGet]
public async Task<IActionResult> GetAllLearners(DateTime? sinceTime = null, int batch_number = 1, int batch_size = 1000)
{
var result = await _mediator.Send(new GetAllLearnersQuery(sinceTime, batch_number, batch_size));
var settings = new JsonSerializerSettings
{
DateFormatString = "yyyy-MM-dd'T'HH:mm:ss"
};
return new JsonResult(new GetAllLearnersResponse()
{
Learners = result.Learners,
BatchNumber = result.BatchNumber,
BatchSize = result.BatchSize,
TotalNumberOfBatches = result.TotalNumberOfBatches
},settings);
}
}
}
|
Add basic execute method to parseresult (temp fix, want to add typechecking and specify return type) | using System.Collections.Generic;
using Jello.Errors;
using Jello.Nodes;
namespace Jello
{
public class ParseResult
{
public bool Success { get; private set; }
public IEnumerable<IError> Errors { get; private set; }
private INode _root;
public ParseResult(INode node)
{
_root = node;
Success = true;
}
public ParseResult(IEnumerable<IError> errors)
{
Success = false;
Errors = errors;
}
}
} | using System.Collections.Generic;
using Jello.DataSources;
using Jello.Errors;
using Jello.Nodes;
namespace Jello
{
public class ParseResult
{
public bool Success { get; private set; }
public IEnumerable<IError> Errors { get; private set; }
private INode _root;
public ParseResult(INode node)
{
_root = node;
Success = true;
}
public ParseResult(IEnumerable<IError> errors)
{
Success = false;
Errors = errors;
}
public object Execute(IDataSource dataSource)
{
return _root.GetValue(dataSource);
}
}
} |
Fix crash when logging in | // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using EndlessClient.ControlSets;
using EndlessClient.HUD.Controls;
using EOLib.Domain.Notifiers;
namespace EndlessClient.Rendering.NPC
{
public class NPCAnimationActions : INPCAnimationNotifier
{
private readonly IHudControlProvider _hudControlProvider;
private readonly INPCStateCache _npcStateCache;
private readonly INPCRendererRepository _npcRendererRepository;
public NPCAnimationActions(IHudControlProvider hudControlProvider,
INPCStateCache npcStateCache,
INPCRendererRepository npcRendererRepository)
{
_hudControlProvider = hudControlProvider;
_npcStateCache = npcStateCache;
_npcRendererRepository = npcRendererRepository;
}
public void StartNPCWalkAnimation(int npcIndex)
{
if (!_hudControlProvider.IsInGame)
return;
var npcAnimator = _hudControlProvider.GetComponent<INPCAnimator>(HudControlIdentifier.NPCAnimator);
npcAnimator.StartWalkAnimation(npcIndex);
}
public void RemoveNPCFromView(int npcIndex, bool showDeathAnimation)
{
_npcStateCache.RemoveStateByIndex(npcIndex);
if (!showDeathAnimation)
{
_npcRendererRepository.NPCRenderers[npcIndex].Dispose();
_npcRendererRepository.NPCRenderers.Remove(npcIndex);
}
else
{
_npcRendererRepository.NPCRenderers[npcIndex].StartDying();
}
}
}
}
| // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using EndlessClient.ControlSets;
using EndlessClient.HUD.Controls;
using EOLib.Domain.Notifiers;
namespace EndlessClient.Rendering.NPC
{
public class NPCAnimationActions : INPCAnimationNotifier
{
private readonly IHudControlProvider _hudControlProvider;
private readonly INPCStateCache _npcStateCache;
private readonly INPCRendererRepository _npcRendererRepository;
public NPCAnimationActions(IHudControlProvider hudControlProvider,
INPCStateCache npcStateCache,
INPCRendererRepository npcRendererRepository)
{
_hudControlProvider = hudControlProvider;
_npcStateCache = npcStateCache;
_npcRendererRepository = npcRendererRepository;
}
public void StartNPCWalkAnimation(int npcIndex)
{
if (!_hudControlProvider.IsInGame)
return;
var npcAnimator = _hudControlProvider.GetComponent<INPCAnimator>(HudControlIdentifier.NPCAnimator);
npcAnimator.StartWalkAnimation(npcIndex);
}
public void RemoveNPCFromView(int npcIndex, bool showDeathAnimation)
{
if (!_hudControlProvider.IsInGame)
return;
_npcStateCache.RemoveStateByIndex(npcIndex);
if (!showDeathAnimation)
{
_npcRendererRepository.NPCRenderers[npcIndex].Dispose();
_npcRendererRepository.NPCRenderers.Remove(npcIndex);
}
else
{
_npcRendererRepository.NPCRenderers[npcIndex].StartDying();
}
}
}
}
|
Change int count to long count in Dequeue extension method | using System.Collections.Generic;
using System.Linq;
namespace DerConverter
{
internal static class QueueExtensions
{
public static IEnumerable<T> Dequeue<T>(this Queue<T> queue, int count)
{
for (int i = 0; i < count; i++) yield return queue.Dequeue();
}
public static IEnumerable<T> DequeueAll<T>(this Queue<T> queue)
{
while (queue.Any()) yield return queue.Dequeue();
}
}
}
| using System.Collections.Generic;
using System.Linq;
namespace DerConverter
{
internal static class QueueExtensions
{
public static IEnumerable<T> Dequeue<T>(this Queue<T> queue, long count)
{
for (long i = 0; i < count; i++) yield return queue.Dequeue();
}
public static IEnumerable<T> DequeueAll<T>(this Queue<T> queue)
{
while (queue.Any()) yield return queue.Dequeue();
}
}
}
|
Add test case for fetch translation metadata capability when getting locales. | using NUnit.Framework;
using ZendeskApi_v2;
namespace Tests
{
[TestFixture]
public class LocaleTests
{
private ZendeskApi api = new ZendeskApi(Settings.Site, Settings.Email, Settings.Password);
[Test]
public void CanGetLocales()
{
var all = api.Locales.GetAllLocales();
Assert.Greater(all.Count, 0);
var agent = api.Locales.GetLocalesForAgents();
Assert.Greater(agent.Count, 0);
var specific = api.Locales.GetLocaleById(all.Locales[0].Id);
Assert.AreEqual(specific.Locale.Id, all.Locales[0].Id);
var current = api.Locales.GetCurrentLocale();
Assert.Greater(current.Locale.Id, 0);
}
}
} | using NUnit.Framework;
using ZendeskApi_v2;
namespace Tests
{
[TestFixture]
public class LocaleTests
{
private ZendeskApi api = new ZendeskApi(Settings.Site, Settings.Email, Settings.Password);
[Test]
public void CanGetLocales()
{
var all = api.Locales.GetAllLocales();
Assert.Greater(all.Count, 0);
var agent = api.Locales.GetLocalesForAgents();
Assert.Greater(agent.Count, 0);
var specific = api.Locales.GetLocaleById(all.Locales[0].Id);
Assert.AreEqual(specific.Locale.Id, all.Locales[0].Id);
Assert.IsNull(specific.Locale.Translations);
var specificWithTranslation = api.Locales.GetLocaleById(all.Locales[0].Id, true);
Assert.AreEqual(specificWithTranslation.Locale.Id, all.Locales[0].Id);
Assert.IsNotNull(specificWithTranslation.Locale.Translations);
var current = api.Locales.GetCurrentLocale();
Assert.Greater(current.Locale.Id, 0);
Assert.IsNull(current.Locale.Translations);
var currentWithTranslation = api.Locales.GetCurrentLocale(true);
Assert.Greater(currentWithTranslation.Locale.Id, 0);
Assert.IsNotNull(currentWithTranslation.Locale.Translations);
}
}
} |
Fix flaky unit test caused by concurrency issue | namespace Nett
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Util;
internal static class UserTypeMetaData
{
private static readonly Dictionary<Type, MetaDataInfo> MetaData = new Dictionary<Type, MetaDataInfo>();
public static bool IsPropertyIgnored(Type ownerType, PropertyInfo pi)
{
if (ownerType == null) { throw new ArgumentNullException(nameof(ownerType)); }
if (pi == null) { throw new ArgumentNullException(nameof(pi)); }
EnsureMetaDataInitialized(ownerType);
return MetaData[ownerType].IgnoredProperties.Contains(pi.Name);
}
private static void EnsureMetaDataInitialized(Type t)
=> Extensions.DictionaryExtensions.AddIfNeeded(MetaData, t, () => ProcessType(t));
private static MetaDataInfo ProcessType(Type t)
{
var ignored = ProcessIgnoredProperties(t);
return new MetaDataInfo(ignored);
}
private static IEnumerable<string> ProcessIgnoredProperties(Type t)
{
var attributes = ReflectionUtil.GetPropertiesWithAttribute<TomlIgnoreAttribute>(t);
return attributes.Select(pi => pi.Name);
}
private sealed class MetaDataInfo
{
public MetaDataInfo(IEnumerable<string> ignoredProperties)
{
this.IgnoredProperties = new HashSet<string>(ignoredProperties);
}
public HashSet<string> IgnoredProperties { get; }
}
}
}
| namespace Nett
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Util;
internal static class UserTypeMetaData
{
private static readonly ConcurrentDictionary<Type, MetaDataInfo> MetaData = new ConcurrentDictionary<Type, MetaDataInfo>();
public static bool IsPropertyIgnored(Type ownerType, PropertyInfo pi)
{
if (ownerType == null) { throw new ArgumentNullException(nameof(ownerType)); }
if (pi == null) { throw new ArgumentNullException(nameof(pi)); }
EnsureMetaDataInitialized(ownerType);
return MetaData[ownerType].IgnoredProperties.Contains(pi.Name);
}
private static void EnsureMetaDataInitialized(Type t)
=> Extensions.DictionaryExtensions.AddIfNeeded(MetaData, t, () => ProcessType(t));
private static MetaDataInfo ProcessType(Type t)
{
var ignored = ProcessIgnoredProperties(t);
return new MetaDataInfo(ignored);
}
private static IEnumerable<string> ProcessIgnoredProperties(Type t)
{
var attributes = ReflectionUtil.GetPropertiesWithAttribute<TomlIgnoreAttribute>(t);
return attributes.Select(pi => pi.Name);
}
private sealed class MetaDataInfo
{
public MetaDataInfo(IEnumerable<string> ignoredProperties)
{
this.IgnoredProperties = new HashSet<string>(ignoredProperties);
}
public HashSet<string> IgnoredProperties { get; }
}
}
}
|
Add copyright header to TransportSocketOptions.cs. | using System;
using System.Collections.Generic;
using System.Text;
namespace Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets
{
// TODO: Come up with some options
public class SocketTransportOptions
{
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Text;
namespace Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets
{
// TODO: Come up with some options
public class SocketTransportOptions
{
}
}
|
Change button location to the right side of dropdown | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics.UserInterface;
using osu.Game.Tournament.IO;
namespace osu.Game.Tournament.Screens.Setup
{
internal class TournamentSwitcher : ActionableInfo
{
private OsuDropdown<string> dropdown;
private OsuButton folderButton;
[Resolved]
private TournamentGameBase game { get; set; }
[BackgroundDependencyLoader]
private void load(TournamentStorage storage)
{
string startupTournament = storage.CurrentTournament.Value;
dropdown.Current = storage.CurrentTournament;
dropdown.Items = storage.ListTournaments();
dropdown.Current.BindValueChanged(v => Button.Enabled.Value = v.NewValue != startupTournament, true);
Action = () => game.GracefullyExit();
folderButton.Action = storage.PresentExternally;
ButtonText = "Close osu!";
}
protected override Drawable CreateComponent()
{
var drawable = base.CreateComponent();
FlowContainer.Insert(-1, dropdown = new OsuDropdown<string>
{
Width = 510
});
FlowContainer.Insert(-2, folderButton = new TriangleButton
{
Text = "Open folder",
Width = 100
});
return drawable;
}
}
}
| // 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.Graphics.UserInterface;
using osu.Game.Tournament.IO;
namespace osu.Game.Tournament.Screens.Setup
{
internal class TournamentSwitcher : ActionableInfo
{
private OsuDropdown<string> dropdown;
private OsuButton folderButton;
[Resolved]
private TournamentGameBase game { get; set; }
[BackgroundDependencyLoader]
private void load(TournamentStorage storage)
{
string startupTournament = storage.CurrentTournament.Value;
dropdown.Current = storage.CurrentTournament;
dropdown.Items = storage.ListTournaments();
dropdown.Current.BindValueChanged(v => Button.Enabled.Value = v.NewValue != startupTournament, true);
Action = () => game.GracefullyExit();
folderButton.Action = storage.PresentExternally;
ButtonText = "Close osu!";
}
protected override Drawable CreateComponent()
{
var drawable = base.CreateComponent();
FlowContainer.Insert(-1, folderButton = new TriangleButton
{
Text = "Open folder",
Width = 100
});
FlowContainer.Insert(-2, dropdown = new OsuDropdown<string>
{
Width = 510
});
return drawable;
}
}
}
|
Add test to make sure normal collection works. | using System;
using System.Collections.Generic;
using System.Linq;
using CSharpViaTest.Collections.Annotations;
using Xunit;
namespace CSharpViaTest.Collections._20_YieldPractices
{
[Medium]
public class TakeUntilCatchingAnException
{
readonly int indexThatWillThrow = new Random().Next(2, 10);
IEnumerable<int> GetSequenceOfData()
{
for (int i = 0;; ++i)
{
if (i == indexThatWillThrow) { throw new Exception("An exception is thrown"); }
yield return i;
}
}
#region Please modifies the code to pass the test
static IEnumerable<int> TakeUntilError(IEnumerable<int> sequence)
{
throw new NotImplementedException();
}
#endregion
[Fact]
public void should_get_sequence_until_an_exception_is_thrown()
{
IEnumerable<int> sequence = TakeUntilError(GetSequenceOfData());
Assert.Equal(Enumerable.Range(0, indexThatWillThrow + 1), sequence);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using CSharpViaTest.Collections.Annotations;
using Xunit;
namespace CSharpViaTest.Collections._20_YieldPractices
{
[Medium]
public class TakeUntilCatchingAnException
{
readonly int indexThatWillThrow = new Random().Next(2, 10);
IEnumerable<int> GetSequenceOfData()
{
for (int i = 0;; ++i)
{
if (i == indexThatWillThrow) { throw new Exception("An exception is thrown"); }
yield return i;
}
}
#region Please modifies the code to pass the test
static IEnumerable<int> TakeUntilError(IEnumerable<int> sequence)
{
throw new NotImplementedException();
}
#endregion
[Fact]
public void should_get_sequence_until_an_exception_is_thrown()
{
IEnumerable<int> sequence = TakeUntilError(GetSequenceOfData());
Assert.Equal(Enumerable.Range(0, indexThatWillThrow + 1), sequence);
}
[Fact]
public void should_get_sequence_given_normal_collection()
{
var sequence = new[] { 1, 2, 3 };
IEnumerable<int> result = TakeUntilError(sequence);
Assert.Equal(sequence, result);
}
}
} |
Update content for feature not enabled |
<div class="grid-row">
<div class="column-two-thirds">
<h1 class="heading-xlarge">Coming soon</h1>
<p>This service isn't available yet.</p>
</div>
</div>
@section breadcrumb {
<div class="breadcrumbs">
<ol>
<li><a href="@Url.Action("Index","Home")">Back to homepage</a></li>
</ol>
</div>
} |
<div class="grid-row">
<div class="column-two-thirds">
<h1 class="heading-xlarge">Under development</h1>
<p>This service is currently being developed and you don't yet have access.</p>
</div>
</div>
@section breadcrumb {
<div class="breadcrumbs">
<ol>
<li><a href="@Url.Action("Index","Home")">Back to homepage</a></li>
</ol>
</div>
} |
Increase timeout for running in container | using System;
using System.Linq;
using NUnit.Framework;
using Shouldly;
namespace Nimbus.UnitTests.MulticastRequestResponseTests
{
[TestFixture]
internal class WhenTakingTwoResponses : GivenAWrapperWithTwoResponses
{
private readonly TimeSpan _timeout = TimeSpan.FromSeconds(1);
private string[] _result;
protected override void When()
{
_result = Subject.ReturnResponsesOpportunistically(_timeout).Take(2).ToArray();
}
[Test]
public void TheElapsedTimeShouldBeLessThanTheTimeout()
{
ElapsedTime.ShouldBeLessThan(_timeout);
}
[Test]
public void ThereShouldBeTwoResults()
{
_result.Count().ShouldBe(2);
}
}
} | using System;
using System.Linq;
using NUnit.Framework;
using Shouldly;
namespace Nimbus.UnitTests.MulticastRequestResponseTests
{
[TestFixture]
internal class WhenTakingTwoResponses : GivenAWrapperWithTwoResponses
{
private readonly TimeSpan _timeout = TimeSpan.FromSeconds(1.5);
private string[] _result;
protected override void When()
{
_result = Subject.ReturnResponsesOpportunistically(_timeout).Take(2).ToArray();
}
[Test]
public void TheElapsedTimeShouldBeLessThanTheTimeout()
{
ElapsedTime.ShouldBeLessThan(_timeout);
}
[Test]
public void ThereShouldBeTwoResults()
{
_result.Count().ShouldBe(2);
}
}
} |
Fix proxied drawables never expiring. | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
namespace osu.Framework.Graphics
{
public class ProxyDrawable : Drawable
{
public ProxyDrawable(Drawable original)
{
Original = original;
}
internal sealed override Drawable Original { get; }
// We do not want to receive updates. That is the business
// of the original drawable.
public override bool IsPresent => false;
}
} | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
namespace osu.Framework.Graphics
{
public class ProxyDrawable : Drawable
{
public ProxyDrawable(Drawable original)
{
Original = original;
}
internal sealed override Drawable Original { get; }
public override bool IsAlive => base.IsAlive && Original.IsAlive;
// We do not want to receive updates. That is the business
// of the original drawable.
public override bool IsPresent => false;
}
} |
Add a list of notification receivers for project create. | using Lykke.EmailSenderProducer.Interfaces;
namespace CompetitionPlatform.Data.AzureRepositories.Settings
{
public class BaseSettings
{
public AzureSettings Azure { get; set; }
public AuthenticationSettings Authentication { get; set; }
public NotificationsSettings Notifications { get; set; }
public string EmailServiceBusSettingsUrl { get; set; }
}
public class AuthenticationSettings
{
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string PostLogoutRedirectUri { get; set; }
public string Authority { get; set; }
}
public class AzureSettings
{
public string StorageConnString { get; set; }
}
public class NotificationsSettings
{
public string EmailsQueueConnString { get; set; }
public string SlackQueueConnString { get; set; }
}
public class EmailServiceBusSettings
{
public EmailServiceBus EmailServiceBus;
}
public class EmailServiceBus : IServiceBusEmailSettings
{
public string Key { get; set; }
public string QueueName { get; set; }
public string NamespaceUrl { get; set; }
public string PolicyName { get; set; }
}
}
| using System.Collections.Generic;
using Lykke.EmailSenderProducer.Interfaces;
namespace CompetitionPlatform.Data.AzureRepositories.Settings
{
public class BaseSettings
{
public AzureSettings Azure { get; set; }
public AuthenticationSettings Authentication { get; set; }
public NotificationsSettings Notifications { get; set; }
public string EmailServiceBusSettingsUrl { get; set; }
public List<string> ProjectCreateNotificationReceiver { get; set; }
}
public class AuthenticationSettings
{
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string PostLogoutRedirectUri { get; set; }
public string Authority { get; set; }
}
public class AzureSettings
{
public string StorageConnString { get; set; }
}
public class NotificationsSettings
{
public string EmailsQueueConnString { get; set; }
public string SlackQueueConnString { get; set; }
}
public class EmailServiceBusSettings
{
public EmailServiceBus EmailServiceBus;
}
public class EmailServiceBus : IServiceBusEmailSettings
{
public string Key { get; set; }
public string QueueName { get; set; }
public string NamespaceUrl { get; set; }
public string PolicyName { get; set; }
}
}
|
Add geometry in GeometryFeature constructor | using Mapsui.Geometries;
using Mapsui.GeometryLayer;
using Mapsui.Layers;
using Mapsui.Providers;
using NUnit.Framework;
namespace Mapsui.Tests.Layers
{
[TestFixture]
public class WritableLayerTests
{
[Test]
public void DoNotCrashOnNullOrEmptyGeometries()
{
// arrange
var writableLayer = new WritableLayer();
writableLayer.Add(new GeometryFeature());
writableLayer.Add(new GeometryFeature { Geometry = new Point() });
writableLayer.Add(new GeometryFeature { Geometry = new LineString() });
writableLayer.Add(new GeometryFeature { Geometry = new Polygon() });
// act
var extent = writableLayer.Extent;
// assert
Assert.IsNull(extent);
}
}
}
| using Mapsui.Geometries;
using Mapsui.GeometryLayer;
using Mapsui.Layers;
using NUnit.Framework;
namespace Mapsui.Tests.Layers
{
[TestFixture]
public class WritableLayerTests
{
[Test]
public void DoNotCrashOnNullOrEmptyGeometries()
{
// arrange
var writableLayer = new WritableLayer();
writableLayer.Add(new GeometryFeature());
writableLayer.Add(new GeometryFeature(new Point()));
writableLayer.Add(new GeometryFeature(new LineString()));
writableLayer.Add(new GeometryFeature(new Polygon()));
// act
var extent = writableLayer.Extent;
// assert
Assert.IsNull(extent);
}
}
}
|
Allow specifying document types to search. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mios.Swiftype {
public class QuerySpecification {
public string Q { get; set; }
public int Page { get; set; }
public int? PerPage { get; set; }
public IDictionary<string, FilterCollection> Filters { get; set; }
public IDictionary<string, IEnumerable<string>> SearchFields { get; set; }
public IDictionary<string, IEnumerable<string>> FetchFields { get; set; }
public QuerySpecification() {
Page = 1;
Filters = new Dictionary<string, FilterCollection>();
SearchFields = new Dictionary<string, IEnumerable<string>>();
FetchFields = new Dictionary<string, IEnumerable<string>>();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mios.Swiftype {
public class QuerySpecification {
public string Q { get; set; }
public int Page { get; set; }
public int? PerPage { get; set; }
public string[] DocumentTypes { get; set; }
public IDictionary<string, FilterCollection> Filters { get; set; }
public IDictionary<string, IEnumerable<string>> SearchFields { get; set; }
public IDictionary<string, IEnumerable<string>> FetchFields { get; set; }
public QuerySpecification() {
Page = 1;
Filters = new Dictionary<string, FilterCollection>();
SearchFields = new Dictionary<string, IEnumerable<string>>();
FetchFields = new Dictionary<string, IEnumerable<string>>();
}
}
}
|
Fix compile error from merging Up and Down | using Mycroft.App;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mycroft.Cmd.App
{
class AppCommand : Command
{
/// <summary>
/// Parses JSON into App command objects
/// </summary>
/// <param name="messageType">The message type that determines the command to create</param>
/// <param name="json">The JSON body of the message</param>
/// <returns>Returns a command object for the parsed message</returns>
public static Command Parse(String type, String json, AppInstance instance)
{
switch (type)
{
case "APP_UP":
return new Up(json, instance);
case "APP_DOWN":
return new DependencyChange(instance);
case "APP_DESTROY":
return new Destroy(json, instance);
case "APP_MANIFEST":
return Manifest.Parse(json, instance);
default:
//data is incorrect - can't do anything with it
// TODO notify that is wrong
break;
}
return null ;
}
}
}
| using Mycroft.App;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mycroft.Cmd.App
{
class AppCommand : Command
{
/// <summary>
/// Parses JSON into App command objects
/// </summary>
/// <param name="messageType">The message type that determines the command to create</param>
/// <param name="json">The JSON body of the message</param>
/// <returns>Returns a command object for the parsed message</returns>
public static Command Parse(String type, String json, AppInstance instance)
{
switch (type)
{
case "APP_UP":
case "APP_DOWN":
return new DependencyChange(instance);
case "APP_DESTROY":
return new Destroy(json, instance);
case "APP_MANIFEST":
return Manifest.Parse(json, instance);
default:
//data is incorrect - can't do anything with it
// TODO notify that is wrong
break;
}
return null ;
}
}
}
|
Send message to specific connection | using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace WebSocketManager
{
public class WebSocketManagerMiddleware
{
private readonly RequestDelegate _next;
private WebSocketManager _webSocketManager { get; set; }
private WebSocketMessageHandler _webSocketMessageHandler { get; set; }
public WebSocketManagerMiddleware(RequestDelegate next,
WebSocketManager webSocketManager,
WebSocketMessageHandler webSocketMessageHandler)
{
_next = next;
_webSocketManager = webSocketManager;
_webSocketMessageHandler = webSocketMessageHandler;
}
public async Task Invoke(HttpContext context)
{
if(!context.WebSockets.IsWebSocketRequest)
return;
var socket = await context.WebSockets.AcceptWebSocketAsync();
_webSocketManager.AddSocket(socket);
await _webSocketMessageHandler.SendMessageAsync(socketId: "",
message: _webSocketManager.GetId(socket));
await _next.Invoke(context);
}
}
}
| using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace WebSocketManager
{
public class WebSocketManagerMiddleware
{
private readonly RequestDelegate _next;
private WebSocketManager _webSocketManager { get; set; }
private WebSocketMessageHandler _webSocketMessageHandler { get; set; }
public WebSocketManagerMiddleware(RequestDelegate next,
WebSocketManager webSocketManager,
WebSocketMessageHandler webSocketMessageHandler)
{
_next = next;
_webSocketManager = webSocketManager;
_webSocketMessageHandler = webSocketMessageHandler;
}
public async Task Invoke(HttpContext context)
{
if(!context.WebSockets.IsWebSocketRequest)
return;
var socket = await context.WebSockets.AcceptWebSocketAsync();
_webSocketManager.AddSocket(socket);
var socketId = _webSocketManager.GetId(socket);
await _webSocketMessageHandler.SendMessageAsync(socketId: socketId,
message: $"SocketId: {_webSocketManager.GetId(socket)}");
await _next.Invoke(context);
}
}
}
|
Remove comment about ffmpeg from interface | // 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.
namespace osu.Framework.Graphics.Animations
{
/// <summary>
/// An animation / playback sequence.
/// </summary>
public interface IAnimation
{
/// <summary>
/// The duration of the animation. Can only be queried after the decoder has started decoding has loaded. This value may be an estimate by FFmpeg, depending on the video loaded.
/// </summary>
public double Duration { get; }
/// <summary>
/// True if the animation has finished playing, false otherwise.
/// </summary>
public bool FinishedPlaying => !Loop && PlaybackPosition > Duration;
/// <summary>
/// True if the animation is playing, false otherwise. Starts true.
/// </summary>
bool IsPlaying { get; set; }
/// <summary>
/// True if the animation should start over from the first frame after finishing. False if it should stop playing and keep displaying the last frame when finishing.
/// </summary>
bool Loop { get; set; }
/// <summary>
/// Seek the animation to a specific time value.
/// </summary>
/// <param name="time">The time value to seek to.</param>
void Seek(double time);
/// <summary>
/// The current position of playback.
/// </summary>
public double PlaybackPosition { get; set; }
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Framework.Graphics.Animations
{
/// <summary>
/// An animation / playback sequence.
/// </summary>
public interface IAnimation
{
/// <summary>
/// The duration of the animation.
/// </summary>
public double Duration { get; }
/// <summary>
/// True if the animation has finished playing, false otherwise.
/// </summary>
public bool FinishedPlaying => !Loop && PlaybackPosition > Duration;
/// <summary>
/// True if the animation is playing, false otherwise. Starts true.
/// </summary>
bool IsPlaying { get; set; }
/// <summary>
/// True if the animation should start over from the first frame after finishing. False if it should stop playing and keep displaying the last frame when finishing.
/// </summary>
bool Loop { get; set; }
/// <summary>
/// Seek the animation to a specific time value.
/// </summary>
/// <param name="time">The time value to seek to.</param>
void Seek(double time);
/// <summary>
/// The current position of playback.
/// </summary>
public double PlaybackPosition { get; set; }
}
}
|
Change + rank strings to be cleaner for the end-user | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.ComponentModel;
namespace osu.Game.Scoring
{
public enum ScoreRank
{
[Description(@"F")]
F,
[Description(@"F")]
D,
[Description(@"C")]
C,
[Description(@"B")]
B,
[Description(@"A")]
A,
[Description(@"S")]
S,
[Description(@"SPlus")]
SH,
[Description(@"SS")]
X,
[Description(@"SSPlus")]
XH,
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.ComponentModel;
namespace osu.Game.Scoring
{
public enum ScoreRank
{
[Description(@"F")]
F,
[Description(@"F")]
D,
[Description(@"C")]
C,
[Description(@"B")]
B,
[Description(@"A")]
A,
[Description(@"S")]
S,
[Description(@"S+")]
SH,
[Description(@"SS")]
X,
[Description(@"SS+")]
XH,
}
}
|
Add more supported commands to test | using GTPWrapper;
using GTPWrapper.DataTypes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GTPWrapperTest {
public class Program {
static void Main(string[] args) {
Engine engine = new Engine();
engine.NewCommand += engine_NewCommand;
engine.ResponsePushed += engine_ResponsePushed;
engine.ConnectionClosed += engine_ConnectionClosed;
while (true) {
string input = Console.ReadLine();
engine.ParseString(input);
}
}
static void engine_ConnectionClosed(object sender, EventArgs e) {
Environment.Exit(0);
}
static void engine_NewCommand(object sender, CommandEventArgs e) {
Engine engine = (Engine)sender;
string response = e.Command.Name;
if (e.Command.Name == "showboard") {
response = new Board(19).ToString();
}
engine.PushResponse(new Response(e.Command, response, e.Command.Name == "error"));
}
static void engine_ResponsePushed(object sender, ResponseEventArgs e) {
Console.Write(e.Response.ToString() + "\n\n");
}
}
}
| using GTPWrapper;
using GTPWrapper.DataTypes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GTPWrapperTest {
public class Program {
static void Main(string[] args) {
Engine engine = new Engine();
engine.NewCommand += engine_NewCommand;
engine.ResponsePushed += engine_ResponsePushed;
engine.ConnectionClosed += engine_ConnectionClosed;
engine.SupportedCommands.AddRange(new string[] { "showboard", "error" });
while (true) {
string input = Console.ReadLine();
engine.ParseString(input);
}
}
static void engine_ConnectionClosed(object sender, EventArgs e) {
Environment.Exit(0);
}
static void engine_NewCommand(object sender, CommandEventArgs e) {
Engine engine = (Engine)sender;
string response = e.Command.Name;
if (e.Command.Name == "showboard") {
response = new Board(13).ToString();
}
engine.PushResponse(new Response(e.Command, response, e.Command.Name == "error"));
}
static void engine_ResponsePushed(object sender, ResponseEventArgs e) {
Console.Write(e.Response.ToString() + "\n\n");
}
}
}
|
Fix banana showers not using cancellation token | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects.Types;
namespace osu.Game.Rulesets.Catch.Objects
{
public class BananaShower : CatchHitObject, IHasEndTime
{
public override FruitVisualRepresentation VisualRepresentation => FruitVisualRepresentation.Banana;
public override bool LastInCombo => true;
public override Judgement CreateJudgement() => new IgnoreJudgement();
protected override void CreateNestedHitObjects(CancellationToken cancellationToken)
{
base.CreateNestedHitObjects(cancellationToken);
createBananas();
}
private void createBananas()
{
double spacing = Duration;
while (spacing > 100)
spacing /= 2;
if (spacing <= 0)
return;
for (double i = StartTime; i <= EndTime; i += spacing)
{
AddNested(new Banana
{
Samples = Samples,
StartTime = i
});
}
}
public double EndTime
{
get => StartTime + Duration;
set => Duration = value - StartTime;
}
public double Duration { get; set; }
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects.Types;
namespace osu.Game.Rulesets.Catch.Objects
{
public class BananaShower : CatchHitObject, IHasEndTime
{
public override FruitVisualRepresentation VisualRepresentation => FruitVisualRepresentation.Banana;
public override bool LastInCombo => true;
public override Judgement CreateJudgement() => new IgnoreJudgement();
protected override void CreateNestedHitObjects(CancellationToken cancellationToken)
{
base.CreateNestedHitObjects(cancellationToken);
createBananas(cancellationToken);
}
private void createBananas(CancellationToken cancellationToken)
{
double spacing = Duration;
while (spacing > 100)
spacing /= 2;
if (spacing <= 0)
return;
for (double i = StartTime; i <= EndTime; i += spacing)
{
cancellationToken.ThrowIfCancellationRequested();
AddNested(new Banana
{
Samples = Samples,
StartTime = i
});
}
}
public double EndTime
{
get => StartTime + Duration;
set => Duration = value - StartTime;
}
public double Duration { get; set; }
}
}
|
Move to SemVer for packaging | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("ScriptCs.Octokit")]
[assembly: AssemblyDescription("Octokit Script Pack for ScriptCs.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Henrik Andersson")]
[assembly: AssemblyProduct("ScriptCs.Octokit")]
[assembly: AssemblyCopyright("Copyright © Henrik Andersson")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("69341200-0230-4734-9F20-CE145B17043E")]
[assembly: AssemblyVersion("0.1.0")]
[assembly: AssemblyFileVersion("0.1.0")]
[assembly: AssemblyInformationalVersion("0.1.14")]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("ScriptCs.Octokit")]
[assembly: AssemblyDescription("Octokit Script Pack for ScriptCs.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Henrik Andersson")]
[assembly: AssemblyProduct("ScriptCs.Octokit")]
[assembly: AssemblyCopyright("Copyright © Henrik Andersson")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("69341200-0230-4734-9F20-CE145B17043E")]
[assembly: AssemblyVersion("0.1.0")]
[assembly: AssemblyFileVersion("0.1.0")]
[assembly: AssemblyInformationalVersion("0.1.0-build14")]
|
Add method to convert scientific notation string to float | namespace SCPI.Extensions
{
public static class ValueTypeExtensions
{
/// <summary>
/// Checks that the value is within specified range
/// </summary>
/// <param name="value">Value to check</param>
/// <param name="minValue">The inclusive lower bound</param>
/// <param name="maxValue">The inclusive upper bound</param>
/// <returns>True if the value is within range otherwise false</returns>
public static bool IsWithin(this int value, int minValue, int maxValue)
{
var ret = false;
if (value >= minValue && value <= maxValue)
{
ret = true;
}
return ret;
}
}
}
| using System.Globalization;
namespace SCPI.Extensions
{
public static class ValueTypeExtensions
{
/// <summary>
/// Checks that the value is within specified range
/// </summary>
/// <param name="value">Value to check</param>
/// <param name="minValue">The inclusive lower bound</param>
/// <param name="maxValue">The inclusive upper bound</param>
/// <returns>True if the value is within range otherwise false</returns>
public static bool IsWithin(this int value, int minValue, int maxValue)
{
var ret = false;
if (value >= minValue && value <= maxValue)
{
ret = true;
}
return ret;
}
/// <summary>
/// Converts the string representation of a number to float
/// </summary>
/// <param name="value">A string representing a number to convert</param>
/// <param name="result">When this method returns, contains the single-precision floating-point
/// number equivalent to the numeric value or symbol contained in value, if the conversion succeeded</param>
/// <returns>True if value was converted successfully; otherwise, false</returns>
public static bool ScientificNotationStringToFloat(this string value, out float result)
{
if (float.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out result))
{
return true;
}
return false;
}
}
}
|
Add public designator to tag | namespace HOLMS.Platform.Support.ReservationTags {
class MigratedReservationTag : ReservationTagBase {
protected override string[] GetDescriptorPartsAfterCategory() =>
new string[] { };
protected override string GetCategoryDescriptor() => MigratedBookingCategory;
public override bool IsPermanent => true;
}
}
| namespace HOLMS.Platform.Support.ReservationTags {
public class MigratedReservationTag : ReservationTagBase {
protected override string[] GetDescriptorPartsAfterCategory() =>
new string[] { };
protected override string GetCategoryDescriptor() => MigratedBookingCategory;
public override bool IsPermanent => true;
}
}
|
Remove deprecated "quirks mode" test coverage: although this concept has been an issue for test frameworks, it was never really an issue for Fixie as Fixie has always targeted net45 or higher, and the problem involved only applied to end users whose projects really targeted 4.0. Also, the test was meant to catch regressions in AppDomain setup, and Fixie no longer has any AppDomain concerns. | #if NET471
namespace Fixie.Tests.Execution
{
using System;
using System.Configuration;
using System.Linq;
using System.Runtime.Versioning;
using Assertions;
public class ExecutionEnvironmentTests
{
public void ShouldEnableAccessToTestAssemblyConfigFile()
{
ConfigurationManager.AppSettings["CanAccessAppConfig"].ShouldEqual("true");
}
public void ShouldTargetFrameworkCompatibleWithQuirksModeStatus()
{
// Test frameworks which support both .NET 4.0 and 4.5 can encounter an issue
// with their AppDomain setup in which test runner behavior can be negatively
// impacted depending on whether code targets 4.0 or 4.5. A test could fail,
// for instance, even when the tested code is actually right.
// Because Fixie targets a minimum of 4.5, it doesn't actually fall prey to
// that issue. Fixie never needs to run in the presence of quirks mode.
// However, we include this sanity check to avoid regressions.
// See https://youtrack.jetbrains.com/issue/RSRP-412080
var quirksAreEnabled = Uri.EscapeDataString("'") == "'";
quirksAreEnabled.ShouldBeFalse();
var targetFramework =
typeof(ExecutionEnvironmentTests)
.Assembly
.GetCustomAttributes(typeof(TargetFrameworkAttribute), true)
.Cast<TargetFrameworkAttribute>()
.Single()
.FrameworkName;
quirksAreEnabled.ShouldEqual(!targetFramework.Contains("4.5"));
}
}
}
#endif | #if NET471
namespace Fixie.Tests.Execution
{
using System;
using System.Configuration;
using System.Linq;
using System.Runtime.Versioning;
using Assertions;
public class ExecutionEnvironmentTests
{
public void ShouldEnableAccessToTestAssemblyConfigFile()
{
ConfigurationManager.AppSettings["CanAccessAppConfig"].ShouldEqual("true");
}
}
}
#endif |
Add error messages to model | namespace SFA.DAS.EmployerUsers.Web.Models
{
public class LoginViewModel
{
public string EmailAddress { get; set; }
public string Password { get; set; }
public string OriginatingAddress { get; set; }
public bool InvalidLoginAttempt { get; set; }
public string ReturnUrl { get; set; }
}
} | namespace SFA.DAS.EmployerUsers.Web.Models
{
public class LoginViewModel : ViewModelBase
{
public string EmailAddress { get; set; }
public string Password { get; set; }
public string OriginatingAddress { get; set; }
public string ReturnUrl { get; set; }
public string PasswordError => GetErrorMessage(nameof(Password));
public string EmailAddressError => GetErrorMessage(nameof(EmailAddress));
}
} |
Update performance tests to use TestData attribute | using System;
using System.Diagnostics;
using System.Linq;
using NUnit.Framework;
using NinjaNye.SearchExtensions.Levenshtein;
namespace NinjaNye.SearchExtensions.Tests.LevenshteinTests
{
[TestFixture]
public class LevenshteinDistancePerformanceTests : BuildStringTestsBase
{
#if DEBUG
// Performance test will always fail in debug mode
[Ignore]
#endif
[Test]
public void ToLevenshteinDistance_CompareOneMillionStringsOfLength7_ExecutesInLessThanOneSecond()
{
//Arrange
var words = this.BuildWords(1000000, 7, 7);
var randomWord = this.BuildRandomWord(7,7);
var stopwatch = new Stopwatch();
//Act
stopwatch.Start();
var result = words.Select(w => LevenshteinProcessor.LevenshteinDistance(w, randomWord)).ToList();
stopwatch.Stop();
//Assert
Console.WriteLine("Elapsed Time: {0}", stopwatch.Elapsed);
Console.WriteLine("Total matching words: {0}", result.Count(i => i == 0));
Console.WriteLine("Total words with distance of 1: {0}", result.Count(i => i == 1));
Console.WriteLine("Total words with distance of 2: {0}", result.Count(i => i == 2));
Console.WriteLine("Total words with distance of 3: {0}", result.Count(i => i == 3));
Assert.IsTrue(stopwatch.Elapsed.TotalMilliseconds <= 1000);
}
}
} | using System;
using System.Diagnostics;
using System.Linq;
using NUnit.Framework;
using NinjaNye.SearchExtensions.Levenshtein;
namespace NinjaNye.SearchExtensions.Tests.LevenshteinTests
{
#if DEBUG
// Performance test will always fail in debug mode
[Ignore]
#endif
[TestFixture]
public class LevenshteinDistancePerformanceTests : BuildStringTestsBase
{
[TestCase(6)]
[TestCase(7)]
public void ToLevenshteinDistance_CompareOneMillionStringsOfLengthX_ExecutesInLessThanOneSecond(int length)
{
//Arrange
var words = this.BuildWords(1000000, length, length);
var randomWord = this.BuildRandomWord(length,length);
var stopwatch = new Stopwatch();
//Act
stopwatch.Start();
var result = words.Select(w => LevenshteinProcessor.LevenshteinDistance(w, randomWord)).ToList();
stopwatch.Stop();
//Assert
Console.WriteLine("Elapsed Time: {0}", stopwatch.Elapsed);
Console.WriteLine("Total matching words: {0}", result.Count(i => i == 0));
Console.WriteLine("Total words with distance of 1: {0}", result.Count(i => i == 1));
Console.WriteLine("Total words with distance of 2: {0}", result.Count(i => i == 2));
Console.WriteLine("Total words with distance of 3: {0}", result.Count(i => i == 3));
Assert.IsTrue(stopwatch.Elapsed.TotalMilliseconds <= 1000);
}
}
} |
Mark assembly as CLS compliant | using System.Reflection;
[assembly: AssemblyTitle("DoTheMath.Linear")]
[assembly: AssemblyDescription("A bunch of stuff for Linear Algebra.")]
| using System;
using System.Reflection;
[assembly: AssemblyTitle("DoTheMath.Linear")]
[assembly: AssemblyDescription("A bunch of stuff for Linear Algebra.")]
[assembly: CLSCompliant(true)]
|
Add value task to FillBuffer() | using System.ComponentModel;
using System.IO;
namespace Sakuno.IO
{
[EditorBrowsable(EditorBrowsableState.Never)]
public static class StreamExtensions
{
public static int FillBuffer(this Stream stream, byte[] buffer, int offset, int count)
{
var remaining = count;
do
{
var length = stream.Read(buffer, offset, remaining);
if (length == 0)
break;
remaining -= length;
offset += length;
} while (remaining > 0);
return count - remaining;
}
}
}
| using System;
using System.ComponentModel;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Sakuno.IO
{
[EditorBrowsable(EditorBrowsableState.Never)]
public static class StreamExtensions
{
public static int FillBuffer(this Stream stream, byte[] buffer, int offset, int count)
{
var remaining = count;
do
{
var length = stream.Read(buffer, offset, remaining);
if (length == 0)
break;
remaining -= length;
offset += length;
} while (remaining > 0);
return count - remaining;
}
#if NETSTANDARD2_1
public static async ValueTask<int> FillBuffer(this Stream stream, Memory<byte> buffer, CancellationToken cancellationToken = default)
{
var remaining = buffer.Length;
var offset = 0;
do
{
var length = await stream.ReadAsync(buffer, cancellationToken);
if (length == 0)
break;
remaining -= length;
offset += length;
} while (remaining > 0);
return buffer.Length - remaining;
}
#endif
}
}
|
Use type/attribute for user secrets | // Copyright (c) Martin Costello, 2016. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.Website
{
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
/// <summary>
/// A class representing the startup logic for the application.
/// </summary>
public class Startup : StartupBase
{
/// <summary>
/// Initializes a new instance of the <see cref="Startup"/> class.
/// </summary>
/// <param name="env">The <see cref="IHostingEnvironment"/> to use.</param>
public Startup(IHostingEnvironment env)
: base(env)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
bool isDevelopment = env.IsDevelopment();
if (isDevelopment)
{
builder.AddUserSecrets("martincostello.com");
}
builder.AddApplicationInsightsSettings(developerMode: isDevelopment);
Configuration = builder.Build();
}
}
}
| // Copyright (c) Martin Costello, 2016. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.Website
{
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
/// <summary>
/// A class representing the startup logic for the application.
/// </summary>
public class Startup : StartupBase
{
/// <summary>
/// Initializes a new instance of the <see cref="Startup"/> class.
/// </summary>
/// <param name="env">The <see cref="IHostingEnvironment"/> to use.</param>
public Startup(IHostingEnvironment env)
: base(env)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
bool isDevelopment = env.IsDevelopment();
if (isDevelopment)
{
builder.AddUserSecrets<Startup>();
}
builder.AddApplicationInsightsSettings(developerMode: isDevelopment);
Configuration = builder.Build();
}
}
}
|
Fix missing string format parameter | using System.IO;
namespace Microsoft.Diagnostics.Runtime
{
/// <summary>
/// Thrown when we fail to read memory from the target process.
/// </summary>
public class MemoryReadException : IOException
{
/// <summary>
/// The address of memory that could not be read.
/// </summary>
public ulong Address { get; private set; }
/// <summary>
/// Constructor
/// </summary>
/// <param name="address">The address of memory that could not be read.</param>
public MemoryReadException(ulong address)
: base(string.Format("Could not read memory at {0:x}."))
{
}
}
}
| using System.IO;
namespace Microsoft.Diagnostics.Runtime
{
/// <summary>
/// Thrown when we fail to read memory from the target process.
/// </summary>
public class MemoryReadException : IOException
{
/// <summary>
/// The address of memory that could not be read.
/// </summary>
public ulong Address { get; private set; }
/// <summary>
/// Constructor
/// </summary>
/// <param name="address">The address of memory that could not be read.</param>
public MemoryReadException(ulong address)
: base(string.Format("Could not read memory at {0:x}.", address))
{
}
}
}
|
Add method to get service settings | using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
namespace DotNetRu.Azure
{
[Route("diagnostics")]
public class DiagnosticsController : ControllerBase
{
private readonly ILogger logger;
public DiagnosticsController(
ILogger<DiagnosticsController> logger)
{
this.logger = logger;
}
[HttpPost]
[Route("ping")]
public async Task<IActionResult> Ping()
{
try
{
logger.LogInformation("Ping is requested");
return new OkObjectResult("Success");
}
catch (Exception e)
{
logger.LogCritical(e, "Unhandled error while ping");
return new ObjectResult(e) {
StatusCode = StatusCodes.Status500InternalServerError
};
}
}
}
}
| using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using DotNetRu.AzureService;
namespace DotNetRu.Azure
{
[Route("diagnostics")]
public class DiagnosticsController : ControllerBase
{
private readonly ILogger logger;
private readonly RealmSettings realmSettings;
private readonly TweetSettings tweetSettings;
private readonly PushSettings pushSettings;
private readonly VkontakteSettings vkontakteSettings;
public DiagnosticsController(
ILogger<DiagnosticsController> logger,
RealmSettings realmSettings,
TweetSettings tweetSettings,
VkontakteSettings vkontakteSettings,
PushSettings pushSettings)
{
this.logger = logger;
this.realmSettings = realmSettings;
this.tweetSettings = tweetSettings;
this.vkontakteSettings = vkontakteSettings;
this.pushSettings = pushSettings;
}
[HttpGet]
[Route("settings")]
public IActionResult Settings()
{
return new ObjectResult(new
{
RealmSettings = realmSettings,
TweetSettings = tweetSettings,
VkontakteSettings = vkontakteSettings,
pushSettings = pushSettings
});
}
}
}
|
Fix to avoid unwanted updates after builds | using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("UpdateVersion")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("UpdateVersion")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("2.0.0.7")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
|
Add get best id method for person. | namespace TraktApiSharp.Objects.Get.People
{
using Extensions;
using Newtonsoft.Json;
using System;
public class TraktPerson
{
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "ids")]
public TraktPersonIds Ids { get; set; }
[JsonProperty(PropertyName = "images")]
public TraktPersonImages Images { get; set; }
[JsonProperty(PropertyName = "biography")]
public string Biography { get; set; }
[JsonProperty(PropertyName = "birthday")]
public DateTime? Birthday { get; set; }
[JsonProperty(PropertyName = "death")]
public DateTime? Death { get; set; }
public int Age => Birthday.HasValue ? (Death.HasValue ? Birthday.YearsBetween(Death) : Birthday.YearsBetween(DateTime.Now)) : 0;
[JsonProperty(PropertyName = "birthplace")]
public string Birthplace { get; set; }
[JsonProperty(PropertyName = "homepage")]
public string Homepage { get; set; }
}
}
| namespace TraktApiSharp.Objects.Get.People
{
using Extensions;
using Newtonsoft.Json;
using System;
/// <summary>A Trakt person.</summary>
public class TraktPerson
{
/// <summary>Gets or sets the person name.</summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
/// <summary>Gets or sets the collection of ids for the person for various web services.</summary>
[JsonProperty(PropertyName = "ids")]
public TraktPersonIds Ids { get; set; }
/// <summary>Gets or sets the collection of images and image sets for the person.</summary>
[JsonProperty(PropertyName = "images")]
public TraktPersonImages Images { get; set; }
/// <summary>Gets or sets the biography of the person.</summary>
[JsonProperty(PropertyName = "biography")]
public string Biography { get; set; }
/// <summary>Gets or sets the UTC datetime when the person was born.</summary>
[JsonProperty(PropertyName = "birthday")]
public DateTime? Birthday { get; set; }
/// <summary>Gets or sets the UTC datetime when the person died.</summary>
[JsonProperty(PropertyName = "death")]
public DateTime? Death { get; set; }
/// <summary>Returns the age of the person, if <see cref="Birthday" /> is set, otherwise zero.</summary>
public int Age => Birthday.HasValue ? (Death.HasValue ? Birthday.YearsBetween(Death) : Birthday.YearsBetween(DateTime.Now)) : 0;
/// <summary>Gets or sets the birthplace of the person.</summary>
[JsonProperty(PropertyName = "birthplace")]
public string Birthplace { get; set; }
/// <summary>Gets or sets the web address of the homepage of the person.</summary>
[JsonProperty(PropertyName = "homepage")]
public string Homepage { get; set; }
}
}
|
Validate nullable attributes are set | #pragma warning disable CA1304
#pragma warning disable MA0011
using System.Globalization;
using TestUtilities;
using Xunit;
namespace Meziantou.Framework.ResxSourceGenerator.GeneratorTests;
public class ResxGeneratorTests
{
[RunIfFact(globalizationMode: FactInvariantGlobalizationMode.Disabled)]
public void FormatString()
{
CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");
Assert.Equal("Hello world!", Resource1.FormatHello("world"));
CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("fr");
Assert.Equal("Bonjour le monde!", Resource1.FormatHello("le monde"));
}
[RunIfFact(globalizationMode: FactInvariantGlobalizationMode.Disabled)]
public void StringValue()
{
CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");
Assert.Equal("value", Resource1.Sample);
CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("fr");
Assert.Equal("valeur", Resource1.Sample);
}
[Fact]
public void TextFile()
{
Assert.Equal("test", Resource1.TextFile1);
}
[Fact]
public void BinaryFile()
{
Assert.Equal(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, Resource1.Image1![0..8]);
}
}
| #pragma warning disable CA1304
#pragma warning disable MA0011
using System.Globalization;
using TestUtilities;
using Xunit;
namespace Meziantou.Framework.ResxSourceGenerator.GeneratorTests;
public class ResxGeneratorTests
{
[RunIfFact(globalizationMode: FactInvariantGlobalizationMode.Disabled)]
public void FormatString()
{
CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");
Assert.Equal("Hello world!", Resource1.FormatHello("world"));
CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("fr");
Assert.Equal("Bonjour le monde!", Resource1.FormatHello("le monde"));
}
[RunIfFact(globalizationMode: FactInvariantGlobalizationMode.Disabled)]
public void StringValue()
{
CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");
Assert.Equal("value", Resource1.Sample);
CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("fr");
Assert.Equal("valeur", Resource1.Sample);
}
#nullable enable
[Fact]
public void GetStringWithDefaultValue()
{
// Ensure the value is not nullable
Assert.Equal(3, Resource1.GetString("UnknownValue", defaultValue: "abc").Length);
}
#nullable disable
[Fact]
public void TextFile()
{
Assert.Equal("test", Resource1.TextFile1);
}
[Fact]
public void BinaryFile()
{
Assert.Equal(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, Resource1.Image1![0..8]);
}
}
|
Add possibility to add department and DepartmentAddDto | 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
{
[HttpGet("")]
public IEnumerable<Department> GetDepartments()
{
return new List<Department>{
new Department {
Id = 1,
Name = "Информационных систем",
ShortName = "ИС"
},
new Department {
Id = 2,
Name = "Информационных технологий и компьютерных систем",
ShortName = "ИТиКС"
},
new Department {
Id = 3,
Name = "Управление в технических системах",
ShortName = "УВТ"
}
};
}
}
}
| 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; }
}
}
|
Test for large binary blobs (more than 8000 bytes), just to be sure it works. | using System;
using NHibernate;
using NUnit.Framework;
namespace NHibernate.Test.TypesTest
{
/// <summary>
/// Summary description for BinaryBlobTypeFixture.
/// </summary>
[TestFixture]
public class BinaryBlobTypeFixture : TypeFixtureBase
{
protected override string TypeName
{
get { return "BinaryBlob"; }
}
[Test]
public void ReadWrite()
{
ISession s = OpenSession();
BinaryBlobClass b = new BinaryBlobClass();
b.BinaryBlob = System.Text.UnicodeEncoding.UTF8.GetBytes("foo/bar/baz");
s.Save(b);
s.Flush();
s.Close();
s = OpenSession();
b = (BinaryBlobClass)s.Load( typeof(BinaryBlobClass), b.Id );
ObjectAssert.AreEqual( System.Text.UnicodeEncoding.UTF8.GetBytes("foo/bar/baz") , b.BinaryBlob );
s.Delete( b );
s.Flush();
s.Close();
}
}
}
| using System;
using NHibernate;
using NUnit.Framework;
namespace NHibernate.Test.TypesTest
{
/// <summary>
/// Summary description for BinaryBlobTypeFixture.
/// </summary>
[TestFixture]
public class BinaryBlobTypeFixture : TypeFixtureBase
{
protected override string TypeName
{
get { return "BinaryBlob"; }
}
[Test]
public void ReadWrite()
{
ISession s = OpenSession();
BinaryBlobClass b = new BinaryBlobClass();
b.BinaryBlob = System.Text.UnicodeEncoding.UTF8.GetBytes("foo/bar/baz");
s.Save(b);
s.Flush();
s.Close();
s = OpenSession();
b = (BinaryBlobClass)s.Load( typeof(BinaryBlobClass), b.Id );
ObjectAssert.AreEqual( System.Text.UnicodeEncoding.UTF8.GetBytes("foo/bar/baz") , b.BinaryBlob );
s.Delete( b );
s.Flush();
s.Close();
}
[Test]
public void ReadWriteLargeBlob()
{
ISession s = OpenSession();
BinaryBlobClass b = new BinaryBlobClass();
b.BinaryBlob = System.Text.UnicodeEncoding.UTF8.GetBytes(new string('T', 10000));
s.Save(b);
s.Flush();
s.Close();
s = OpenSession();
b = (BinaryBlobClass)s.Load( typeof(BinaryBlobClass), b.Id );
ObjectAssert.AreEqual( System.Text.UnicodeEncoding.UTF8.GetBytes(new string('T', 10000)) , b.BinaryBlob );
s.Delete( b );
s.Flush();
s.Close();
}
}
}
|
Set FTBPass to true by default | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Runtime;
using osu.Framework.Caching;
namespace osu.Framework.Configuration
{
public class FrameworkDebugConfigManager : IniConfigManager<DebugSetting>
{
protected override string Filename => null;
public FrameworkDebugConfigManager()
: base(null)
{
}
protected override void InitialiseDefaults()
{
base.InitialiseDefaults();
Set(DebugSetting.ActiveGCMode, GCLatencyMode.SustainedLowLatency);
Set(DebugSetting.BypassCaching, false).ValueChanged += delegate { StaticCached.BypassCache = Get<bool>(DebugSetting.BypassCaching); };
Set(DebugSetting.FTBPass, false);
}
}
public enum DebugSetting
{
ActiveGCMode,
BypassCaching,
FTBPass
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Runtime;
using osu.Framework.Caching;
namespace osu.Framework.Configuration
{
public class FrameworkDebugConfigManager : IniConfigManager<DebugSetting>
{
protected override string Filename => null;
public FrameworkDebugConfigManager()
: base(null)
{
}
protected override void InitialiseDefaults()
{
base.InitialiseDefaults();
Set(DebugSetting.ActiveGCMode, GCLatencyMode.SustainedLowLatency);
Set(DebugSetting.BypassCaching, false).ValueChanged += delegate { StaticCached.BypassCache = Get<bool>(DebugSetting.BypassCaching); };
Set(DebugSetting.FTBPass, true);
}
}
public enum DebugSetting
{
ActiveGCMode,
BypassCaching,
FTBPass
}
}
|
Tweak the hello world test | public static unsafe class Program
{
public static extern void* malloc(ulong size);
public static extern void free(void* data);
public static extern int puts(byte* str);
public static int Main()
{
byte* str = (byte*)malloc(3);
*str = (byte)'h';
*(str + 1) = (byte)'i';
*(str + 2) = (byte)'\0';
puts(str);
free((void*)str);
return 0;
}
} | public static unsafe class Program
{
public static extern void* malloc(ulong size);
public static extern void free(void* data);
public static extern int puts(byte* str);
public static void FillString(byte* str)
{
*str = (byte)'h';
*(str + 1) = (byte)'i';
*(str + 2) = (byte)'\0';
}
public static int Main()
{
byte* str = (byte*)malloc(3);
FillString(str);
puts(str);
free((void*)str);
return 0;
}
} |
Disable error for invalid asmdef reference | using System.Collections.Generic;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.Plugins.Unity.Json.Daemon.Errors;
using JetBrains.ReSharper.Plugins.Unity.Json.Psi.Resolve;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.JavaScript.LanguageImpl.JSon;
using JetBrains.ReSharper.Psi.Resolve;
namespace JetBrains.ReSharper.Plugins.Unity.Json.Daemon.Stages.Resolve
{
[Language(typeof(JsonLanguage))]
public class UnresolvedReferenceErrorHandler : IResolveProblemHighlighter
{
public IHighlighting Run(IReference reference)
{
return new UnresolvedProjectReferenceError(reference);
}
public IEnumerable<ResolveErrorType> ErrorTypes => new[]
{
AsmDefResolveErrorType.ASMDEF_UNRESOLVED_REFERENCED_PROJECT_ERROR
};
}
} | using System.Collections.Generic;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.Plugins.Unity.Json.Daemon.Errors;
using JetBrains.ReSharper.Plugins.Unity.Json.Psi.Resolve;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.JavaScript.LanguageImpl.JSon;
using JetBrains.ReSharper.Psi.Resolve;
namespace JetBrains.ReSharper.Plugins.Unity.Json.Daemon.Stages.Resolve
{
[Language(typeof(JsonLanguage))]
public class UnresolvedReferenceErrorHandler : IResolveProblemHighlighter
{
public IHighlighting Run(IReference reference)
{
// Don't show the error highlight for now - there are too many false positive hits due to references to
// assembly definitions in .asmdef files that are not part of the solution. These files need to be added
// into a custom PSI module to make this work properly. This is a quick fix
// return new UnresolvedProjectReferenceError(reference);
return null;
}
public IEnumerable<ResolveErrorType> ErrorTypes => new[]
{
AsmDefResolveErrorType.ASMDEF_UNRESOLVED_REFERENCED_PROJECT_ERROR
};
}
} |
Add maxWidth Image API 2.1 property | using Newtonsoft.Json;
namespace Digirati.IIIF.Model.Types.ImageApi
{
public class ImageServiceProfile : IProfile
{
[JsonProperty(Order = 1, PropertyName = "formats")]
public string[] Formats { get; set; }
[JsonProperty(Order = 2, PropertyName = "qualities")]
public string[] Qualities { get; set; }
[JsonProperty(Order = 3, PropertyName = "supports")]
public string[] Supports { get; set; }
}
}
| using Newtonsoft.Json;
namespace Digirati.IIIF.Model.Types.ImageApi
{
public class ImageServiceProfile : IProfile
{
[JsonProperty(Order = 1, PropertyName = "formats")]
public string[] Formats { get; set; }
[JsonProperty(Order = 2, PropertyName = "qualities")]
public string[] Qualities { get; set; }
[JsonProperty(Order = 3, PropertyName = "supports")]
public string[] Supports { get; set; }
// 2.1
[JsonProperty(Order = 4, PropertyName = "maxWidth")]
public int MaxWidth { get; set; }
}
}
|
Add debug info to troubleshoot failing test | using System;
using System.Linq;
using System.Net;
using AngleSharp.Dom;
using PreMailer.Net.Downloaders;
namespace PreMailer.Net.Sources
{
public class LinkTagCssSource : ICssSource
{
private readonly Uri _downloadUri;
private string _cssContents;
public LinkTagCssSource(IElement node, Uri baseUri)
{
// There must be an href
var href = node.Attributes.First(a => a.Name.Equals("href", StringComparison.OrdinalIgnoreCase)).Value;
if (Uri.IsWellFormedUriString(href, UriKind.Relative) && baseUri != null)
{
_downloadUri = new Uri(baseUri, href);
}
else
{
// Assume absolute
_downloadUri = new Uri(href);
}
}
public string GetCss()
{
if (IsSupported(_downloadUri.Scheme))
{
try
{
return _cssContents ?? (_cssContents = WebDownloader.SharedDownloader.DownloadString(_downloadUri));
} catch (WebException)
{
throw new WebException($"PreMailer.Net is unable to fetch the requested URL: {_downloadUri}");
}
}
return string.Empty;
}
private static bool IsSupported(string scheme)
{
return
scheme == "http" ||
scheme == "https" ||
scheme == "ftp" ||
scheme == "file";
}
}
} | using System;
using System.Linq;
using System.Net;
using AngleSharp.Dom;
using PreMailer.Net.Downloaders;
namespace PreMailer.Net.Sources
{
public class LinkTagCssSource : ICssSource
{
private readonly Uri _downloadUri;
private string _cssContents;
public LinkTagCssSource(IElement node, Uri baseUri)
{
// There must be an href
var href = node.Attributes.First(a => a.Name.Equals("href", StringComparison.OrdinalIgnoreCase)).Value;
if (Uri.IsWellFormedUriString(href, UriKind.Relative) && baseUri != null)
{
_downloadUri = new Uri(baseUri, href);
}
else
{
// Assume absolute
_downloadUri = new Uri(href);
}
}
public string GetCss()
{
Console.WriteLine($"GetCss scheme: {_downloadUri.Scheme}");
if (IsSupported(_downloadUri.Scheme))
{
try
{
Console.WriteLine($"Will download from '{_downloadUri}' using {WebDownloader.SharedDownloader.GetType()}");
return _cssContents ?? (_cssContents = WebDownloader.SharedDownloader.DownloadString(_downloadUri));
} catch (WebException)
{
throw new WebException($"PreMailer.Net is unable to fetch the requested URL: {_downloadUri}");
}
}
return string.Empty;
}
private static bool IsSupported(string scheme)
{
return
scheme == "http" ||
scheme == "https" ||
scheme == "ftp" ||
scheme == "file";
}
}
} |
Move Kevin's blog to his new domain at powershellexplained.com | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class KevinMarquette : IAmAMicrosoftMVP
{
public string FirstName => "Kevin";
public string LastName => "Marquette";
public string ShortBioOrTagLine => "Sr. DevOps Engineer, 2018 PowerShell Community Hero, Microsoft MVP, and SoCal PowerShell UserGroup Organizer.";
public string StateOrRegion => "Orange County, USA";
public string EmailAddress => "kevmar@gmail.com";
public string TwitterHandle => "kevinmarquette";
public string GitHubHandle => "kevinmarquette";
public string GravatarHash => "d7d29e9573b5da44d9886df24fcc6142";
public GeoPosition Position => new GeoPosition(33.6800000,-117.7900000);
public Uri WebSite => new Uri("https://kevinmarquette.github.io");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://kevinmarquette.github.io/feed.xml"); } }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class KevinMarquette : IAmAMicrosoftMVP
{
public string FirstName => "Kevin";
public string LastName => "Marquette";
public string ShortBioOrTagLine => "Sr. DevOps Engineer, 2018 PowerShell Community Hero, Microsoft MVP, and SoCal PowerShell UserGroup Organizer.";
public string StateOrRegion => "Orange County, USA";
public string EmailAddress => "kevmar@gmail.com";
public string TwitterHandle => "kevinmarquette";
public string GitHubHandle => "kevinmarquette";
public string GravatarHash => "d7d29e9573b5da44d9886df24fcc6142";
public GeoPosition Position => new GeoPosition(33.6800000,-117.7900000);
public Uri WebSite => new Uri("https://PowerShellExplained.com");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://powershellexplained.com/feed.xml"); } }
}
}
|
Return new IDSContext if data is null | using System;
using System.Text;
using System.Web.Security;
using Newtonsoft.Json;
using NLog;
namespace SFA.DAS.EmployerUsers.Web.Authentication
{
public class IdsContext
{
public string ReturnUrl { get; set; }
public string ClientId { get; set; }
public static string CookieName => "IDS";
public static IdsContext ReadFrom(string data)
{
try
{
var unEncData = Encoding.UTF8.GetString(MachineKey.Unprotect(Convert.FromBase64String(data)));
return JsonConvert.DeserializeObject<IdsContext>(unEncData);
}
catch (ArgumentException ex)
{
LogManager.GetCurrentClassLogger().Info(ex, ex.Message);
return new IdsContext();
}
catch (Exception ex)
{
LogManager.GetCurrentClassLogger().Error(ex, ex.Message);
return new IdsContext();
}
}
}
} | using System;
using System.Text;
using System.Web.Security;
using Newtonsoft.Json;
using NLog;
namespace SFA.DAS.EmployerUsers.Web.Authentication
{
public class IdsContext
{
public string ReturnUrl { get; set; }
public string ClientId { get; set; }
public static string CookieName => "IDS";
public static IdsContext ReadFrom(string data)
{
try
{
if (string.IsNullOrEmpty(data))
{
return new IdsContext();
}
var unEncData = Encoding.UTF8.GetString(MachineKey.Unprotect(Convert.FromBase64String(data)));
return JsonConvert.DeserializeObject<IdsContext>(unEncData);
}
catch (ArgumentException ex)
{
LogManager.GetCurrentClassLogger().Info(ex, ex.Message);
return new IdsContext();
}
catch (Exception ex)
{
LogManager.GetCurrentClassLogger().Error(ex, ex.Message);
return new IdsContext();
}
}
}
} |
Print all route information to debug stream (Visual Studio Output panel). | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace AspNetCore.RouteAnalyzer.SampleWebProject
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddRouteAnalyzer();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRouteAnalyzer("/routes");
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics;
namespace AspNetCore.RouteAnalyzer.SampleWebProject
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
private IRouteAnalyzer m_routeAnalyzer;
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddRouteAnalyzer();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
IApplicationLifetime applicationLifetime,
IRouteAnalyzer routeAnalyzer
)
{
m_routeAnalyzer = routeAnalyzer;
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRouteAnalyzer("/routes");
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
// Lifetime events
applicationLifetime.ApplicationStarted.Register(OnStarted);
applicationLifetime.ApplicationStopping.Register(OnStopping);
applicationLifetime.ApplicationStopped.Register(OnStopped);
}
void OnStarted()
{
var infos = m_routeAnalyzer.GetAllRouteInformations();
Debug.WriteLine("======== ALL ROUTE INFORMATION ========");
foreach(var info in infos)
{
Debug.WriteLine(info.ToString());
}
Debug.WriteLine("");
Debug.WriteLine("");
}
void OnStopping()
{
}
void OnStopped()
{
}
}
}
|
Add test coverage for null mod on seeding screen | // 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.Models;
using osu.Game.Tournament.Screens.TeamIntro;
namespace osu.Game.Tournament.Tests.Screens
{
public class TestSceneSeedingScreen : TournamentTestScene
{
[Cached]
private readonly LadderInfo ladder = new LadderInfo();
[BackgroundDependencyLoader]
private void load()
{
Add(new SeedingScreen
{
FillMode = FillMode.Fit,
FillAspectRatio = 16 / 9f
});
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Tournament.Models;
using osu.Game.Tournament.Screens.Ladder.Components;
using osu.Game.Tournament.Screens.TeamIntro;
namespace osu.Game.Tournament.Tests.Screens
{
public class TestSceneSeedingScreen : TournamentTestScene
{
[Cached]
private readonly LadderInfo ladder = new LadderInfo
{
Teams =
{
new TournamentTeam
{
FullName = { Value = @"Japan" },
Acronym = { Value = "JPN" },
SeedingResults =
{
new SeedingResult
{
// Mod intentionally left blank.
Seed = { Value = 4 }
},
new SeedingResult
{
Mod = { Value = "DT" },
Seed = { Value = 8 }
}
}
}
}
};
[Test]
public void TestBasic()
{
AddStep("create seeding screen", () => Add(new SeedingScreen
{
FillMode = FillMode.Fit,
FillAspectRatio = 16 / 9f
}));
AddStep("set team to Japan", () => this.ChildrenOfType<SettingsTeamDropdown>().Single().Current.Value = ladder.Teams.Single());
}
}
}
|
Fix invalid GC latency mode being set | // 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;
using System.Runtime;
using osu.Framework.Allocation;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
namespace osu.Game.Overlays.Settings.Sections.Debug
{
public class GCSettings : SettingsSubsection
{
protected override string Header => "Garbage Collector";
[BackgroundDependencyLoader]
private void load(FrameworkDebugConfigManager config)
{
Children = new Drawable[]
{
new SettingsEnumDropdown<GCLatencyMode>
{
LabelText = "Active mode",
Bindable = config.GetBindable<GCLatencyMode>(DebugSetting.ActiveGCMode)
},
new SettingsButton
{
Text = "Force garbage collection",
Action = GC.Collect
},
};
}
}
}
| // 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;
using System.Runtime;
using osu.Framework.Allocation;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
namespace osu.Game.Overlays.Settings.Sections.Debug
{
public class GCSettings : SettingsSubsection
{
protected override string Header => "Garbage Collector";
private readonly Bindable<LatencyMode> latencyMode = new Bindable<LatencyMode>();
private Bindable<GCLatencyMode> configLatencyMode;
[BackgroundDependencyLoader]
private void load(FrameworkDebugConfigManager config)
{
Children = new Drawable[]
{
new SettingsEnumDropdown<LatencyMode>
{
LabelText = "Active mode",
Bindable = latencyMode
},
new SettingsButton
{
Text = "Force garbage collection",
Action = GC.Collect
},
};
configLatencyMode = config.GetBindable<GCLatencyMode>(DebugSetting.ActiveGCMode);
configLatencyMode.BindValueChanged(v => latencyMode.Value = (LatencyMode)v, true);
latencyMode.BindValueChanged(v => configLatencyMode.Value = (GCLatencyMode)v);
}
private enum LatencyMode
{
Batch = GCLatencyMode.Batch,
Interactive = GCLatencyMode.Interactive,
LowLatency = GCLatencyMode.LowLatency,
SustainedLowLatency = GCLatencyMode.SustainedLowLatency
}
}
}
|
Make _shouldEndSession false rather than null | using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
namespace Alexa.NET.Response
{
public class ResponseBody
{
[JsonProperty("outputSpeech", NullValueHandling = NullValueHandling.Ignore)]
public IOutputSpeech OutputSpeech { get; set; }
[JsonProperty("card", NullValueHandling = NullValueHandling.Ignore)]
public ICard Card { get; set; }
[JsonProperty("reprompt", NullValueHandling = NullValueHandling.Ignore)]
public Reprompt Reprompt { get; set; }
private bool? _shouldEndSession = null;
[JsonProperty("shouldEndSession", NullValueHandling = NullValueHandling.Ignore)]
public bool? ShouldEndSession
{
get
{
var overrideDirectives = Directives?.OfType<IEndSessionDirective>();
if (overrideDirectives == null || !overrideDirectives.Any())
{
return _shouldEndSession;
}
var first = overrideDirectives.First().ShouldEndSession;
if (!overrideDirectives.All(od => od.ShouldEndSession == first))
{
return _shouldEndSession;
}
return first;
}
set => _shouldEndSession = value;
}
[JsonProperty("directives", NullValueHandling = NullValueHandling.Ignore)]
public IList<IDirective> Directives { get; set; } = new List<IDirective>();
public bool ShouldSerializeDirectives()
{
return Directives.Count > 0;
}
}
}
| using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
namespace Alexa.NET.Response
{
public class ResponseBody
{
[JsonProperty("outputSpeech", NullValueHandling = NullValueHandling.Ignore)]
public IOutputSpeech OutputSpeech { get; set; }
[JsonProperty("card", NullValueHandling = NullValueHandling.Ignore)]
public ICard Card { get; set; }
[JsonProperty("reprompt", NullValueHandling = NullValueHandling.Ignore)]
public Reprompt Reprompt { get; set; }
private bool? _shouldEndSession = false;
[JsonProperty("shouldEndSession", NullValueHandling = NullValueHandling.Ignore)]
public bool? ShouldEndSession
{
get
{
var overrideDirectives = Directives?.OfType<IEndSessionDirective>();
if (overrideDirectives == null || !overrideDirectives.Any())
{
return _shouldEndSession;
}
var first = overrideDirectives.First().ShouldEndSession;
if (!overrideDirectives.All(od => od.ShouldEndSession == first))
{
return _shouldEndSession;
}
return first;
}
set => _shouldEndSession = value;
}
[JsonProperty("directives", NullValueHandling = NullValueHandling.Ignore)]
public IList<IDirective> Directives { get; set; } = new List<IDirective>();
public bool ShouldSerializeDirectives()
{
return Directives.Count > 0;
}
}
}
|
Make the language XML file optional | using System.Collections.Generic;
using System.Xml;
namespace PROProtocol
{
public class Language
{
private Dictionary<string, string> _texts;
public Language()
{
XmlDocument xml = new XmlDocument();
xml.Load("Resources/Lang.xml");
_texts = new Dictionary<string, string>();
XmlNode languageNode = xml.DocumentElement.GetElementsByTagName("English")[0];
if (languageNode != null)
{
foreach (XmlElement textNode in languageNode)
{
_texts.Add(textNode.GetAttribute("name"), textNode.InnerText);
}
}
}
public string GetText(string name)
{
return _texts[name];
}
public string Replace(string originalText)
{
if (originalText.IndexOf('$') != -1)
{
foreach (var text in _texts)
{
originalText = originalText.Replace("$" + text.Key, text.Value);
}
}
return originalText;
}
}
}
| using System.Collections.Generic;
using System.IO;
using System.Xml;
namespace PROProtocol
{
public class Language
{
private const string FileName = "Resources/Lang.xml";
private Dictionary<string, string> _texts = new Dictionary<string, string>();
public Language()
{
if (File.Exists(FileName))
{
XmlDocument xml = new XmlDocument();
xml.Load(FileName);
LoadXmlDocument(xml);
}
}
private void LoadXmlDocument(XmlDocument xml)
{
XmlNode languageNode = xml.DocumentElement.GetElementsByTagName("English")[0];
if (languageNode != null)
{
foreach (XmlElement textNode in languageNode)
{
_texts.Add(textNode.GetAttribute("name"), textNode.InnerText);
}
}
}
public string GetText(string name)
{
return _texts[name];
}
public string Replace(string originalText)
{
if (originalText.IndexOf('$') != -1)
{
foreach (var text in _texts)
{
originalText = originalText.Replace("$" + text.Key, text.Value);
}
}
return originalText;
}
}
}
|
Use explicit type to cast back to SampleType. | using Ploeh.AutoFixture.Xunit;
using Xunit;
using Xunit.Extensions;
namespace BobTheBuilder.Tests
{
public class BuildFacts
{
[Fact]
public void CreateADynamicInstanceOfTheRequestedType()
{
var sut = A.BuilderFor<SampleType>();
var result = sut.Build();
Assert.IsAssignableFrom<dynamic>(result);
Assert.IsAssignableFrom<SampleType>(result);
}
[Theory, AutoData]
public void SetStringStateByName(string expected)
{
var sut = A.BuilderFor<SampleType>();
sut.WithStringProperty(expected);
var result = sut.Build();
Assert.Equal(expected, result.StringProperty);
}
}
}
| using Ploeh.AutoFixture.Xunit;
using Xunit;
using Xunit.Extensions;
namespace BobTheBuilder.Tests
{
public class BuildFacts
{
[Fact]
public void CreateADynamicInstanceOfTheRequestedType()
{
var sut = A.BuilderFor<SampleType>();
var result = sut.Build();
Assert.IsAssignableFrom<dynamic>(result);
Assert.IsAssignableFrom<SampleType>(result);
}
[Theory, AutoData]
public void SetStringStateByName(string expected)
{
var sut = A.BuilderFor<SampleType>();
sut.WithStringProperty(expected);
SampleType result = sut.Build();
Assert.Equal(expected, result.StringProperty);
}
}
}
|
Fix path to annotations in tests | using System;
using System.Collections.Generic;
using JetBrains.Application;
using JetBrains.Diagnostics;
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, VirtualFileSystemPath> myAnnotations;
public AnnotationsLoader()
{
myAnnotations = new OneToSetMap<string, VirtualFileSystemPath>(StringComparer.OrdinalIgnoreCase);
var testDataPathBase = TestUtil.GetTestDataPathBase(GetType().Assembly).ToVirtualFileSystemPath();
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<VirtualFileSystemPath> GetAnnotationsFiles(AssemblyNameInfo assemblyName = null, VirtualFileSystemPath assemblyLocation = null)
{
if (assemblyName == null)
return myAnnotations.Values;
return myAnnotations[assemblyName.Name];
}
}
} | using System;
using System.Collections.Generic;
using JetBrains.Application;
using JetBrains.Diagnostics;
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, VirtualFileSystemPath> myAnnotations;
public AnnotationsLoader()
{
myAnnotations = new OneToSetMap<string, VirtualFileSystemPath>(StringComparer.OrdinalIgnoreCase);
var testDataPathBase = TestUtil.GetTestDataPathBase(GetType().Assembly).ToVirtualFileSystemPath();
var annotationsPath = testDataPathBase.Parent.Parent / "src" / "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<VirtualFileSystemPath> GetAnnotationsFiles(AssemblyNameInfo assemblyName = null, VirtualFileSystemPath assemblyLocation = null)
{
if (assemblyName == null)
return myAnnotations.Values;
return myAnnotations[assemblyName.Name];
}
}
} |
Add a playback state property to the playlist | using System.Collections.ObjectModel;
namespace Espera.Network
{
public class NetworkPlaylist
{
public int? CurrentIndex { get; set; }
public string Name { get; set; }
public int? RemainingVotes { get; set; }
public ReadOnlyCollection<NetworkSong> Songs { get; set; }
}
} | using System.Collections.ObjectModel;
namespace Espera.Network
{
public class NetworkPlaylist
{
public int? CurrentIndex { get; set; }
public string Name { get; set; }
public NetworkPlaybackState PlaybackState { get; set; }
public int? RemainingVotes { get; set; }
public ReadOnlyCollection<NetworkSong> Songs { get; set; }
}
} |
Fix bug about not redirecting to forums | using JoinRpg.DataModel;
using JoinRpg.Domain;
using Microsoft.AspNetCore.Mvc;
namespace JoinRpg.Portal.Controllers.Comments
{
internal static class CommentRedirectHelper
{
public static ActionResult RedirectToDiscussion(IUrlHelper Url, CommentDiscussion discussion, int? commentId = null)
{
var extra = commentId != null ? $"#comment{commentId}" : null;
var claim = discussion.GetClaim();
if (claim != null)
{
var actionLink = Url.Action("Edit", "Claim", new { claim.ClaimId, discussion.ProjectId });
return new RedirectResult(actionLink + extra);
}
var forumThread = discussion.GetForumThread();
if (forumThread != null)
{
var actionLink = Url.Action("ViewThread", new { discussion.ProjectId, forumThread.ForumThreadId });
return new RedirectResult(actionLink + extra);
}
return new NotFoundResult();
}
}
}
| using JoinRpg.DataModel;
using JoinRpg.Domain;
using Microsoft.AspNetCore.Mvc;
namespace JoinRpg.Portal.Controllers.Comments
{
internal static class CommentRedirectHelper
{
public static ActionResult RedirectToDiscussion(IUrlHelper Url, CommentDiscussion discussion, int? commentId = null)
{
var extra = commentId != null ? $"#comment{commentId}" : null;
var claim = discussion.GetClaim();
if (claim != null)
{
var actionLink = Url.Action("Edit", "Claim", new { claim.ClaimId, discussion.ProjectId });
return new RedirectResult(actionLink + extra);
}
var forumThread = discussion.GetForumThread();
if (forumThread != null)
{
var actionLink = Url.Action("ViewThread", "Forum", new { discussion.ProjectId, forumThread.ForumThreadId });
return new RedirectResult(actionLink + extra);
}
return new NotFoundResult();
}
}
}
|
Revert assembly version and assembly file version back to 0.2.0.0 | //
// Copyright (c) Microsoft. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System.Reflection;
using System.Resources;
[assembly: AssemblyTitle("Microsoft Azure Cognitive Services Management Library")]
[assembly: AssemblyDescription("Provides Microsoft Azure Cognitive Services management functions for managing Microsoft Azure Cognitive Services accounts.")]
[assembly: AssemblyVersion("0.2.1.0")]
[assembly: AssemblyFileVersion("0.2.1.0")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Microsoft Azure .NET SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
| //
// Copyright (c) Microsoft. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System.Reflection;
using System.Resources;
[assembly: AssemblyTitle("Microsoft Azure Cognitive Services Management Library")]
[assembly: AssemblyDescription("Provides Microsoft Azure Cognitive Services management functions for managing Microsoft Azure Cognitive Services accounts.")]
[assembly: AssemblyVersion("0.2.0.0")]
[assembly: AssemblyFileVersion("0.2.0.0")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Microsoft Azure .NET SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
|
Introduce EndOffset to Analyze token | using Newtonsoft.Json;
namespace Nest
{
[JsonObject]
public class AnalyzeToken
{
[JsonProperty(PropertyName = "token")]
public string Token { get; internal set; }
[JsonProperty(PropertyName = "type")]
public string Type { get; internal set; }
//TODO change to long in 6.0
[JsonProperty(PropertyName = "start_offset")]
public int StartOffset { get; internal set; }
[JsonProperty(PropertyName = "end_offset")]
public int EndPostion { get; internal set; }
[JsonProperty(PropertyName = "position")]
public int Position { get; internal set; }
[JsonProperty(PropertyName = "position_length")]
public long? PositionLength { get; internal set; }
}
}
| using System;
using Newtonsoft.Json;
namespace Nest
{
[JsonObject]
public class AnalyzeToken
{
[JsonProperty("token")]
public string Token { get; internal set; }
[JsonProperty("type")]
public string Type { get; internal set; }
//TODO change to long in 6.0... RC: (this is int in Elasticsearch codebase)
[JsonProperty("start_offset")]
public int StartOffset { get; internal set; }
[JsonProperty("end_offset")]
public int EndOffset { get; internal set; }
[JsonProperty("position")]
public int Position { get; internal set; }
[JsonProperty("position_length")]
public long? PositionLength { get; internal set; }
}
}
|
Remove Restrictions on search endpoint | using System;
using System.Linq;
using FluentValidation;
using SFA.DAS.CommitmentsV2.Models;
namespace SFA.DAS.CommitmentsV2.Application.Queries.GetApprenticeships
{
public class GetApprenticeshipsQueryValidator : AbstractValidator<GetApprenticeshipsQuery>
{
public GetApprenticeshipsQueryValidator()
{
Unless(request => request.EmployerAccountId.HasValue && request.EmployerAccountId.Value > 0, () =>
{
RuleFor(request => request.ProviderId)
.Must(id => id.HasValue && id.Value > 0)
.WithMessage("The provider id must be set");
});
Unless(request => request.ProviderId.HasValue && request.ProviderId.Value > 0, () =>
{
RuleFor(request => request.EmployerAccountId)
.Must(id => id.HasValue && id.Value > 0)
.WithMessage("The employer account id must be set");
});
When(request => request.ProviderId.HasValue && request.EmployerAccountId.HasValue, () =>
{
Unless(request => request.EmployerAccountId.Value == 0, () =>
{
RuleFor(request => request.ProviderId)
.Must(id => id.Value == 0)
.WithMessage("The provider id must be zero if employer account id is set");
});
Unless(request => request.ProviderId.Value == 0, () =>
{
RuleFor(request => request.EmployerAccountId)
.Must(id => id.Value == 0)
.WithMessage("The employer account id must be zero if provider id is set");
});
});
RuleFor(request => request.SortField)
.Must(field => string.IsNullOrEmpty(field) ||
typeof(Apprenticeship).GetProperties().Select(c => c.Name).Contains(field) ||
typeof(Cohort).GetProperties().Select(c => c.Name).Contains(field) ||
typeof(AccountLegalEntity).GetProperties().Select(c => c.Name).Contains(field) ||
field.Equals("ProviderName", StringComparison.CurrentCultureIgnoreCase))
.WithMessage("Sort field must be empty or property on Apprenticeship ");
}
}
}
| using System;
using System.Linq;
using FluentValidation;
using SFA.DAS.CommitmentsV2.Models;
namespace SFA.DAS.CommitmentsV2.Application.Queries.GetApprenticeships
{
public class GetApprenticeshipsQueryValidator : AbstractValidator<GetApprenticeshipsQuery>
{
public GetApprenticeshipsQueryValidator()
{
RuleFor(request => request.SortField)
.Must(field => string.IsNullOrEmpty(field) ||
typeof(Apprenticeship).GetProperties().Select(c => c.Name).Contains(field) ||
typeof(Cohort).GetProperties().Select(c => c.Name).Contains(field) ||
typeof(AccountLegalEntity).GetProperties().Select(c => c.Name).Contains(field) ||
field.Equals("ProviderName", StringComparison.CurrentCultureIgnoreCase))
.WithMessage("Sort field must be empty or property on Apprenticeship ");
}
}
}
|
Remove form Fields from Container Edit | @model Portal.CMS.Web.Areas.Builder.ViewModels.Container.EditViewModel
@{
Layout = "";
}
<script type="text/javascript">
function Delete()
{
$('#@Model.ContainerElementId').remove();
var dataParams = { "pageSectionId": @Model.PageSectionId , "componentId": "@Model.ContainerElementId", "__RequestVerificationToken": $('input[name=__RequestVerificationToken]').val() };
$('#container-editor-' + @Model.PageSectionId).fadeOut();
$.ajax({
data: dataParams,
type: 'POST',
cache: false,
url: '@Url.Action("Delete", "Component", new { area = "Builder" })',
success: function (data) {
if (data.State === false)
{
alert("Error: The document has lost synchronisation. Reloading document...");
location.reload();
}
},
});
}
</script>
@using (Html.BeginForm("Edit", "Container", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(x => x.PageSectionId)
@Html.HiddenFor(x => x.ContainerElementId)
<br />
<div class="footer">
<button class="btn primary">Save</button>
<a onclick="Delete()" data-dismiss="modal" class="btn delete">Delete</a>
<button class="btn" data-dismiss="modal">Cancel</button>
</div>
} | @model Portal.CMS.Web.Areas.Builder.ViewModels.Container.EditViewModel
@{
Layout = "";
}
<script type="text/javascript">
function Delete()
{
$('#@Model.ContainerElementId').remove();
var dataParams = { "pageSectionId": @Model.PageSectionId , "componentId": "@Model.ContainerElementId", "__RequestVerificationToken": $('input[name=__RequestVerificationToken]').val() };
$('#container-editor-' + @Model.PageSectionId).fadeOut();
$.ajax({
data: dataParams,
type: 'POST',
cache: false,
url: '@Url.Action("Delete", "Component", new { area = "Builder" })',
success: function (data) {
if (data.State === false)
{
alert("Error: The document has lost synchronisation. Reloading document...");
location.reload();
}
},
});
}
</script>
<br />
<div class="footer">
<a onclick="Delete()" data-dismiss="modal" class="btn delete">Delete</a>
<button class="btn" data-dismiss="modal">Cancel</button>
</div> |
Test for accelerating whilst falling now passes | using UnityEngine;
using System.Collections.Generic;
public class PlayerMovement
{
private const float Gravity = -1.0f;
public bool IsOnGround { get; set; }
public Vector3 Update()
{
if (IsOnGround)
{
return Vector2.zero;
}
return new Vector3(0.0f, Gravity);
}
} | using UnityEngine;
using System.Collections.Generic;
public class PlayerMovement
{
private const float Gravity = -1.0f;
public bool IsOnGround { get; set; }
private Vector3 currentVelocity;
public Vector3 Update()
{
if (IsOnGround)
{
return Vector2.zero;
}
currentVelocity += new Vector3(0.0f, Gravity);
return currentVelocity;
}
} |
Align .NET4 assembly version with main project | using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("Eve.NET.Net4")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("CIR 2000")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("nicola")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("Eve.NET.Net4")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("CIR 2000")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("nicola")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("0.1.0.1")]
[assembly: AssemblyFileVersion("0.1.0.1")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
|
Fix code quality for CI | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Localisation;
using osu.Game.Graphics.UserInterfaceV2;
using osu.Game.Localisation;
namespace osu.Game.Screens.Edit.Setup
{
internal class ColoursSection : SetupSection
{
public override LocalisableString Title => EditorSetupStrings.ColoursHeader;
private LabelledColourPalette comboColours;
[BackgroundDependencyLoader]
private void load()
{
Children = new Drawable[]
{
comboColours = new LabelledColourPalette
{
Label = EditorSetupStrings.HitcircleSliderCombos,
FixedLabelWidth = LABEL_WIDTH,
ColourNamePrefix = EditorSetupStrings.ComboColourPrefix }
};
if (Beatmap.BeatmapSkin != null)
comboColours.Colours.BindTo(Beatmap.BeatmapSkin.ComboColours);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Localisation;
using osu.Game.Graphics.UserInterfaceV2;
using osu.Game.Localisation;
namespace osu.Game.Screens.Edit.Setup
{
internal class ColoursSection : SetupSection
{
public override LocalisableString Title => EditorSetupStrings.ColoursHeader;
private LabelledColourPalette comboColours;
[BackgroundDependencyLoader]
private void load()
{
Children = new Drawable[]
{
comboColours = new LabelledColourPalette
{
Label = EditorSetupStrings.HitcircleSliderCombos,
FixedLabelWidth = LABEL_WIDTH,
ColourNamePrefix = EditorSetupStrings.ComboColourPrefix
}
};
if (Beatmap.BeatmapSkin != null)
comboColours.Colours.BindTo(Beatmap.BeatmapSkin.ComboColours);
}
}
}
|
Add locations to allow scopes to dictionary | using IdentityModel.Client;
using System;
using System.Collections.Generic;
namespace eShopOnContainers.Core.Services.Identity
{
public class IdentityService : IIdentityService
{
public string CreateAuthorizationRequest()
{
// Create URI to authorization endpoint
var authorizeRequest = new AuthorizeRequest(GlobalSetting.Instance.IdentityEndpoint);
// Dictionary with values for the authorize request
var dic = new Dictionary<string, string>();
dic.Add("client_id", "xamarin");
dic.Add("client_secret", "secret");
dic.Add("response_type", "code id_token token");
dic.Add("scope", "openid profile basket orders offline_access");
dic.Add("redirect_uri", GlobalSetting.Instance.IdentityCallback);
dic.Add("nonce", Guid.NewGuid().ToString("N"));
// Add CSRF token to protect against cross-site request forgery attacks.
var currentCSRFToken = Guid.NewGuid().ToString("N");
dic.Add("state", currentCSRFToken);
var authorizeUri = authorizeRequest.Create(dic);
return authorizeUri;
}
public string CreateLogoutRequest(string token)
{
if(string.IsNullOrEmpty(token))
{
return string.Empty;
}
return string.Format("{0}?id_token_hint={1}&post_logout_redirect_uri={2}",
GlobalSetting.Instance.LogoutEndpoint,
token,
GlobalSetting.Instance.LogoutCallback);
}
}
}
| using IdentityModel.Client;
using System;
using System.Collections.Generic;
namespace eShopOnContainers.Core.Services.Identity
{
public class IdentityService : IIdentityService
{
public string CreateAuthorizationRequest()
{
// Create URI to authorization endpoint
var authorizeRequest = new AuthorizeRequest(GlobalSetting.Instance.IdentityEndpoint);
// Dictionary with values for the authorize request
var dic = new Dictionary<string, string>();
dic.Add("client_id", "xamarin");
dic.Add("client_secret", "secret");
dic.Add("response_type", "code id_token token");
dic.Add("scope", "openid profile basket orders locations offline_access");
dic.Add("redirect_uri", GlobalSetting.Instance.IdentityCallback);
dic.Add("nonce", Guid.NewGuid().ToString("N"));
// Add CSRF token to protect against cross-site request forgery attacks.
var currentCSRFToken = Guid.NewGuid().ToString("N");
dic.Add("state", currentCSRFToken);
var authorizeUri = authorizeRequest.Create(dic);
return authorizeUri;
}
public string CreateLogoutRequest(string token)
{
if(string.IsNullOrEmpty(token))
{
return string.Empty;
}
return string.Format("{0}?id_token_hint={1}&post_logout_redirect_uri={2}",
GlobalSetting.Instance.LogoutEndpoint,
token,
GlobalSetting.Instance.LogoutCallback);
}
}
}
|
Update ai/navmesh agents to stop pursuing during content display state. | using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Engine.Game.Actor {
public class NavMeshAgentFollowController : MonoBehaviour {
public NavMeshAgent agent;
public Transform targetFollow;
// Use this for initialization
private void Start() {
agent = GetComponent<NavMeshAgent>();
NavigateToDestination();
}
public void NavigateToDestination() {
if (agent != null) {
if (targetFollow != null) {
float distance = Vector3.Distance(agent.destination, targetFollow.position);
if (distance < 5) {
agent.Stop();
}
else {
agent.destination = targetFollow.position;
}
}
}
}
// Update is called once per frame
private void Update() {
if (agent != null) {
if (agent.remainingDistance == 0 || agent.isPathStale) {
NavigateToDestination();
}
}
}
}
} | using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Engine.Game.Actor {
public class NavMeshAgentFollowController : MonoBehaviour {
public NavMeshAgent agent;
public Transform targetFollow;
// Use this for initialization
private void Start() {
agent = GetComponent<NavMeshAgent>();
NavigateToDestination();
}
public void NavigateToDestination() {
if (agent != null) {
if (targetFollow != null) {
float distance = Vector3.Distance(agent.destination, targetFollow.position);
if (distance < 5) {
agent.Stop();
}
else {
agent.destination = targetFollow.position;
}
}
}
}
// Update is called once per frame
private void Update() {
if(!GameConfigs.isGameRunning) {
if (agent != null) {
agent.Stop();
}
return;
}
if (agent != null) {
if (agent.remainingDistance == 0 || agent.isPathStale) {
NavigateToDestination();
}
}
}
}
} |
Call ShowPlayPauseControls and ShowNavigationControls setters in base constructor | using System;
using System.Collections.Generic;
using System.Text;
namespace MediaManager
{
public abstract class NotificationManagerBase : INotificationManager
{
protected NotificationManagerBase()
{
Enabled = true;
}
private bool _enabled = true;
private bool _showPlayPauseControls = true;
private bool _showNavigationControls = true;
public virtual bool Enabled
{
get => _enabled;
set
{
_enabled = value;
UpdateNotification();
}
}
public virtual bool ShowPlayPauseControls
{
get => _showPlayPauseControls;
set
{
_showPlayPauseControls = value;
UpdateNotification();
}
}
public virtual bool ShowNavigationControls
{
get => _showNavigationControls;
set
{
_showNavigationControls = value;
UpdateNotification();
}
}
public abstract void UpdateNotification();
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace MediaManager
{
public abstract class NotificationManagerBase : INotificationManager
{
protected NotificationManagerBase()
{
Enabled = true;
ShowPlayPauseControls = true;
ShowNavigationControls = true;
}
private bool _enabled;
private bool _showPlayPauseControls;
private bool _showNavigationControls;
public virtual bool Enabled
{
get => _enabled;
set
{
_enabled = value;
UpdateNotification();
}
}
public virtual bool ShowPlayPauseControls
{
get => _showPlayPauseControls;
set
{
_showPlayPauseControls = value;
UpdateNotification();
}
}
public virtual bool ShowNavigationControls
{
get => _showNavigationControls;
set
{
_showNavigationControls = value;
UpdateNotification();
}
}
public abstract void UpdateNotification();
}
}
|
Update Authorize attribute to use Bearer policy | using LearnWordsFast.API.Exceptions;
using LearnWordsFast.API.Services;
using LearnWordsFast.API.ViewModels.TrainingController;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace LearnWordsFast.API.Controllers
{
[Route("api/Training")]
[Authorize]
public class TrainingController : ApiController
{
private readonly ITrainingService _trainingService;
private readonly ILogger<TrainingController> _log;
public TrainingController(
ITrainingService trainingService,
ILogger<TrainingController> log)
{
_trainingService = trainingService;
_log = log;
}
[HttpGet]
public IActionResult Get()
{
_log.LogInformation("Get next training");
var training = _trainingService.CreateTraining(UserId);
if (training == null)
{
return NotFound();
}
return Ok(training);
}
[HttpPost]
public IActionResult Finish([FromBody]TrainingResultViewModel[] results)
{
_log.LogInformation("Finish training");
foreach (var result in results)
{
try
{
_trainingService.FinishTraining(UserId, result);
}
catch (NotFoundException)
{
return NotFound(result.WordId);
}
}
return Ok();
}
}
} | using LearnWordsFast.API.Exceptions;
using LearnWordsFast.API.Services;
using LearnWordsFast.API.ViewModels.TrainingController;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace LearnWordsFast.API.Controllers
{
[Route("api/Training")]
[Authorize("Bearer")]
public class TrainingController : ApiController
{
private readonly ITrainingService _trainingService;
private readonly ILogger<TrainingController> _log;
public TrainingController(
ITrainingService trainingService,
ILogger<TrainingController> log)
{
_trainingService = trainingService;
_log = log;
}
[HttpGet]
public IActionResult Get()
{
_log.LogInformation("Get next training");
var training = _trainingService.CreateTraining(UserId);
if (training == null)
{
return NotFound();
}
return Ok(training);
}
[HttpPost]
public IActionResult Finish([FromBody]TrainingResultViewModel[] results)
{
_log.LogInformation("Finish training");
foreach (var result in results)
{
try
{
_trainingService.FinishTraining(UserId, result);
}
catch (NotFoundException)
{
return NotFound(result.WordId);
}
}
return Ok();
}
}
} |
Use Pascal casing for method name | using System;
using System.Collections.Generic;
namespace WinRSJS
{
public sealed class Collections
{
static public object /* IMap<?, ?> */ createMap(string keyTypeName, string valTypeName)
{
Type typeKey = Type.GetType(keyTypeName);
if (typeKey == null)
{
throw new ArgumentException("Key type name `" + keyTypeName + "` is invalid.");
}
Type typeVal = Type.GetType(valTypeName);
if (typeVal == null)
{
throw new ArgumentException("Value type name `" + valTypeName + "` is invalid.");
}
Type typeDict = typeof(Dictionary<,>).MakeGenericType(new Type[] { typeKey, typeVal });
return Activator.CreateInstance(typeDict);
}
}
}
| using System;
using System.Collections.Generic;
namespace WinRSJS
{
public sealed class Collections
{
static public object /* IMap<?, ?> */ CreateMap(string keyTypeName, string valTypeName)
{
Type typeKey = Type.GetType(keyTypeName);
if (typeKey == null)
{
throw new ArgumentException("Key type name `" + keyTypeName + "` is invalid.");
}
Type typeVal = Type.GetType(valTypeName);
if (typeVal == null)
{
throw new ArgumentException("Value type name `" + valTypeName + "` is invalid.");
}
Type typeDict = typeof(Dictionary<,>).MakeGenericType(new Type[] { typeKey, typeVal });
return Activator.CreateInstance(typeDict);
}
}
}
|
Add more supported image extensions to the image viewer plugin. | using System.IO;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using NuGetPackageExplorer.Types;
namespace PackageExplorer {
[PackageContentViewerMetadata(99, ".jpg", ".gif", ".png", ".tif")]
internal class ImageFileViewer : IPackageContentViewer {
public object GetView(string extension, Stream stream) {
var source = new BitmapImage();
source.BeginInit();
source.CacheOption = BitmapCacheOption.OnLoad;
source.StreamSource = stream;
source.EndInit();
return new Image {
Source = source,
Width = source.Width,
Height = source.Height
};
}
}
} | using System.IO;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using NuGetPackageExplorer.Types;
namespace PackageExplorer {
[PackageContentViewerMetadata(99, ".jpg", ".gif", ".png", ".tif", ".bmp", ".ico")]
internal class ImageFileViewer : IPackageContentViewer {
public object GetView(string extension, Stream stream) {
var source = new BitmapImage();
source.BeginInit();
source.CacheOption = BitmapCacheOption.OnLoad;
source.StreamSource = stream;
source.EndInit();
return new Image {
Source = source,
Width = source.Width,
Height = source.Height
};
}
}
} |
Clear all view engines and add only Razor view engine (performance) | using AnimalHope.Web.Infrastructure.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace AnimalHope.Web
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AutoMapperConfig.Execute();
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
| using AnimalHope.Web.Infrastructure.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace AnimalHope.Web
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new RazorViewEngine());
AutoMapperConfig.Execute();
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
|
Load environment variables from different targets to support ASP.Net applications. | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Archaius
{
public class EnvironmentConfiguration : DictionaryConfiguration
{
public EnvironmentConfiguration()
: base(GetEnvironmentVariables())
{
}
public override void AddProperty(string key, object value)
{
throw new NotSupportedException("EnvironmentConfiguration is readonly.");
}
public override void SetProperty(string key, object value)
{
throw new NotSupportedException("EnvironmentConfiguration is readonly.");
}
public override void ClearProperty(string key)
{
throw new NotSupportedException("EnvironmentConfiguration is readonly.");
}
public override void Clear()
{
throw new NotSupportedException("EnvironmentConfiguration is readonly.");
}
private static IDictionary<string, object> GetEnvironmentVariables()
{
return Environment.GetEnvironmentVariables()
.Cast<DictionaryEntry>()
.ToDictionary(variable => (string)variable.Key, variable => variable.Value);
}
}
} | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Archaius
{
public class EnvironmentConfiguration : DictionaryConfiguration
{
public EnvironmentConfiguration()
: base(GetEnvironmentVariables())
{
}
public override void AddProperty(string key, object value)
{
throw new NotSupportedException("EnvironmentConfiguration is readonly.");
}
public override void SetProperty(string key, object value)
{
throw new NotSupportedException("EnvironmentConfiguration is readonly.");
}
public override void ClearProperty(string key)
{
throw new NotSupportedException("EnvironmentConfiguration is readonly.");
}
public override void Clear()
{
throw new NotSupportedException("EnvironmentConfiguration is readonly.");
}
private static IDictionary<string, object> GetEnvironmentVariables()
{
var variables = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Process)
.Cast<DictionaryEntry>()
.ToDictionary(variable => (string)variable.Key, variable => variable.Value);
foreach (DictionaryEntry userVariable in Environment.GetEnvironmentVariables(EnvironmentVariableTarget.User))
{
if (!variables.ContainsKey((string)userVariable.Key))
{
variables.Add((string)userVariable.Key, userVariable.Value);
}
}
foreach (DictionaryEntry machineVariable in Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Machine))
{
if (!variables.ContainsKey((string)machineVariable.Key))
{
variables.Add((string)machineVariable.Key, machineVariable.Value);
}
}
return variables;
}
}
} |
Revert "Add failing test case" | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Catch.Skinning.Legacy;
using osu.Game.Skinning;
using osu.Game.Tests.Visual;
namespace osu.Game.Rulesets.Catch.Tests
{
[TestFixture]
public class TestSceneCatchPlayerLegacySkin : LegacySkinPlayerTestScene
{
[Test]
public void TestUsingLegacySkin()
{
// check for the existence of a random legacy component to ensure using legacy skin.
// this should exist in LegacySkinPlayerTestScene but the weird transformer logic below needs to be "fixed" or otherwise first.
AddAssert("using legacy skin", () => this.ChildrenOfType<LegacyScoreCounter>().Any());
}
protected override Ruleset CreatePlayerRuleset() => new TestCatchRuleset();
private class TestCatchRuleset : CatchRuleset
{
public override ISkin CreateLegacySkinProvider(ISkinSource source, IBeatmap beatmap) => new TestCatchLegacySkinTransformer(source);
}
private class TestCatchLegacySkinTransformer : CatchLegacySkinTransformer
{
public TestCatchLegacySkinTransformer(ISkinSource source)
: base(source)
{
}
public override Drawable GetDrawableComponent(ISkinComponent component)
{
var drawable = base.GetDrawableComponent(component);
if (drawable != null)
return drawable;
// it shouldn't really matter whether to return null or return this,
// but returning null skips over the beatmap skin, so this needs to exist to test things properly.
return Source.GetDrawableComponent(component);
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Game.Tests.Visual;
namespace osu.Game.Rulesets.Catch.Tests
{
[TestFixture]
public class TestSceneCatchPlayerLegacySkin : LegacySkinPlayerTestScene
{
protected override Ruleset CreatePlayerRuleset() => new CatchRuleset();
}
}
|
Add contracts to verifty the DrawModel() method doesn't receive null data. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace MonoGameUtils.Drawing
{
/// <summary>
/// Various useful utility methods that don't obviously go elsewhere.
/// </summary>
public static class Utilities
{
/// <summary>
/// Draw the provided model in the world, given the provided matrices.
/// </summary>
/// <param name="model">The model to draw.</param>
/// <param name="world">The world matrix that the model should be drawn in.</param>
/// <param name="view">The view matrix that the model should be drawn in.</param>
/// <param name="projection">The projection matrix that the model should be drawn in.</param>
public static void DrawModel(Model model, Matrix world, Matrix view, Matrix projection)
{
foreach (ModelMesh mesh in model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = world;
effect.View = view;
effect.Projection = projection;
}
mesh.Draw();
}
}
}
} | using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace MonoGameUtils.Drawing
{
/// <summary>
/// Various useful utility methods that don't obviously go elsewhere.
/// </summary>
public static class Utilities
{
/// <summary>
/// Draw the provided model in the world, given the provided matrices.
/// </summary>
/// <param name="model">The model to draw.</param>
/// <param name="world">The world matrix that the model should be drawn in.</param>
/// <param name="view">The view matrix that the model should be drawn in.</param>
/// <param name="projection">The projection matrix that the model should be drawn in.</param>
public static void DrawModel(Model model, Matrix world, Matrix view, Matrix projection)
{
Contract.Requires(model != null);
Contract.Requires(world != null);
Contract.Requires(view != null);
Contract.Requires(projection != null);
foreach (ModelMesh mesh in model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = world;
effect.View = view;
effect.Projection = projection;
}
mesh.Draw();
}
}
}
} |
Clean up and add comments |
using System.Collections.Generic;
using LinqToTTreeInterfacesLib;
namespace LINQToTTreeLib.Statements
{
/// <summary>
/// Sits inside a loop and records the integer that it is given on each call by pushing it onto a vector. It *does not*
/// check for uniqueness.
/// </summary>
class StatementRecordIndicies : IStatement
{
private LinqToTTreeInterfacesLib.IValue iValue;
private Variables.VarArray arrayRecord;
/// <summary>
/// Create a statement that will record this index into this array each time through.
/// </summary>
/// <param name="iValue"></param>
/// <param name="arrayRecord"></param>
public StatementRecordIndicies(IValue iValue, Variables.VarArray arrayRecord)
{
// TODO: Complete member initialization
this.iValue = iValue;
this.arrayRecord = arrayRecord;
}
/// <summary>
/// Returns a IValue that represents
/// </summary>
public IValue HolderArray { get; private set; }
/// <summary>
/// Return the code for this statement.
/// </summary>
/// <returns></returns>
public IEnumerable<string> CodeItUp()
{
yield return string.Format("{0}.push_back({1});", arrayRecord.RawValue, iValue.RawValue);
}
}
}
|
using System.Collections.Generic;
using LinqToTTreeInterfacesLib;
using LINQToTTreeLib.Variables;
namespace LINQToTTreeLib.Statements
{
/// <summary>
/// Sits inside a loop and records the integer that it is given on each call by pushing it onto a vector. It *does not*
/// check for uniqueness of that integer that is pushed on - this is pretty simple. The vector it is pushing onto should
/// be declared at an outter level to be of any use. :-)
/// </summary>
class StatementRecordIndicies : IStatement
{
/// <summary>
/// The integer to record
/// </summary>
private IValue _intToRecord;
/// <summary>
/// The array to be storing things in
/// </summary>
private Variables.VarArray _storageArray;
/// <summary>
/// Create a statement that will record this index into this array each time through.
/// </summary>
/// <param name="intToRecord">Integer that should be cached on each time through</param>
/// <param name="storageArray">The array where the indicies should be written</param>
public StatementRecordIndicies(IValue intToRecord, VarArray storageArray)
{
_intToRecord = intToRecord;
_storageArray = storageArray;
}
/// <summary>
/// Returns a IValue that represents
/// </summary>
public IValue HolderArray { get; private set; }
/// <summary>
/// Return the code for this statement.
/// </summary>
/// <returns></returns>
public IEnumerable<string> CodeItUp()
{
yield return string.Format("{0}.push_back({1});", _storageArray.RawValue, _intToRecord.RawValue);
}
}
}
|
Check validity if the ImageView before trying to access its Drawable | using Android.Widget;
using FFImageLoading.Work;
namespace FFImageLoading.Extensions
{
public static class ImageViewExtensions
{
/// <summary>
/// Retrieve the currently active work task (if any) associated with this imageView.
/// </summary>
/// <param name="imageView"></param>
/// <returns></returns>
public static ImageLoaderTask GetImageLoaderTask(this ImageView imageView)
{
if (imageView == null)
return null;
var drawable = imageView.Drawable;
var asyncDrawable = drawable as AsyncDrawable;
if (asyncDrawable != null)
{
return asyncDrawable.GetImageLoaderTask();
}
return null;
}
}
} | using Android.Widget;
using FFImageLoading.Work;
using System;
namespace FFImageLoading.Extensions
{
public static class ImageViewExtensions
{
/// <summary>
/// Retrieve the currently active work task (if any) associated with this imageView.
/// </summary>
/// <param name="imageView"></param>
/// <returns></returns>
public static ImageLoaderTask GetImageLoaderTask(this ImageView imageView)
{
if (imageView == null || imageView.Handle == IntPtr.Zero)
return null;
var drawable = imageView.Drawable;
var asyncDrawable = drawable as AsyncDrawable;
if (asyncDrawable != null)
{
return asyncDrawable.GetImageLoaderTask();
}
return null;
}
}
} |
Set collections on property groups | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Umbraco.Web.Models.ContentEditing
{
[DataContract(Name = "propertyGroup", Namespace = "")]
public class PropertyGroupDisplay
{
public PropertyGroupDisplay()
{
Properties = new List<PropertyTypeDisplay>();
}
[DataMember(Name = "id")]
public int Id { get; set; }
[DataMember(Name = "parentGroupId")]
public int ParentGroupId { get; set; }
[DataMember(Name = "sortOrder")]
public int SortOrder { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "properties")]
public IEnumerable<PropertyTypeDisplay> Properties { get; set; }
//Indicate if this tab was inherited
[DataMember(Name = "inherited")]
public bool Inherited { get; set; }
[DataMember(Name = "contentTypeId")]
public int ContentTypeId { get; set; }
[DataMember(Name = "parentTabContentTypes")]
public IEnumerable<int> ParentTabContentTypes { get; set; }
[DataMember(Name = "parentTabContentTypeNames")]
public IEnumerable<string> ParentTabContentTypeNames { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Umbraco.Web.Models.ContentEditing
{
[DataContract(Name = "propertyGroup", Namespace = "")]
public class PropertyGroupDisplay
{
public PropertyGroupDisplay()
{
Properties = new List<PropertyTypeDisplay>();
ParentTabContentTypeNames = new List<string>();
ParentTabContentTypes = new List<int>();
}
[DataMember(Name = "id")]
public int Id { get; set; }
[DataMember(Name = "parentGroupId")]
public int ParentGroupId { get; set; }
[DataMember(Name = "sortOrder")]
public int SortOrder { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "properties")]
public IEnumerable<PropertyTypeDisplay> Properties { get; set; }
//Indicate if this tab was inherited
[DataMember(Name = "inherited")]
public bool Inherited { get; set; }
[DataMember(Name = "contentTypeId")]
public int ContentTypeId { get; set; }
[DataMember(Name = "parentTabContentTypes")]
public IEnumerable<int> ParentTabContentTypes { get; set; }
[DataMember(Name = "parentTabContentTypeNames")]
public IEnumerable<string> ParentTabContentTypeNames { get; set; }
}
}
|
Add audio feedback for rearranging list items | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
namespace osu.Game.Graphics.Containers
{
public abstract class OsuRearrangeableListContainer<TModel> : RearrangeableListContainer<TModel>
{
/// <summary>
/// Whether any item is currently being dragged. Used to hide other items' drag handles.
/// </summary>
protected readonly BindableBool DragActive = new BindableBool();
protected override ScrollContainer<Drawable> CreateScrollContainer() => new OsuScrollContainer();
protected sealed override RearrangeableListItem<TModel> CreateDrawable(TModel item) => CreateOsuDrawable(item).With(d =>
{
d.DragActive.BindTo(DragActive);
});
protected abstract OsuRearrangeableListItem<TModel> CreateOsuDrawable(TModel item);
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System.Collections.Specialized;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Utils;
namespace osu.Game.Graphics.Containers
{
public abstract class OsuRearrangeableListContainer<TModel> : RearrangeableListContainer<TModel>
{
/// <summary>
/// Whether any item is currently being dragged. Used to hide other items' drag handles.
/// </summary>
protected readonly BindableBool DragActive = new BindableBool();
protected override ScrollContainer<Drawable> CreateScrollContainer() => new OsuScrollContainer();
private Sample sampleSwap;
private double sampleLastPlaybackTime;
protected sealed override RearrangeableListItem<TModel> CreateDrawable(TModel item) => CreateOsuDrawable(item).With(d =>
{
d.DragActive.BindTo(DragActive);
});
protected abstract OsuRearrangeableListItem<TModel> CreateOsuDrawable(TModel item);
protected OsuRearrangeableListContainer()
{
Items.CollectionChanged += (_, args) =>
{
if (args.Action == NotifyCollectionChangedAction.Move)
playSwapSample();
};
}
private void playSwapSample()
{
if (Time.Current - sampleLastPlaybackTime <= 35)
return;
var channel = sampleSwap?.GetChannel();
if (channel == null)
return;
channel.Frequency.Value = 0.96 + RNG.NextDouble(0.08);
channel.Play();
sampleLastPlaybackTime = Time.Current;
}
[BackgroundDependencyLoader]
private void load(AudioManager audio)
{
sampleSwap = audio.Samples.Get(@"UI/item-swap");
sampleLastPlaybackTime = Time.Current;
}
}
}
|
Update benchmarks to new format | using Microsoft.Xunit.Performance;
using Xunit;
namespace DNXLibrary
{
// This project can output the Class library as a NuGet Package.
// To enable this option, right-click on the project and select the Properties menu item. In the Build tab select "Produce outputs on build".
public class DNXSampleTests
{
[Fact]
public void AlwaysPass()
{
Assert.True(true);
}
[Fact]
public void AlwaysFail()
{
Assert.True(false);
}
[Benchmark]
public void Benchmark1()
{
}
[Benchmark]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
public void Benchmark2(int x)
{
}
}
} | using Microsoft.Xunit.Performance;
using Xunit;
namespace DNXLibrary
{
// This project can output the Class library as a NuGet Package.
// To enable this option, right-click on the project and select the Properties menu item. In the Build tab select "Produce outputs on build".
public class DNXSampleTests
{
[Fact]
public void AlwaysPass()
{
Assert.True(true);
}
[Fact]
public void AlwaysFail()
{
Assert.True(false);
}
[Benchmark]
public void Benchmark1()
{
Benchmark.Iterate(() => { });
}
[Benchmark]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
public void Benchmark2(int x)
{
Benchmark.Iterate(() => { });
}
}
} |
Make Markdown help open in another window | @model JoinRpg.DataModel.MarkdownString
@{
var requiredMsg = new MvcHtmlString("");
var validation = false;
foreach (var attr in @Html.GetUnobtrusiveValidationAttributes(@ViewData.TemplateInfo.HtmlFieldPrefix, @ViewData.ModelMetadata))
{
if (attr.Key == "data-val-required")
{
requiredMsg = new MvcHtmlString("data-val-required='" + HttpUtility.HtmlAttributeEncode((string) attr.Value) + "'");
validation = true;
}
}
}
<div>
Можно использовать <a href="http://daringfireball.net/projects/markdown/syntax">MarkDown</a> (**<b>полужирный</b>**, _<i>курсив</i>_) <br/>
<textarea
class="form-control"
cols="100"
id="@(ViewData.TemplateInfo.HtmlFieldPrefix)_Contents"
name="@(ViewData.TemplateInfo.HtmlFieldPrefix).Contents"
@requiredMsg @(validation ? "data-val=true" : "")
rows="4">@(Model == null ? "" : Model.Contents)</textarea>
</div>
@if (validation)
{
@Html.ValidationMessageFor(model => Model.Contents, "", new { @class = "text-danger" })
} | @model JoinRpg.DataModel.MarkdownString
@{
var requiredMsg = new MvcHtmlString("");
var validation = false;
foreach (var attr in @Html.GetUnobtrusiveValidationAttributes(@ViewData.TemplateInfo.HtmlFieldPrefix, @ViewData.ModelMetadata))
{
if (attr.Key == "data-val-required")
{
requiredMsg = new MvcHtmlString("data-val-required='" + HttpUtility.HtmlAttributeEncode((string) attr.Value) + "'");
validation = true;
}
}
}
<div>
Можно использовать <a href="http://daringfireball.net/projects/markdown/syntax" target="_blank">MarkDown</a> (**<b>полужирный</b>**, _<i>курсив</i>_) <br/>
<textarea
class="form-control"
cols="100"
id="@(ViewData.TemplateInfo.HtmlFieldPrefix)_Contents"
name="@(ViewData.TemplateInfo.HtmlFieldPrefix).Contents"
@requiredMsg @(validation ? "data-val=true" : "")
rows="4">@(Model == null ? "" : Model.Contents)</textarea>
</div>
@if (validation)
{
@Html.ValidationMessageFor(model => Model.Contents, "", new { @class = "text-danger" })
} |
Add english as well as german | // WhistTest.cs
// <copyright file="WhistTest.cs"> This code is protected under the MIT License. </copyright>
using System;
using CardGames.Whist;
namespace ConsoleTesting
{
/// <summary>
/// The whist test class
/// </summary>
public class WhistTest : IGameTest
{
/// <summary>
/// Run the test
/// </summary>
public void RunTest()
{
Whist whist = new Whist();
ConsolePlayer p1 = new ConsolePlayer();
ConsolePlayer p2 = new ConsolePlayer();
ConsolePlayer p3 = new ConsolePlayer();
whist.AddPlayer(p1);
whist.AddPlayer(p2);
whist.AddPlayer(p3);
whist.Start();
}
public void RunWithAi()
{
Console.WriteLine("Es gibt kein AI");
}
}
}
| // WhistTest.cs
// <copyright file="WhistTest.cs"> This code is protected under the MIT License. </copyright>
using System;
using CardGames.Whist;
namespace ConsoleTesting
{
/// <summary>
/// The whist test class
/// </summary>
public class WhistTest : IGameTest
{
/// <summary>
/// Run the test
/// </summary>
public void RunTest()
{
Whist whist = new Whist();
ConsolePlayer p1 = new ConsolePlayer();
ConsolePlayer p2 = new ConsolePlayer();
ConsolePlayer p3 = new ConsolePlayer();
whist.AddPlayer(p1);
whist.AddPlayer(p2);
whist.AddPlayer(p3);
whist.Start();
}
public void RunWithAi()
{
Console.WriteLine("Es gibt kein AI");
Console.WriteLine("There is no AI")
}
}
}
|
Fix "Search" widget ignoring search errors | using System.Diagnostics;
using System.Windows.Input;
using DesktopWidgets.Classes;
using DesktopWidgets.Helpers;
using DesktopWidgets.ViewModelBase;
using GalaSoft.MvvmLight.Command;
namespace DesktopWidgets.Widgets.Search
{
public class ViewModel : WidgetViewModelBase
{
private string _searchText;
public ViewModel(WidgetId id) : base(id)
{
Settings = id.GetSettings() as Settings;
if (Settings == null)
return;
Go = new RelayCommand(GoExecute);
OnKeyUp = new RelayCommand<KeyEventArgs>(OnKeyUpExecute);
}
public Settings Settings { get; }
public ICommand Go { get; set; }
public ICommand OnKeyUp { get; set; }
public string SearchText
{
get { return _searchText; }
set
{
if (_searchText != value)
{
_searchText = value;
RaisePropertyChanged(nameof(SearchText));
}
}
}
private void GoExecute()
{
var searchText = SearchText;
SearchText = string.Empty;
try
{
Process.Start($"{Settings.BaseUrl}{searchText}{Settings.URLSuffix}");
}
catch
{
// ignored
}
if (Settings.HideOnSearch)
_id.GetView()?.HideUI();
}
private void OnKeyUpExecute(KeyEventArgs args)
{
if (args.Key == Key.Enter)
GoExecute();
}
}
} | using System.Diagnostics;
using System.Windows.Input;
using DesktopWidgets.Classes;
using DesktopWidgets.Helpers;
using DesktopWidgets.ViewModelBase;
using GalaSoft.MvvmLight.Command;
namespace DesktopWidgets.Widgets.Search
{
public class ViewModel : WidgetViewModelBase
{
private string _searchText;
public ViewModel(WidgetId id) : base(id)
{
Settings = id.GetSettings() as Settings;
if (Settings == null)
return;
Go = new RelayCommand(GoExecute);
OnKeyUp = new RelayCommand<KeyEventArgs>(OnKeyUpExecute);
}
public Settings Settings { get; }
public ICommand Go { get; set; }
public ICommand OnKeyUp { get; set; }
public string SearchText
{
get { return _searchText; }
set
{
if (_searchText != value)
{
_searchText = value;
RaisePropertyChanged(nameof(SearchText));
}
}
}
private void GoExecute()
{
var searchText = SearchText;
SearchText = string.Empty;
Process.Start($"{Settings.BaseUrl}{searchText}{Settings.URLSuffix}");
if (Settings.HideOnSearch)
_id.GetView()?.HideUI();
}
private void OnKeyUpExecute(KeyEventArgs args)
{
if (args.Key == Key.Enter)
GoExecute();
}
}
} |
Add skin traget resetting on setup/teardown steps | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.IO.Stores;
using osu.Game.Rulesets;
using osu.Game.Skinning;
namespace osu.Game.Tests.Visual
{
[TestFixture]
public abstract class LegacySkinPlayerTestScene : PlayerTestScene
{
protected LegacySkin LegacySkin { get; private set; }
private ISkinSource legacySkinSource;
protected override TestPlayer CreatePlayer(Ruleset ruleset) => new SkinProvidingPlayer(legacySkinSource);
[BackgroundDependencyLoader]
private void load(OsuGameBase game, SkinManager skins)
{
LegacySkin = new DefaultLegacySkin(new NamespacedResourceStore<byte[]>(game.Resources, "Skins/Legacy"), skins);
legacySkinSource = new SkinProvidingContainer(LegacySkin);
}
public class SkinProvidingPlayer : TestPlayer
{
[Cached(typeof(ISkinSource))]
private readonly ISkinSource skinSource;
public SkinProvidingPlayer(ISkinSource skinSource)
{
this.skinSource = skinSource;
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.IO.Stores;
using osu.Framework.Testing;
using osu.Game.Rulesets;
using osu.Game.Skinning;
namespace osu.Game.Tests.Visual
{
[TestFixture]
public abstract class LegacySkinPlayerTestScene : PlayerTestScene
{
protected LegacySkin LegacySkin { get; private set; }
private ISkinSource legacySkinSource;
protected override TestPlayer CreatePlayer(Ruleset ruleset) => new SkinProvidingPlayer(legacySkinSource);
[BackgroundDependencyLoader]
private void load(OsuGameBase game, SkinManager skins)
{
LegacySkin = new DefaultLegacySkin(new NamespacedResourceStore<byte[]>(game.Resources, "Skins/Legacy"), skins);
legacySkinSource = new SkinProvidingContainer(LegacySkin);
}
[SetUpSteps]
public override void SetUpSteps()
{
base.SetUpSteps();
addResetTargetsStep();
}
[TearDownSteps]
public override void TearDownSteps()
{
addResetTargetsStep();
base.TearDownSteps();
}
private void addResetTargetsStep()
{
AddStep("reset targets", () => this.ChildrenOfType<SkinnableTargetContainer>().ForEach(t =>
{
LegacySkin.ResetDrawableTarget(t);
t.Reload();
}));
}
public class SkinProvidingPlayer : TestPlayer
{
[Cached(typeof(ISkinSource))]
private readonly ISkinSource skinSource;
public SkinProvidingPlayer(ISkinSource skinSource)
{
this.skinSource = skinSource;
}
}
}
}
|
Implement last update model, had forgotten, hehe | namespace pinboard.net.Models
{
public class LastUpdate
{
}
} | using Newtonsoft.Json;
using System;
namespace pinboard.net.Models
{
public class LastUpdate
{
[JsonProperty("update_time")]
public DateTimeOffset UpdateTime { get; set; }
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.