Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add a convert extension for MessageProperty - convert message property to extra message property. | using Cosmos.Logging.Events;
namespace Cosmos.Logging.ExtraSupports
{
public static class ExtraMessagePropertyExtensions
{
public static ExtraMessageProperty AsExtra(this MessageProperty property) => new ExtraMessageProperty(property);
}
} | |
Remove text between CommentRangeStart and CommentRangeEnd | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Aspose.Words.Examples.CSharp.Programming_Documents.Comments
{
class RemoveRegionText
{
public static void Run()
{
// ExStart:RemoveRegionText
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithComments();
string fileName = "TestFile.doc";
// Open the document.
Document doc = new Document(dataDir + fileName);
CommentRangeStart commentStart = (CommentRangeStart)doc.GetChild(NodeType.CommentRangeStart, 0, true);
CommentRangeEnd commentEnd = (CommentRangeEnd)doc.GetChild(NodeType.CommentRangeEnd, 0, true);
Node currentNode = commentStart;
Boolean isRemoving = true;
while (currentNode != null && isRemoving)
{
if (currentNode.NodeType == NodeType.CommentRangeEnd)
isRemoving = false;
Node nextNode = currentNode.NextPreOrder(doc);
currentNode.Remove();
currentNode = nextNode;
}
dataDir = dataDir + "RemoveRegionText_out.doc";
// Save the document.
doc.Save(dataDir);
// ExEnd:RemoveRegionText
Console.WriteLine("\nComments added successfully.\nFile saved at " + dataDir);
}
}
}
| |
Add Coinstamp as price provider | using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using WalletWasabi.Backend.Models;
using WalletWasabi.Interfaces;
namespace WalletWasabi.WebClients.BlockchainInfo
{
public class CoinstampExchangeRateProvider : IExchangeRateProvider
{
public async Task<List<ExchangeRate>> GetExchangeRateAsync()
{
using var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("https://www.bitstamp.net");
using var response = await httpClient.GetAsync("/api/v2/ticker/btcusd");
using var content = response.Content;
var rate = await content.ReadAsJsonAsync<CoinstampExchangeRate>();
var exchangeRates = new List<ExchangeRate>
{
new ExchangeRate { Rate = rate.Rate, Ticker = "USD" }
};
return exchangeRates;
}
public class CoinstampExchangeRate
{
[JsonProperty(PropertyName = "bid")]
public decimal Rate { get; set; }
}
}
}
| |
Return exceptions in faulted tasks. | using System;
using System.Threading.Tasks;
using Orleans;
using Orleans.Streams;
using Orleans.Providers;
namespace Tester.TestStreamProviders
{
/// <summary>
/// This is a test stream provider that throws exceptions when config file contains certain properties.
/// </summary>
public enum FailureInjectionStreamProviderMode
{
NoFault,
InitializationThrowsException,
StartThrowsException
}
public class FailureInjectionStreamProvider : IStreamProviderImpl
{
private FailureInjectionStreamProviderMode mode;
public static string FailureInjectionModeString => "FAILURE_INJECTION_STREAM_PROVIDER_MODE";
public string Name { get; set; }
public IAsyncStream<T> GetStream<T>(Guid streamId, string streamNamespace)
{
throw new NotImplementedException();
}
public bool IsRewindable => false;
public Task Close()
{
return TaskDone.Done;
}
public Task Init(string name, IProviderRuntime providerUtilitiesManager, IProviderConfiguration providerConfig)
{
Name = name;
mode = providerConfig.GetEnumProperty(FailureInjectionModeString, FailureInjectionStreamProviderMode.NoFault);
if (mode == FailureInjectionStreamProviderMode.InitializationThrowsException)
{
throw new ProviderInitializationException("Error initializing provider "+typeof(FailureInjectionStreamProvider));
}
return TaskDone.Done;
}
public Task Start()
{
if (mode == FailureInjectionStreamProviderMode.StartThrowsException)
{
throw new ProviderStartException("Error starting provider " + typeof(FailureInjectionStreamProvider).Name);
}
return TaskDone.Done;
}
}
}
| using System;
using System.Threading.Tasks;
using Orleans;
using Orleans.Async;
using Orleans.Streams;
using Orleans.Providers;
namespace Tester.TestStreamProviders
{
/// <summary>
/// This is a test stream provider that throws exceptions when config file contains certain properties.
/// </summary>
public enum FailureInjectionStreamProviderMode
{
NoFault,
InitializationThrowsException,
StartThrowsException
}
public class FailureInjectionStreamProvider : IStreamProviderImpl
{
private FailureInjectionStreamProviderMode mode;
public static string FailureInjectionModeString => "FAILURE_INJECTION_STREAM_PROVIDER_MODE";
public string Name { get; set; }
public IAsyncStream<T> GetStream<T>(Guid streamId, string streamNamespace)
{
throw new NotImplementedException();
}
public bool IsRewindable => false;
public Task Close()
{
return TaskDone.Done;
}
public Task Init(string name, IProviderRuntime providerUtilitiesManager, IProviderConfiguration providerConfig)
{
Name = name;
mode = providerConfig.GetEnumProperty(FailureInjectionModeString, FailureInjectionStreamProviderMode.NoFault);
return mode == FailureInjectionStreamProviderMode.InitializationThrowsException
? TaskUtility.Faulted(new ProviderInitializationException("Error initializing provider " + typeof(FailureInjectionStreamProvider)))
: TaskDone.Done;
}
public Task Start()
{
return mode == FailureInjectionStreamProviderMode.StartThrowsException
? TaskUtility.Faulted(new ProviderStartException("Error starting provider " + typeof(FailureInjectionStreamProvider).Name))
: TaskDone.Done;
}
}
}
|
Add ToStringInvariant method for IFormattable | using System.Globalization;
namespace Meziantou.Framework;
public static class FormattableExtensions
{
public static string ToStringInvariant<T>(this T value) where T : IFormattable
{
return ToStringInvariant(value, format: null);
}
public static string ToStringInvariant<T>(this T value, string? format) where T : IFormattable
{
if (format != null)
return value.ToString(format, CultureInfo.InvariantCulture);
return "";
}
}
| |
Add basic test scene for testing platform actions | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osuTK;
namespace osu.Framework.Tests.Visual.Input
{
public class TestScenePlatformActionContainer : FrameworkTestScene
{
[BackgroundDependencyLoader]
private void load()
{
Add(new TestPlatformActionHandler
{
RelativeSizeAxes = Axes.Both
});
}
private class TestPlatformActionHandler : CompositeDrawable
{
[BackgroundDependencyLoader]
private void load()
{
InternalChild = new FillFlowContainer
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding(20),
Spacing = new Vector2(10),
ChildrenEnumerable = Enum.GetValues(typeof(PlatformAction))
.Cast<PlatformAction>()
.Select(action => new PlatformBindingBox(action))
};
}
}
private class PlatformBindingBox : CompositeDrawable, IKeyBindingHandler<PlatformAction>
{
private readonly PlatformAction platformAction;
private Box background;
public PlatformBindingBox(PlatformAction platformAction)
{
this.platformAction = platformAction;
}
[BackgroundDependencyLoader]
private void load()
{
AutoSizeAxes = Axes.Both;
InternalChildren = new Drawable[]
{
background = new Box
{
RelativeSizeAxes = Axes.Both,
Colour = FrameworkColour.GreenDarker
},
new SpriteText
{
Text = platformAction.ToString(),
Margin = new MarginPadding(10)
}
};
}
public bool OnPressed(KeyBindingPressEvent<PlatformAction> e)
{
if (e.Action != platformAction)
return false;
background.FlashColour(FrameworkColour.YellowGreen, 250, Easing.OutQuint);
return true;
}
public void OnReleased(KeyBindingReleaseEvent<PlatformAction> e)
{
}
}
}
}
| |
Add file missed in bug fix 440109 | // ***********************************************************************
// Copyright (c) 2009 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
// ****************************************************************
// Generated by the NUnit Syntax Generator
//
// Command Line: __COMMANDLINE__
//
// DO NOT MODIFY THIS FILE DIRECTLY
// ****************************************************************
using System;
using System.Collections;
using NUnit.Framework.Constraints;
namespace NUnit.Framework
{
/// <summary>
/// Helper class with properties and methods that supply
/// a number of constraints used in Asserts.
/// </summary>
public class Contains
{
// $$GENERATE$$ $$STATIC$$
}
}
| |
Add cmdlet information for Remove-AzureDataDisk | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests.IaasCmdletInfo
{
using Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests.PowershellCore;
using Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests.ConfigDataInfo;
public class RemoveAzureDataDiskCmdletInfo : CmdletsInfo
{
public RemoveAzureDataDiskCmdletInfo(RemoveAzureDataDiskConfig discCfg)
{
this.cmdletName = Utilities.RemoveAzureDataDiskCmdletName;
this.cmdletParams.Add(new CmdletParam("LUN", discCfg.lun));
this.cmdletParams.Add(new CmdletParam("VM", discCfg.Vm));
}
}
}
| |
Add class to get information about the current assembly. | #region auto-generated FILE INFORMATION
// ==============================================
// This file is distributed under the MIT License
// ==============================================
//
// Filename: AssemblyInfo.cs
// Version: 2018-06-02 15:41
//
// Copyright (c) 2018, Si13n7 Developments (r)
// All rights reserved.
// ______________________________________________
#endregion
namespace SilDev
{
using System;
using System.Reflection;
/// <summary>
/// Provides information for the current assembly.
/// </summary>
public static class AssemblyInfo
{
/// <summary>
/// Gets company name information.
/// </summary>
public static string Company => GetAssembly<AssemblyCompanyAttribute>()?.Company;
/// <summary>
/// Gets configuration information.
/// </summary>
public static string Configuration => GetAssembly<AssemblyDescriptionAttribute>()?.Description;
/// <summary>
/// Gets copyright information.
/// </summary>
public static string Copyright => GetAssembly<AssemblyCopyrightAttribute>()?.Copyright;
/// <summary>
/// Gets description information.
/// </summary>
public static string Description => GetAssembly<AssemblyDescriptionAttribute>()?.Description;
/// <summary>
/// Gets file version information.
/// </summary>
public static string FileVersion => GetAssembly<AssemblyFileVersionAttribute>()?.Version;
/// <summary>
/// Gets product information.
/// </summary>
public static string Product => GetAssembly<AssemblyProductAttribute>()?.Product;
/// <summary>
/// Gets title information.
/// </summary>
public static string Title => GetAssembly<AssemblyTitleAttribute>()?.Title;
/// <summary>
/// Gets trademark information.
/// </summary>
public static string Trademark => GetAssembly<AssemblyTrademarkAttribute>()?.Trademark;
/// <summary>
/// Gets version information.
/// </summary>
public static string Version => Assembly.GetEntryAssembly()?.GetName().Version?.ToString();
private static TSource GetAssembly<TSource>() where TSource : Attribute
{
try
{
var assembly = Attribute.GetCustomAttribute(Assembly.GetEntryAssembly(), typeof(TSource));
return (TSource)assembly;
}
catch
{
return default(TSource);
}
}
}
}
| |
Add composite managing display of selection box drag handles | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
namespace osu.Game.Screens.Edit.Compose.Components
{
/// <summary>
/// Represents a display composite containing and managing the visibility state of the selection box's drag handles.
/// </summary>
public class SelectionBoxDragHandleDisplay : CompositeDrawable
{
private Container<SelectionBoxScaleHandle> scaleHandles;
private Container<SelectionBoxRotationHandle> rotationHandles;
private readonly List<SelectionBoxDragHandle> allDragHandles = new List<SelectionBoxDragHandle>();
public new MarginPadding Padding
{
get => base.Padding;
set => base.Padding = value;
}
[BackgroundDependencyLoader]
private void load()
{
InternalChildren = new Drawable[]
{
scaleHandles = new Container<SelectionBoxScaleHandle>
{
RelativeSizeAxes = Axes.Both,
},
rotationHandles = new Container<SelectionBoxRotationHandle>
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding(-12.5f),
},
};
}
public void AddScaleHandle(SelectionBoxScaleHandle handle)
{
bindDragHandle(handle);
scaleHandles.Add(handle);
}
public void AddRotationHandle(SelectionBoxRotationHandle handle)
{
handle.Alpha = 0;
handle.AlwaysPresent = true;
bindDragHandle(handle);
rotationHandles.Add(handle);
}
private void bindDragHandle(SelectionBoxDragHandle handle)
{
handle.HoverGained += updateRotationHandlesVisibility;
handle.HoverLost += updateRotationHandlesVisibility;
handle.OperationStarted += updateRotationHandlesVisibility;
handle.OperationEnded += updateRotationHandlesVisibility;
allDragHandles.Add(handle);
}
private SelectionBoxRotationHandle displayedRotationHandle;
private SelectionBoxDragHandle activeHandle;
private void updateRotationHandlesVisibility()
{
if (activeHandle?.InOperation == true || activeHandle?.IsHovered == true)
return;
displayedRotationHandle?.FadeOut(SelectionBoxControl.TRANSFORM_DURATION, Easing.OutQuint);
displayedRotationHandle = null;
activeHandle = allDragHandles.SingleOrDefault(h => h.InOperation);
activeHandle ??= allDragHandles.SingleOrDefault(h => h.IsHovered);
if (activeHandle != null)
{
displayedRotationHandle = getCorrespondingRotationHandle(activeHandle, rotationHandles);
displayedRotationHandle?.FadeIn(SelectionBoxControl.TRANSFORM_DURATION, Easing.OutQuint);
}
}
/// <summary>
/// Gets the rotation handle corresponding to the given handle.
/// </summary>
[CanBeNull]
private static SelectionBoxRotationHandle getCorrespondingRotationHandle(SelectionBoxDragHandle handle, IEnumerable<SelectionBoxRotationHandle> rotationHandles)
{
if (handle is SelectionBoxRotationHandle rotationHandle)
return rotationHandle;
return rotationHandles.SingleOrDefault(r => r.Anchor == handle.Anchor);
}
}
}
| |
Add Prepend and Append extension methods | // Copyright 2018 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
namespace Nuke.Common.Utilities
{
public static partial class StringExtensions
{
[Pure]
public static string Prepend(this string str, string prependText)
{
return prependText + str;
}
[Pure]
public static string Append(this string str, string appendText)
{
return str + appendText;
}
}
}
| |
Add handwritten code for Operation.ToLroResponse() | // Copyright 2021 Google LLC
//
// 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
//
// https://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 lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
// Note: this will eventually be generated in ComputeLroAdaptation.g.cs. It's the last bit of generator work we need to do.
namespace Google.Cloud.Compute.V1
{
partial class Operation
{
internal lro::Operation ToLroResponse(string name)
{
// TODO: Work this out much more carefully. In particular, consider whether a Compute LRO can complete successfully with errors...
var proto = new lro::Operation
{
// Derived from [(google.cloud.operation_field) = STATUS]
Done = Status == Types.Status.Done,
// Taken from [(google.cloud.operation_field) = NAME]
Name = name,
// Always pack the raw response as metadata
Metadata = wkt::Any.Pack(this)
};
if (proto.Done)
{
// Only pack the raw response as the LRO Response if we're done
proto.Response = proto.Metadata;
}
// Derived from [(google.cloud.operation_field) = ERROR_CODE] and [(google.cloud.operation_field) = ERROR_MESSAGE]
if (HasHttpErrorStatusCode)
{
// FIXME: Convert the HTTP status code into a suitable Rpc.Status code.
proto.Error = new Rpc.Status { Code = HttpErrorStatusCode, Message = HttpErrorMessage };
}
return proto;
}
}
}
| |
Add what's that song script |
var robot = Require<Robot>();
var baseUri = robot.GetConfigVariable("MMBOT_PLAYME_URL");
if(baseUri != null && !baseUri.EndsWith("/")){
baseUri = baseUri + "/";
}
robot.Respond(@"what'?s that song\??", msg => {
msg.Http(baseUri + "Queue/CurrentTrack")
.GetJson((err, res, body) => {
try{
if(err != null){
throw err;
}
if(body == null || body["Id"] == null){
msg.Send("Nothin', you're hearing things. Weirdo!");
return;
}
var track = body["Track"]["Name"].ToString();
var artist = string.Join(", ", body["Track"]["Artists"].Select(a => a["Name"].ToString()));
var album = body["Track"]["Album"]["Name"].ToString();
msg.Send(track, artist, album);
}
catch(Exception ex){
msg.Send("Don't know, something went horribly wrong: " + err.Message);
return;
}
});
});
| |
Update state to be used after redirect | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
namespace SimpleWAWS.Authentication
{
public class GoogleAuthProvider : BaseOpenIdConnectAuthProvider
{
public override string GetLoginUrl(HttpContextBase context)
{
var culture = CultureInfo.CurrentCulture.Name.ToLowerInvariant();
var builder = new StringBuilder();
builder.Append("https://accounts.google.com/o/oauth2/auth");
builder.Append("?response_type=id_token");
builder.AppendFormat("&redirect_uri={0}", WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "https://{0}/Login", context.Request.Headers["HOST"])));
builder.AppendFormat("&client_id={0}", AuthSettings.GoogleAppId);
builder.AppendFormat("&scope={0}", "email");
builder.AppendFormat("&state={0}", WebUtility.UrlEncode(context.IsAjaxRequest() ? string.Format(CultureInfo.InvariantCulture, "/{0}{1}", culture, context.Request.Url.Query) : context.Request.Url.PathAndQuery));
return builder.ToString();
}
protected override string GetValidAudiance()
{
return AuthSettings.GoogleAppId;
}
public override string GetIssuerName(string altSecId)
{
return "Google";
}
}
} | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
namespace SimpleWAWS.Authentication
{
public class GoogleAuthProvider : BaseOpenIdConnectAuthProvider
{
public override string GetLoginUrl(HttpContextBase context)
{
var culture = CultureInfo.CurrentCulture.Name.ToLowerInvariant();
var builder = new StringBuilder();
builder.Append("https://accounts.google.com/o/oauth2/auth");
builder.Append("?response_type=id_token");
builder.AppendFormat("&redirect_uri={0}", WebUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "https://{0}/Login", context.Request.Headers["HOST"])));
builder.AppendFormat("&client_id={0}", AuthSettings.GoogleAppId);
builder.AppendFormat("&scope={0}", "email");
builder.AppendFormat("&state={0}", WebUtility.UrlEncode(context.IsAjaxRequest()|| context.IsFunctionsPortalRequest() ? string.Format(CultureInfo.InvariantCulture, "/{0}{1}", culture, context.Request.Url.Query) : context.Request.Url.PathAndQuery));
return builder.ToString();
}
protected override string GetValidAudiance()
{
return AuthSettings.GoogleAppId;
}
public override string GetIssuerName(string altSecId)
{
return "Google";
}
}
} |
Fix on User table migration | using FluentMigrator;
namespace Abp.Modules.Core.Data.Migrations.V20130824
{
[Migration(2013082402)]
public class _02_CreateAbpUsersTable : Migration
{
public override void Up()
{
Create.Table("AbpUsers")
.WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity()
.WithColumn("TenantId").AsInt32().NotNullable().ForeignKey("AbpTenants", "Id")
.WithColumn("Name").AsString(30).NotNullable()
.WithColumn("Surname").AsString(30).NotNullable()
.WithColumn("EmailAddress").AsString(100).NotNullable()
.WithColumn("Password").AsString(80).NotNullable()
.WithColumn("ProfileImage").AsString(100).NotNullable()
.WithColumn("IsTenantOwner").AsBoolean().NotNullable().WithDefaultValue(false);
Insert.IntoTable("AbpUsers").Row(
new
{
TenantId = 1,
Name = "System",
Surname = "Admin",
EmailAddress = "admin@aspnetboilerplate.com",
Password = "123"
}
);
}
public override void Down()
{
Delete.Table("AbpUsers");
}
}
}
| using FluentMigrator;
namespace Abp.Modules.Core.Data.Migrations.V20130824
{
[Migration(2013082402)]
public class _02_CreateAbpUsersTable : Migration
{
public override void Up()
{
Create.Table("AbpUsers")
.WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity()
.WithColumn("TenantId").AsInt32().NotNullable().ForeignKey("AbpTenants", "Id")
.WithColumn("Name").AsString(30).NotNullable()
.WithColumn("Surname").AsString(30).NotNullable()
.WithColumn("EmailAddress").AsString(100).NotNullable()
.WithColumn("Password").AsString(80).NotNullable()
.WithColumn("ProfileImage").AsString(100).Nullable()
.WithColumn("IsTenantOwner").AsBoolean().NotNullable().WithDefaultValue(false);
Insert.IntoTable("AbpUsers").Row(
new
{
TenantId = 1,
Name = "System",
Surname = "Admin",
EmailAddress = "admin@aspnetboilerplate.com",
Password = "123"
}
);
}
public override void Down()
{
Delete.Table("AbpUsers");
}
}
}
|
Copy test helper from main project | namespace AngleSharp.Core.Tests
{
using NUnit.Framework;
using System;
using System.IO;
using System.Net.NetworkInformation;
/// <summary>
/// Small (but quite useable) code to enable / disable some
/// test(s) depending on the current network status.
/// Taken from
/// http://stackoverflow.com/questions/520347/c-sharp-how-do-i-check-for-a-network-connection
/// </summary>
class Helper
{
/// <summary>
/// Indicates whether any network connection is available
/// Filter connections below a specified speed, as well as virtual network cards.
/// Additionally writes an inconclusive message if no network is available.
/// </summary>
/// <returns>True if a network connection is available; otherwise false.</returns>
public static Boolean IsNetworkAvailable()
{
if (IsNetworkAvailable(0))
return true;
Assert.Inconclusive("No network has been detected. Test skipped.");
return false;
}
/// <summary>
/// Indicates whether any network connection is available.
/// Filter connections below a specified speed, as well as virtual network cards.
/// </summary>
/// <param name="minimumSpeed">The minimum speed required. Passing 0 will not filter connection using speed.</param>
/// <returns>True if a network connection is available; otherwise false.</returns>
public static Boolean IsNetworkAvailable(Int64 minimumSpeed)
{
if (!NetworkInterface.GetIsNetworkAvailable())
return false;
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
// discard because of standard reasons
if ((ni.OperationalStatus != OperationalStatus.Up) ||
(ni.NetworkInterfaceType == NetworkInterfaceType.Loopback) ||
(ni.NetworkInterfaceType == NetworkInterfaceType.Tunnel))
continue;
// this allow to filter modems, serial, etc.
// I use 10000000 as a minimum speed for most cases
if (ni.Speed < minimumSpeed)
continue;
// discard virtual cards (virtual box, virtual pc, etc.)
if ((ni.Description.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) >= 0))
continue;
// discard "Microsoft Loopback Adapter", it will not show as NetworkInterfaceType.Loopback but as Ethernet Card.
if (ni.Description.Equals("Microsoft Loopback Adapter", StringComparison.OrdinalIgnoreCase))
continue;
return true;
}
return false;
}
public static Stream StreamFromBytes(Byte[] content)
{
var stream = new MemoryStream(content);
stream.Position = 0;
return stream;
}
public static Stream StreamFromString(String s)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
}
}
| |
Add file with DynamicTimeWarping.onDeserialized to source contol | // Accord Statistics Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © César Souza, 2009-2015
// cesarsouza at gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
namespace Accord.Statistics.Kernels
{
using System.Runtime.Serialization;
public partial class DynamicTimeWarping
{
[OnDeserialized]
private void onDeserialized(StreamingContext context)
{
this.initialize();
}
}
}
| |
Add unit test for CreateExtractJobOptions | // Copyright 2017 Google Inc. 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 Google.Apis.Bigquery.v2.Data;
using Xunit;
namespace Google.Cloud.BigQuery.V2.Tests
{
public class CreateExtractJobOptionsTest
{
[Fact]
public void ModifyRequest()
{
var options = new CreateExtractJobOptions
{
Compression = CompressionType.Gzip,
PrintHeader = false,
DestinationFormat = FileFormat.NewlineDelimitedJson,
// May not make any sense for JSON, but we don't validate...
FieldDelimiter = "gronkle"
};
JobConfigurationExtract extract = new JobConfigurationExtract();
options.ModifyRequest(extract);
Assert.Equal("GZIP", extract.Compression);
Assert.Equal(false, extract.PrintHeader);
Assert.Equal("NEWLINE_DELIMITED_JSON", extract.DestinationFormat);
Assert.Equal("gronkle", extract.FieldDelimiter);
}
}
}
| |
Move ExeptionMessages to StaticData folder | namespace BashSoft.Exceptions
{
public static class ExceptionMessages
{
public const string DataAlreadyInitialisedException = "Data is already initialized!";
public const string DataNotInitializedExceptionMessage = "The data structure must be initialised first in order to make any operations with it.";
public const string InexistingCourseInDataBase = "The course you are trying to get does not exist in the data base!";
public const string InexistingStudentInDataBase = "The user name for the student you are trying to get does not exist!";
public const string InvalidPath = "The name of the path is not valid!";
public const string ComparisonOfFilesWithDifferentSizes = "Files not of equal size, certain mismatch.";
public const string ForbiddenSymbolContainedInName = "Directory contains forbidden symbol in its name.";
public const string UnauthorizedAccessExceptionMessage = "The folder/file you are trying to get access needs a higher level of rights than you currently have.";
public static string UnableToGoHigherInPartitionHierarchy "Unable to go higher in partition hierarchy.";
}
}
| |
Add new unit Tests for BasicBlocks | using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NUnit.Tests.Middle_End
{
[TestFixture]
public class BasicBlockTests
{
[Test]
public void TestMethod()
{
// TODO: Add your test code here
Assert.Pass("Your first passing test");
}
}
}
| |
Add first pass of function (mostly already done via linqpad script) | using System.Net;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req)
{
try
{
//log.Info("Going to find an art idea...");
var idea = FindRandomArtIdea();
//log.Info($"Found the idea \"{idea}\"");
return req.CreateResponse(HttpStatusCode.OK, idea);
}
catch (Exception ex)
{
return req.CreateResponse(HttpStatusCode.InternalServerError, "An internal server error has occured");
}
}
private const string ArtPromptsUrl = "http://artprompts.org/";
private static readonly string[] KnownCategories = new[]
{
"character",
"creature-prompts",
"environment-prompts",
"object-prompt",
"situation-prompts",
};
private static string FindRandomArtIdea()
{
var randomIndex = (new Random()).Next(0, KnownCategories.Length - 1);
var category = KnownCategories[randomIndex];
return GetAnArtIdea(category);
}
private static string GetAnArtIdea(string category)
{
using (var client = new WebClient())
{
var response = client.DownloadString(ArtPromptsUrl + category);
var startIndex = response.IndexOf("prompttextdiv\">") + 15;
var endIndex = response.IndexOf("<", startIndex);
var idea = response.Substring(startIndex, endIndex - startIndex);
var formattedCategory = category.Split(new[] { "-" }, StringSplitOptions.None)[0];
return $"{formattedCategory}: {idea}";
}
} | |
Add missing unit test file. | using NUnit.Framework;
using System;
using Symbooglix;
using Microsoft.Boogie;
using Microsoft.Basetypes;
namespace ConstantFoldingTests
{
[TestFixture()]
public class FoldBVor : TestBase
{
[Test()]
public void AllOnes()
{
helper(5, 10, 15);
}
[Test()]
public void SomeOnes()
{
helper(1, 2, 3);
}
[Test()]
public void Ends()
{
helper(1, 8, 9);
}
private void helper(int value0, int value1, int expectedValue)
{
var simple = builder.ConstantBV(value0, 4);
var simple2 = builder.ConstantBV(value1, 4);
var expr = builder.BVOR(simple, simple2);
expr.Typecheck(new TypecheckingContext(this));
var CFT = new ConstantFoldingTraverser();
var result = CFT.Traverse(expr);
Assert.IsInstanceOfType(typeof(LiteralExpr), result);
Assert.IsTrue(( result as LiteralExpr ).isBvConst);
Assert.AreEqual(BigNum.FromInt(expectedValue), ( result as LiteralExpr ).asBvConst.Value);
}
}
}
| |
Update server side API for single multiple answer question | using Microsoft.AspNetCore.Mvc;
using Promact.Trappist.DomainModel.Models.Question;
using Promact.Trappist.Repository.Questions;
using System;
namespace Promact.Trappist.Core.Controllers
{
[Route("api/question")]
public class QuestionsController : Controller
{
private readonly IQuestionRepository _questionsRepository;
public QuestionsController(IQuestionRepository questionsRepository)
{
_questionsRepository = questionsRepository;
}
[HttpGet]
/// <summary>
/// Gets all questions
/// </summary>
/// <returns>Questions list</returns>
public IActionResult GetQuestions()
{
var questions = _questionsRepository.GetAllQuestions();
return Json(questions);
}
[HttpPost]
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <returns></returns>
public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
{
_questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion);
return Ok();
}
/// <summary>
/// Add options of single multiple answer question to SingleMultipleAnswerQuestionOption model
/// </summary>
/// <param name="singleMultipleAnswerQuestionOption"></param>
/// <returns></returns>
public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption);
return Ok();
}
}
}
| |
Read initialize properties of config file | using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using FuzzyCore.Server;
namespace FuzzyCore.Initialize
{
public class ConfigReader
{
public string ConfigFile_Path = "./config.json";
public string ConfigFile_Content = "";
bool ConfigFile_Control()
{
return File.Exists(ConfigFile_Path);
}
public InitType Read(string path = "./config.json")
{
try
{
ConfigFile_Path = path;
using (StreamReader Rd = new StreamReader(ConfigFile_Path))
{
ConfigFile_Content = Rd.ReadToEnd();
return JsonConvert.DeserializeObject<InitType>(ConfigFile_Content);
}
}
catch (Exception Ex)
{
ConsoleMessage.WriteException(Ex.Message,"ConfigReader.cs","Read");
return new InitType();
}
}
}
}
| |
Compress array in intervals of consecutive elements | // http://careercup.com/question?id=5693954190213120
//
// Given an ordered array, find segments
//
using System;
using System.Collections.Generic;
using System.Linq;
static class Program
{
static IEnumerable<int[]> Segment(this int[] array)
{
int n = array.Length;
int start = array[0];
for (int i = 1; i < n - 1; i++)
{
if (array[i] + 1 != array[i + 1])
{
yield return
array[i] != start ?
new [] {start, array[i]} :
new [] {array[i]};
start = array[i + 1];
}
}
yield return
array.Last() != start ?
new [] {start, array.Last()} :
new [] {array.Last()};
}
static void Main()
{
Random rand = new Random();
for (int i = 0; i < rand.Next(5, 100); i++)
{
int size = rand.Next(10, 40);
int[] array = new int[size];
for (int k = 0; k < size; k++)
{
int random = rand.Next(1, 5);
array[k] = (k != 0 ? array[k - 1] + 1 : 0) + random % 2;
}
Console.WriteLine(String.Join(", ", array));
Console.WriteLine(String.Join(
", ",
array.Segment().
Select(x =>
String.Format(x.Length == 1 ? "{0}" : "[{0}]",
String.Join(", ",x)))));
Console.WriteLine();
}
}
}
| |
Add - Inizio implementazione evento trasferimento chiamata | using SO115App.API.Models.Classi.Soccorso;
using SO115App.API.Models.Classi.Soccorso.Eventi;
using System;
namespace SO115App.Models.Classi.Soccorso.Eventi
{
public class TrasferimentoChiamata : Evento
{
public TrasferimentoChiamata(RichiestaAssistenza richiesta, DateTime istante, string codiceFonte, string tipoEvento)
: base(richiesta, istante, codiceFonte, "TrasferimentoChiamata")
{
TipoEvento = tipoEvento;
}
}
}
| |
Add container struct for search index values. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SourceBrowser.Search.ViewModels
{
public struct TokenViewModel
{
public string DocumentId { get; }
public string FullName { get; }
public int LineNumber { get; }
public TokenViewModel(string documentId, string fullName, int lineNumber)
{
DocumentId = documentId;
FullName = fullName;
LineNumber = lineNumber;
}
}
}
| |
Add a boring wrapper around Engine since it's sealed | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Tools.WindowsInstallerXml.Bootstrapper;
namespace Shimmer.WiXUi
{
public interface IEngine
{
Engine.Variables<long> NumericVariables { get; }
int PackageCount { get; }
Engine.Variables<string> StringVariables { get; }
Engine.Variables<Version> VersionVariables { get; }
void Apply(IntPtr hwndParent);
void CloseSplashScreen();
void Detect();
bool Elevate(IntPtr hwndParent);
string EscapeString(string input);
bool EvaluateCondition(string condition);
string FormatString(string format);
void Log(Microsoft.Tools.WindowsInstallerXml.Bootstrapper.LogLevel level, string message);
void Plan(LaunchAction action);
void SetLocalSource(string packageOrContainerId, string payloadId, string path);
void SetDownloadSource(string packageOrContainerId, string payloadId, string url, string user, string password);
int SendEmbeddedError(int errorCode, string message, int uiHint);
int SendEmbeddedProgress(int progressPercentage, int overallPercentage);
void Quit(int exitCode);
}
public class EngineWrapper : IEngine
{
readonly Engine inner;
public EngineWrapper(Engine inner)
{
this.inner = inner;
}
public Engine.Variables<long> NumericVariables { get { return inner.NumericVariables; } }
public int PackageCount { get { return inner.PackageCount; } }
public Engine.Variables<string> StringVariables { get { return inner.StringVariables; } }
public Engine.Variables<Version> VersionVariables { get { return inner.VersionVariables; } }
public void Apply(IntPtr hwndParent)
{
inner.Apply(hwndParent);
}
public void CloseSplashScreen()
{
inner.CloseSplashScreen();
}
public void Detect()
{
inner.Detect();
}
public bool Elevate(IntPtr hwndParent)
{
return inner.Elevate(hwndParent);
}
public string EscapeString(string input)
{
return inner.EscapeString(input);
}
public bool EvaluateCondition(string condition)
{
return inner.EvaluateCondition(condition);
}
public string FormatString(string format)
{
return inner.FormatString(format);
}
public void Log(LogLevel level, string message)
{
inner.Log(level, message);
}
public void Plan(LaunchAction action)
{
inner.Plan(action);
}
public void SetLocalSource(string packageOrContainerId, string payloadId, string path)
{
inner.SetLocalSource(packageOrContainerId, payloadId, path);
}
public void SetDownloadSource(string packageOrContainerId, string payloadId, string url, string user, string password)
{
inner.SetDownloadSource(packageOrContainerId, payloadId, url, user, password);
}
public int SendEmbeddedError(int errorCode, string message, int uiHint)
{
return inner.SendEmbeddedError(errorCode, message, uiHint);
}
public int SendEmbeddedProgress(int progressPercentage, int overallPercentage)
{
return inner.SendEmbeddedProgress(progressPercentage, overallPercentage);
}
public void Quit(int exitCode)
{
inner.Quit(exitCode);
}
}
}
| |
Fix for using two kinds of RssMonitor objects. | /* ------------------------------------------------------------------------- */
//
// Copyright (c) 2010 CubeSoft, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/* ------------------------------------------------------------------------- */
using System.Collections.Generic;
namespace Cube.Xui
{
/* --------------------------------------------------------------------- */
///
/// BindableOperator
///
/// <summary>
/// Bindable(T) および BindableCollection(T) の拡張用クラスです。
/// </summary>
///
/* --------------------------------------------------------------------- */
public static class BindableOperator
{
/* ----------------------------------------------------------------- */
///
/// ToBindable
///
/// <summary>
/// コレクションを BindingCollection(T) オブジェクトに変換します。
/// </summary>
///
/// <param name="src">コレクション</param>
///
/// <returns>BindableCollection(T) オブジェクト</returns>
///
/* ----------------------------------------------------------------- */
public static BindableCollection<T> ToBindable<T>(this IEnumerable<T> src) =>
new BindableCollection<T>(src);
}
}
| |
Add test to show a handler is instantiated twice, when using a pipeline | using Microsoft.Extensions.DependencyInjection;
namespace MediatR.Extensions.Microsoft.DependencyInjection.Tests
{
using System.Reflection;
using System.Threading.Tasks;
using Shouldly;
using Xunit;
public class PipelineMultiCallToConstructorTests
{
public class ConstructorTestBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
private readonly Logger _output;
public ConstructorTestBehavior(Logger output)
{
_output = output;
}
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next)
{
_output.Messages.Add("ConstructorTestBehavior before");
var response = await next();
_output.Messages.Add("ConstructorTestBehavior after");
return response;
}
}
public class ConstructorTestRequest : IRequest<ConstructorTestResponse>
{
public string Message { get; set; }
}
public class ConstructorTestResponse
{
public string Message { get; set; }
}
public class ConstructorTestHandler : IRequestHandler<ConstructorTestRequest, ConstructorTestResponse>
{
private static volatile object _lockObject = new object();
private readonly Logger _logger;
private static int _constructorCallCount;
public static int ConstructorCallCount
{
get { return _constructorCallCount; }
}
public static void ResetCallCount()
{
lock (_lockObject)
{
_constructorCallCount = 0;
}
}
public ConstructorTestHandler(Logger logger)
{
_logger = logger;
lock (_lockObject)
{
_constructorCallCount++;
}
}
public ConstructorTestResponse Handle(ConstructorTestRequest message)
{
_logger.Messages.Add("Handler");
return new ConstructorTestResponse { Message = message.Message + " ConstructorPong" };
}
}
[Fact]
public async Task Should_not_call_constructor_multiple_times_when_using_a_pipeline()
{
ConstructorTestHandler.ResetCallCount();
ConstructorTestHandler.ConstructorCallCount.ShouldBe(0);
var output = new Logger();
IServiceCollection services = new ServiceCollection();
services.AddSingleton(output);
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ConstructorTestBehavior<,>));
services.AddMediatR(typeof(Ping).GetTypeInfo().Assembly);
var provider = services.BuildServiceProvider();
var mediator = provider.GetService<IMediator>();
var response = await mediator.Send(new ConstructorTestRequest { Message = "ConstructorPing" });
response.Message.ShouldBe("ConstructorPing ConstructorPong");
output.Messages.ShouldBe(new[]
{
"ConstructorTestBehavior before",
"Handler",
"ConstructorTestBehavior after"
});
ConstructorTestHandler.ConstructorCallCount.ShouldBe(1);
}
}
} | |
Add temporary extension for bridging osuTK | // 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 TKVector2 = osuTK.Vector2;
using SNVector2 = System.Numerics.Vector2;
namespace osu.Framework.Extensions
{
/// <summary>
/// Temporary extension functions for bridging between osuTK, Veldrid, and System.Numerics
/// </summary>
public static class BridgingExtensions
{
public static TKVector2 ToOsuTK(this SNVector2 vec) =>
new TKVector2(vec.X, vec.Y);
public static SNVector2 ToSystemNumerics(this TKVector2 vec) =>
new SNVector2(vec.X, vec.Y);
}
}
| |
Move class to final location | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.Configuration;
using osu.Game.Database;
using osu.Game.Online.API;
using osu.Game.Online.Spectator;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Screens.Play.HUD
{
public class MultiplayerGameplayLeaderboard : GameplayLeaderboard
{
private readonly ScoreProcessor scoreProcessor;
/// <summary>
/// Construct a new leaderboard.
/// </summary>
/// <param name="scoreProcessor">A score processor instance to handle score calculation for scores of users in the match.</param>
public MultiplayerGameplayLeaderboard(ScoreProcessor scoreProcessor)
{
this.scoreProcessor = scoreProcessor;
AddPlayer(new BindableDouble(), new GuestUser());
}
[Resolved]
private SpectatorStreamingClient streamingClient { get; set; }
[Resolved]
private UserLookupCache userLookupCache { get; set; }
private readonly Dictionary<int, TrackedUserData> userScores = new Dictionary<int, TrackedUserData>();
private Bindable<ScoringMode> scoringMode;
[BackgroundDependencyLoader]
private void load(OsuConfigManager config)
{
streamingClient.OnNewFrames += handleIncomingFrames;
foreach (var user in streamingClient.PlayingUsers)
{
streamingClient.WatchUser(user);
var resolvedUser = userLookupCache.GetUserAsync(user).Result;
var trackedUser = new TrackedUserData();
userScores[user] = trackedUser;
AddPlayer(trackedUser.Score, resolvedUser);
}
scoringMode = config.GetBindable<ScoringMode>(OsuSetting.ScoreDisplayMode);
scoringMode.BindValueChanged(updateAllScores, true);
}
private void updateAllScores(ValueChangedEvent<ScoringMode> mode)
{
foreach (var trackedData in userScores.Values)
trackedData.UpdateScore(scoreProcessor, mode.NewValue);
}
private void handleIncomingFrames(int userId, FrameDataBundle bundle)
{
if (userScores.TryGetValue(userId, out var trackedData))
{
trackedData.LastHeader = bundle.Header;
trackedData.UpdateScore(scoreProcessor, scoringMode.Value);
}
}
private class TrackedUserData
{
public readonly BindableDouble Score = new BindableDouble();
public readonly BindableDouble Accuracy = new BindableDouble();
public readonly BindableInt CurrentCombo = new BindableInt();
[CanBeNull]
public FrameHeader LastHeader;
public void UpdateScore(ScoreProcessor processor, ScoringMode mode)
{
if (LastHeader == null)
return;
(Score.Value, Accuracy.Value) = processor.GetScoreAndAccuracy(mode, LastHeader.MaxCombo, LastHeader.Statistics.ToDictionary(s => s.Result, s => s.Count));
CurrentCombo.Value = LastHeader.Combo;
}
}
}
}
| |
Test program for using new RDF wrapper classes | /* -*- Mode: csharp; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: t -*- */
/***************************************************************************
* SimpleLookupTest.cs
*
* Copyright (C) 2005 Novell
* Written by Aaron Bockover (aaron@aaronbock.net)
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
using System;
using MusicBrainz;
public class SimpleLookupTest
{
private static void Main()
{
string id = "3738da94-663e-44c1-84af-f850b0bdb763";
using(Client client = new Client()) {
Console.WriteLine(new SimpleAlbum(client, id));
}
}
}
| |
Add convenience method to update data objects in list. | using System;
using Toggl.Phoebe.Data.DataObjects;
namespace Toggl.Phoebe.Data
{
public static class DataExtensions
{
/// <summary>
/// Checks if the two objects share the same type and primary key.
/// </summary>
/// <param name="data">Data object.</param>
/// <param name="other">Other data object.</param>
public static bool Matches (this CommonData data, object other)
{
if (data == other)
return true;
if (data == null || other == null)
return false;
if (data.GetType () != other.GetType ())
return false;
return data.Id == ((CommonData)data).Id;
}
}
}
| using System;
using System.Collections.Generic;
using Toggl.Phoebe.Data.DataObjects;
namespace Toggl.Phoebe.Data
{
public static class DataExtensions
{
/// <summary>
/// Checks if the two objects share the same type and primary key.
/// </summary>
/// <param name="data">Data object.</param>
/// <param name="other">Other data object.</param>
public static bool Matches (this CommonData data, object other)
{
if (data == other)
return true;
if (data == null || other == null)
return false;
if (data.GetType () != other.GetType ())
return false;
return data.Id == ((CommonData)data).Id;
}
public static bool UpdateData<T> (this IList<T> list, T data)
where T : CommonData
{
var updateCount = 0;
for (var idx = 0; idx < list.Count; idx++) {
if (data.Matches (list [idx])) {
list [idx] = data;
updateCount++;
}
}
return updateCount > 0;
}
}
}
|
Create implementation for Inspectors InspectorStartup | using System.Collections.Generic;
namespace Glimpse.Agent.Web
{
public class InspectorsInspectorStartup : IInspectorStartup
{
private readonly IEnumerable<IInspector> _inspectors;
public InspectorsInspectorStartup(IInspectorProvider inspectorProvider)
{
_inspectors = inspectorProvider.Inspectors;
}
public void Configure(IInspectorBuilder builder)
{
builder.Use(next => async context =>
{
foreach (var inspector in _inspectors)
{
await inspector.Before(context);
}
await next(context);
foreach (var inspector in _inspectors)
{
await inspector.After(context);
}
});
}
}
}
| |
Add example for When failing | using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Xunit.ScenarioReporting;
namespace Examples
{
public class FailingWhen
{
[Fact]
public Task<ScenarioRunResult> ShouldFail()
{
return new TestRunner().Run(def => def.Given().When(new object()).Then());
}
class TestRunner : ReflectionBasedScenarioRunner<object, object, object>
{
protected override Task Given(IReadOnlyList<object> givens)
{
return Task.CompletedTask;
}
protected override Task When(object when)
{
throw new NotImplementedException();
}
protected override Task<IReadOnlyList<object>> ActualResults()
{
throw new NotImplementedException();
}
}
}
}
| |
Create missing train describer context factory | using System.Data.Entity.Infrastructure;
using RailDataEngine.Data.Common;
namespace RailDataEngine.Data.TrainDescriber
{
public class TrainDescriberContextFactory : IDbContextFactory<TrainDescriberContext>
{
public TrainDescriberContext Create()
{
ITrainDescriberDatabase db = new TrainDescriberDatabase(new ConfigConnectionStringProvider());
return db.BuildContext() as TrainDescriberContext;
}
}
}
| |
Add basic testing of new beatmaps persistence | // 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.Beatmaps;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu;
using osu.Game.Storyboards;
namespace osu.Game.Tests.Visual.Editing
{
public class TestSceneEditorBeatmapCreation : EditorTestScene
{
protected override Ruleset CreateEditorRuleset() => new OsuRuleset();
protected override WorkingBeatmap CreateWorkingBeatmap(IBeatmap beatmap, Storyboard storyboard = null) => new DummyWorkingBeatmap(Audio, null);
[Test]
public void TestCreateNewBeatmap()
{
AddStep("save beatmap", () => Editor.Save());
AddAssert("new beatmap persisted", () => EditorBeatmap.BeatmapInfo.ID > 0);
}
}
}
| |
Remove Obsolete attribute. bugid: 294 | using System;
using System.Security.Principal;
using Csla.Serialization;
using System.Collections.Generic;
using Csla.Core.FieldManager;
using System.Runtime.Serialization;
using Csla.Core;
namespace Csla.Security
{
public abstract partial class CslaIdentity : ReadOnlyBase<CslaIdentity>, IIdentity
{
#region Constructor
/// <summary>
/// Creates an instance of the object.
/// </summary>
[Obsolete("For use by MobileFormatter")]
public CslaIdentity()
{
_forceInit = _forceInit && false;
}
#endregion
/// <summary>
/// Retrieves an instance of the identity
/// object.
/// </summary>
/// <typeparam name="T">
/// Type of object.
/// </typeparam>
/// <param name="completed">
/// Method called when the operation is
/// complete.
/// </param>
/// <param name="criteria">
/// Criteria object for the query.
/// </param>
public static void GetCslaIdentity<T>(EventHandler<DataPortalResult<T>> completed, object criteria) where T : CslaIdentity
{
DataPortal<T> dp = new DataPortal<T>();
dp.FetchCompleted += completed;
dp.BeginFetch(criteria);
}
protected override void OnDeserialized()
{
_forceInit = _forceInit && false;
base.OnDeserialized();
}
}
}
| using System;
using System.Security.Principal;
using Csla.Serialization;
using System.Collections.Generic;
using Csla.Core.FieldManager;
using System.Runtime.Serialization;
using Csla.Core;
namespace Csla.Security
{
public abstract partial class CslaIdentity : ReadOnlyBase<CslaIdentity>, IIdentity
{
#region Constructor
/// <summary>
/// Creates an instance of the object.
/// </summary>
public CslaIdentity()
{
_forceInit = _forceInit && false;
}
#endregion
/// <summary>
/// Retrieves an instance of the identity
/// object.
/// </summary>
/// <typeparam name="T">
/// Type of object.
/// </typeparam>
/// <param name="completed">
/// Method called when the operation is
/// complete.
/// </param>
/// <param name="criteria">
/// Criteria object for the query.
/// </param>
public static void GetCslaIdentity<T>(EventHandler<DataPortalResult<T>> completed, object criteria) where T : CslaIdentity
{
DataPortal<T> dp = new DataPortal<T>();
dp.FetchCompleted += completed;
dp.BeginFetch(criteria);
}
protected override void OnDeserialized()
{
_forceInit = _forceInit && false;
base.OnDeserialized();
}
}
}
|
Update countingSorter to take a IList<int> instead of int[] | using System;
using System.Collections.Generic;
using Algorithms.Common;
namespace Algorithms.Sorting
{
public static class CountingSorter
{
public static void CountingSort(this int[] array)
{
if (array == null || array.Length == 0)
return;
//
// Get the maximum number in array.
int maxK = 0;
int index = 0;
while (true)
{
if (index >= array.Length)
break;
maxK = Math.Max(maxK, array[index] + 1);
index++;
}
// The array of keys, used to sort the original array.
int[] keys = new int[maxK];
keys.Populate(0); // populate it with zeros
// Assign the keys
for (int i = 0; i < array.Length; ++i)
{
keys[array[i]] += 1;
}
// Reset index.
index = 0;
// Sort the elements
for (int j = 0; j < keys.Length; ++j)
{
var val = keys[j];
if (val > 0)
{
while (val-- > 0)
{
array[index] = j;
index++;
}
}
}
}
}
}
| using System;
using System.Collections.Generic;
using Algorithms.Common;
namespace Algorithms.Sorting
{
public static class CountingSorter
{
public static void CountingSort(this IList<int> collection)
{
if (collection == null || collection.Count == 0)
return;
// Get the maximum number in array.
int maxK = 0;
int index = 0;
while (true)
{
if (index >= collection.Count)
break;
maxK = Math.Max(maxK, collection[index] + 1);
index++;
}
// The array of keys, used to sort the original array.
int[] keys = new int[maxK];
keys.Populate(0); // populate it with zeros
// Assign the keys
for (int i = 0; i < collection.Count; ++i)
{
keys[collection[i]] += 1;
}
// Reset index.
index = 0;
// Sort the elements
for (int j = 0; j < keys.Length; ++j)
{
var val = keys[j];
if (val > 0)
{
while (val-- > 0)
{
collection[index] = j;
index++;
}
}
}
}
}
}
|
Add codex for mater messages | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Apex7000_BillValidator
{
class MasterCodex
{
internal enum MasterMessage : int
{
// Byte0 - bit 0
Accept1 = 1 << 0,
Accept2 = 1 << 1,
Accept3 = 1 << 2,
Accept4 = 1 << 3,
Accept5 = 1 << 4,
Accept6 = 1 << 5,
Accept7 = 1 << 6,
// Ignore 8th bit
x1 = 1 << 7,
// Byte 1 - bit 0
Reserved0 = 1 << 8, // Set to 0
Security = 1 << 9, // Set to 0
Orientation1 = 1 << 10, // Set to 0
Orientation2 = 1 << 11, // Set to 0
Escrow = 1 << 12, // Set to 1 to enable
Stack = 1 << 13, // In Escrow mode, set to 1 to stack
Return = 1 << 15, // In Escrow mode, set to 1 to return
// Ignore 8th bit
x2 = 1 << 16,
// Not part of spec, just added for decoding
InvalidCommand = 1 << 17
}
internal static MasterMessage ToMasterMessage(byte[] message)
{
if (message.Length != 8)
return MasterMessage.InvalidCommand;
int combined = (
(message[5] << 8) |
(message[4])
);
return (MasterMessage)combined;
}
}
}
| |
Address potential threading issue when sorting the list, by adding a lock around the sort process. | using System;
using System.Collections.Generic;
namespace Csla.Validation
{
internal class RulesList
{
private List<IRuleMethod> _list = new List<IRuleMethod>();
private bool _sorted;
private List<string> _dependantProperties;
public void Add(IRuleMethod item)
{
_list.Add(item);
_sorted = false;
}
public List<IRuleMethod> GetList(bool applySort)
{
if (applySort && !_sorted)
{
_list.Sort();
_sorted = true;
}
return _list;
}
public List<string> GetDependancyList(bool create)
{
if (_dependantProperties == null && create)
_dependantProperties = new List<string>();
return _dependantProperties;
}
}
}
| using System;
using System.Collections.Generic;
namespace Csla.Validation
{
internal class RulesList
{
private List<IRuleMethod> _list = new List<IRuleMethod>();
private bool _sorted;
private List<string> _dependantProperties;
public void Add(IRuleMethod item)
{
_list.Add(item);
_sorted = false;
}
public List<IRuleMethod> GetList(bool applySort)
{
if (applySort && !_sorted)
{
lock (_list)
{
if (applySort && !_sorted)
{
_list.Sort();
_sorted = true;
}
}
}
return _list;
}
public List<string> GetDependancyList(bool create)
{
if (_dependantProperties == null && create)
_dependantProperties = new List<string>();
return _dependantProperties;
}
}
}
|
Add enumeration for deep linking types | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace umbraco.cms.helpers
{
public enum DeepLinkType
{
Template,
DocumentType,
Content,
Media,
MediaType,
XSLT,
RazorScript,
Css,
Javascript,
Macro,
DataType
}
}
| |
Add back missing test scene | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Online.Chat;
using osu.Game.Overlays;
using osu.Game.Overlays.Chat;
using osu.Game.Overlays.Chat.Tabs;
namespace osu.Game.Tests.Visual.Online
{
[Description("Testing chat api and overlay")]
public class TestSceneChatOverlay : OsuTestScene
{
public override IReadOnlyList<Type> RequiredTypes => new[]
{
typeof(ChatLine),
typeof(DrawableChannel),
typeof(ChannelSelectorTabItem),
typeof(ChannelTabControl),
typeof(ChannelTabItem),
typeof(PrivateChannelTabItem),
typeof(TabCloseButton)
};
[Cached]
private readonly ChannelManager channelManager = new ChannelManager();
[BackgroundDependencyLoader]
private void load()
{
Children = new Drawable[]
{
channelManager,
new ChatOverlay { State = { Value = Visibility.Visible } }
};
}
}
}
| |
Add Extension Methods class that was not added in previous commit. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SKGL
{
public static class ExtensionMethods
{
public static bool IsValid(this KeyInformation keyInformation )
{
if(keyInformation != null)
{
return true;
}
return false;
}
public static KeyInformation HasNotExpired(this KeyInformation keyInformation)
{
if (keyInformation != null)
{
TimeSpan ts = keyInformation.ExpirationDate - DateTime.Today;
if (ts.Days >= 0)
{
return keyInformation;
}
}
return null;
}
}
}
| |
Add automapping override for account entity | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentNHibernate.Automapping;
using FluentNHibernate.Automapping.Alterations;
using FluentNHibernate.Mapping;
using MiTrello.Domain.Entities;
namespace MiniTrello.Data.AutoMappingOverride
{
public class AccountOverride : IAutoMappingOverride<Account>
{
public void Override(AutoMapping<Account> mapping)
{
//mapping.HasMany(x => x.Referrals)
// .Inverse()
// .Access.CamelCaseField(Prefix.Underscore);
}
}
}
| |
Add Passing and Failing Async Function Tests | using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NiL.JS.BaseLibrary;
using NiL.JS.Core;
using NiL.JS.Extensions;
namespace FunctionalTests
{
[TestClass]
public class AsyncFunctionTests
{
[TestMethod]
public async Task MarshalResolvedPromiseAsTask()
{
var context = new Context();
var result = await context.Eval("function getPromise() { return new Promise((a, b) => { a('test'); }); } async function test() { return await getPromise(); } test();").As<Promise>().Task;
Assert.AreEqual("test", result.ToString());
}
[TestMethod]
public async Task MarshalRejectedPromiseAsFailedTask()
{
var context = new Context();
await Assert.ThrowsExceptionAsync<Exception>(async () =>
{
await context.Eval("function getPromise() { return new Promise((a, b) => { b('test'); }); } async function test() { return await getPromise(); } test();").As<Promise>().Task;
});
}
}
}
| |
Add integration test for single and multiple common_words | using System;
using System.Linq;
using Elasticsearch.Net;
using FluentAssertions;
using Nest;
using Tests.Framework;
using Tests.Framework.ManagedElasticsearch.Clusters;
using Tests.Framework.MockData;
using Xunit;
namespace Tests.Reproduce
{
public class GithubIssue2886 : IClusterFixture<WritableCluster>
{
private readonly WritableCluster _cluster;
public GithubIssue2886(WritableCluster cluster) => _cluster = cluster;
[I]
public void CanReadSingleOrMultipleCommonGramsCommonWordsItem()
{
var client = _cluster.Client;
var json = @"
{
""settings"": {
""analysis"": {
""filter"": {
""single_common_words"": {
""type"": ""common_grams"",
""common_words"": ""_english_""
},
""multiple_common_words"": {
""type"": ""common_grams"",
""common_words"": [""_english_"", ""_french_""]
}
}
}
}
}";
var response = client.LowLevel.IndicesCreate<string>("common_words_token_filter", json);
response.Success.Should().BeTrue();
var settingsResponse = client.GetIndex("common_words_token_filter");
var indexState = settingsResponse.Indices["common_words_token_filter"];
indexState.Should().NotBeNull();
var tokenFilters = indexState.Settings.Analysis.TokenFilters;
tokenFilters.Should().HaveCount(2);
var commonGramsTokenFilter = tokenFilters["single_common_words"] as ICommonGramsTokenFilter;
commonGramsTokenFilter.Should().NotBeNull();
commonGramsTokenFilter.CommonWords.Should().NotBeNull().And.HaveCount(1);
commonGramsTokenFilter = tokenFilters["multiple_common_words"] as ICommonGramsTokenFilter;
commonGramsTokenFilter.Should().NotBeNull();
commonGramsTokenFilter.CommonWords.Should().NotBeNull().And.HaveCount(2);
}
}
}
| |
Test file 'Value Controller' added | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace CloudBread_Admin_Web.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
| |
Add missing file to VC | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Nett
{
internal class TomlComment
{
public string CommentText { get; private set; }
public CommentLocation Location { get; private set; }
public TomlComment(string commentText, CommentLocation location)
{
this.CommentText = commentText;
this.Location = location;
}
}
}
| |
Add a common object to provide wall locking. | using System;
using System.Threading;
using System.Threading.Tasks;
namespace KafkaNet.Common
{
public class ThreadWall
{
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
public void Block()
{
_semaphore.Wait();
}
public void Release()
{
_semaphore.Release();
}
public Task RequestPassageAsync()
{
return AsTask(_semaphore.AvailableWaitHandle, Timeout.InfiniteTimeSpan);
}
private static Task AsTask(WaitHandle handle, TimeSpan timeout)
{
var tcs = new TaskCompletionSource<object>();
var registration = ThreadPool.RegisterWaitForSingleObject(handle, (state, timedOut) =>
{
var localTcs = (TaskCompletionSource<object>)state;
if (timedOut)
localTcs.TrySetCanceled();
else
localTcs.TrySetResult(null);
}, tcs, timeout, executeOnlyOnce: true);
tcs.Task.ContinueWith((_, state) => ((RegisteredWaitHandle)state).Unregister(null), registration, TaskScheduler.Default);
return tcs.Task;
}
}
}
| |
Add test for interface derived classes | using NUnit.Framework;
using Python.Runtime;
namespace Python.EmbeddingTest
{
public class TestInterfaceClasses
{
public string testCode = @"
from clr import AddReference
AddReference(""System"")
AddReference(""Python.EmbeddingTest"")
from Python.EmbeddingTest import *
testModule = TestInterfaceClasses.GetInstance()
print(testModule.Child.ChildBool)
";
[OneTimeSetUp]
public void SetUp()
{
PythonEngine.Initialize();
}
[OneTimeTearDown]
public void Dispose()
{
PythonEngine.Shutdown();
}
[Test]
public void TestInterfaceDerivedClassMembers()
{
// This test gets an instance of the CSharpTestModule in Python
// and then attempts to access it's member "Child"'s bool that is
// not defined in the interface.
PythonEngine.Exec(testCode);
}
public interface IInterface
{
bool InterfaceBool { get; set; }
}
public class Parent : IInterface
{
public bool InterfaceBool { get; set; }
public bool ParentBool { get; set; }
}
public class Child : Parent
{
public bool ChildBool { get; set; }
}
public class CSharpTestModule
{
public IInterface Child;
public CSharpTestModule()
{
Child = new Child
{
ChildBool = true,
ParentBool = true,
InterfaceBool = true
};
}
}
public static CSharpTestModule GetInstance()
{
return new CSharpTestModule();
}
}
}
| |
Add test coverage of `SubmittableScore` serialisation to (roughly) match spec | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using Newtonsoft.Json;
using NUnit.Framework;
using osu.Game.IO.Serialization;
using osu.Game.Online.Solo;
using osu.Game.Tests.Resources;
namespace osu.Game.Tests.Online
{
/// <summary>
/// Basic testing to ensure our attribute-based naming is correctly working.
/// </summary>
[TestFixture]
public class TestSubmittableScoreJsonSerialization
{
[Test]
public void TestScoreSerialisationViaExtensionMethod()
{
var score = new SubmittableScore(TestResources.CreateTestScoreInfo());
string serialised = score.Serialize();
Assert.That(serialised, Contains.Substring("large_tick_hit"));
Assert.That(serialised, Contains.Substring("\"rank\": \"S\""));
}
[Test]
public void TestScoreSerialisationWithoutSettings()
{
var score = new SubmittableScore(TestResources.CreateTestScoreInfo());
string serialised = JsonConvert.SerializeObject(score);
Assert.That(serialised, Contains.Substring("large_tick_hit"));
Assert.That(serialised, Contains.Substring("\"rank\":\"S\""));
}
}
}
| |
Add failing test case for player sending wrong ruleset ID to spectator server | // 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.Game.Online.API;
using osu.Game.Online.Spectator;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mania;
using osu.Game.Tests.Visual.Spectator;
using osu.Game.Users;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneSpectatorHost : PlayerTestScene
{
protected override Ruleset CreatePlayerRuleset() => new ManiaRuleset();
[Cached(typeof(SpectatorClient))]
private TestSpectatorClient spectatorClient { get; } = new TestSpectatorClient();
private DummyAPIAccess dummyAPIAccess => (DummyAPIAccess)API;
private const int dummy_user_id = 42;
public override void SetUpSteps()
{
AddStep("set dummy user", () => dummyAPIAccess.LocalUser.Value = new User
{
Id = dummy_user_id,
Username = "DummyUser"
});
AddStep("add test spectator client", () => Add(spectatorClient));
AddStep("add watching user", () => spectatorClient.WatchUser(dummy_user_id));
base.SetUpSteps();
}
[Test]
public void TestClientSendsCorrectRuleset()
{
AddUntilStep("spectator client sending frames", () => spectatorClient.PlayingUserStates.ContainsKey(dummy_user_id));
AddAssert("spectator client sent correct ruleset", () => spectatorClient.PlayingUserStates[dummy_user_id].RulesetID == Ruleset.Value.ID);
}
public override void TearDownSteps()
{
base.TearDownSteps();
AddStep("stop watching user", () => spectatorClient.StopWatchingUser(dummy_user_id));
AddStep("remove test spectator client", () => Remove(spectatorClient));
}
}
}
| |
Add shell sort implementation in csharp | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace shellsort
{
public class ShellSort
{
private readonly int[] _array;
public ShellSort(int[] array)
{
this._array = array;
}
public int[] Sort()
{
int i, j, inc, temp;
var array_size = _array.Length;
inc = 3;
while (inc > 0)
{
for (i = 0; i < array_size; i++)
{
j = i;
temp = _array[i];
while ((j >= inc) && (_array[j - inc] > temp))
{
_array[j] = _array[j - inc];
j = j - inc;
}
_array[j] = temp;
}
if (inc / 2 != 0)
inc = inc / 2;
else if (inc == 1)
inc = 0;
else
inc = 1;
}
return _array;
}
}
}
| |
Add a few tests for F.Range | using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace CSharp.Functional.Tests
{
public class RangeTests
{
[Theory]
[InlineData(0, 1)]
public void RangeProvidesAnIEnumerable(int start, int end)
{
var result = F.Range(start, end);
Assert.IsAssignableFrom<IEnumerable>(result);
}
[Theory]
[InlineData(0, 1)]
public void RangeProvidesAnIEnumerableOfIntegers(int start, int end)
{
var result = F.Range(start, end);
Assert.IsAssignableFrom<IEnumerable<int>>(result);
}
[Theory]
[InlineData(0, 1)]
[InlineData(0, 0)]
public void RangeBeginssAtStartValue(int start, int end)
{
var result = F.Range(start, end).First();
Assert.Equal(start, result);
}
[Theory]
[InlineData(0, 1)]
[InlineData(0, 0)]
public void RangeTerminatesAtEndValue(int start, int end)
{
var result = F.Range(start, end).Last();
Assert.Equal(end, result);
}
}
} | |
Split some methods off into a private class. | using Microsoft.AspNet.SignalR;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using VJoyWrapper;
namespace WebsocketGamepad
{
public partial class PhoneHub : Hub
{
private double Rescale(double input, Tuple<long, long> destination, Tuple<int, int> source)
{
return (input + (destination.Item1 - source.Item1)) * ((destination.Item2 - destination.Item1) / (source.Item2 - source.Item1));
}
protected static ConcurrentDictionary<string, Lazy<Task<Gamepad>>> Gamepads = new ConcurrentDictionary<string, Lazy<Task<Gamepad>>>();
protected static ConcurrentDictionary<string, string> ConnectionIdToClientMap = new ConcurrentDictionary<string, string>();
protected static SemaphoreSlim AvailableGamepads;
private Task<Gamepad> GetUniqueGamepad(string id)
{
ConnectionIdToClientMap.AddOrUpdate(Context.ConnectionId, id, (a, b) => id);
return Gamepads.GetOrAdd(id, new Lazy<Task<Gamepad>>(Gamepad.Construct, LazyThreadSafetyMode.ExecutionAndPublication)).Value;
}
private async Task ReturnClientGamepad() {
string userId;
Lazy<Task<Gamepad>> gamepadWrapper;
if (ConnectionIdToClientMap.TryGetValue(Context.ConnectionId, out userId) && Gamepads.TryRemove(userId, out gamepadWrapper)) {
var gamepad = await gamepadWrapper.Value;
gamepad.Dispose();
}
}
}
}
| |
Add benchmark coverage of mod retrieval | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using BenchmarkDotNet.Attributes;
using osu.Game.Online.API;
using osu.Game.Rulesets.Osu;
namespace osu.Game.Benchmarks
{
public class BenchmarkRuleset : BenchmarkTest
{
private OsuRuleset ruleset;
private APIMod apiModDoubleTime;
private APIMod apiModDifficultyAdjust;
public override void SetUp()
{
base.SetUp();
ruleset = new OsuRuleset();
apiModDoubleTime = new APIMod { Acronym = "DT" };
apiModDifficultyAdjust = new APIMod { Acronym = "DA" };
}
[Benchmark]
public void BenchmarkToModDoubleTime()
{
apiModDoubleTime.ToMod(ruleset);
}
[Benchmark]
public void BenchmarkToModDifficultyAdjust()
{
apiModDifficultyAdjust.ToMod(ruleset);
}
[Benchmark]
public void BenchmarkGetAllMods()
{
ruleset.GetAllMods();
}
}
}
| |
Add Entity Framework job storage tests | using System;
using Hangfire.EntityFramework.Utils;
using Xunit;
namespace Hangfire.EntityFramework
{
public class EntityFrameworkJobStorageTests
{
private EntityFrameworkJobStorageOptions Options;
public EntityFrameworkJobStorageTests()
{
Options = new EntityFrameworkJobStorageOptions();
}
[Fact]
public void Ctor_ThrowsAnException_WhenConnectionStringIsNull()
{
Assert.Throws<ArgumentNullException>("nameOrConnectionString",
() => new EntityFrameworkJobStorage(null));
}
[Fact]
public void Ctor_ThrowsAnException_WhenOptionsValueIsNull()
{
Assert.Throws<ArgumentNullException>("options",
() => new EntityFrameworkJobStorage(string.Empty, null));
}
[Fact, CleanDatabase]
public void GetMonitoringApi_ReturnsNonNullInstance()
{
var storage = CreateStorage();
var api = storage.GetMonitoringApi();
Assert.NotNull(api);
}
[Fact, CleanDatabase]
public void GetConnection_ReturnsNonNullInstance()
{
var storage = CreateStorage();
using (var connection = (EntityFrameworkJobStorageConnection)storage.GetConnection())
{
Assert.NotNull(connection);
}
}
private EntityFrameworkJobStorage CreateStorage() =>
new EntityFrameworkJobStorage(ConnectionUtils.GetConnectionString(), Options);
}
}
| |
Add platform specified root exception class | using System;
using System.Runtime.Serialization;
namespace Xemi.Core
{
public class XemiException:Exception
{
public XemiException()
{ }
public XemiException(string message)
: base(message)
{
}
public XemiException(string messageFormat, params object[] args)
: base(string.Format(messageFormat, args))
{
}
public XemiException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
public XemiException(string message, Exception innerException)
: base(message, innerException)
{
}
}
} | |
Add a integration test to verify we can retrieve the current profile from the ProfileClient | using Mollie.Api.Models.Profile.Response;
using Mollie.Tests.Integration.Framework;
using NUnit.Framework;
using System.Threading.Tasks;
namespace Mollie.Tests.Integration.Api {
[TestFixture]
public class ProfileTests : BaseMollieApiTestClass {
[Test]
public async Task GetCurrentProfileAsync_ReturnsCurrentProfile() {
// Given
// When: We retrieve the current profile from the mollie API
ProfileResponse profileResponse = await this._profileClient.GetCurrentProfileAsync();
// Then: Make sure we get a valid response
Assert.IsNotNull(profileResponse);
Assert.IsNotNull(profileResponse.Id);
Assert.IsNotNull(profileResponse.Email);
Assert.IsNotNull(profileResponse.Status);
}
}
}
| |
Add a convenience method for converting transform positions to gui positions | using UnityEngine;
using System.Collections;
public class TransformToGuiFinder {
public static Vector2 Find(Transform target) {
var position = Camera.main.WorldToScreenPoint(target.position);
position.y = Screen.height - position.y;
return position;
}
}
| |
Add missing file and other changes. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Canon.Eos.Framework.Eventing
{
public class EosExceptionEventArgs : EventArgs
{
public Exception Exception { get; internal set; }
}
}
| |
Update assembly version for NuGet | using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("mustache-sharp")]
[assembly: AssemblyDescription("A extension of the mustache text template engine for .NET.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("truncon")]
[assembly: AssemblyProduct("mustache-sharp")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: Guid("e5a4263d-d450-4d85-a4d5-44c0a2822668")]
[assembly: AssemblyVersion("0.2.7.1")]
[assembly: AssemblyFileVersion("0.2.7.1")]
[assembly: InternalsVisibleTo("mustache-sharp.test")] | using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("mustache-sharp")]
[assembly: AssemblyDescription("A extension of the mustache text template engine for .NET.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("truncon")]
[assembly: AssemblyProduct("mustache-sharp")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: Guid("e5a4263d-d450-4d85-a4d5-44c0a2822668")]
[assembly: AssemblyVersion("0.2.8.0")]
[assembly: AssemblyFileVersion("0.2.8.0")]
[assembly: InternalsVisibleTo("mustache-sharp.test")] |
Fix issue with nested actions not being shown. | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
{
/// <summary>
/// Lightbulb item that has child items that should be displayed as 'menu items'
/// (as opposed to 'flavor items').
/// </summary>
internal sealed class SuggestedActionWithNestedActions : SuggestedAction
{
public readonly SuggestedActionSet NestedActionSet;
public SuggestedActionWithNestedActions(
SuggestedActionsSourceProvider sourceProvider, Workspace workspace,
ITextBuffer subjectBuffer, object provider,
CodeAction codeAction, SuggestedActionSet nestedActionSet)
: base(sourceProvider, workspace, subjectBuffer, provider, codeAction)
{
NestedActionSet = nestedActionSet;
}
public sealed override Task<IEnumerable<SuggestedActionSet>> GetActionSetsAsync(CancellationToken cancellationToken)
=> Task.FromResult<IEnumerable<SuggestedActionSet>>(ImmutableArray.Create(NestedActionSet));
}
} | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
{
/// <summary>
/// Lightbulb item that has child items that should be displayed as 'menu items'
/// (as opposed to 'flavor items').
/// </summary>
internal sealed class SuggestedActionWithNestedActions : SuggestedAction
{
public readonly SuggestedActionSet NestedActionSet;
public SuggestedActionWithNestedActions(
SuggestedActionsSourceProvider sourceProvider, Workspace workspace,
ITextBuffer subjectBuffer, object provider,
CodeAction codeAction, SuggestedActionSet nestedActionSet)
: base(sourceProvider, workspace, subjectBuffer, provider, codeAction)
{
NestedActionSet = nestedActionSet;
}
public override bool HasActionSets => true;
public sealed override Task<IEnumerable<SuggestedActionSet>> GetActionSetsAsync(CancellationToken cancellationToken)
=> Task.FromResult<IEnumerable<SuggestedActionSet>>(ImmutableArray.Create(NestedActionSet));
}
} |
Add interface to handle local beatmap presentation logic | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Beatmaps;
using osu.Game.Rulesets;
namespace osu.Game.Screens
{
/// <summary>
/// Denotes a screen which can handle beatmap / ruleset selection via local logic.
/// This is used in the <see cref="OsuGame.PresentBeatmap"/> flow to handle cases which require custom logic,
/// for instance, if a lease is held on the Beatmap.
/// </summary>
public interface IHandlePresentBeatmap
{
/// <summary>
/// Invoked with a requested beatmap / ruleset for selection.
/// </summary>
/// <param name="beatmap">The beatmap to be selected.</param>
/// <param name="ruleset">The ruleset to be selected.</param>
public void PresentBeatmap(WorkingBeatmap beatmap, RulesetInfo ruleset);
}
}
| |
Add an Uri extension to work with Uri scheme. | using System;
using System.Text.RegularExpressions;
using Microsoft.Win32;
namespace SteamFriendsManager.Utility
{
public static class UriExtension
{
public static bool CheckSchemeExistance(this Uri uri)
{
var schemeKey = Registry.ClassesRoot.OpenSubKey(uri.Scheme);
return schemeKey != null && schemeKey.GetValue("URL Protocol") != null;
}
public static string GetSchemeExecutable(this Uri uri)
{
var commandKey = Registry.ClassesRoot.OpenSubKey(string.Format(@"{0}\Shell\Open\Command", uri.Scheme));
if (commandKey == null)
return null;
var command = commandKey.GetValue(null) as string;
if (command == null)
return null;
return Regex.Match(command, @"(?<="").*?(?="")").Value;
}
}
} | |
Add prefix module to get or set the current prefix | using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using SoraBot.Common.Extensions.Modules;
using SoraBot.Services.Guilds;
namespace SoraBot.Bot.Modules
{
[Name("Prefix")]
[Summary("Commands to get and set the prefix inside a Guild")]
public class PrefixModule : SoraSocketCommandModule
{
private readonly IPrefixService _prefixService;
public PrefixModule(IPrefixService prefixService)
{
_prefixService = prefixService;
}
[Command("prefix")]
[Summary("Gets the current prefix in the guild")]
public async Task GetPrefix()
{
var prefix = await _prefixService.GetPrefix(Context.Guild.Id).ConfigureAwait(false);
await ReplySuccessEmbed($"The Prefix for this Guild is `{prefix}`");
}
[Command("prefix")]
[Summary("This lets you change the prefix in the Guild. " +
"You need to be an Administrator to do this!")]
[RequireUserPermission(GuildPermission.Administrator, ErrorMessage = "You must be an Administrator to use this command!")]
public async Task SetPrefix(string prefix)
{
prefix = prefix.Trim();
if (prefix.Length > 20)
{
await ReplyFailureEmbed("Please specify a prefix that is shorter than 20 Characters!");
return;
}
if (!await _prefixService.SetPrefix(Context.Guild.Id, prefix).ConfigureAwait(false))
{
await ReplyFailureEmbed("Something failed when trying to save the prefix. Please try again");
return;
}
await ReplySuccessEmbed($"Successfully updated Guild Prefix to `{prefix}`!");
}
}
} | |
Create root entry point for SystemWeb | #if SystemWeb
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
namespace Glimpse
{
public static class Glimpse
{
public static IServiceCollection Start()
{
return Start(null);
}
public static IServiceCollection Start(IServiceCollection serviceProvider)
{
return null;
}
}
}
#endif | |
Add basic structure for hex colour picker part | // 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.Bindables;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
namespace osu.Framework.Graphics.UserInterface
{
public abstract class HexColourPicker : CompositeDrawable, IHasCurrentValue<Colour4>
{
private readonly BindableWithCurrent<Colour4> current = new BindableWithCurrent<Colour4>();
public Bindable<Colour4> Current
{
get => current.Current;
set => current.Current = value;
}
private readonly Box background;
private readonly TextBox hexCodeTextBox;
private readonly Drawable spacer;
private readonly ColourPreview colourPreview;
protected HexColourPicker()
{
InternalChildren = new Drawable[]
{
background = new Box
{
RelativeSizeAxes = Axes.Both
},
new GridContainer
{
ColumnDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.AutoSize),
new Dimension()
},
Content = new[]
{
new[]
{
hexCodeTextBox = CreateHexCodeTextBox(),
spacer = Empty(),
colourPreview = CreateColourPreview()
}
}
}
};
}
/// <summary>
/// Creates the text box to be used for specifying the hex code of the target colour.
/// </summary>
protected abstract TextBox CreateHexCodeTextBox();
/// <summary>
/// Creates the control that will be used for displaying the preview of the target colour.
/// </summary>
protected abstract ColourPreview CreateColourPreview();
protected override void LoadComplete()
{
base.LoadComplete();
colourPreview.Current.BindTo(Current);
}
public abstract class ColourPreview : CompositeDrawable
{
public Bindable<Colour4> Current = new Bindable<Colour4>();
}
}
}
| |
Add very basic TestGetRootPartPosition() test | /*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Reflection;
using System.Threading;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Tests.Common;
using OpenSim.Tests.Common.Mock;
namespace OpenSim.Region.Framework.Scenes.Tests
{
/// <summary>
/// Spatial scene object tests (will eventually cover root and child part position, rotation properties, etc.)
/// </summary>
[TestFixture]
public class SceneObjectSpatialTests
{
[Test]
public void TestGetRootPartPosition()
{
TestHelpers.InMethod();
Scene scene = SceneHelpers.SetupScene();
UUID ownerId = TestHelpers.ParseTail(0x1);
Vector3 partPosition = new Vector3(10, 20, 30);
SceneObjectGroup so
= SceneHelpers.CreateSceneObject(1, ownerId, "obj1", 0x10);
so.AbsolutePosition = partPosition;
scene.AddNewSceneObject(so, false);
Assert.That(so.AbsolutePosition, Is.EqualTo(partPosition));
Assert.That(so.RootPart.AbsolutePosition, Is.EqualTo(partPosition));
}
}
} | |
Improve parsing of issues in release notes | namespace FakeItEasy.Tools
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using Octokit;
public static class ReleaseHelpers
{
public static ICollection<int> GetIssueNumbersReferencedFromReleases(IEnumerable<Release> releases)
{
// Release bodies should contain references to fixed issues in the form
// (#1234), or (#1234, #1235, #1236) if multiple issues apply to a topic.
// It's hard (impossible?) to harvest values from a repeated capture group,
// so grab everything between the ()s and split manually.
var issuesReferencedFromRelease = new HashSet<int>();
foreach (var release in releases)
{
foreach (Match match in Regex.Matches(release.Body, @"\((?<issueNumbers>#[0-9]+((, )#[0-9]+)*)\)"))
{
var issueNumbers = match.Groups["issueNumbers"].Value;
foreach (var issueNumber in issueNumbers.Split(new[] { '#', ' ', ',' }, StringSplitOptions.RemoveEmptyEntries))
{
issuesReferencedFromRelease.Add(int.Parse(issueNumber, NumberStyles.Integer, NumberFormatInfo.InvariantInfo));
}
}
}
return issuesReferencedFromRelease;
}
}
}
| namespace FakeItEasy.Tools
{
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using Octokit;
public static class ReleaseHelpers
{
public static ICollection<int> GetIssueNumbersReferencedFromReleases(IEnumerable<Release> releases)
{
var issuesReferencedFromRelease = new HashSet<int>();
foreach (var release in releases)
{
foreach (Match match in Regex.Matches(release.Body, @"\(\s*#(?<issueNumber>[0-9]+)(,\s*#(?<issueNumber>[0-9]+))*\s*\)"))
{
foreach (Capture capture in match.Groups["issueNumber"].Captures)
{
issuesReferencedFromRelease.Add(int.Parse(capture.Value, NumberStyles.Integer, NumberFormatInfo.InvariantInfo));
}
}
}
return issuesReferencedFromRelease;
}
}
}
|
Add ability to run evaluation tests | using System;
using Xunit;
namespace NQuery.Tests.Evaluation
{
public class EvaluationTest
{
protected void AssertProduces<T>(string text, T[] expected)
{
var expectedColumns = new[] { typeof(T) };
var expectedRows = new object[expected.Length][];
for (var i = 0; i < expected.Length; i++)
expectedRows[i] = new object[] { expected[i] };
AssertProduces(text, expectedColumns, expectedRows);
}
protected void AssertProduces<T1, T2>(string text, (T1, T2)[] expected)
{
var expectedColumns = new[] { typeof(T1), typeof(T2) };
var expectedRows = new object[expected.Length][];
for (var i = 0; i < expected.Length; i++)
expectedRows[i] = new object[] { expected[i].Item1, expected[i].Item2 };
AssertProduces(text, expectedColumns, expectedRows);
}
private void AssertProduces(string text, Type[] expectedColumns, object[][] expectedRows)
{
var dataContext = NorthwindDataContext.Instance;
var query = Query.Create(dataContext, text);
using (var data = query.ExecuteReader())
{
Assert.Equal(expectedColumns.Length, data.ColumnCount);
for (var i = 0; i < expectedColumns.Length; i++)
Assert.Equal(expectedColumns[i], data.GetColumnType(i));
var rowIndex = 0;
while (data.Read())
{
var expectedRow = expectedRows[rowIndex];
for (var columnIndex = 0; columnIndex < expectedColumns.Length; columnIndex++)
Assert.Equal(expectedRow[columnIndex], data[columnIndex]);
rowIndex++;
}
}
}
}
}
| |
Add mouse tint debug component | using System;
using System.Collections.Generic;
using System.Text;
using SadConsole.Input;
using SadRogue.Primitives;
namespace SadConsole.Components
{
/// <summary>
/// Tints a surface when that surface would use the mouse. Helps debug which object is receiving mouse input as you move the mouse around.
/// </summary>
public class MouseTint : UpdateComponent
{
IScreenObject _previous;
SadConsole.Input.Mouse _mouse;
/// <inheritdoc/>
public override void OnAdded(IScreenObject host)
{
_mouse = new SadConsole.Input.Mouse();
_mouse.Update(TimeSpan.Zero);
}
/// <inheritdoc/>
public override void Update(IScreenObject host, TimeSpan delta)
{
_mouse.Update(delta);
// Build a list of all screen objects
var screenObjects = new List<IScreenObject>();
GetConsoles(GameHost.Instance.Screen, ref screenObjects);
// Process top-most screen objects first.
screenObjects.Reverse();
for (int i = 0; i < screenObjects.Count; i++)
{
var state = new MouseScreenObjectState(screenObjects[i], _mouse);
if (screenObjects[i].IsVisible && screenObjects[i].UseMouse && state.IsOnScreenObject)
{
if (_previous != null && _previous != screenObjects[i])
if (_previous is IScreenSurface prevSurface)
prevSurface.Tint = Color.Transparent;
_previous = screenObjects[i];
if (_previous is IScreenSurface newSurface)
newSurface.Tint = Color.Purple.SetAlpha(128);
break;
}
}
}
private void GetConsoles(IScreenObject screen, ref List<IScreenObject> list)
{
if (!screen.IsVisible) return;
if (screen.UseMouse)
list.Add(screen);
foreach (IScreenObject child in screen.Children)
GetConsoles(child, ref list);
}
}
}
| |
Add utils class which holds temporary linking info between user-device. | using A2BBAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace A2BBAPI.Utils
{
/// <summary>
/// Class holding info for device linking.
/// </summary>
public class LinkHolder
{
#region Public properties
/// <summary>
/// The device to link.
/// </summary>
public Device Device { get; set; }
/// <summary>
/// The user username.
/// </summary>
public string Username { get; set; }
/// <summary>
/// The user password.
/// </summary>
public string Password { get; set; }
/// <summary>
/// The user subject id.
/// </summary>
public string Subject { get; set; }
/// <summary>
/// Whether the link has been actually estabilished or not.
/// </summary>
public bool IsEstabilished { get; set; }
#endregion
}
}
| |
Drop PAssertException from public api | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
namespace ExpressionToCodeLib
{
[Obsolete(
"This class is *not* the base class of all assertion violation exceptions - don't rely on it! It will be removed in version 2."
), Serializable]
public class PAssertFailedException : Exception
{
public PAssertFailedException(string message)
: base(message) { }
public PAssertFailedException(string message, Exception inner)
: base(message, inner) { }
public PAssertFailedException(SerializationInfo info, StreamingContext context)
: base(info, context) { }
}
#pragma warning disable 618
[Serializable]
sealed class AssertFailedException : PAssertFailedException
#pragma warning restore 618
{
public AssertFailedException(string message)
: base(message) { }
public AssertFailedException(string message, Exception inner)
: base(message, inner) { }
public AssertFailedException(SerializationInfo info, StreamingContext context)
: base(info, context) { }
}
namespace Internal
{
/// <summary>
/// This class is not part of the public API: it's undocumented and minor version bumps may break compatiblity.
/// </summary>
public static class UnitTestingInternalsAccess
{
public static Exception CreateException(string msg) { return new AssertFailedException(msg); }
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
namespace ExpressionToCodeLib
{
[Serializable]
sealed class AssertFailedException : Exception
{
public AssertFailedException(string message)
: base(message) { }
public AssertFailedException(string message, Exception inner)
: base(message, inner) { }
public AssertFailedException(SerializationInfo info, StreamingContext context)
: base(info, context) { }
}
namespace Internal
{
/// <summary>
/// This class is not part of the public API: it's undocumented and minor version bumps may break compatiblity.
/// </summary>
public static class UnitTestingInternalsAccess
{
public static Exception CreateException(string msg) { return new AssertFailedException(msg); }
}
}
}
|
Add content media type tests | using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Porthor.Models;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Porthor.Tests
{
public class ContentDefinitionTests
{
[Fact]
public async Task Request_WithInvalidMediaType_ReturnsUnsupportedMediaType()
{
// Arrange
var builder = new WebHostBuilder()
.ConfigureServices(services =>
{
services.AddPorthor(options =>
{
options.Content.ValidationEnabled = true;
});
})
.Configure(app =>
{
var resource = new Resource
{
Method = HttpMethod.Post,
Path = "api/v5.1/data",
ContentDefinitions = new List<ContentDefinition>
{
new ContentDefinition{ MediaType = PorthorConstants.MediaType.Json }
},
EndpointUrl = $"http://example.org/api/v5.1/data"
};
app.UsePorthor(new[] { resource });
});
var server = new TestServer(builder);
// Act
var requestMessage = new HttpRequestMessage(HttpMethod.Post, "api/v5.1/data");
requestMessage.Content = new StringContent("Request Body");
var responseMessage = await server.CreateClient().SendAsync(requestMessage);
// Assert
Assert.Equal(HttpStatusCode.UnsupportedMediaType, responseMessage.StatusCode);
}
[Fact]
public async Task Request_WithValidMediaType_ReturnsOk()
{
// Arrange
var builder = new WebHostBuilder()
.ConfigureServices(services =>
{
services.AddPorthor(options =>
{
options.BackChannelMessageHandler = new TestMessageHandler
{
Sender = request =>
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
return response;
}
};
options.Content.ValidationEnabled = true;
});
})
.Configure(app =>
{
var resource = new Resource
{
Method = HttpMethod.Post,
Path = "api/v5.2/data",
ContentDefinitions = new List<ContentDefinition>
{
new ContentDefinition{ MediaType = PorthorConstants.MediaType.Json }
},
EndpointUrl = $"http://example.org/api/v5.2/data"
};
app.UsePorthor(new[] { resource });
});
var server = new TestServer(builder);
// Act
var requestMessage = new HttpRequestMessage(HttpMethod.Post, "api/v5.2/data");
requestMessage.Content = new StringContent("{ \"name\": \"demo\" }", Encoding.UTF8, PorthorConstants.MediaType.Json);
var responseMessage = await server.CreateClient().SendAsync(requestMessage);
// Assert
Assert.Equal(HttpStatusCode.OK, responseMessage.StatusCode);
}
}
}
| |
Add class for fixed point data | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LBD2OBJ.Types
{
class FixedPoint
{
public int IntegralPart { get; set; }
public int DecimalPart { get; set; }
public FixedPoint(byte[] data)
{
if (data.Length != 2) { throw new ArgumentException("data must be 2 bytes", "data"); }
byte[] _data = new byte[2];
data.CopyTo(_data, 0);
var signMask = (byte)128;
var integralMask = (byte)112;
var firstPartOfDecimalMask = (byte)15;
bool isNegative = (_data[0] & signMask) == 128;
int integralPart = (_data[0] & integralMask) * (isNegative ? -1 : 1);
int decimalPart = (_data[0] & firstPartOfDecimalMask);
decimalPart <<= 8;
decimalPart += data[1];
IntegralPart = integralPart;
DecimalPart = decimalPart;
}
}
}
| |
Add presenter for asmdef occurrences | using System.Drawing;
using JetBrains.Application.UI.Controls.JetPopupMenu;
using JetBrains.Diagnostics;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Feature.Services.Occurrences;
using JetBrains.ReSharper.Feature.Services.Presentation;
using JetBrains.ReSharper.Plugins.Unity.AsmDef.Psi.Caches;
using JetBrains.ReSharper.Plugins.Unity.AsmDef.Psi.DeclaredElements;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Resources.Shell;
using JetBrains.UI.Icons;
using JetBrains.UI.RichText;
namespace JetBrains.ReSharper.Plugins.Unity.AsmDef.Feature.Services.Occurrences
{
// Used to present an occurrence. Surprisingly, used by (at least) Rider when double clicking on an element used as
// a target in a find usage. All occurrences are added to a menu, presented but the menu will automatically click
// a single entry. If there's no presenter, the element appears disabled, and can't be clicked.
[OccurrencePresenter(Priority = 4.0)]
public class AsmDefNameOccurrencePresenter : IOccurrencePresenter
{
public bool IsApplicable(IOccurrence occurrence) => occurrence is AsmDefNameOccurrence;
public bool Present(IMenuItemDescriptor descriptor, IOccurrence occurrence,
OccurrencePresentationOptions options)
{
if (occurrence is not AsmDefNameOccurrence asmDefNameOccurrence)
return false;
var solution = occurrence.GetSolution().NotNull("occurrence.GetSolution() != null");
var cache = solution.GetComponent<AsmDefNameCache>();
descriptor.Text = asmDefNameOccurrence.Name;
if (options.IconDisplayStyle != IconDisplayStyle.NoIcon)
descriptor.Icon = GetIcon(solution, asmDefNameOccurrence, options);
var fileName = cache.GetPathFor(asmDefNameOccurrence.Name);
if (fileName != null && !fileName.IsEmpty)
{
var style = TextStyle.FromForeColor(SystemColors.GrayText);
descriptor.ShortcutText = new RichText($" in {fileName.Name}", style);
descriptor.TailGlyph = AsmDefDeclaredElementType.AsmDef.GetImage();
}
descriptor.Style = MenuItemStyle.Enabled;
return true;
}
private static IconId GetIcon(ISolution solution,
AsmDefNameOccurrence asmDefNameOccurrence,
OccurrencePresentationOptions options)
{
var presentationService = asmDefNameOccurrence.SourceFile.GetPsiServices()
.GetComponent<PsiSourceFilePresentationService>();
switch (options.IconDisplayStyle)
{
case IconDisplayStyle.OccurrenceKind:
return OccurrencePresentationUtil.GetOccurrenceKindImage(asmDefNameOccurrence, solution).Icon;
case IconDisplayStyle.File:
var iconId = presentationService.GetIconId(asmDefNameOccurrence.SourceFile);
if (iconId == null)
{
var projectFile = asmDefNameOccurrence.SourceFile.ToProjectFile();
if (projectFile != null)
{
iconId = Shell.Instance.GetComponent<ProjectModelElementPresentationService>()
.GetIcon(projectFile);
}
}
if (iconId == null)
iconId = AsmDefDeclaredElementType.AsmDef.GetImage();
return iconId;
default:
return AsmDefDeclaredElementType.AsmDef.GetImage();
}
}
}
} | |
Switch over metadata to use its own script order reference | using Glimpse.Core2.Extensibility;
namespace Glimpse.Core2.ClientScript
{
public class Metadata:IDynamicClientScript
{
public ScriptOrder Order
{
get { return ScriptOrder.IncludeAfterClientInterfaceScript; }
}
public string GetResourceName()
{
return Resource.Metadata.InternalName;
}
}
} | using Glimpse.Core2.Extensibility;
namespace Glimpse.Core2.ClientScript
{
public class Metadata:IDynamicClientScript
{
public ScriptOrder Order
{
get { return ScriptOrder.RequestMetadataScript; }
}
public string GetResourceName()
{
return Resource.Metadata.InternalName;
}
}
} |
Add component for unstable rate statistic | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Screens.Ranking.Statistics
{
/// <summary>
/// Displays the unstable rate statistic for a given play.
/// </summary>
public class UnstableRate : SimpleStatisticItem<double>
{
/// <summary>
/// Creates and computes an <see cref="UnstableRate"/> statistic.
/// </summary>
/// <param name="hitEvents">Sequence of <see cref="HitEvent"/>s to calculate the unstable rate based on.</param>
public UnstableRate(IEnumerable<HitEvent> hitEvents)
: base("Unstable Rate")
{
var timeOffsets = hitEvents.Select(ev => ev.TimeOffset).ToArray();
Value = 10 * standardDeviation(timeOffsets);
}
private static double standardDeviation(double[] timeOffsets)
{
if (timeOffsets.Length == 0)
return double.NaN;
var mean = timeOffsets.Average();
var squares = timeOffsets.Select(offset => Math.Pow(offset - mean, 2)).Sum();
return Math.Sqrt(squares / timeOffsets.Length);
}
protected override string DisplayValue(double value) => double.IsNaN(value) ? "(not available)" : value.ToString("N2");
}
}
| |
Add regression test for checking scene close when SceneManager is asked to close | /*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenSim.Tests.Common;
using OpenSim.Tests.Common.Mock;
namespace OpenSim.Region.Framework.Scenes.Tests
{
[TestFixture]
public class SceneManagerTests
{
[Test]
public void TestClose()
{
TestHelpers.InMethod();
SceneHelpers sh = new SceneHelpers();
Scene scene = sh.SetupScene();
sh.SceneManager.Close();
Assert.That(scene.ShuttingDown, Is.True);
}
}
} | |
Add test coverage for failing scenario | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading.Tasks;
using NUnit.Framework;
using osu.Framework.IO.Stores;
using osu.Framework.Tests.Visual;
namespace osu.Framework.Tests.IO
{
public class DllResourceStoreTest
{
[Test]
public async Task TestSuccessfulAsyncLookup()
{
var resourceStore = new DllResourceStore(typeof(FrameworkTestScene).Assembly);
byte[]? stream = await resourceStore.GetAsync("Resources.Tracks.sample-track.mp3");
Assert.That(stream, Is.Not.Null);
}
[Test]
public async Task TestFailedAsyncLookup()
{
var resourceStore = new DllResourceStore(typeof(FrameworkTestScene).Assembly);
byte[]? stream = await resourceStore.GetAsync("Resources.Tracks.sample-track.mp5");
Assert.That(stream, Is.Null);
}
}
}
| |
Add some tests for ErgastClient | using System;
using System.Threading.Tasks;
using ErgastApi.Client;
using ErgastApi.Client.Caching;
using ErgastApi.Requests;
using ErgastApi.Responses;
using FluentAssertions;
using NSubstitute;
using Xunit;
namespace ErgastApi.Tests.Client
{
public class ErgastClientTests
{
private ErgastClient Client { get; }
private IErgastCache Cache { get; set; }
private IUrlBuilder UrlBuilder { get; set; }
public ErgastClientTests()
{
Cache = Substitute.For<IErgastCache>();
UrlBuilder = Substitute.For<IUrlBuilder>();
Client = new ErgastClient
{
Cache = Cache,
UrlBuilder = UrlBuilder
};
}
[Theory]
[AutoMockedData("invalid string")]
[AutoMockedData("C:\\")]
[AutoMockedData("C:")]
[AutoMockedData("ftp://example.com")]
[AutoMockedData("ftp://example.com/")]
[AutoMockedData("C:\\example.txt")]
[AutoMockedData("/example/api")]
[AutoMockedData("example/api")]
public void ApiRoot_Set_NonUrlShouldThrowArgumentException(string url)
{
Action act = () => Client.ApiRoot = url;
act.ShouldThrow<ArgumentException>();
}
[Theory]
[AutoMockedData("http://example.com")]
[AutoMockedData("https://example.com")]
public void ApiRoot_Set_ShouldAcceptHttpAndHttpsUrls(string url)
{
Client.ApiRoot = url;
Client.ApiRoot.Should().Be(url);
}
[Theory]
[AutoMockedData("http://example.com/api/")]
[AutoMockedData("https://example.com/")]
public void ApiRoot_Set_ShouldRemoveTrailingSlash(string url)
{
Client.ApiRoot = url;
Client.ApiRoot.Should().Be(url.TrimEnd('/'));
}
[Theory]
[AutoMockedData]
public void GetResponseAsync_RequestWithRoundWithoutSeason_ThrowsInvalidOperationException(ErgastRequest<ErgastResponse> request)
{
// Arrange
request.Season = null;
request.Round = "1";
// Act
Func<Task> act = async () => await Client.GetResponseAsync(request);
// Assert
act.ShouldThrow<InvalidOperationException>();
}
[Theory]
[AutoMockedData]
public async Task GetResponseAsync_ReturnsCachedResponse(ErgastResponse expectedResponse)
{
Cache.Get<ErgastResponse>(null).ReturnsForAnyArgs(expectedResponse);
var response = await Client.GetResponseAsync<ErgastResponse>(null);
response.Should().Be(expectedResponse);
}
}
}
| |
Add utility class for Xml-related tasks | #region License
/* Copyright (c) 2017 Wes Hampson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#endregion
using System.Xml;
using System.Xml.Linq;
namespace WHampson.BFT
{
internal static class XmlUtils
{
public static string BuildXmlErrorMsg(XObject o, string msgFmt, params object[] fmtArgs)
{
IXmlLineInfo lineInfo = o;
string msg = string.Format(msgFmt, fmtArgs);
if (!msg.EndsWith("."))
{
msg += ".";
}
msg += " " + string.Format(" Line {0}, position {1}.", lineInfo.LineNumber, lineInfo.LinePosition);
return msg;
}
}
}
| |
Check for valid user before adding claims | using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Bonobo.Git.Server.Models;
using Microsoft.Practices.Unity;
using System.Web;
using Microsoft.Owin.Security.WsFederation;
using Microsoft.Owin.Security.Cookies;
using Owin;
namespace Bonobo.Git.Server.Security
{
public abstract class AuthenticationProvider : IAuthenticationProvider
{
[Dependency]
public IMembershipService MembershipService { get; set; }
[Dependency]
public IRoleProvider RoleProvider { get; set; }
public abstract void Configure(IAppBuilder app);
public abstract void SignIn(string username, string returnUrl);
public abstract void SignOut();
public IEnumerable<Claim> GetClaimsForUser(string username)
{
List<Claim> result = new List<Claim>();
UserModel user = MembershipService.GetUser(username);
result.Add(new Claim(ClaimTypes.Name, user.DisplayName));
result.Add(new Claim(ClaimTypes.Upn, user.Name));
result.Add(new Claim(ClaimTypes.Email, user.Email));
result.Add(new Claim(ClaimTypes.Role, Definitions.Roles.Member));
result.AddRange(RoleProvider.GetRolesForUser(user.Name).Select(x => new Claim(ClaimTypes.Role, x)));
return result;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Bonobo.Git.Server.Models;
using Microsoft.Practices.Unity;
using Owin;
namespace Bonobo.Git.Server.Security
{
public abstract class AuthenticationProvider : IAuthenticationProvider
{
[Dependency]
public IMembershipService MembershipService { get; set; }
[Dependency]
public IRoleProvider RoleProvider { get; set; }
public abstract void Configure(IAppBuilder app);
public abstract void SignIn(string username, string returnUrl);
public abstract void SignOut();
public IEnumerable<Claim> GetClaimsForUser(string username)
{
List<Claim> result = null;
UserModel user = MembershipService.GetUser(username.StripDomain());
if (user != null)
{
result = new List<Claim>();
result.Add(new Claim(ClaimTypes.Name, user.DisplayName));
result.Add(new Claim(ClaimTypes.Upn, user.Name));
result.Add(new Claim(ClaimTypes.Email, user.Email));
result.Add(new Claim(ClaimTypes.Role, Definitions.Roles.Member));
result.AddRange(RoleProvider.GetRolesForUser(user.Name).Select(x => new Claim(ClaimTypes.Role, x)));
}
return result;
}
}
} |
Add joint trigger (OnJointBreak() + OnJointBreak2D()) | using System; // require keep for Windows Universal App
using UnityEngine;
namespace UniRx.Triggers
{
[DisallowMultipleComponent]
public class ObservableJointTrigger : ObservableTriggerBase
{
Subject<float> onJointBreak;
void OnJointBreak(float breakForce)
{
if (onJointBreak != null) onJointBreak.OnNext(breakForce);
}
public IObservable<float> OnJointBreakAsObservable()
{
return onJointBreak ?? (onJointBreak = new Subject<float>());
}
Subject<Joint2D> onJointBreak2D;
void OnJointBreak2D(Joint2D brokenJoint)
{
if (onJointBreak2D != null) onJointBreak2D.OnNext(brokenJoint);
}
public IObservable<Joint2D> OnJointBreak2DAsObservable()
{
return onJointBreak2D ?? (onJointBreak2D = new Subject<Joint2D>());
}
protected override void RaiseOnCompletedOnDestroy()
{
if (onJointBreak != null)
{
onJointBreak.OnCompleted();
}
if (onJointBreak2D != null)
{
onJointBreak2D.OnCompleted();
}
}
}
} | |
Add extensions to byte for getting a value from the first or last n bits of said byte. | using System;
namespace mcThings.Extensions
{
public static class ByteExtensions
{
public static byte ReadFirstNBits(this byte value, byte n)
{
if (n > 8)
throw new ArgumentException($"{nameof(n)} cannot be greater than 8.", nameof(n));
return (byte) (value >> (8 - n));
}
public static byte ReadLastNBits(this byte value, byte n)
{
if (n > 8)
throw new ArgumentException($"{nameof(n)} cannot be greater than 8.", nameof(n));
byte mask = (byte) ((1 << n) - 1);
return (byte) (value & mask);
}
}
}
| |
Add a compilation unit type that represents a parse tree from a specific file. | using slang.AST;
namespace slang.Compilation
{
public class CompilationUnit
{
public CompilationUnit (string sourceFilename, ProgramNode root)
{
SourceFile = sourceFilename;
Root = root;
}
public string SourceFile { get; set; }
public ProgramNode Root { get; set; }
}
}
| |
Add structure for legacy hit explosions | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Rulesets.UI.Scrolling;
namespace osu.Game.Rulesets.Mania.Skinning
{
public class LegacyHitExplosion : LegacyManiaColumnElement
{
private readonly IBindable<ScrollingDirection> direction = new Bindable<ScrollingDirection>();
private Drawable explosion;
[BackgroundDependencyLoader]
private void load(IScrollingInfo scrollingInfo)
{
InternalChild = explosion = new Sprite
{
};
direction.BindTo(scrollingInfo.Direction);
direction.BindValueChanged(onDirectionChanged, true);
// Todo: LightingN
// Todo: LightingL
}
private void onDirectionChanged(ValueChangedEvent<ScrollingDirection> obj)
{
throw new System.NotImplementedException();
}
protected override void LoadComplete()
{
base.LoadComplete();
lighting.FadeInFromZero(80)
.Then().FadeOut(120);
}
}
}
| |
Remove unban timer on actual unban event | using DSharpPlus.EventArgs;
using ModCore.Entities;
using ModCore.Logic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModCore.Listeners
{
public class UnbanTimerRemove
{
[AsyncListener(EventTypes.GuildBanRemoved)]
public static async Task CommandError(ModCoreShard bot, GuildBanRemoveEventArgs e)
{
using (var db = bot.Database.CreateContext())
{
if (db.Timers.Any(x => x.ActionType == TimerActionType.Unmute && (ulong)x.UserId == e.Member.Id))
{
db.Timers.Remove(db.Timers.First(x => (ulong)x.UserId == e.Member.Id && x.ActionType == TimerActionType.Unban));
await db.SaveChangesAsync();
}
}
}
}
}
| |
Move string extensions to own file | namespace MediaFileParser.MediaTypes.MediaFile.Junk
{
/// <summary>
/// Junk String Extensions Class
/// </summary>
public static class JunkStringExtensions
{
/// <summary>
/// Determines whether the beginning of this string instance matches a specified JunkString.
/// </summary>
/// <param name="str">The string to compare to.</param>
/// <param name="startsWith">The JunkString to compare.</param>
/// <returns>true if value matches the beginning of this string; otherwise, false.</returns>
public static bool StartsWith(this string str, JunkString startsWith)
{
return str.StartsWith(startsWith.String);
}
/// <summary>
/// Determines whether this instance and another specified JunkString object have the same value.
/// </summary>
/// <param name="str">The string to compare to.</param>
/// <param name="obj">The JunkString to compare to this instance.</param>
/// <returns>true if the value of the value parameter is the same as this instance; otherwise, false.</returns>
public static bool EqualsJunk(this string str, JunkString obj)
{
return str.Equals(obj.String);
}
}
}
| |
Add Retry Test(not done yet) | using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Unosquare.Swan.Components;
using Unosquare.Swan.Networking;
namespace Unosquare.Swan.Test
{
[TestFixture]
public class ComponentsRetryTest
{
private static int count = 0;
[Test]
public async Task RetryTest()
{
var retryCount = 4;
await Retry.Do(FailFunction, TimeSpan.FromSeconds(1), retryCount);
Assert.IsTrue(count == retryCount);
}
internal async Task FailFunction()
{
count++;
var token = await JsonClient.GetString("http://accesscore.azurewebsites.net/api/token");
}
}
}
| |
Add unit test for autoscale command | using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace SCPI.Tests
{
public class AUTOSCALE_Tests
{
[Fact]
public void ValidCommand()
{
// Arrange
var cmd = new AUTOSCALE();
var expected = ":AUToscale";
// Act
var actual = cmd.Command();
// Assert
Assert.Equal(expected, actual);
}
}
}
| |
Add Autonum and Identity retrieval Tests | using NUnit.Framework;
using SimpleStack.Orm.Attributes;
namespace SimpleStack.Orm.Tests
{
[TestFixture]
public partial class ExpressionTests
{
public class ModeWithAutoIncrement
{
/// <summary>Gets or sets the identifier.</summary>
/// <value>The identifier.</value>
[AutoIncrement]
[PrimaryKey]
public int Id { get; set; }
/// <summary>Gets or sets the name.</summary>
/// <value>The name.</value>
public string Name { get; set; }
}
public class ModeWithoutAutoIncrement
{
/// <summary>Gets or sets the identifier.</summary>
/// <value>The identifier.</value>
[PrimaryKey]
public int Id { get; set; }
/// <summary>Gets or sets the name.</summary>
/// <value>The name.</value>
public string Name { get; set; }
}
[Test]
public void InsertAndRetrieveIdentity()
{
using (var conn = OpenDbConnection())
{
conn.CreateTable<ModeWithAutoIncrement>(true);
var identity = conn.Insert(new ModeWithAutoIncrement{Name = "hello"});
var identity2 = conn.Insert(new ModeWithAutoIncrement{Name = "hello"});
Assert.NotNull(identity);
Assert.False(identity == identity2);
}
}
[Test]
public void InsertWithoutAutoIncrementAndRetrieveIdentity()
{
using (var conn = OpenDbConnection())
{
conn.CreateTable<ModeWithoutAutoIncrement>(true);
var identity = conn.Insert(new ModeWithoutAutoIncrement{Id=10, Name = "hello"});
Assert.AreEqual(0,identity);
}
}
}
} | |
Add a linq extension to Distinct objects using a Func | using System;
using System.Collections.Generic;
using System.Linq;
namespace libgitface
{
public static class LinqExtensions
{
class DelegateComparer<T, TCompare> : IEqualityComparer<T>
{
Func<T, TCompare> Selector;
public DelegateComparer (Func<T, TCompare> selector) => Selector = selector;
public bool Equals (T x, T y) => EqualityComparer<TCompare>.Default.Equals (Selector (x), Selector (y));
public int GetHashCode (T obj) => EqualityComparer<TCompare>.Default.GetHashCode (Selector (obj));
}
public static IEnumerable<T> Distinct<T, TCompare> (this IEnumerable<T> self, Func<T, TCompare> selector)
{
var comparer = new DelegateComparer<T, TCompare> (selector);
return self.Distinct (comparer);
}
}
}
| |
Add snippets for the DateInterval type | // Copyright 2017 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using NUnit.Framework;
namespace NodaTime.Demo
{
public class DateIntervalDemo
{
[Test]
public void Construction()
{
var calendar = CalendarSystem.Gregorian;
LocalDate start = new LocalDate(2017, 1, 1, calendar);
LocalDate end = new LocalDate(2017, 12, 31, calendar);
DateInterval interval = Snippet.For(new DateInterval(start, end));
Assert.AreEqual(365, interval.Length);
Assert.AreEqual("[2017-01-01, 2017-12-31]", interval.ToString());
Assert.AreEqual(start, interval.Start);
Assert.AreEqual(end, interval.End);
Assert.AreEqual(calendar, interval.Calendar);
}
[Test]
public void Intersection()
{
DateInterval januaryToAugust = new DateInterval(
new LocalDate(2017, 1, 1),
new LocalDate(2017, 8, 31));
DateInterval juneToNovember = new DateInterval(
new LocalDate(2017, 6, 1),
new LocalDate(2017, 11, 30));
DateInterval juneToAugust = new DateInterval(
new LocalDate(2017, 6, 1),
new LocalDate(2017, 8, 31));
var result = Snippet.For(januaryToAugust.Intersection(juneToNovember));
Assert.AreEqual(juneToAugust, result);
}
[Test]
public void Contains_LocalDate()
{
LocalDate start = new LocalDate(2017, 1, 1);
LocalDate end = new LocalDate(2017, 12, 31);
DateInterval interval = new DateInterval(start, end);
var result = Snippet.For(interval.Contains(new LocalDate(2017, 12, 5)));
Assert.AreEqual(true, result);
}
[Test]
public void Contains_Interval()
{
LocalDate start = new LocalDate(2017, 1, 1);
LocalDate end = new LocalDate(2017, 12, 31);
DateInterval interval = new DateInterval(start, end);
DateInterval june = new DateInterval(
new LocalDate(2017, 6, 1),
new LocalDate(2017, 6, 30));
var result = Snippet.For(interval.Contains(june));
Assert.AreEqual(true, result);
}
}
}
| |
Add facade for the game (interface) | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FierceGalaxyInterface
{
interface IGameFacade
{
IPlayerManager PlayerManager { get; }
}
}
| |
Revert "Changes to this file no longer needed" | using System;
namespace MQTTnet.Extensions.ManagedClient
{
public class ManagedMqttApplicationMessage : IEquatable<ManagedMqttApplicationMessage>
{
public Guid Id { get; set; } = Guid.NewGuid();
public MqttApplicationMessage ApplicationMessage { get; set; }
public bool Equals(ManagedMqttApplicationMessage other)
{
return Id.Equals(other.Id);
}
}
}
| |
Add test that ensures our exported components can be loaded | using System;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Xunit;
using Xunit.Abstractions;
namespace Moq.Proxy.Tests
{
public class CompositionTests
{
ITestOutputHelper output;
public CompositionTests(ITestOutputHelper output) => this.output = output;
[Fact]
public void CanGetProxyGenerationServices()
{
var host = ProxyGenerator.CreateHost();
var workspace = new AdhocWorkspace(host);
var services = workspace.Services.GetService<ICodeAnalysisServices>();
var serviceTypes = typeof(ProxyGenerator).Assembly.GetTypes()
.Select(x => new
{
Type = x,
Export = x.GetCustomAttributes(typeof(ExportLanguageServiceAttribute), false)
.OfType<ExportLanguageServiceAttribute>().FirstOrDefault()
})
.Where(x => x.Export != null)
.Select(x => new
{
Key = Tuple.Create(x.Export.Language, x.Export.ServiceType, x.Export.Layer),
x.Type
})
.GroupBy(x => x.Key)
.ToArray();
foreach (var group in serviceTypes)
{
var instances = services.GetLanguageServices(group.Key.Item1, group.Key.Item2, group.Key.Item3).ToArray();
Assert.Equal(group.Count(), instances.Length);
output.WriteLine(group.Key.Item1 + ":" + group.Key.Item2.Substring(0, group.Key.Item2.IndexOf(",")) + ":" + group.Key.Item3 + "=" + instances.Length);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.