Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix osu! slider ticks appearing too late | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Osu.Judgements;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Osu.Objects
{
public class SliderTick : OsuHitObject
{
public int SpanIndex { get; set; }
public double SpanStartTime { get; set; }
protected override void ApplyDefaultsToSelf(ControlPointInfo controlPointInfo, IBeatmapDifficultyInfo difficulty)
{
base.ApplyDefaultsToSelf(controlPointInfo, difficulty);
double offset;
if (SpanIndex > 0)
// Adding 200 to include the offset stable used.
// This is so on repeats ticks don't appear too late to be visually processed by the player.
offset = 200;
else
offset = TimeFadeIn * 0.66f;
TimePreempt = (StartTime - SpanStartTime) / 2 + offset;
}
protected override HitWindows CreateHitWindows() => HitWindows.Empty;
public override Judgement CreateJudgement() => new SliderTickJudgement();
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Osu.Judgements;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Osu.Objects
{
public class SliderTick : OsuHitObject
{
public int SpanIndex { get; set; }
public double SpanStartTime { get; set; }
protected override void ApplyDefaultsToSelf(ControlPointInfo controlPointInfo, IBeatmapDifficultyInfo difficulty)
{
base.ApplyDefaultsToSelf(controlPointInfo, difficulty);
double offset;
if (SpanIndex > 0)
// Adding 200 to include the offset stable used.
// This is so on repeats ticks don't appear too late to be visually processed by the player.
offset = 200;
else
offset = TimePreempt * 0.66f;
TimePreempt = (StartTime - SpanStartTime) / 2 + offset;
}
protected override HitWindows CreateHitWindows() => HitWindows.Empty;
public override Judgement CreateJudgement() => new SliderTickJudgement();
}
}
|
Set flag to enable package restore for future versions of nuget. | using System;
using System.Linq;
using System.Threading.Tasks;
using Kudu.Contracts.Tracing;
using Kudu.Core.Infrastructure;
namespace Kudu.Core.Deployment
{
public abstract class MsBuildSiteBuilder : ISiteBuilder
{
private const string NuGetCachePathKey = "NuGetCachePath";
private readonly Executable _msbuildExe;
private readonly IBuildPropertyProvider _propertyProvider;
private readonly string _tempPath;
public MsBuildSiteBuilder(IBuildPropertyProvider propertyProvider, string workingDirectory, string tempPath, string nugetCachePath)
{
_propertyProvider = propertyProvider;
_msbuildExe = new Executable(PathUtility.ResolveMSBuildPath(), workingDirectory);
// Disable this for now
// _msbuildExe.EnvironmentVariables[NuGetCachePathKey] = nugetCachePath;
_tempPath = tempPath;
}
protected string GetPropertyString()
{
return String.Join(";", _propertyProvider.GetProperties().Select(p => p.Key + "=" + p.Value));
}
public string ExecuteMSBuild(ITracer tracer, string arguments, params object[] args)
{
return _msbuildExe.Execute(tracer, arguments, args).Item1;
}
public abstract Task Build(DeploymentContext context);
}
}
| using System;
using System.Linq;
using System.Threading.Tasks;
using Kudu.Contracts.Tracing;
using Kudu.Core.Infrastructure;
namespace Kudu.Core.Deployment
{
public abstract class MsBuildSiteBuilder : ISiteBuilder
{
private const string NuGetCachePathKey = "NuGetCachePath";
private const string NuGetPackageRestoreKey = "EnableNuGetPackageRestore";
private readonly Executable _msbuildExe;
private readonly IBuildPropertyProvider _propertyProvider;
private readonly string _tempPath;
public MsBuildSiteBuilder(IBuildPropertyProvider propertyProvider, string workingDirectory, string tempPath, string nugetCachePath)
{
_propertyProvider = propertyProvider;
_msbuildExe = new Executable(PathUtility.ResolveMSBuildPath(), workingDirectory);
// Disable this for now
// _msbuildExe.EnvironmentVariables[NuGetCachePathKey] = nugetCachePath;
// NuGet.exe 1.8 will require an environment variable to make package restore work
_msbuildExe.EnvironmentVariables[NuGetPackageRestoreKey] = "true";
_tempPath = tempPath;
}
protected string GetPropertyString()
{
return String.Join(";", _propertyProvider.GetProperties().Select(p => p.Key + "=" + p.Value));
}
public string ExecuteMSBuild(ITracer tracer, string arguments, params object[] args)
{
return _msbuildExe.Execute(tracer, arguments, args).Item1;
}
public abstract Task Build(DeploymentContext context);
}
}
|
Add method to solver interface to tell it about functions it might see in queries. | using System;
using System.Collections.Generic;
namespace symbooglix
{
public interface ISolver
{
void SetConstraints(ConstraintManager cm);
// This can be used as a hint to the solver to destroy Constraints created internally in the solver
void DropConstraints();
// Given the constraints is the query expression satisfiable
// \return True iff sat
// if sat the assignment will be set to an assignment object
//
// If another query is made the previously received assignment object may be
// invalid.
bool IsQuerySat(Microsoft.Boogie.Expr Query, out IAssignment assignment);
// Given the constraints is the negation of the query expression satisfiable
// \return True iff sat
// if sat the assignment will be set to an assignment object
//
// If another query is made the previously received assignment object may be
// invalid.
bool IsNotQuerySat(Microsoft.Boogie.Expr Query, out IAssignment assignment);
}
public interface IAssignment
{
Microsoft.Boogie.LiteralExpr GetAssignment(SymbolicVariable SV);
}
}
| using System;
using System.Collections.Generic;
namespace symbooglix
{
public interface ISolver
{
void SetConstraints(ConstraintManager cm);
void SetFunctions(IEnumerable<Microsoft.Boogie.Function> functions);
// Given the constraints is the query expression satisfiable
// \return True iff sat
// if sat the assignment will be set to an assignment object
//
// If another query is made the previously received assignment object may be
// invalid.
bool IsQuerySat(Microsoft.Boogie.Expr Query, out IAssignment assignment);
// Given the constraints is the negation of the query expression satisfiable
// \return True iff sat
// if sat the assignment will be set to an assignment object
//
// If another query is made the previously received assignment object may be
// invalid.
bool IsNotQuerySat(Microsoft.Boogie.Expr Query, out IAssignment assignment);
}
public interface IAssignment
{
Microsoft.Boogie.LiteralExpr GetAssignment(SymbolicVariable SV);
}
}
|
Check if table exist before creating it in the install | using MultipleStartNodes.Models;
using MultipleStartNodes.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using umbraco.cms.businesslogic.packager.standardPackageActions;
using umbraco.interfaces;
using Umbraco.Core.Logging;
namespace MultipleStartNodes.PackageActions
{
class CreateDatabase : IPackageAction
{
public string Alias()
{
return "MultipleStartNodes_CreateDatabase";
}
public bool Execute(string packageName, XmlNode xmlData)
{
try
{
Resources.DatabaseSchemaHelper.CreateTable<UserStartNodes>(false);
return true;
}
catch (Exception ex)
{
var message = string.Concat("Error at install ", this.Alias(), " package action: ", ex);
LogHelper.Error(typeof(CreateDatabase), message, ex);
}
return false;
}
public XmlNode SampleXml()
{
var xml = string.Concat("<Action runat=\"install\" undo=\"true\" alias=\"", this.Alias(), "\" />");
return helper.parseStringToXmlNode(xml);
}
public bool Undo(string packageName, XmlNode xmlData)
{
try
{
Resources.DatabaseSchemaHelper.DropTable<UserStartNodes>();
return true;
}
catch (Exception ex)
{
var message = string.Concat("Error at undo ", this.Alias(), " package action: ", ex);
LogHelper.Error(typeof(CreateDatabase), message, ex);
}
return false;
}
}
}
| using MultipleStartNodes.Models;
using MultipleStartNodes.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using umbraco.cms.businesslogic.packager.standardPackageActions;
using umbraco.interfaces;
using Umbraco.Core.Logging;
namespace MultipleStartNodes.PackageActions
{
class CreateDatabase : IPackageAction
{
public string Alias()
{
return "MultipleStartNodes_CreateDatabase";
}
public bool Execute(string packageName, XmlNode xmlData)
{
try
{
if (!Resources.DatabaseSchemaHelper.TableExist("userStartNodes"))
{
Resources.DatabaseSchemaHelper.CreateTable<UserStartNodes>(false);
}
return true;
}
catch (Exception ex)
{
var message = string.Concat("Error at install ", this.Alias(), " package action: ", ex);
LogHelper.Error(typeof(CreateDatabase), message, ex);
}
return false;
}
public XmlNode SampleXml()
{
var xml = string.Concat("<Action runat=\"install\" undo=\"true\" alias=\"", this.Alias(), "\" />");
return helper.parseStringToXmlNode(xml);
}
public bool Undo(string packageName, XmlNode xmlData)
{
try
{
Resources.DatabaseSchemaHelper.DropTable<UserStartNodes>();
return true;
}
catch (Exception ex)
{
var message = string.Concat("Error at undo ", this.Alias(), " package action: ", ex);
LogHelper.Error(typeof(CreateDatabase), message, ex);
}
return false;
}
}
}
|
Fix sample perf (Option 1) | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
namespace SampleApp
{
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.Run(async context =>
{
Console.WriteLine("{0} {1}{2}{3}",
context.Request.Method,
context.Request.PathBase,
context.Request.Path,
context.Request.QueryString);
context.Response.ContentLength = 11;
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync("Hello world");
});
}
}
} | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
namespace SampleApp
{
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.Run(context =>
{
Console.WriteLine("{0} {1}{2}{3}",
context.Request.Method,
context.Request.PathBase,
context.Request.Path,
context.Request.QueryString);
context.Response.ContentLength = 11;
context.Response.ContentType = "text/plain";
return context.Response.WriteAsync("Hello world");
});
}
}
}
|
Correct way to wait for indexing | using System;
using System.Linq;
using MvcContrib.TestHelper;
using Snittlistan.Infrastructure.Indexes;
using Snittlistan.Models;
using Xunit;
namespace Snittlistan.Test
{
public class PlayerStat_Test : DbTest
{
[Fact]
public void VerifyIndex()
{
// Arrange
IndexCreator.CreateIndexes(Store);
// Act
var match = DbSeed.CreateMatch();
Session.Store(match);
Session.SaveChanges();
WaitForNonStaleResults<Match>();
Matches_PlayerStats.Results stats = Session.Query<Matches_PlayerStats.Results, Matches_PlayerStats>()
.Single(s => s.Player == "Mikael Axelsson");
// Assert
stats.Count.ShouldBe(4);
stats.TotalPins.ShouldBe(845);
stats.Max.ShouldBe(223);
stats.Min.ShouldBe(202);
}
}
}
| using System;
using System.Linq;
using MvcContrib.TestHelper;
using Snittlistan.Infrastructure.Indexes;
using Snittlistan.Models;
using Xunit;
namespace Snittlistan.Test
{
public class PlayerStat_Test : DbTest
{
[Fact]
public void VerifyIndex()
{
// Arrange
IndexCreator.CreateIndexes(Store);
// Act
var match = DbSeed.CreateMatch();
Session.Store(match);
Session.SaveChanges();
Matches_PlayerStats.Results stats = Session.Query<Matches_PlayerStats.Results, Matches_PlayerStats>()
.Customize(c => c.WaitForNonStaleResults())
.Single(s => s.Player == "Mikael Axelsson");
// Assert
stats.Count.ShouldBe(4);
stats.TotalPins.ShouldBe(845);
stats.Max.ShouldBe(223);
stats.Min.ShouldBe(202);
}
}
}
|
Add missing namespace and using statements. | public class MikeKanakos : IAmACommunityMember
{
public string FirstName => "Mike";
public string LastName => "Kanakos";
public string ShortBioOrTagLine => "Windows IT pro located in the RTP area of North Carolina. Active Directory, Azure AD, Group Policy, and automation.";
public string StateOrRegion => "Apex, NC";
public string EmailAddress => "mike@networkadm.in";
public string TwitterHandle => "MikeKanakos";
public string GravatarHash => "2bca167386e229ec2c5606f6c1677493";
public string GitHubHandle => "compwiz32";
public GeoPosition Position => new GeoPosition(35.7327, 78.8503);
public Uri WebSite => new Uri("https://www.networkadm.in/");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.networkadm.in/rss/"); } }
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class MikeKanakos : IAmACommunityMember
{
public string FirstName => "Mike";
public string LastName => "Kanakos";
public string ShortBioOrTagLine => "Windows IT pro located in the RTP area of North Carolina. Active Directory, Azure AD, Group Policy, and automation.";
public string StateOrRegion => "Apex, NC";
public string EmailAddress => "mike@networkadm.in";
public string TwitterHandle => "MikeKanakos";
public string GravatarHash => "2bca167386e229ec2c5606f6c1677493";
public string GitHubHandle => "compwiz32";
public GeoPosition Position => new GeoPosition(35.7327, 78.8503);
public Uri WebSite => new Uri("https://www.networkadm.in/");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.networkadm.in/rss/"); } }
}
}
|
Add status to cat indices response | using Newtonsoft.Json;
namespace Nest
{
[JsonObject]
public class CatIndicesRecord : ICatRecord
{
[JsonProperty("docs.count")]
public string DocsCount { get; set; }
[JsonProperty("docs.deleted")]
public string DocsDeleted { get; set; }
[JsonProperty("health")]
public string Health { get; set; }
[JsonProperty("index")]
public string Index { get; set; }
[JsonProperty("pri")]
public string Primary { get; set; }
[JsonProperty("pri.store.size")]
public string PrimaryStoreSize { get; set; }
[JsonProperty("rep")]
public string Replica { get; set; }
[JsonProperty("store.size")]
public string StoreSize { get; set; }
}
} | using Newtonsoft.Json;
namespace Nest
{
[JsonObject]
public class CatIndicesRecord : ICatRecord
{
[JsonProperty("docs.count")]
public string DocsCount { get; set; }
[JsonProperty("docs.deleted")]
public string DocsDeleted { get; set; }
[JsonProperty("health")]
public string Health { get; set; }
[JsonProperty("index")]
public string Index { get; set; }
[JsonProperty("pri")]
public string Primary { get; set; }
[JsonProperty("pri.store.size")]
public string PrimaryStoreSize { get; set; }
[JsonProperty("rep")]
public string Replica { get; set; }
[JsonProperty("store.size")]
public string StoreSize { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
}
} |
Normalize all file headers to the expected Apache 2.0 license | // Copyright(c) .NET Foundation.All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Testing;
namespace Microsoft.Extensions.Logging.Testing
{
/// <summary>
/// Capture the memory dump upon test failure.
/// </summary>
/// <remarks>
/// This currently only works in Windows environments
/// </remarks>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class CollectDumpAttribute : Attribute, ITestMethodLifecycle
{
public Task OnTestStartAsync(TestContext context, CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
public Task OnTestEndAsync(TestContext context, Exception exception, CancellationToken cancellationToken)
{
if (exception != null)
{
var path = Path.Combine(context.FileOutput.TestClassOutputDirectory, context.FileOutput.GetUniqueFileName(context.FileOutput.TestName, ".dmp"));
var process = Process.GetCurrentProcess();
DumpCollector.Collect(process, path);
}
return Task.CompletedTask;
}
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Testing;
namespace Microsoft.Extensions.Logging.Testing
{
/// <summary>
/// Capture the memory dump upon test failure.
/// </summary>
/// <remarks>
/// This currently only works in Windows environments
/// </remarks>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class CollectDumpAttribute : Attribute, ITestMethodLifecycle
{
public Task OnTestStartAsync(TestContext context, CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
public Task OnTestEndAsync(TestContext context, Exception exception, CancellationToken cancellationToken)
{
if (exception != null)
{
var path = Path.Combine(context.FileOutput.TestClassOutputDirectory, context.FileOutput.GetUniqueFileName(context.FileOutput.TestName, ".dmp"));
var process = Process.GetCurrentProcess();
DumpCollector.Collect(process, path);
}
return Task.CompletedTask;
}
}
}
|
Add lookup for spinner background colour | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Rulesets.Osu.Skinning
{
public enum OsuSkinColour
{
SliderTrackOverride,
SliderBorder,
SliderBall
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Rulesets.Osu.Skinning
{
public enum OsuSkinColour
{
SliderTrackOverride,
SliderBorder,
SliderBall,
SpinnerBackground,
}
}
|
Add new method stub for generating routes | namespace RestfulRouting
{
public abstract class Mapper
{
}
}
| using System;
using System.Web.Routing;
namespace RestfulRouting
{
public abstract class Mapper
{
protected Route GenerateRoute(string path, string controller, string action, string[] httpMethods)
{
throw new NotImplementedException();
}
}
}
|
Replace reference by using regex | using SyntaxTree.VisualStudio.Unity.Bridge;
using UnityEditor;
[InitializeOnLoad]
public class NCrunchAdapterForUnity
{
public const string NUnitUnityReference = @"<Reference Include=""nunit.framework"">
<HintPath>Library\UnityAssemblies\nunit.framework.dll</HintPath>
</Reference>";
public const string NUnitOfficialReference = @"<Reference Include=""nunit.framework"">
<HintPath>Assets\Plugins\Editor\NCrunchAdapterForUnity\NUnit.3.5.0\lib\net35\nunit.framework.dll</HintPath>
</Reference>";
static NCrunchAdapterForUnity()
{
ProjectFilesGenerator.ProjectFileGeneration += (string name, string content) =>
{
return content.Replace(NUnitUnityReference, NUnitOfficialReference);
};
}
}
| using System.Text.RegularExpressions;
using SyntaxTree.VisualStudio.Unity.Bridge;
using UnityEditor;
[InitializeOnLoad]
public class NCrunchAdapterForUnity
{
public const string NUnitUnityReference = @"<Reference Include=""nunit.framework"">
<HintPath>.*nunit.framework.dll</HintPath>
</Reference>";
public const string NUnitOfficialReference = @"<Reference Include=""nunit.framework"">
<HintPath>Assets\Plugins\Editor\NCrunchAdapterForUnity\NUnit.3.5.0\lib\net35\nunit.framework.dll</HintPath>
</Reference>";
static NCrunchAdapterForUnity()
{
ProjectFilesGenerator.ProjectFileGeneration += (string name, string content) =>
{
var regex = new Regex(NUnitUnityReference);
return regex.Replace(content, NUnitOfficialReference);
};
}
}
|
Remove tall grass metadata when dropping seed | using System;
using TrueCraft.API.Logic;
using TrueCraft.Core.Logic.Items;
using TrueCraft.API;
namespace TrueCraft.Core.Logic.Blocks
{
public class TallGrassBlock : BlockProvider
{
public static readonly byte BlockID = 0x1F;
public override byte ID { get { return 0x1F; } }
public override double BlastResistance { get { return 0; } }
public override double Hardness { get { return 0; } }
public override byte Luminance { get { return 0; } }
public override bool Opaque { get { return false; } }
public override string DisplayName { get { return "Tall Grass"; } }
public override Tuple<int, int> GetTextureMap(byte metadata)
{
return new Tuple<int, int>(7, 2);
}
protected override ItemStack[] GetDrop(BlockDescriptor descriptor)
{
return new[] { new ItemStack(SeedsItem.ItemID, (sbyte)MathHelper.Random.Next(2), descriptor.Metadata) };
}
}
} | using System;
using TrueCraft.API.Logic;
using TrueCraft.Core.Logic.Items;
using TrueCraft.API;
namespace TrueCraft.Core.Logic.Blocks
{
public class TallGrassBlock : BlockProvider
{
public static readonly byte BlockID = 0x1F;
public override byte ID { get { return 0x1F; } }
public override double BlastResistance { get { return 0; } }
public override double Hardness { get { return 0; } }
public override byte Luminance { get { return 0; } }
public override bool Opaque { get { return false; } }
public override string DisplayName { get { return "Tall Grass"; } }
public override Tuple<int, int> GetTextureMap(byte metadata)
{
return new Tuple<int, int>(7, 2);
}
protected override ItemStack[] GetDrop(BlockDescriptor descriptor)
{
return new[] { new ItemStack(SeedsItem.ItemID, (sbyte)MathHelper.Random.Next(2)) };
}
}
} |
Add other to the enum | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace Anlab.Core.Domain
{
public class TestItem
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(7)]
public string FeeSchedule { get; set; }
[Required]
[StringLength(512)]
public string Analysis { get; set; }
[Required]
[StringLength(128)]
public string Code { get; set; }
public decimal InternalCost { get; set; }
public decimal ExternalCost { get; set; }
public decimal SetupCost { get; set; }
[Required]
[StringLength(64)]
public string Category { get; set; }
[Required]
[StringLength(8)]
public string Group { get; set; }
[Range(0, int.MaxValue)]
public int Multiplier { get; set; }
public bool Multiplies { get; set; }
public bool ChargeSet { get; set; }
public bool Public { get; set; }
public string GroupType { get; set; }
public string Notes { get; set; }
}
public static class TestCategories
{
public static string Soil = "Soil";
public static string Plant = "Plant";
public static string Water = "Water";
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace Anlab.Core.Domain
{
public class TestItem
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(7)]
public string FeeSchedule { get; set; }
[Required]
[StringLength(512)]
public string Analysis { get; set; }
[Required]
[StringLength(128)]
public string Code { get; set; }
public decimal InternalCost { get; set; }
public decimal ExternalCost { get; set; }
public decimal SetupCost { get; set; }
[Required]
[StringLength(64)]
public string Category { get; set; }
[Required]
[StringLength(8)]
public string Group { get; set; }
[Range(0, int.MaxValue)]
public int Multiplier { get; set; }
public bool Multiplies { get; set; }
public bool ChargeSet { get; set; }
public bool Public { get; set; }
public string GroupType { get; set; }
public string Notes { get; set; }
}
public static class TestCategories
{
public static string Soil = "Soil";
public static string Plant = "Plant";
public static string Water = "Water";
public static string Other = "Other";
}
}
|
Fix bug in which class members polluted the surrounding namespace. | using System.Collections.Generic;
using System.Linq;
using Parsley;
using Rook.Compiling.Types;
namespace Rook.Compiling.Syntax
{
public class Class : TypedSyntaxTree, Binding
{
public Position Position { get; private set; }
public Name Name { get; private set; }
public IEnumerable<Function> Methods { get; private set; }
public DataType Type { get; private set; }
public Class(Position position, Name name, IEnumerable<Function> methods)
: this(position, name, methods, ConstructorFunctionType(name)) { }
private Class(Position position, Name name, IEnumerable<Function> methods, DataType type)
{
Position = position;
Name = name;
Methods = methods;
Type = type;
}
public TResult Visit<TResult>(Visitor<TResult> visitor)
{
return visitor.Visit(this);
}
public TypeChecked<Class> WithTypes(Environment environment)
{
var localEnvironment = new Environment(environment);
foreach (var method in Methods)
if (!environment.TryIncludeUniqueBinding(method))
return TypeChecked<Class>.DuplicateIdentifierError(method);
var typeCheckedMethods = Methods.WithTypes(localEnvironment);
var errors = typeCheckedMethods.Errors();
if (errors.Any())
return TypeChecked<Class>.Failure(errors);
return TypeChecked<Class>.Success(new Class(Position, Name, typeCheckedMethods.Functions()));
}
private static NamedType ConstructorFunctionType(Name name)
{
return NamedType.Constructor(new NamedType(name.Identifier));
}
string Binding.Identifier
{
get { return Name.Identifier; }
}
}
} | using System.Collections.Generic;
using System.Linq;
using Parsley;
using Rook.Compiling.Types;
namespace Rook.Compiling.Syntax
{
public class Class : TypedSyntaxTree, Binding
{
public Position Position { get; private set; }
public Name Name { get; private set; }
public IEnumerable<Function> Methods { get; private set; }
public DataType Type { get; private set; }
public Class(Position position, Name name, IEnumerable<Function> methods)
: this(position, name, methods, ConstructorFunctionType(name)) { }
private Class(Position position, Name name, IEnumerable<Function> methods, DataType type)
{
Position = position;
Name = name;
Methods = methods;
Type = type;
}
public TResult Visit<TResult>(Visitor<TResult> visitor)
{
return visitor.Visit(this);
}
public TypeChecked<Class> WithTypes(Environment environment)
{
var localEnvironment = new Environment(environment);
foreach (var method in Methods)
if (!localEnvironment.TryIncludeUniqueBinding(method))
return TypeChecked<Class>.DuplicateIdentifierError(method);
var typeCheckedMethods = Methods.WithTypes(localEnvironment);
var errors = typeCheckedMethods.Errors();
if (errors.Any())
return TypeChecked<Class>.Failure(errors);
return TypeChecked<Class>.Success(new Class(Position, Name, typeCheckedMethods.Functions()));
}
private static NamedType ConstructorFunctionType(Name name)
{
return NamedType.Constructor(new NamedType(name.Identifier));
}
string Binding.Identifier
{
get { return Name.Identifier; }
}
}
} |
Test for Jame's Github mirror | using System.Reflection;
using System.Security;
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyCopyright("Copyright 2008-2009 James Gregory and contributors (Paul Batum, Andrew Stewart, Chad Myers et al). All rights reserved.")]
[assembly: AssemblyProduct("Fluent NHibernate")]
[assembly: AssemblyCompany("http://fluentnhibernate.org")]
[assembly: AssemblyConfiguration("debug")]
[assembly: AssemblyInformationalVersion("0.1.0.0")]
[assembly: AllowPartiallyTrustedCallers] | using System.Reflection;
using System.Security;
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyCopyright("Copyright 2008-2009 James Gregory and contributors (Paul Batum, Andrew Stewart, Chad Myers, Hudson Akridge et al). All rights reserved.")]
[assembly: AssemblyProduct("Fluent NHibernate")]
[assembly: AssemblyCompany("http://fluentnhibernate.org")]
[assembly: AssemblyConfiguration("debug")]
[assembly: AssemblyInformationalVersion("0.1.0.0")]
[assembly: AllowPartiallyTrustedCallers] |
Access allwed for all addresses (by CORS) | namespace FsxWebApi.Services
{
using System.Web.Http.Cors;
using Infrastructure;
using Model;
using System.Web.Http;
[EnableCors(origins: "http://localhost:26759", headers: "*", methods: "*")]
public class PlaneController : ApiController
{
private readonly FsxManager _fsxManager = new FsxManager();
// GET: api/Plane
public IHttpActionResult Get()
{
//return ActionRes;
PlaneData planeData = _fsxManager.GetCurrentPlaneData();
if (planeData == null)
{
return NotFound();
}
return Ok(planeData);
}
// POST: api/Plane
public void Post(Location newLocation)
{
// Pass the values to the FSX
}
}
}
| namespace FsxWebApi.Services
{
using System.Web.Http.Cors;
using Infrastructure;
using Model;
using System.Web.Http;
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class PlaneController : ApiController
{
private readonly FsxManager _fsxManager = new FsxManager();
// GET: api/Plane
public IHttpActionResult Get()
{
//return ActionRes;
PlaneData planeData = _fsxManager.GetCurrentPlaneData();
if (planeData == null)
{
return NotFound();
}
return Ok(planeData);
}
// POST: api/Plane
public void Post(Location newLocation)
{
// Pass the values to the FSX
}
}
}
|
Remove redundant login widget in page | @model OpenOrderFramework.Models.Order
@{
ViewBag.Title = "P4MCheckout";
}
<link rel="import" href="/Scripts/widgets/p4m-checkout/p4m-checkout.html">
<link rel="import" href="/Scripts/widgets/p4m-login/p4m-login.html">
<h2>Parcel For Me</h2>
<p4m-login></p4m-login>
<p4m-checkout></p4m-checkout> | @model OpenOrderFramework.Models.Order
@{
ViewBag.Title = "P4MCheckout";
}
<link rel="import" href="/Scripts/widgets/p4m-checkout/p4m-checkout.html">
<link rel="import" href="/Scripts/widgets/p4m-login/p4m-login.html">
<h2>Parcel For Me</h2>
<p4m-checkout></p4m-checkout> |
Add default value for frame in constructor | using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace NutEngine
{
public class Sprite : Node, IDrawable
{
public Texture2D Atlas { get; }
public Rectangle? Frame { get; set; }
public Color Color { get; set; }
public Vector2 Origin { get; set; }
public SpriteEffects Effects { get; set; }
public float LayerDepth { get; set; }
public Sprite(Texture2D atlas, Rectangle? frame) : base()
{
Atlas = atlas;
Frame = frame;
Color = Color.White;
if (Frame != null) {
var center = Frame.Value.Center;
Origin = new Vector2(center.X, center.Y);
}
else {
Origin = new Vector2(Atlas.Width / 2.0f, Atlas.Height / 2.0f);
}
Effects = SpriteEffects.None;
LayerDepth = 0;
}
public void Draw(SpriteBatch spriteBatch, Transform2D currentTransform)
{
Vector2 position, scale;
float rotation;
currentTransform.Decompose(out scale, out rotation, out position);
spriteBatch.Draw(
Atlas
, position
, Frame
, Color
, rotation
, Origin
, scale
, Effects
, LayerDepth);
}
}
}
| using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace NutEngine
{
public class Sprite : Node, IDrawable
{
public Texture2D Atlas { get; }
public Rectangle? Frame { get; set; }
public Color Color { get; set; }
public Vector2 Origin { get; set; }
public SpriteEffects Effects { get; set; }
public float LayerDepth { get; set; }
public Sprite(Texture2D atlas, Rectangle? frame = null) : base()
{
Atlas = atlas;
Frame = frame;
Color = Color.White;
if (Frame != null) {
var center = Frame.Value.Center;
Origin = new Vector2(center.X, center.Y);
}
else {
Origin = new Vector2(Atlas.Width / 2.0f, Atlas.Height / 2.0f);
}
Effects = SpriteEffects.None;
LayerDepth = 0;
}
public void Draw(SpriteBatch spriteBatch, Transform2D currentTransform)
{
Vector2 position, scale;
float rotation;
currentTransform.Decompose(out scale, out rotation, out position);
spriteBatch.Draw(
Atlas
, position
, Frame
, Color
, rotation
, Origin
, scale
, Effects
, LayerDepth);
}
}
}
|
Increment assembly version to 1.1.2 | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Treenumerable")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Toshiba")]
[assembly: AssemblyProduct("Treenumerable")]
[assembly: AssemblyCopyright("Copyright © Toshiba 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.1")]
[assembly: AssemblyFileVersion("1.1.1")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Treenumerable")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Toshiba")]
[assembly: AssemblyProduct("Treenumerable")]
[assembly: AssemblyCopyright("Copyright © Toshiba 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.2")]
[assembly: AssemblyFileVersion("1.1.2")]
|
Add [KnownType(typeof(Dictionary<string,object>))] to allow for Object mapping to be passed over WCF channel | using System.Runtime.Serialization;
namespace CefSharp
{
[DataContract]
[KnownType(typeof(object[]))]
public class JavascriptResponse
{
[DataMember]
public string Message { get; set; }
[DataMember]
public bool Success { get; set; }
[DataMember]
public object Result { get; set; }
}
}
| using System.Collections.Generic;
using System.Runtime.Serialization;
namespace CefSharp
{
[DataContract]
[KnownType(typeof(object[]))]
[KnownType(typeof(Dictionary<string,object>))]
public class JavascriptResponse
{
[DataMember]
public string Message { get; set; }
[DataMember]
public bool Success { get; set; }
[DataMember]
public object Result { get; set; }
}
}
|
Add cast on return value if needed | using Swigged.LLVM;
using Mono.Cecil;
using Mono.Cecil.Cil;
using CSharpLLVM.Compilation;
using CSharpLLVM.Stack;
namespace CSharpLLVM.Generator.Instructions.FlowControl
{
[InstructionHandler(Code.Ret)]
class EmitRet : ICodeEmitter
{
/// <summary>
/// Emits a ret instruction.
/// </summary>
/// <param name="instruction">The instruction.</param>
/// <param name="context">The context.</param>
/// <param name="builder">The builder.</param>
public void Emit(Instruction instruction, MethodContext context, BuilderRef builder)
{
if (context.Method.ReturnType.MetadataType == MetadataType.Void)
{
LLVM.BuildRetVoid(builder);
}
else
{
StackElement element = context.CurrentStack.Pop();
LLVM.BuildRet(builder, element.Value);
}
}
}
}
| using Swigged.LLVM;
using Mono.Cecil;
using Mono.Cecil.Cil;
using CSharpLLVM.Compilation;
using CSharpLLVM.Stack;
using CSharpLLVM.Helpers;
namespace CSharpLLVM.Generator.Instructions.FlowControl
{
[InstructionHandler(Code.Ret)]
class EmitRet : ICodeEmitter
{
/// <summary>
/// Emits a ret instruction.
/// </summary>
/// <param name="instruction">The instruction.</param>
/// <param name="context">The context.</param>
/// <param name="builder">The builder.</param>
public void Emit(Instruction instruction, MethodContext context, BuilderRef builder)
{
TypeReference returnType = context.Method.ReturnType;
if (returnType.MetadataType == MetadataType.Void)
{
LLVM.BuildRetVoid(builder);
}
else
{
StackElement element = context.CurrentStack.Pop();
TypeRef returnTypeRef = TypeHelper.GetTypeRefFromType(returnType);
if (element.Type != returnTypeRef)
{
CastHelper.HelpIntAndPtrCast(builder, ref element.Value, element.Type, returnTypeRef);
}
LLVM.BuildRet(builder, element.Value);
}
}
}
}
|
Add connection to the Bitcoin network test | using MagicalCryptoWallet.KeyManagement;
using MagicalCryptoWallet.Services;
using NBitcoin;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace MagicalCryptoWallet.Tests
{
public class WalletTests : IClassFixture<SharedFixture>
{
private SharedFixture SharedFixture { get; }
public WalletTests(SharedFixture fixture)
{
SharedFixture = fixture;
}
[Fact]
public async Task BasicWalletTestAsync()
{
var manager = KeyManager.CreateNew(out Mnemonic mnemonic, "password");
var dataFolder = Path.Combine(SharedFixture.DataDir, nameof(BasicWalletTestAsync));
using (var wallet = new WalletService(dataFolder, Network.Main, manager))
{
wallet.Start();
await Task.Delay(1000);
}
}
}
}
| using MagicalCryptoWallet.KeyManagement;
using MagicalCryptoWallet.Logging;
using MagicalCryptoWallet.Services;
using NBitcoin;
using NBitcoin.Protocol;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace MagicalCryptoWallet.Tests
{
public class WalletTests : IClassFixture<SharedFixture>
{
private SharedFixture SharedFixture { get; }
public WalletTests(SharedFixture fixture)
{
SharedFixture = fixture;
}
[Fact]
public async Task CanConnectToNodesTestAsync()
{
var manager = KeyManager.CreateNew(out Mnemonic mnemonic, "password");
var dataFolder = Path.Combine(SharedFixture.DataDir, nameof(CanConnectToNodesTestAsync));
using (var wallet = new WalletService(dataFolder, Network.Main, manager))
{
wallet.Nodes.ConnectedNodes.Added += ConnectedNodes_Added;
wallet.Nodes.ConnectedNodes.Removed += ConnectedNodes_Removed;
wallet.Start();
// Using the interlocked, not because it makes sense in this context, but to
// set an example that these values are often concurrency sensitive
while (Interlocked.Read(ref _nodeCount) < 3)
{
await Task.Delay(100);
}
}
}
private long _nodeCount = 0;
private void ConnectedNodes_Added(object sender, NodeEventArgs e)
{
var nodes = sender as NodesCollection;
Interlocked.Increment(ref _nodeCount);
Logger.LogInfo<WalletTests>($"Node count:{Interlocked.Read(ref _nodeCount)}");
}
private void ConnectedNodes_Removed(object sender, NodeEventArgs e)
{
var nodes = sender as NodesCollection;
Interlocked.Decrement(ref _nodeCount);
// Trace is fine here, building the connections is more exciting than removing them.
Logger.LogTrace<WalletTests>($"Node count:{Interlocked.Read(ref _nodeCount)}");
}
}
}
|
Implement basic behaviour of favourite button | // 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.Graphics.Sprites;
using osu.Game.Online.API.Requests.Responses;
namespace osu.Game.Beatmaps.Drawables.Cards.Buttons
{
public class FavouriteButton : BeatmapCardIconButton
{
private readonly APIBeatmapSet beatmapSet;
public FavouriteButton(APIBeatmapSet beatmapSet)
{
this.beatmapSet = beatmapSet;
Icon.Icon = FontAwesome.Regular.Heart;
}
// TODO: implement behaviour
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics.Sprites;
using osu.Game.Online.API.Requests.Responses;
using osu.Framework.Logging;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Resources.Localisation.Web;
namespace osu.Game.Beatmaps.Drawables.Cards.Buttons
{
public class FavouriteButton : BeatmapCardIconButton
{
private readonly APIBeatmapSet beatmapSet;
private PostBeatmapFavouriteRequest favouriteRequest;
public FavouriteButton(APIBeatmapSet beatmapSet)
{
this.beatmapSet = beatmapSet;
updateState();
}
[BackgroundDependencyLoader]
private void load(IAPIProvider api)
{
Action = () =>
{
var actionType = beatmapSet.HasFavourited ? BeatmapFavouriteAction.UnFavourite : BeatmapFavouriteAction.Favourite;
favouriteRequest?.Cancel();
favouriteRequest = new PostBeatmapFavouriteRequest(beatmapSet.OnlineID, actionType);
Enabled.Value = false;
favouriteRequest.Success += () =>
{
beatmapSet.HasFavourited = actionType == BeatmapFavouriteAction.Favourite;
Enabled.Value = true;
updateState();
};
favouriteRequest.Failure += e =>
{
Logger.Error(e, $"Failed to {actionType.ToString().ToLower()} beatmap: {e.Message}");
Enabled.Value = true;
};
api.Queue(favouriteRequest);
};
}
private void updateState()
{
if (beatmapSet.HasFavourited)
{
Icon.Icon = FontAwesome.Solid.Heart;
TooltipText = BeatmapsetsStrings.ShowDetailsUnfavourite;
}
else
{
Icon.Icon = FontAwesome.Regular.Heart;
TooltipText = BeatmapsetsStrings.ShowDetailsFavourite;
}
}
}
}
|
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major. | using System.Reflection;
[assembly: AssemblyTitle("Autofac.Extras.Tests.EnterpriseLibraryConfigurator")]
[assembly: AssemblyDescription("Tests for the Autofac container configurator for Enterprise Library.")]
| using System.Reflection;
[assembly: AssemblyTitle("Autofac.Extras.Tests.EnterpriseLibraryConfigurator")]
|
Allow OptiPNG to fix some apparently broken PNGs | using System;
using System.ComponentModel;
using System.Diagnostics;
namespace WOptiPng
{
public static class OptiPngWrapper
{
public static bool OptiPngExists()
{
var process = new Process
{
StartInfo = new ProcessStartInfo("optipng")
{
UseShellExecute = false,
CreateNoWindow = true
}
};
try
{
process.Start();
}
catch (Win32Exception)
{
return false;
}
return true;
}
public static int Optimize(string inputPath, string outputPath, Settings settings,
Action<string> standardErrorCallback)
{
using (var p = new Process
{
StartInfo = new ProcessStartInfo("optipng")
{
UseShellExecute = false,
CreateNoWindow = true,
Arguments = FormatArguments(outputPath, inputPath, settings.OptLevel),
RedirectStandardError = true,
}
})
{
p.Start();
p.PriorityClass = settings.ProcessPriority;
p.ErrorDataReceived += (sender, e) =>
{
if (standardErrorCallback != null)
{
standardErrorCallback(e.Data);
}
};
p.BeginErrorReadLine();
p.WaitForExit();
return p.ExitCode;
}
}
private static string FormatArguments(string outputPath, string inputPath, int optLevel)
{
return string.Format("-clobber -preserve -out \"{0}\" -o {1} \"{2}\"", outputPath, optLevel, inputPath);
}
}
} | using System;
using System.ComponentModel;
using System.Diagnostics;
namespace WOptiPng
{
public static class OptiPngWrapper
{
public static bool OptiPngExists()
{
var process = new Process
{
StartInfo = new ProcessStartInfo("optipng")
{
UseShellExecute = false,
CreateNoWindow = true
}
};
try
{
process.Start();
}
catch (Win32Exception)
{
return false;
}
return true;
}
public static int Optimize(string inputPath, string outputPath, Settings settings,
Action<string> standardErrorCallback)
{
using (var p = new Process
{
StartInfo = new ProcessStartInfo("optipng")
{
UseShellExecute = false,
CreateNoWindow = true,
Arguments = FormatArguments(outputPath, inputPath, settings.OptLevel),
RedirectStandardError = true,
}
})
{
p.Start();
p.PriorityClass = settings.ProcessPriority;
p.ErrorDataReceived += (sender, e) =>
{
if (standardErrorCallback != null)
{
standardErrorCallback(e.Data);
}
};
p.BeginErrorReadLine();
p.WaitForExit();
return p.ExitCode;
}
}
private static string FormatArguments(string outputPath, string inputPath, int optLevel)
{
return string.Format("-clobber -preserve -fix -out \"{0}\" -o {1} \"{2}\"", outputPath, optLevel, inputPath);
}
}
} |
Update tranportype with new additions for Mqtt/Ws and Mqtt/Tcp | using System;
using System.Collections.Generic;
using System.Text;
namespace Microsoft.Azure.Devices.Client
{
/// <summary>
/// Transport types supported by DeviceClient
/// </summary>
public enum TransportType
{
/// <summary>
/// Advanced Message Queuing Protocol transport.
/// Try Amqp over TCP first and fallback to Amqp over WebSocket if that fails
/// </summary>
Amqp = 0,
/// <summary>
/// HyperText Transfer Protocol version 1 transport.
/// </summary>
Http1 = 1,
/// <summary>
/// Advanced Message Queuing Protocol transport over WebSocket only.
/// </summary>
Amqp_WebSocket_Only = 2,
/// <summary>
/// Advanced Message Queuing Protocol transport over native TCP only
/// </summary>
Amqp_Tcp_Only = 3,
/// <summary>
/// Message Queuing Telemetry Transport.
/// </summary>
Mqtt = 4
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.Devices.Client
{
/// <summary>
/// Transport types supported by DeviceClient - AMQP/TCP, HTTP 1.1, MQTT/TCP, AMQP/WS, MQTT/WS
/// </summary>
public enum TransportType
{
/// <summary>
/// Advanced Message Queuing Protocol transport.
/// Try Amqp over TCP first and fallback to Amqp over WebSocket if that fails
/// </summary>
Amqp = 0,
/// <summary>
/// HyperText Transfer Protocol version 1 transport.
/// </summary>
Http1 = 1,
/// <summary>
/// Advanced Message Queuing Protocol transport over WebSocket only.
/// </summary>
Amqp_WebSocket_Only = 2,
/// <summary>
/// Advanced Message Queuing Protocol transport over native TCP only
/// </summary>
Amqp_Tcp_Only = 3,
/// <summary>
/// Message Queuing Telemetry Transport.
/// Try Mqtt over TCP first and fallback to Mqtt over WebSocket if that fails
/// </summary>
Mqtt = 4,
/// <summary>
/// Message Queuing Telemetry Transport over Websocket only.
/// </summary>
Mqtt_WebSocket_Only = 5,
/// <summary>
/// Message Queuing Telemetry Transport over native TCP only
/// </summary>
Mqtt_Tcp_Only = 6,
}
}
|
Add sitename to MSI specialization payload. | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Collections.Generic;
namespace Microsoft.Azure.WebJobs.Script.WebHost.Models
{
public class MSIContext
{
public string MSISecret { get; set; }
public IEnumerable<ManagedServiceIdentity> Identities { get; set; }
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Collections.Generic;
namespace Microsoft.Azure.WebJobs.Script.WebHost.Models
{
public class MSIContext
{
public string SiteName { get; set; }
public string MSISecret { get; set; }
public IEnumerable<ManagedServiceIdentity> Identities { get; set; }
}
}
|
Verify that executing single argument command works as expected | namespace AppHarbor.Tests
{
public class CommandDispatcherTest
{
public class FooCommand : ICommand
{
public virtual void Execute(string[] arguments)
{
}
}
}
}
| using System.Linq;
using Castle.MicroKernel;
using Moq;
using Ploeh.AutoFixture.Xunit;
using Xunit.Extensions;
namespace AppHarbor.Tests
{
public class CommandDispatcherTest
{
public class FooCommand : ICommand
{
public virtual void Execute(string[] arguments)
{
}
}
[Theory]
[InlineAutoCommandData("foo", "foo", null)]
[InlineAutoCommandData("foo:bar", "foo", "bar")]
public void ShouldDispatchCommandWithASingleParameter(
string argument,
string commandName,
string scope,
[Frozen]Mock<ITypeNameMatcher> typeNameMatcher,
[Frozen]Mock<IKernel> kernel,
Mock<FooCommand> command,
CommandDispatcher commandDispatcher)
{
var commandType = typeof(FooCommand);
typeNameMatcher.Setup(x => x.GetMatchedType(commandName, scope)).Returns(commandType);
kernel.Setup(x => x.Resolve(commandType)).Returns(command.Object);
var dispatchArguments = new string[] { argument };
commandDispatcher.Dispatch(dispatchArguments);
command.Verify(x => x.Execute(It.Is<string[]>(y => !y.Any())));
}
}
}
|
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major. | using System.Reflection;
[assembly: AssemblyTitle("Autofac.Extras.Tests.Multitenant")]
[assembly: AssemblyDescription("Tests for the Autofac multitenancy feature.")]
| using System.Reflection;
[assembly: AssemblyTitle("Autofac.Extras.Tests.Multitenant")]
|
Fix pos of main menu buttons | using UnityEngine;
using System.Collections;
public class mainMenuHandler : MonoBehaviour {
// private Texture2D startButton;
void OnGUI () {
GUI.backgroundColor = Color.clear;
if (GUI.Button (new Rect (260,300, 300, 300), "")) {
// print ("Start Game");
//start game
Application.LoadLevel(2);
}
if (GUI.Button (new Rect (860, 300, 300, 300), "")) {
print ("Level Selection");
Application.LoadLevel(1);
}
}
} | using UnityEngine;
using System.Collections;
public class mainMenuHandler : MonoBehaviour {
public Texture2D startButton;
void OnGUI () {
GUI.backgroundColor = Color.clear;
if (GUI.Button (new Rect (Screen.width/20*3,Screen.height/10*4, 250, 250), startButton)) {
// print ("Start Game");
//start game
Application.LoadLevel(2);
}
if (GUI.Button (new Rect (Screen.width/10*5, Screen.height/10*4, 250, 250), startButton)) {
print ("Level Selection");
Application.LoadLevel(1);
}
}
} |
Add DbContext null check to FieldInterceptor.cs | namespace EntityFramework.Filters
{
using System.Data.Entity.Core.Common.CommandTrees;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure.Interception;
using System.Linq;
public class FilterInterceptor : IDbCommandTreeInterceptor
{
public void TreeCreated(DbCommandTreeInterceptionContext interceptionContext)
{
if (interceptionContext.OriginalResult.DataSpace == DataSpace.SSpace)
{
var queryCommand = interceptionContext.Result as DbQueryCommandTree;
if (queryCommand != null)
{
var newQuery =
queryCommand.Query.Accept(new FilterQueryVisitor(interceptionContext.DbContexts.First()));
interceptionContext.Result = new DbQueryCommandTree(
queryCommand.MetadataWorkspace, queryCommand.DataSpace, newQuery);
}
}
}
}
} | namespace EntityFramework.Filters
{
using System.Data.Entity.Core.Common.CommandTrees;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure.Interception;
using System.Linq;
public class FilterInterceptor : IDbCommandTreeInterceptor
{
public void TreeCreated(DbCommandTreeInterceptionContext interceptionContext)
{
if (interceptionContext.OriginalResult.DataSpace == DataSpace.SSpace)
{
var queryCommand = interceptionContext.Result as DbQueryCommandTree;
if (queryCommand != null)
{
var context = interceptionContext.DbContexts.FirstOrDefault();
if (context != null)
{
var newQuery =
queryCommand.Query.Accept(new FilterQueryVisitor(context));
interceptionContext.Result = new DbQueryCommandTree(
queryCommand.MetadataWorkspace, queryCommand.DataSpace, newQuery);
}
}
}
}
}
}
|
Add file that was missed in rename | using Glimpse.Core.Extensibility;
namespace Glimpse.Core.Resource
{
/// <summary>
/// The <see cref="IResource"/> implementation responsible for providing the Glimpse JavaScript client to the browser.
/// </summary>
public class InsightResource : FileResource, IKey
{
internal const string InternalName = "glimpse_insight";
private EmbeddedResourceInfo ResourceInfo { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="ClientResource" /> class.
/// </summary>
public InsightResource()
{
Name = InternalName;
ResourceInfo = new EmbeddedResourceInfo(GetType().Assembly, "Glimpse.Core.glimpsePre.js", "application/x-javascript");
}
/// <summary>
/// Gets the key.
/// </summary>
/// <value>
/// The key. Only valid JavaScript identifiers should be used for future compatibility.
/// </value>
public string Key
{
get { return Name; }
}
/// <summary>
/// Returns the embedded resource that represents the Glimpse Client which will be returned during the execution of the <see cref="FileResource"/>
/// </summary>
/// <param name="context">The resource context</param>
/// <returns>Information about the embedded Glimpse Client</returns>
protected override EmbeddedResourceInfo GetEmbeddedResourceInfo(IResourceContext context)
{
return ResourceInfo;
}
}
} | using Glimpse.Core.Extensibility;
namespace Glimpse.Core.Resource
{
/// <summary>
/// The <see cref="IResource"/> implementation responsible for providing the Glimpse JavaScript client to the browser.
/// </summary>
public class InsightResource : FileResource, IKey
{
internal const string InternalName = "glimpse_insight";
private EmbeddedResourceInfo ResourceInfo { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="ClientResource" /> class.
/// </summary>
public InsightResource()
{
Name = InternalName;
ResourceInfo = new EmbeddedResourceInfo(GetType().Assembly, "Glimpse.Core.glimpseInsight.js", "application/x-javascript");
}
/// <summary>
/// Gets the key.
/// </summary>
/// <value>
/// The key. Only valid JavaScript identifiers should be used for future compatibility.
/// </value>
public string Key
{
get { return Name; }
}
/// <summary>
/// Returns the embedded resource that represents the Glimpse Client which will be returned during the execution of the <see cref="FileResource"/>
/// </summary>
/// <param name="context">The resource context</param>
/// <returns>Information about the embedded Glimpse Client</returns>
protected override EmbeddedResourceInfo GetEmbeddedResourceInfo(IResourceContext context)
{
return ResourceInfo;
}
}
} |
Add plugin bridge object to script variable list | using System;
using System.Collections.Generic;
namespace TweetDck.Plugins{
[Flags]
enum PluginEnvironment{
None = 0,
Browser = 1,
Notification = 2
}
static class PluginEnvironmentExtensions{
public static IEnumerable<PluginEnvironment> Values{
get{
yield return PluginEnvironment.Browser;
yield return PluginEnvironment.Notification;
}
}
public static string GetScriptFile(this PluginEnvironment environment){
switch(environment){
case PluginEnvironment.Browser: return "browser.js";
case PluginEnvironment.Notification: return "notification.js";
default: return null;
}
}
public static string GetScriptVariables(this PluginEnvironment environment){
switch(environment){
case PluginEnvironment.Browser: return "$,$TD,TD";
case PluginEnvironment.Notification: return "$TD";
default: return string.Empty;
}
}
}
}
| using System;
using System.Collections.Generic;
namespace TweetDck.Plugins{
[Flags]
enum PluginEnvironment{
None = 0,
Browser = 1,
Notification = 2
}
static class PluginEnvironmentExtensions{
public static IEnumerable<PluginEnvironment> Values{
get{
yield return PluginEnvironment.Browser;
yield return PluginEnvironment.Notification;
}
}
public static string GetScriptFile(this PluginEnvironment environment){
switch(environment){
case PluginEnvironment.Browser: return "browser.js";
case PluginEnvironment.Notification: return "notification.js";
default: return null;
}
}
public static string GetScriptVariables(this PluginEnvironment environment){
switch(environment){
case PluginEnvironment.Browser: return "$,$TD,$TDP,TD";
case PluginEnvironment.Notification: return "$TD,$TDP";
default: return string.Empty;
}
}
}
}
|
Fix create map not using MemberList property | using System;
using Abp.Collections.Extensions;
using AutoMapper;
namespace Abp.AutoMapper
{
public class AutoMapFromAttribute : AutoMapAttributeBase
{
public MemberList MemberList { get; set; } = MemberList.Destination;
public AutoMapFromAttribute(params Type[] targetTypes)
: base(targetTypes)
{
}
public AutoMapFromAttribute(MemberList memberList, params Type[] targetTypes)
: this(targetTypes)
{
MemberList = memberList;
}
public override void CreateMap(IMapperConfigurationExpression configuration, Type type)
{
if (TargetTypes.IsNullOrEmpty())
{
return;
}
foreach (var targetType in TargetTypes)
{
configuration.CreateMap(targetType, type, MemberList.Destination);
}
}
}
} | using System;
using Abp.Collections.Extensions;
using AutoMapper;
namespace Abp.AutoMapper
{
public class AutoMapFromAttribute : AutoMapAttributeBase
{
public MemberList MemberList { get; set; } = MemberList.Destination;
public AutoMapFromAttribute(params Type[] targetTypes)
: base(targetTypes)
{
}
public AutoMapFromAttribute(MemberList memberList, params Type[] targetTypes)
: this(targetTypes)
{
MemberList = memberList;
}
public override void CreateMap(IMapperConfigurationExpression configuration, Type type)
{
if (TargetTypes.IsNullOrEmpty())
{
return;
}
foreach (var targetType in TargetTypes)
{
configuration.CreateMap(targetType, type, MemberList);
}
}
}
} |
Fix for using Length before GetPosition. | using UnityEngine;
public abstract class Curve : ICurve {
protected abstract Vector3 GetPositionImpl(float u);
protected abstract float LengthImpl { get; }
public static readonly Vector3 DefaultUpVector = Vector3.up;
protected bool Invalid { get; private set; }
public float Length { get; private set; }
protected void Invalidate() {
Invalid = true;
}
protected void Validate() {
if (Invalid) {
Update();
Invalid = false;
}
}
protected virtual void Update() {
Length = LengthImpl;
}
public Vector3 GetPosition(float u) {
Validate();
return GetPositionImpl(u);
}
public Vector3 GetForward(float u) {
u = Mathf.Clamp01(u);
const float epsilon = 0.01f;
Validate();
return (GetPosition(Mathf.Clamp01(u + epsilon)) -
GetPosition(Mathf.Clamp01(u - epsilon))).normalized;
}
public Vector3 GetNormal(float u, Vector3 up) {
return Vector3.Cross(GetForward(u), up);
}
public Vector3 GetNormal(float u) {
return GetNormal(u, DefaultUpVector);
}
}
| using UnityEngine;
public abstract class Curve : ICurve {
protected abstract Vector3 GetPositionImpl(float u);
protected abstract float LengthImpl { get; }
public static readonly Vector3 DefaultUpVector = Vector3.up;
protected bool Invalid { get; private set; }
private float _length;
public float Length { get {
Validate();
return _length;
}
}
protected void Invalidate() {
Invalid = true;
}
protected void Validate() {
if (Invalid) {
Update();
Invalid = false;
}
}
protected virtual void Update() {
_length = LengthImpl;
}
public Vector3 GetPosition(float u) {
Validate();
return GetPositionImpl(u);
}
public Vector3 GetForward(float u) {
u = Mathf.Clamp01(u);
const float epsilon = 0.01f;
Validate();
return (GetPosition(Mathf.Clamp01(u + epsilon)) -
GetPosition(Mathf.Clamp01(u - epsilon))).normalized;
}
public Vector3 GetNormal(float u, Vector3 up) {
return Vector3.Cross(GetForward(u), up);
}
public Vector3 GetNormal(float u) {
return GetNormal(u, DefaultUpVector);
}
}
|
Return NotFound on invalid team ID's | using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using SupportManager.DAL;
namespace SupportManager.Web.Areas.Teams
{
[Area("Teams")]
[Authorize]
public abstract class BaseController : Controller
{
protected int TeamId => int.Parse((string) ControllerContext.RouteData.Values["teamId"]);
protected SupportTeam Team { get; private set; }
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var db = (SupportManagerContext) context.HttpContext.RequestServices.GetService(typeof(SupportManagerContext));
Team = await db.Teams.FindAsync(TeamId);
ViewData["TeamName"] = Team.Name;
await base.OnActionExecutionAsync(context, next);
}
}
}
| using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using SupportManager.DAL;
namespace SupportManager.Web.Areas.Teams
{
[Area("Teams")]
[Authorize]
public abstract class BaseController : Controller
{
protected int TeamId => int.Parse((string) ControllerContext.RouteData.Values["teamId"]);
protected SupportTeam Team { get; private set; }
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var db = (SupportManagerContext) context.HttpContext.RequestServices.GetService(typeof(SupportManagerContext));
Team = await db.Teams.FindAsync(TeamId);
if (Team == null)
{
context.Result = NotFound();
return;
}
ViewData["TeamName"] = Team.Name;
await base.OnActionExecutionAsync(context, next);
}
}
}
|
Read file before the reader is disposed | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.IO;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Newtonsoft.Json;
namespace Microsoft.CodeAnalysis.UnusedReferences.ProjectAssets
{
internal static partial class ProjectAssetsFileReader
{
/// <summary>
/// Enhances references with the assemblies they bring into the compilation and their dependency hierarchy.
/// </summary>
public static async Task<ImmutableArray<ReferenceInfo>> ReadReferencesAsync(
ImmutableArray<ReferenceInfo> projectReferences,
string projectAssetsFilePath)
{
var doesProjectAssetsFileExist = IOUtilities.PerformIO(() => File.Exists(projectAssetsFilePath));
if (!doesProjectAssetsFileExist)
{
return ImmutableArray<ReferenceInfo>.Empty;
}
var projectAssetsFileContents = await IOUtilities.PerformIOAsync(() =>
{
using var fileStream = File.OpenRead(projectAssetsFilePath);
using var reader = new StreamReader(fileStream);
return reader.ReadToEndAsync();
}).ConfigureAwait(false);
if (projectAssetsFileContents is null)
{
return ImmutableArray<ReferenceInfo>.Empty;
}
try
{
var projectAssets = JsonConvert.DeserializeObject<ProjectAssetsFile>(projectAssetsFileContents);
return ProjectAssetsReader.AddDependencyHierarchies(projectReferences, projectAssets);
}
catch
{
return ImmutableArray<ReferenceInfo>.Empty;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.IO;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Newtonsoft.Json;
namespace Microsoft.CodeAnalysis.UnusedReferences.ProjectAssets
{
internal static partial class ProjectAssetsFileReader
{
/// <summary>
/// Enhances references with the assemblies they bring into the compilation and their dependency hierarchy.
/// </summary>
public static async Task<ImmutableArray<ReferenceInfo>> ReadReferencesAsync(
ImmutableArray<ReferenceInfo> projectReferences,
string projectAssetsFilePath)
{
var doesProjectAssetsFileExist = IOUtilities.PerformIO(() => File.Exists(projectAssetsFilePath));
if (!doesProjectAssetsFileExist)
{
return ImmutableArray<ReferenceInfo>.Empty;
}
var projectAssetsFileContents = await IOUtilities.PerformIOAsync(async () =>
{
using var fileStream = File.OpenRead(projectAssetsFilePath);
using var reader = new StreamReader(fileStream);
return await reader.ReadToEndAsync().ConfigureAwait(false);
}).ConfigureAwait(false);
if (projectAssetsFileContents is null)
{
return ImmutableArray<ReferenceInfo>.Empty;
}
try
{
var projectAssets = JsonConvert.DeserializeObject<ProjectAssetsFile>(projectAssetsFileContents);
return ProjectAssetsReader.AddDependencyHierarchies(projectReferences, projectAssets);
}
catch
{
return ImmutableArray<ReferenceInfo>.Empty;
}
}
}
}
|
Remove import for empty script file | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - Quadruped WebInterface</title>
<link rel="stylesheet" href="~/css/site.css" />
<script src="~/js/site.min.js"></script>
</head>
<body>
@RenderBody()
@RenderSection("scripts", required: false)
</body>
</html>
| <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - Quadruped WebInterface</title>
<link rel="stylesheet" href="~/css/site.css" />
@*<script src="~/js/site.min.js"></script>*@
</head>
<body>
@RenderBody()
@RenderSection("scripts", required: false)
</body>
</html>
|
Improve wording of an exception | using Microsoft.Extensions.Configuration;
using System;
using System.Linq;
namespace Tgstation.Server.Host.Core
{
/// <inheritdoc />
sealed class ServerPortProivder : IServerPortProvider
{
/// <inheritdoc />
public ushort HttpApiPort { get; }
/// <summary>
/// Initializes a new instance of the <see cref="ServerPortProivder"/> <see langword="class"/>.
/// </summary>
/// <param name="configuration">The <see cref="IConfiguration"/> to use.</param>
public ServerPortProivder(IConfiguration configuration)
{
if (configuration == null)
throw new ArgumentNullException(nameof(configuration));
var httpEndpoint = configuration
.GetSection("Kestrel")
.GetSection("EndPoints")
.GetSection("Http")
.GetSection("Url")
.Value;
if (httpEndpoint == null)
throw new InvalidOperationException("Missing required configuration option for Kestrel:EndPoints:Http:Url!");
var splits = httpEndpoint.Split(":", StringSplitOptions.RemoveEmptyEntries);
var portString = splits.Last();
portString = portString.TrimEnd('/');
if (!UInt16.TryParse(portString, out var result))
throw new InvalidOperationException($"Failed to parse HTTP EndPoint port: {httpEndpoint}");
HttpApiPort = result;
}
}
}
| using Microsoft.Extensions.Configuration;
using System;
using System.Linq;
namespace Tgstation.Server.Host.Core
{
/// <inheritdoc />
sealed class ServerPortProivder : IServerPortProvider
{
/// <inheritdoc />
public ushort HttpApiPort { get; }
/// <summary>
/// Initializes a new instance of the <see cref="ServerPortProivder"/> <see langword="class"/>.
/// </summary>
/// <param name="configuration">The <see cref="IConfiguration"/> to use.</param>
public ServerPortProivder(IConfiguration configuration)
{
if (configuration == null)
throw new ArgumentNullException(nameof(configuration));
var httpEndpoint = configuration
.GetSection("Kestrel")
.GetSection("EndPoints")
.GetSection("Http")
.GetSection("Url")
.Value;
if (httpEndpoint == null)
throw new InvalidOperationException("Missing required configuration option Kestrel:EndPoints:Http:Url!");
var splits = httpEndpoint.Split(":", StringSplitOptions.RemoveEmptyEntries);
var portString = splits.Last();
portString = portString.TrimEnd('/');
if (!UInt16.TryParse(portString, out var result))
throw new InvalidOperationException($"Failed to parse HTTP EndPoint port: {httpEndpoint}");
HttpApiPort = result;
}
}
}
|
Fix camel case on the Learners response | using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using SFA.DAS.CommitmentsV2.Api.Types.Responses;
using SFA.DAS.CommitmentsV2.Application.Queries.GetAllLearners;
using System;
using System.Net;
using System.Threading.Tasks;
namespace SFA.DAS.CommitmentsV2.Api.Controllers
{
[ApiController]
[Authorize]
[Route("api/learners")]
public class LearnerController : ControllerBase
{
private readonly IMediator _mediator;
public LearnerController(IMediator mediator)
{
_mediator = mediator;
}
[HttpGet]
public async Task<IActionResult> GetAllLearners(DateTime? sinceTime = null, int batch_number = 1, int batch_size = 1000)
{
var result = await _mediator.Send(new GetAllLearnersQuery(sinceTime, batch_number, batch_size));
var settings = new JsonSerializerSettings
{
DateFormatString = "yyyy-MM-dd'T'HH:mm:ss"
};
var jsonResult = new JsonResult(new GetAllLearnersResponse()
{
Learners = result.Learners,
BatchNumber = result.BatchNumber,
BatchSize = result.BatchSize,
TotalNumberOfBatches = result.TotalNumberOfBatches
}, settings);
jsonResult.StatusCode = (int)HttpStatusCode.OK;
jsonResult.ContentType = "application/json";
return jsonResult;
}
}
}
| using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using SFA.DAS.CommitmentsV2.Api.Types.Responses;
using SFA.DAS.CommitmentsV2.Application.Queries.GetAllLearners;
using System;
using System.Net;
using System.Threading.Tasks;
namespace SFA.DAS.CommitmentsV2.Api.Controllers
{
[ApiController]
[Authorize]
[Route("api/learners")]
public class LearnerController : ControllerBase
{
private readonly IMediator _mediator;
public LearnerController(IMediator mediator)
{
_mediator = mediator;
}
[HttpGet]
public async Task<IActionResult> GetAllLearners(DateTime? sinceTime = null, int batch_number = 1, int batch_size = 1000)
{
var result = await _mediator.Send(new GetAllLearnersQuery(sinceTime, batch_number, batch_size));
var settings = new JsonSerializerSettings
{
DateFormatString = "yyyy-MM-dd'T'HH:mm:ss",
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var jsonResult = new JsonResult(new GetAllLearnersResponse()
{
Learners = result.Learners,
BatchNumber = result.BatchNumber,
BatchSize = result.BatchSize,
TotalNumberOfBatches = result.TotalNumberOfBatches
}, settings);
jsonResult.StatusCode = (int)HttpStatusCode.OK;
jsonResult.ContentType = "application/json";
return jsonResult;
}
}
}
|
Remove only remaining .NET desktop code | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.IO;
using System.Linq;
using osu.Framework;
using osu.Framework.Platform;
using osu.Game.IPC;
#if NET_FRAMEWORK
using System.Runtime;
#endif
namespace osu.Desktop
{
public static class Program
{
[STAThread]
public static int Main(string[] args)
{
useMultiCoreJit();
// Back up the cwd before DesktopGameHost changes it
var cwd = Environment.CurrentDirectory;
using (DesktopGameHost host = Host.GetSuitableHost(@"osu", true))
{
if (!host.IsPrimaryInstance)
{
var importer = new ArchiveImportIPCChannel(host);
// Restore the cwd so relative paths given at the command line work correctly
Directory.SetCurrentDirectory(cwd);
foreach (var file in args)
{
Console.WriteLine(@"Importing {0}", file);
if (!importer.ImportAsync(Path.GetFullPath(file)).Wait(3000))
throw new TimeoutException(@"IPC took too long to send");
}
}
else
{
switch (args.FirstOrDefault() ?? string.Empty)
{
default:
host.Run(new OsuGameDesktop(args));
break;
}
}
return 0;
}
}
private static void useMultiCoreJit()
{
#if NET_FRAMEWORK
var directory = Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Profiles"));
ProfileOptimization.SetProfileRoot(directory.FullName);
ProfileOptimization.StartProfile("Startup.Profile");
#endif
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.IO;
using System.Linq;
using osu.Framework;
using osu.Framework.Platform;
using osu.Game.IPC;
namespace osu.Desktop
{
public static class Program
{
[STAThread]
public static int Main(string[] args)
{
// Back up the cwd before DesktopGameHost changes it
var cwd = Environment.CurrentDirectory;
using (DesktopGameHost host = Host.GetSuitableHost(@"osu", true))
{
if (!host.IsPrimaryInstance)
{
var importer = new ArchiveImportIPCChannel(host);
// Restore the cwd so relative paths given at the command line work correctly
Directory.SetCurrentDirectory(cwd);
foreach (var file in args)
{
Console.WriteLine(@"Importing {0}", file);
if (!importer.ImportAsync(Path.GetFullPath(file)).Wait(3000))
throw new TimeoutException(@"IPC took too long to send");
}
}
else
{
switch (args.FirstOrDefault() ?? string.Empty)
{
default:
host.Run(new OsuGameDesktop(args));
break;
}
}
return 0;
}
}
}
}
|
Fix path, because NUnit does nto run from the current assembly dir | using System;
using System.IO;
using System.Net;
using NUnit.Framework;
namespace HttpMock.Integration.Tests
{
[TestFixture]
public class EndpointsReturningFilesTests
{
private const string FILE_NAME = "transcode-input.mp3";
private const string RES_TRANSCODE_INPUT_MP3 = "./res/"+FILE_NAME;
[Test]
public void A_Setting_return_file_return_the_correct_content_length() {
var stubHttp = HttpMockRepository.At("http://localhost.:9191");
stubHttp.Stub(x => x.Get("/afile"))
.ReturnFile(RES_TRANSCODE_INPUT_MP3)
.OK();
Console.WriteLine(stubHttp.WhatDoIHave());
var fileLength = new FileInfo(RES_TRANSCODE_INPUT_MP3).Length;
var webRequest = (HttpWebRequest) WebRequest.Create("http://localhost.:9191/afile");
using (var response = webRequest.GetResponse())
using(var responseStream = response.GetResponseStream())
{
var bytes = new byte[response.ContentLength];
responseStream.Read(bytes, 0, (int) response.ContentLength);
Assert.That(response.ContentLength, Is.EqualTo(fileLength));
}
}
}
} | using System;
using System.IO;
using System.Net;
using NUnit.Framework;
namespace HttpMock.Integration.Tests
{
[TestFixture]
public class EndpointsReturningFilesTests
{
private const string FILE_NAME = "transcode-input.mp3";
private const string RES_TRANSCODE_INPUT_MP3 = "res\\"+FILE_NAME;
[Test]
public void A_Setting_return_file_return_the_correct_content_length() {
var stubHttp = HttpMockRepository.At("http://localhost.:9191");
var pathToFile = Path.Combine(TestContext.CurrentContext.TestDirectory, RES_TRANSCODE_INPUT_MP3);
stubHttp.Stub(x => x.Get("/afile"))
.ReturnFile(pathToFile)
.OK();
Console.WriteLine(stubHttp.WhatDoIHave());
var fileLength = new FileInfo(pathToFile).Length;
var webRequest = (HttpWebRequest) WebRequest.Create("http://localhost.:9191/afile");
using (var response = webRequest.GetResponse())
using(var responseStream = response.GetResponseStream())
{
var bytes = new byte[response.ContentLength];
responseStream.Read(bytes, 0, (int) response.ContentLength);
Assert.That(response.ContentLength, Is.EqualTo(fileLength));
}
}
}
} |
Fix authentication crash on edit | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace BeerCellier
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
| using System.Security.Claims;
using System.Web.Helpers;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace BeerCellier
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
}
}
}
|
Remove unused references from example client | using System;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using Obvs.Types;
using Obvs.ActiveMQ.Configuration;
using Obvs.Configuration;
using Obvs.Example.Messages;
using Obvs.Serialization.Json.Configuration;
namespace Obvs.Example.Client
{
internal static class Program
{
private static void Main(string[] args)
{
var brokerUri = Environment.GetEnvironmentVariable("ACTIVEMQ_BROKER_URI") ?? "tcp://localhost:61616";
var serviceName = Environment.GetEnvironmentVariable("OBVS_SERVICE_NAME") ?? "Obvs.Service1";
Console.WriteLine($"Starting {serviceName}, connecting to broker {brokerUri}");
var serviceBus = ServiceBus.Configure()
.WithActiveMQEndpoints<IServiceMessage1>()
.Named(serviceName)
.UsingQueueFor<ICommand>()
.ConnectToBroker(brokerUri)
.WithCredentials("admin", "admin")
.SerializedAsJson()
.AsClient()
.CreateClient();
serviceBus.Events.Subscribe(ev => Console.WriteLine("Received event: " + ev));
Console.WriteLine("Type some text and hit <Enter> to send as command.");
while (true)
{
string data = Console.ReadLine();
serviceBus.SendAsync(new Command1 { Data = data });
}
}
}
}
| using System;
using Obvs.Types;
using Obvs.ActiveMQ.Configuration;
using Obvs.Configuration;
using Obvs.Example.Messages;
using Obvs.Serialization.Json.Configuration;
namespace Obvs.Example.Client
{
internal static class Program
{
private static void Main(string[] args)
{
var brokerUri = Environment.GetEnvironmentVariable("ACTIVEMQ_BROKER_URI") ?? "tcp://localhost:61616";
var serviceName = Environment.GetEnvironmentVariable("OBVS_SERVICE_NAME") ?? "Obvs.Service1";
Console.WriteLine($"Starting {serviceName}, connecting to broker {brokerUri}");
var serviceBus = ServiceBus.Configure()
.WithActiveMQEndpoints<IServiceMessage1>()
.Named(serviceName)
.UsingQueueFor<ICommand>()
.ConnectToBroker(brokerUri)
.WithCredentials("admin", "admin")
.SerializedAsJson()
.AsClient()
.CreateClient();
serviceBus.Events.Subscribe(ev => Console.WriteLine("Received event: " + ev));
Console.WriteLine("Type some text and hit <Enter> to send as command.");
while (true)
{
string data = Console.ReadLine();
serviceBus.SendAsync(new Command1 { Data = data });
}
}
}
}
|
Set NUnit tests to run scripts under the current domain for access to the same console. | using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Text;
using IronAHK.Scripting;
using NUnit.Framework;
namespace Tests
{
[TestFixture]
public partial class Scripting
{
[Test]
public void RunScripts()
{
string path = string.Format("..{0}..{0}Scripting{0}Code", Path.DirectorySeparatorChar.ToString());
foreach (string file in Directory.GetFiles(path, "*.ia"))
{
string name = Path.GetFileNameWithoutExtension(file);
var provider = new IACodeProvider();
var options = new CompilerParameters();
options.GenerateExecutable = true;
options.GenerateInMemory = false;
options.ReferencedAssemblies.Add(typeof(IronAHK.Rusty.Core).Namespace + ".dll");
options.OutputAssembly = Path.GetTempFileName() + ".exe";
provider.CompileAssemblyFromFile(options, file);
bool exists = File.Exists(options.OutputAssembly);
Assert.IsTrue(exists, name + " assembly");
if (exists)
{
AppDomain domain = AppDomain.CreateDomain(name);
var buffer = new StringBuilder();
var writer = new StringWriter(buffer);
Console.SetOut(writer);
domain.ExecuteAssembly(options.OutputAssembly);
AppDomain.Unload(domain);
string output = buffer.ToString();
Assert.AreEqual("pass", output, name);
var standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
}
}
}
}
}
| using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Text;
using IronAHK.Scripting;
using NUnit.Framework;
namespace Tests
{
[TestFixture]
public partial class Scripting
{
[Test]
public void RunScripts()
{
string path = string.Format("..{0}..{0}Scripting{0}Code", Path.DirectorySeparatorChar.ToString());
foreach (string file in Directory.GetFiles(path, "*.ia"))
{
string name = Path.GetFileNameWithoutExtension(file);
var provider = new IACodeProvider();
var options = new CompilerParameters();
options.GenerateExecutable = true;
options.GenerateInMemory = false;
options.ReferencedAssemblies.Add(typeof(IronAHK.Rusty.Core).Namespace + ".dll");
options.OutputAssembly = Path.GetTempFileName() + ".exe";
provider.CompileAssemblyFromFile(options, file);
bool exists = File.Exists(options.OutputAssembly);
Assert.IsTrue(exists, name + " assembly");
if (exists)
{
var buffer = new StringBuilder();
var writer = new StringWriter(buffer);
Console.SetOut(writer);
AppDomain.CurrentDomain.ExecuteAssembly(options.OutputAssembly);
try { File.Delete(options.OutputAssembly); }
catch (UnauthorizedAccessException) { }
writer.Flush();
string output = buffer.ToString();
Assert.AreEqual("pass", output, name);
var stdout = new StreamWriter(Console.OpenStandardOutput());
stdout.AutoFlush = true;
Console.SetOut(stdout);
}
}
}
}
}
|
Fix version number for the fake release | // 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 System.Collections.Generic;
namespace NodaTime.Web.Models
{
/// <summary>
/// Fake implementation of IReleaseRepository used in cases of emergency...
/// </summary>
public class FakeReleaseRepository : IReleaseRepository
{
private static readonly IList<ReleaseDownload> releases = new[]
{
new ReleaseDownload(new StructuredVersion("2.4.3"), "NodaTime-2.4.4.zip",
"https://storage.cloud.google.com/nodatime/releases/NodaTime-2.4.4.zip",
"5a672e0910353eef53cd3b6a4ff08e1287ec6fe40faf96ca42e626b107c8f8d4",
new LocalDate(2018, 12, 31))
};
public ReleaseDownload LatestRelease => releases[0];
public IList<ReleaseDownload> GetReleases() => releases;
}
}
| // 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 System.Collections.Generic;
namespace NodaTime.Web.Models
{
/// <summary>
/// Fake implementation of IReleaseRepository used in cases of emergency...
/// </summary>
public class FakeReleaseRepository : IReleaseRepository
{
private static readonly IList<ReleaseDownload> releases = new[]
{
new ReleaseDownload(new StructuredVersion("2.4.4"), "NodaTime-2.4.4.zip",
"https://storage.cloud.google.com/nodatime/releases/NodaTime-2.4.4.zip",
"5a672e0910353eef53cd3b6a4ff08e1287ec6fe40faf96ca42e626b107c8f8d4",
new LocalDate(2018, 12, 31))
};
public ReleaseDownload LatestRelease => releases[0];
public IList<ReleaseDownload> GetReleases() => releases;
}
}
|
Set the driver property in TranslationUnitPass when adding new passes. | using System;
using System.Collections.Generic;
using System.Linq;
using CppSharp.Passes;
namespace CppSharp
{
/// <summary>
/// This class is used to build passes that will be run against the AST
/// that comes from C++.
/// </summary>
public class PassBuilder<T>
{
public List<T> Passes { get; private set; }
public Driver Driver { get; private set; }
public PassBuilder(Driver driver)
{
Passes = new List<T>();
Driver = driver;
}
/// <summary>
/// Adds a new pass to the builder.
/// </summary>
public void AddPass(T pass)
{
Passes.Add(pass);
}
/// <summary>
/// Finds a previously-added pass of the given type.
/// </summary>
public U FindPass<U>() where U : TranslationUnitPass
{
return Passes.OfType<U>().Select(pass => pass as U).FirstOrDefault();
}
/// <summary>
/// Adds a new pass to the builder.
/// </summary>
public void RunPasses(Action<T> action)
{
foreach (var pass in Passes)
action(pass);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using CppSharp.Passes;
namespace CppSharp
{
/// <summary>
/// This class is used to build passes that will be run against the AST
/// that comes from C++.
/// </summary>
public class PassBuilder<T>
{
public List<T> Passes { get; private set; }
public Driver Driver { get; private set; }
public PassBuilder(Driver driver)
{
Passes = new List<T>();
Driver = driver;
}
/// <summary>
/// Adds a new pass to the builder.
/// </summary>
public void AddPass(T pass)
{
if (pass is TranslationUnitPass)
(pass as TranslationUnitPass).Driver = Driver;
Passes.Add(pass);
}
/// <summary>
/// Finds a previously-added pass of the given type.
/// </summary>
public U FindPass<U>() where U : TranslationUnitPass
{
return Passes.OfType<U>().Select(pass => pass as U).FirstOrDefault();
}
/// <summary>
/// Adds a new pass to the builder.
/// </summary>
public void RunPasses(Action<T> action)
{
foreach (var pass in Passes)
action(pass);
}
}
}
|
Increase nuget version to 2.0.0-beta02 | using System.Reflection;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyInformationalVersion("2.0.0-beta01")] | using System.Reflection;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyInformationalVersion("2.0.0-beta02")] |
Make a method static because it can be | using System;
using System.Reflection;
namespace Configgy.Coercion
{
/// <summary>
/// A base class for any coercer attributes.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public abstract class ValueCoercerAttributeBase : Attribute, IValueCoercer
{
private static readonly Type NullableType = typeof(Nullable<>);
/// <summary>
/// Coerce the raw string value into the expected result type.
/// </summary>
/// <typeparam name="T">The expected result type after coercion.</typeparam>
/// <param name="value">The raw string value to be coerced.</param>
/// <param name="valueName">The name of the value to be coerced.</param>
/// <param name="property">If this value is directly associated with a property on a <see cref="Config"/> instance this is the reference to that property.</param>
/// <param name="result">The coerced value.</param>
/// <returns>True if the value could be coerced, false otherwise.</returns>
public abstract bool Coerce<T>(string value, string valueName, PropertyInfo property, out T result);
protected bool IsNullable<T>()
{
var type = typeof(T);
return type.IsClass || (type.IsGenericType && type.GetGenericTypeDefinition() == NullableType);
}
}
}
| using System;
using System.Reflection;
namespace Configgy.Coercion
{
/// <summary>
/// A base class for any coercer attributes.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public abstract class ValueCoercerAttributeBase : Attribute, IValueCoercer
{
private static readonly Type NullableType = typeof(Nullable<>);
/// <summary>
/// Coerce the raw string value into the expected result type.
/// </summary>
/// <typeparam name="T">The expected result type after coercion.</typeparam>
/// <param name="value">The raw string value to be coerced.</param>
/// <param name="valueName">The name of the value to be coerced.</param>
/// <param name="property">If this value is directly associated with a property on a <see cref="Config"/> instance this is the reference to that property.</param>
/// <param name="result">The coerced value.</param>
/// <returns>True if the value could be coerced, false otherwise.</returns>
public abstract bool Coerce<T>(string value, string valueName, PropertyInfo property, out T result);
protected static bool IsNullable<T>()
{
var type = typeof(T);
return type.IsClass || (type.IsGenericType && type.GetGenericTypeDefinition() == NullableType);
}
}
}
|
Use ExceptionDispatchInfo to rethrow test class constructor exceptions, now that all other such exception rethrows use ExceptionDispatchInfo. | namespace Fixie
{
using System;
using System.Reflection;
using Internal;
/// <summary>
/// The context in which a test class is running.
/// </summary>
public class TestClass
{
readonly Action<Action<Case>> runCases;
readonly bool isStatic;
internal TestClass(Type type, Action<Action<Case>> runCases) : this(type, runCases, null) { }
internal TestClass(Type type, Action<Action<Case>> runCases, MethodInfo targetMethod)
{
this.runCases = runCases;
Type = type;
TargetMethod = targetMethod;
isStatic = Type.IsStatic();
}
/// <summary>
/// The test class to execute.
/// </summary>
public Type Type { get; }
/// <summary>
/// Gets the target MethodInfo identified by the
/// test runner as the sole method to be executed.
/// Null under normal test execution.
/// </summary>
public MethodInfo TargetMethod { get; }
/// <summary>
/// Constructs an instance of the test class type, using its default constructor.
/// If the class is static, no action is taken and null is returned.
/// </summary>
public object Construct()
{
if (isStatic)
return null;
try
{
return Activator.CreateInstance(Type);
}
catch (TargetInvocationException exception)
{
throw new PreservedException(exception.InnerException);
}
}
public void RunCases(Action<Case> caseLifecycle)
{
runCases(caseLifecycle);
}
}
} | namespace Fixie
{
using System;
using System.Reflection;
using System.Runtime.ExceptionServices;
using Internal;
/// <summary>
/// The context in which a test class is running.
/// </summary>
public class TestClass
{
readonly Action<Action<Case>> runCases;
readonly bool isStatic;
internal TestClass(Type type, Action<Action<Case>> runCases) : this(type, runCases, null) { }
internal TestClass(Type type, Action<Action<Case>> runCases, MethodInfo targetMethod)
{
this.runCases = runCases;
Type = type;
TargetMethod = targetMethod;
isStatic = Type.IsStatic();
}
/// <summary>
/// The test class to execute.
/// </summary>
public Type Type { get; }
/// <summary>
/// Gets the target MethodInfo identified by the
/// test runner as the sole method to be executed.
/// Null under normal test execution.
/// </summary>
public MethodInfo TargetMethod { get; }
/// <summary>
/// Constructs an instance of the test class type, using its default constructor.
/// If the class is static, no action is taken and null is returned.
/// </summary>
public object Construct()
{
if (isStatic)
return null;
try
{
return Activator.CreateInstance(Type);
}
catch (TargetInvocationException exception)
{
ExceptionDispatchInfo.Capture(exception.InnerException).Throw();
throw; //Unreachable.
}
}
public void RunCases(Action<Case> caseLifecycle)
{
runCases(caseLifecycle);
}
}
} |
Change BuildAndOrExpr to use AndAlso & OrElse to make NHibernate Linq happy | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace Breeze.Core {
/**
* @author IdeaBlade
*
*/
public class AndOrPredicate : BasePredicate {
private List<BasePredicate> _predicates;
public AndOrPredicate(Operator op, params BasePredicate[] predicates) : this(op, predicates.ToList()) {
}
public AndOrPredicate(Operator op, IEnumerable<BasePredicate> predicates) : base(op) {
_predicates = predicates.ToList();
}
public IEnumerable<BasePredicate> Predicates {
get { return _predicates.AsReadOnly(); }
}
public override void Validate(Type entityType) {
_predicates.ForEach(p => p.Validate(entityType));
}
public override Expression ToExpression(ParameterExpression paramExpr) {
var exprs = _predicates.Select(p => p.ToExpression(paramExpr));
return BuildAndOrExpr(exprs, Operator);
}
private Expression BuildAndOrExpr(IEnumerable<Expression> exprs, Operator op) {
if (op == Operator.And) {
return exprs.Aggregate((result, expr) => Expression.And(result, expr));
} else if (op == Operator.Or) {
return exprs.Aggregate((result, expr) => Expression.Or(result, expr));
} else {
throw new Exception("Invalid AndOr operator" + op.Name);
}
}
}
} | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace Breeze.Core {
/**
* @author IdeaBlade
*
*/
public class AndOrPredicate : BasePredicate {
private List<BasePredicate> _predicates;
public AndOrPredicate(Operator op, params BasePredicate[] predicates) : this(op, predicates.ToList()) {
}
public AndOrPredicate(Operator op, IEnumerable<BasePredicate> predicates) : base(op) {
_predicates = predicates.ToList();
}
public IEnumerable<BasePredicate> Predicates {
get { return _predicates.AsReadOnly(); }
}
public override void Validate(Type entityType) {
_predicates.ForEach(p => p.Validate(entityType));
}
public override Expression ToExpression(ParameterExpression paramExpr) {
var exprs = _predicates.Select(p => p.ToExpression(paramExpr));
return BuildAndOrExpr(exprs, Operator);
}
private Expression BuildAndOrExpr(IEnumerable<Expression> exprs, Operator op) {
if (op == Operator.And) {
return exprs.Aggregate((result, expr) => Expression.AndAlso(result, expr));
} else if (op == Operator.Or) {
return exprs.Aggregate((result, expr) => Expression.OrElse(result, expr));
} else {
throw new Exception("Invalid AndOr operator " + op.Name);
}
}
}
}
|
Remove unnecessary test step creating needless skins | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu;
using osu.Game.Skinning;
using osu.Game.Skinning.Editor;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneSkinEditor : PlayerTestScene
{
private SkinEditor skinEditor;
[Resolved]
private SkinManager skinManager { get; set; }
[SetUpSteps]
public override void SetUpSteps()
{
AddStep("set empty legacy skin", () =>
{
var imported = skinManager.Import(new SkinInfo { Name = "test skin" }).Result;
skinManager.CurrentSkinInfo.Value = imported;
});
base.SetUpSteps();
AddStep("reload skin editor", () =>
{
skinEditor?.Expire();
Player.ScaleTo(SkinEditorOverlay.VISIBLE_TARGET_SCALE);
LoadComponentAsync(skinEditor = new SkinEditor(Player), Add);
});
}
[Test]
public void TestToggleEditor()
{
AddToggleStep("toggle editor visibility", visible => skinEditor.ToggleVisibility());
}
protected override Ruleset CreatePlayerRuleset() => new OsuRuleset();
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu;
using osu.Game.Skinning;
using osu.Game.Skinning.Editor;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneSkinEditor : PlayerTestScene
{
private SkinEditor skinEditor;
[Resolved]
private SkinManager skinManager { get; set; }
[SetUpSteps]
public override void SetUpSteps()
{
base.SetUpSteps();
AddStep("reload skin editor", () =>
{
skinEditor?.Expire();
Player.ScaleTo(SkinEditorOverlay.VISIBLE_TARGET_SCALE);
LoadComponentAsync(skinEditor = new SkinEditor(Player), Add);
});
}
[Test]
public void TestToggleEditor()
{
AddToggleStep("toggle editor visibility", visible => skinEditor.ToggleVisibility());
}
protected override Ruleset CreatePlayerRuleset() => new OsuRuleset();
}
}
|
Update lazer default combo colours to match stable | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osuTK.Graphics;
namespace osu.Game.Skinning
{
/// <summary>
/// A skin configuration pre-populated with sane defaults.
/// </summary>
public class DefaultSkinConfiguration : SkinConfiguration
{
public DefaultSkinConfiguration()
{
ComboColours.AddRange(new[]
{
new Color4(17, 136, 170, 255),
new Color4(102, 136, 0, 255),
new Color4(204, 102, 0, 255),
new Color4(121, 9, 13, 255)
});
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osuTK.Graphics;
namespace osu.Game.Skinning
{
/// <summary>
/// A skin configuration pre-populated with sane defaults.
/// </summary>
public class DefaultSkinConfiguration : SkinConfiguration
{
public DefaultSkinConfiguration()
{
ComboColours.AddRange(new[]
{
new Color4(255, 192, 0, 255),
new Color4(0, 202, 0, 255),
new Color4(18, 124, 255, 255),
new Color4(242, 24, 57, 255),
});
}
}
}
|
Remove HTML content type check from response filter because the check is performed in CassetteApplication instead. | using System;
using System.IO;
using System.Web;
using Cassette.UI;
namespace Cassette.Web
{
public class PlaceholderReplacingResponseFilter : MemoryStream
{
public PlaceholderReplacingResponseFilter(HttpResponseBase response, IPlaceholderTracker placeholderTracker)
{
this.response = response;
this.placeholderTracker = placeholderTracker;
outputStream = response.Filter;
}
readonly Stream outputStream;
readonly HttpResponseBase response;
readonly IPlaceholderTracker placeholderTracker;
public override void Write(byte[] buffer, int offset, int count)
{
if (response.Headers["Content-Encoding"] != null)
{
throw new InvalidOperationException("Cannot rewrite page output when it has been compressed. Either set ICassetteApplication.HtmlRewritingEnabled to false in the Cassette configuration, or set <urlCompression dynamicCompressionBeforeCache=\"false\" /> in Web.config.");
}
if (IsHtmlResponse)
{
buffer = ReplacePlaceholders(buffer, offset, count);
outputStream.Write(buffer, 0, buffer.Length);
}
else
{
outputStream.Write(buffer, offset, count);
}
}
byte[] ReplacePlaceholders(byte[] buffer, int offset, int count)
{
var encoding = response.Output.Encoding;
var html = encoding.GetString(buffer, offset, count);
html = placeholderTracker.ReplacePlaceholders(html);
return encoding.GetBytes(html);
}
bool IsHtmlResponse
{
get
{
return response.ContentType == "text/html" ||
response.ContentType == "application/xhtml+xml";
}
}
}
}
| using System;
using System.IO;
using System.Web;
using Cassette.UI;
namespace Cassette.Web
{
public class PlaceholderReplacingResponseFilter : MemoryStream
{
public PlaceholderReplacingResponseFilter(HttpResponseBase response, IPlaceholderTracker placeholderTracker)
{
this.response = response;
this.placeholderTracker = placeholderTracker;
outputStream = response.Filter;
}
readonly Stream outputStream;
readonly HttpResponseBase response;
readonly IPlaceholderTracker placeholderTracker;
public override void Write(byte[] buffer, int offset, int count)
{
if (response.Headers["Content-Encoding"] != null)
{
throw new InvalidOperationException("Cannot rewrite page output when it has been compressed. Either set ICassetteApplication.HtmlRewritingEnabled to false in the Cassette configuration, or set <urlCompression dynamicCompressionBeforeCache=\"false\" /> in Web.config.");
}
buffer = ReplacePlaceholders(buffer, offset, count);
outputStream.Write(buffer, 0, buffer.Length);
}
byte[] ReplacePlaceholders(byte[] buffer, int offset, int count)
{
var encoding = response.Output.Encoding;
var html = encoding.GetString(buffer, offset, count);
html = placeholderTracker.ReplacePlaceholders(html);
return encoding.GetBytes(html);
}
}
} |
Remove interface that is no longer user. | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.NavigateTo
{
internal interface INavigateToSearchService : ILanguageService
{
IImmutableSet<string> KindsProvided { get; }
bool CanFilter { get; }
Task<ImmutableArray<INavigateToSearchResult>> SearchProjectAsync(Project project, ImmutableArray<Document> priorityDocuments, string searchPattern, IImmutableSet<string> kinds, CancellationToken cancellationToken);
Task<ImmutableArray<INavigateToSearchResult>> SearchDocumentAsync(Document document, string searchPattern, IImmutableSet<string> kinds, CancellationToken cancellationToken);
}
[Obsolete("Use " + nameof(INavigateToSearchResult) + " instead", error: false)]
internal interface INavigateToSeINavigateToSearchService_RemoveInterfaceAboveAndRenameThisAfterInternalsVisibleToUsersUpdatearchService : ILanguageService
{
IImmutableSet<string> KindsProvided { get; }
bool CanFilter { get; }
Task<ImmutableArray<INavigateToSearchResult>> SearchProjectAsync(Project project, ImmutableArray<Document> priorityDocuments, string searchPattern, IImmutableSet<string> kinds, CancellationToken cancellationToken);
Task<ImmutableArray<INavigateToSearchResult>> SearchDocumentAsync(Document document, string searchPattern, IImmutableSet<string> kinds, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.NavigateTo
{
internal interface INavigateToSearchService : ILanguageService
{
IImmutableSet<string> KindsProvided { get; }
bool CanFilter { get; }
Task<ImmutableArray<INavigateToSearchResult>> SearchProjectAsync(Project project, ImmutableArray<Document> priorityDocuments, string searchPattern, IImmutableSet<string> kinds, CancellationToken cancellationToken);
Task<ImmutableArray<INavigateToSearchResult>> SearchDocumentAsync(Document document, string searchPattern, IImmutableSet<string> kinds, CancellationToken cancellationToken);
}
}
|
Add Validation Messages to the Clone Section Screen | @model Portal.CMS.Web.Areas.PageBuilder.ViewModels.Section.CloneViewModel
@{
Layout = "";
var pageList = Model.PageList.Select(x => new SelectListItem { Value = x.PageId.ToString(), Text = x.PageName });
}
<div class="panel-inner">
@using (Html.BeginForm("Clone", "Section", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(x => x.PageAssociationId)
<div class="alert alert-warning" role="alert">Clone a Section onto another Page to keep your content synced across all relevant pages</div>
@Html.ValidationMessage("PageId")
<div class="control-group">
@Html.LabelFor(x => x.PageId)
@Html.DropDownListFor(m => m.PageId, pageList)
</div>
<div class="footer">
<button class="btn primary"><span class="fa fa-check"></span><span class="hidden-xs">Clone Section</span></button>
<button class="btn" data-dismiss="modal"><span class="fa fa-times"></span><span class="hidden-xs">Cancel</span></button>
</div>
}
</div> | @model Portal.CMS.Web.Areas.PageBuilder.ViewModels.Section.CloneViewModel
@{
Layout = "";
var pageList = Model.PageList.Select(x => new SelectListItem { Value = x.PageId.ToString(), Text = x.PageName });
}
<div class="panel-inner">
@using (Html.BeginForm("Clone", "Section", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(x => x.PageAssociationId)
if (pageList.Any())
{
<div class="alert alert-warning" role="alert">Clone a Section onto another Page to keep your content synced across all relevant pages</div>
}
else
{
<div class="alert alert-danger" role="alert">You can't Clone this Section because you don't have any other pages yet...</div>
}
@Html.ValidationMessageFor(x => x.PageId)
<div class="control-group">
@Html.LabelFor(x => x.PageId)
@Html.DropDownListFor(m => m.PageId, pageList)
</div>
<div class="footer">
<button class="btn primary"><span class="fa fa-check"></span><span class="hidden-xs">Clone Section</span></button>
<button class="btn" data-dismiss="modal"><span class="fa fa-times"></span><span class="hidden-xs">Cancel</span></button>
</div>
}
</div> |
Simplify logic in user profile validation | using Microsoft.AspNet.Identity.EntityFramework;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace AllReady.Models
{
// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
[Display(Name = "Associated skills")]
public List<UserSkill> AssociatedSkills { get; set; } = new List<UserSkill>();
public string Name { get; set; }
[Display(Name = "Time Zone")]
[Required]
public string TimeZoneId { get; set; }
public string PendingNewEmail { get; set; }
public IEnumerable<ValidationResult> ValidateProfileCompleteness()
{
List<ValidationResult> validationResults = new List<ValidationResult>();
if (!EmailConfirmed)
{
validationResults.Add(new ValidationResult("Verify your email address", new string[] { nameof(Email) }));
}
if (string.IsNullOrWhiteSpace(Name))
{
validationResults.Add(new ValidationResult("Enter your name", new string[] { nameof(Name) }));
}
if (string.IsNullOrWhiteSpace(PhoneNumber))
{
validationResults.Add(new ValidationResult("Add a phone number", new string[] { nameof(PhoneNumber) }));
}
if (!string.IsNullOrWhiteSpace(PhoneNumber) && !PhoneNumberConfirmed)
{
validationResults.Add(new ValidationResult("Confirm your phone number", new string[] { nameof(PhoneNumberConfirmed) }));
}
return validationResults;
}
public bool IsProfileComplete()
{
return !ValidateProfileCompleteness().Any();
}
}
} | using Microsoft.AspNet.Identity.EntityFramework;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace AllReady.Models
{
// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
[Display(Name = "Associated skills")]
public List<UserSkill> AssociatedSkills { get; set; } = new List<UserSkill>();
public string Name { get; set; }
[Display(Name = "Time Zone")]
[Required]
public string TimeZoneId { get; set; }
public string PendingNewEmail { get; set; }
public IEnumerable<ValidationResult> ValidateProfileCompleteness()
{
List<ValidationResult> validationResults = new List<ValidationResult>();
if (!EmailConfirmed)
{
validationResults.Add(new ValidationResult("Verify your email address", new string[] { nameof(Email) }));
}
if (string.IsNullOrWhiteSpace(Name))
{
validationResults.Add(new ValidationResult("Enter your name", new string[] { nameof(Name) }));
}
if (string.IsNullOrWhiteSpace(PhoneNumber))
{
validationResults.Add(new ValidationResult("Add a phone number", new string[] { nameof(PhoneNumber) }));
}
else if (!PhoneNumberConfirmed)
{
validationResults.Add(new ValidationResult("Confirm your phone number", new string[] { nameof(PhoneNumberConfirmed) }));
}
return validationResults;
}
public bool IsProfileComplete()
{
return !ValidateProfileCompleteness().Any();
}
}
} |
Add group role to relationship | namespace AlertRoster.Web.Models
{
public class MemberGroup
{
public int MemberId { get; private set; }
public virtual Member Member { get; private set; }
public int GroupId { get; private set; }
public virtual Group Group { get; private set; }
private MemberGroup()
{
// Parameter-less ctor for EF
}
public MemberGroup(int memberId, int groupId)
{
this.MemberId = memberId;
this.GroupId = groupId;
}
}
} | namespace AlertRoster.Web.Models
{
public class MemberGroup
{
public int MemberId { get; private set; }
public virtual Member Member { get; private set; }
public int GroupId { get; private set; }
public virtual Group Group { get; private set; }
public GroupRole Role { get; set; } = GroupRole.Member;
private MemberGroup()
{
// Parameter-less ctor for EF
}
public MemberGroup(int memberId, int groupId)
{
this.MemberId = memberId;
this.GroupId = groupId;
}
public enum GroupRole : byte
{
Member = 0,
Administrator = 1
}
}
} |
Fix license header from wrong project | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Graphics;
using osu.Game.Beatmaps;
using osu.Game.Screens.Edit.Components;
using osu.Game.Tests.Beatmaps;
using OpenTK;
namespace osu.Game.Tests.Visual
{
public class TestCasePlaybackControl : OsuTestCase
{
public TestCasePlaybackControl()
{
var playback = new PlaybackControl
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(200,100)
};
playback.Beatmap.Value = new TestWorkingBeatmap(new Beatmap());
Add(playback);
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics;
using osu.Game.Beatmaps;
using osu.Game.Screens.Edit.Components;
using osu.Game.Tests.Beatmaps;
using OpenTK;
namespace osu.Game.Tests.Visual
{
public class TestCasePlaybackControl : OsuTestCase
{
public TestCasePlaybackControl()
{
var playback = new PlaybackControl
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(200,100)
};
playback.Beatmap.Value = new TestWorkingBeatmap(new Beatmap());
Add(playback);
}
}
}
|
Modify method to abstract which will force a compile error if the implementation is not supplied in a derived class rather than throw a NotImplementedException() | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using ThoughtWorks.CruiseControl.Remote.Parameters;
namespace JenkinsTransport.BuildParameters
{
public abstract class BaseBuildParameter
{
public string Name { get; private set; }
public string Description { get; private set; }
public BuildParameterType ParameterType { get; protected set; }
public string DefaultValue { get; private set; }
public virtual ParameterBase ToParameterBase()
{
throw new NotImplementedException("Must be overridden in derived class");
}
protected BaseBuildParameter(XContainer document)
{
Name = (string)document.Element("name");
Description = (string)document.Element("description");
DefaultValue = (string)document.Descendants("defaultParameterValue").First().Element("value");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using ThoughtWorks.CruiseControl.Remote.Parameters;
namespace JenkinsTransport.BuildParameters
{
public abstract class BaseBuildParameter
{
public string Name { get; private set; }
public string Description { get; private set; }
public BuildParameterType ParameterType { get; protected set; }
public string DefaultValue { get; private set; }
public abstract ParameterBase ToParameterBase();
protected BaseBuildParameter(XContainer document)
{
Name = (string)document.Element("name");
Description = (string)document.Element("description");
DefaultValue = (string)document.Descendants("defaultParameterValue").First().Element("value");
}
}
}
|
Cover CMAC -> Key property setter with null check test | using Xunit;
namespace OpenGost.Security.Cryptography
{
public abstract class CmacTest<T> : CryptoConfigRequiredTest
where T : CMAC, new()
{
protected void VerifyCmac(string dataHex, string keyHex, string digestHex)
{
var digestBytes = digestHex.HexToByteArray();
byte[] computedDigest;
using (var cmac = new T())
{
Assert.True(cmac.HashSize > 0);
var key = keyHex.HexToByteArray();
cmac.Key = key;
// make sure the getter returns different objects each time
Assert.NotSame(key, cmac.Key);
Assert.NotSame(cmac.Key, cmac.Key);
// make sure the setter didn't cache the exact object we passed in
key[0] = (byte)(key[0] + 1);
Assert.NotEqual<byte>(key, cmac.Key);
computedDigest = cmac.ComputeHash(dataHex.HexToByteArray());
}
Assert.Equal(digestBytes, computedDigest);
}
}
}
| using System;
using Xunit;
namespace OpenGost.Security.Cryptography
{
public abstract class CmacTest<T> : CryptoConfigRequiredTest
where T : CMAC, new()
{
protected void VerifyCmac(string dataHex, string keyHex, string digestHex)
{
var digestBytes = digestHex.HexToByteArray();
byte[] computedDigest;
using (var cmac = new T())
{
Assert.True(cmac.HashSize > 0);
var key = keyHex.HexToByteArray();
cmac.Key = key;
// make sure the getter returns different objects each time
Assert.NotSame(key, cmac.Key);
Assert.NotSame(cmac.Key, cmac.Key);
// make sure the setter didn't cache the exact object we passed in
key[0] = (byte)(key[0] + 1);
Assert.NotEqual<byte>(key, cmac.Key);
computedDigest = cmac.ComputeHash(dataHex.HexToByteArray());
}
Assert.Equal(digestBytes, computedDigest);
}
[Fact]
public void Key_Throws_IfValueIsNull()
{
byte[] value = null!;
using var cmac = new T();
Assert.Throws<ArgumentNullException>(nameof(value), () => cmac.Key = value);
}
}
}
|
Make VisitingMind's Mind readable by VV | using Content.Server.Mobs;
using Robust.Shared.GameObjects;
namespace Content.Server.GameObjects.Components.Mobs
{
[RegisterComponent]
public sealed class VisitingMindComponent : Component
{
public override string Name => "VisitingMind";
public Mind Mind { get; set; }
public override void OnRemove()
{
base.OnRemove();
Mind?.UnVisit();
}
}
}
| using Content.Server.Mobs;
using Robust.Shared.GameObjects;
using Robust.Shared.ViewVariables;
namespace Content.Server.GameObjects.Components.Mobs
{
[RegisterComponent]
public sealed class VisitingMindComponent : Component
{
public override string Name => "VisitingMind";
[ViewVariables]
public Mind Mind { get; set; }
public override void OnRemove()
{
base.OnRemove();
Mind?.UnVisit();
}
}
}
|
Remove Marshal.GetHRForLastWin32Error call from Diagnostics.Process | using System;
using System.Threading;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace System.Diagnostics {
internal class ProcessWaitHandle : WaitHandle {
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
internal ProcessWaitHandle( SafeProcessHandle processHandle): base() {
SafeWaitHandle waitHandle = null;
bool succeeded = NativeMethods.DuplicateHandle(
new HandleRef(this, NativeMethods.GetCurrentProcess()),
processHandle,
new HandleRef(this, NativeMethods.GetCurrentProcess()),
out waitHandle,
0,
false,
NativeMethods.DUPLICATE_SAME_ACCESS);
if (!succeeded) {
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
this.SafeWaitHandle = waitHandle;
}
}
}
| using System;
using System.Threading;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace System.Diagnostics {
internal class ProcessWaitHandle : WaitHandle {
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
internal ProcessWaitHandle( SafeProcessHandle processHandle): base() {
SafeWaitHandle waitHandle = null;
bool succeeded = NativeMethods.DuplicateHandle(
new HandleRef(this, NativeMethods.GetCurrentProcess()),
processHandle,
new HandleRef(this, NativeMethods.GetCurrentProcess()),
out waitHandle,
0,
false,
NativeMethods.DUPLICATE_SAME_ACCESS);
if (!succeeded) {
#if MONO
// In Mono, Marshal.GetHRForLastWin32Error is not implemented;
// and also DuplicateHandle throws its own exception rather
// than returning false on error, so this code is unreachable.
throw new SystemException("Unknown error in DuplicateHandle");
#else
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
#endif
}
this.SafeWaitHandle = waitHandle;
}
}
}
|
Use UseServer() instead of UseKestrel() to allow override in tests | using Microsoft.AspNetCore.Hosting;
namespace MusicStore
{
public static class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
// We set the server before default args so that command line arguments can override it.
// This is used to allow deployers to choose the server for testing.
.UseKestrel()
.UseDefaultHostingConfiguration(args)
.UseIISIntegration()
.UseStartup("MusicStore")
.Build();
host.Run();
}
}
}
| using Microsoft.AspNetCore.Hosting;
namespace MusicStore
{
public static class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
// We set the server by name before default args so that command line arguments can override it.
// This is used to allow deployers to choose the server for testing.
.UseServer("Microsoft.AspNetCore.Server.Kestrel")
.UseDefaultHostingConfiguration(args)
.UseIISIntegration()
.UseStartup("MusicStore")
.Build();
host.Run();
}
}
}
|
Add assertion of only usage game-wide | // 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 JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Platform;
namespace osu.Game.Screens.Play
{
/// <summary>
/// Ensures screen is not suspended / dimmed while gameplay is active.
/// </summary>
public class ScreenSuspensionHandler : Component
{
private readonly GameplayClockContainer gameplayClockContainer;
private Bindable<bool> isPaused;
[Resolved]
private GameHost host { get; set; }
public ScreenSuspensionHandler([NotNull] GameplayClockContainer gameplayClockContainer)
{
this.gameplayClockContainer = gameplayClockContainer ?? throw new ArgumentNullException(nameof(gameplayClockContainer));
}
protected override void LoadComplete()
{
base.LoadComplete();
isPaused = gameplayClockContainer.IsPaused.GetBoundCopy();
isPaused.BindValueChanged(paused => host.AllowScreenSuspension.Value = paused.NewValue, true);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
isPaused?.UnbindAll();
if (host != null)
host.AllowScreenSuspension.Value = true;
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Diagnostics;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Platform;
namespace osu.Game.Screens.Play
{
/// <summary>
/// Ensures screen is not suspended / dimmed while gameplay is active.
/// </summary>
public class ScreenSuspensionHandler : Component
{
private readonly GameplayClockContainer gameplayClockContainer;
private Bindable<bool> isPaused;
[Resolved]
private GameHost host { get; set; }
public ScreenSuspensionHandler([NotNull] GameplayClockContainer gameplayClockContainer)
{
this.gameplayClockContainer = gameplayClockContainer ?? throw new ArgumentNullException(nameof(gameplayClockContainer));
}
protected override void LoadComplete()
{
base.LoadComplete();
// This is the only usage game-wide of suspension changes.
// Assert to ensure we don't accidentally forget this in the future.
Debug.Assert(host.AllowScreenSuspension.Value);
isPaused = gameplayClockContainer.IsPaused.GetBoundCopy();
isPaused.BindValueChanged(paused => host.AllowScreenSuspension.Value = paused.NewValue, true);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
isPaused?.UnbindAll();
if (host != null)
host.AllowScreenSuspension.Value = true;
}
}
}
|
Include build number in version | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CollectdWinService")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Bloomberg LP")]
[assembly: AssemblyProduct("CollectdWinService")]
[assembly: AssemblyCopyright("Copyright © Bloomberg LP 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("dc0404f4-acd7-40b3-ab7a-6e63f023ac40")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.5.2.0")]
[assembly: AssemblyFileVersion("0.5.2.0")] | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CollectdWinService")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Bloomberg LP")]
[assembly: AssemblyProduct("CollectdWinService")]
[assembly: AssemblyCopyright("Copyright © Bloomberg LP 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("dc0404f4-acd7-40b3-ab7a-6e63f023ac40")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.6.0.*")]
|
Fix show-build-chain logic to properly detect cloned build configs. | using System.Linq;
using System.Threading.Tasks;
using TeamCityApi.Helpers;
using TeamCityApi.Logging;
namespace TeamCityApi.UseCases
{
public class ShowBuildChainUseCase
{
private static readonly ILog Log = LogProvider.GetLogger(typeof(ShowBuildChainUseCase));
private readonly ITeamCityClient _client;
public ShowBuildChainUseCase(ITeamCityClient client)
{
_client = client;
}
public async Task Execute(string buildConfigId)
{
Log.Info("================Show Build Chain: start ================");
var buildConfig = await _client.BuildConfigs.GetByConfigurationId(buildConfigId);
var buildChainId = buildConfig.Parameters[ParameterName.BuildConfigChainId].Value;
var buildConfigChain = new BuildConfigChain(_client.BuildConfigs, buildConfig);
ShowBuildChain(buildConfigChain, buildChainId);
}
private static void ShowBuildChain(BuildConfigChain buildConfigChain, string buildChainId)
{
foreach (var node in buildConfigChain.Nodes)
{
if (node.Value.Parameters[ParameterName.BuildConfigChainId].Value == buildChainId)
{
Log.InfoFormat("BuildConfigId: (CLONED) {0}", node.Value.Id);
}
else
{
Log.InfoFormat("BuildConfigId: {0}", node.Value.Id);
}
}
}
}
} | using System.Linq;
using System.Threading.Tasks;
using TeamCityApi.Helpers;
using TeamCityApi.Logging;
namespace TeamCityApi.UseCases
{
public class ShowBuildChainUseCase
{
private static readonly ILog Log = LogProvider.GetLogger(typeof(ShowBuildChainUseCase));
private readonly ITeamCityClient _client;
public ShowBuildChainUseCase(ITeamCityClient client)
{
_client = client;
}
public async Task Execute(string buildConfigId)
{
Log.Info("================Show Build Chain: start ================");
var buildConfig = await _client.BuildConfigs.GetByConfigurationId(buildConfigId);
var buildChainId = buildConfig.Parameters[ParameterName.BuildConfigChainId].Value;
var buildConfigChain = new BuildConfigChain(_client.BuildConfigs, buildConfig);
ShowBuildChain(buildConfigChain, buildChainId);
}
private static void ShowBuildChain(BuildConfigChain buildConfigChain, string buildChainId)
{
foreach (var node in buildConfigChain.Nodes.OrderBy(n=>n.Value.Id))
{
Log.InfoFormat(
!string.IsNullOrEmpty(node.Value.Parameters[ParameterName.ClonedFromBuildId]?.Value)
? "BuildConfigId: (CLONED) {0}"
: "BuildConfigId: {0}", node.Value.Id);
}
}
}
} |
Duplicate some methods from TransformExtensions for convenience | using UnityEngine;
namespace Alensia.Core.Common
{
public static class ComponentExtensions
{
public static T GetOrAddComponent<T>(this Component component) where T : Component
{
return component.GetComponent<T>() ?? component.gameObject.AddComponent<T>();
}
}
} | using System.Collections.Generic;
using UnityEngine;
namespace Alensia.Core.Common
{
public static class ComponentExtensions
{
public static T GetOrAddComponent<T>(this Component component) where T : Component
{
return component.GetComponent<T>() ?? component.gameObject.AddComponent<T>();
}
public static IEnumerable<Transform> GetChildren(this Component parent) => parent.transform.GetChildren();
public static T FindComponent<T>(this Component parent, string path) where T : class =>
parent.transform.Find(path)?.GetComponent<T>();
public static T FindComponentInChildren<T>(this Component parent, string path) where T : class =>
parent.transform.Find(path)?.GetComponentInChildren<T>();
}
} |
Remove empty line in name spaces | using System.Data.Common;
using System.Data.SqlClient;
using DapperTesting.Core.Configuration;
namespace DapperTesting.Core.Data
{
public class MsSqlConnectionFactory : IConnectionFactory
{
private readonly IConfiguration _configuration;
public MsSqlConnectionFactory(IConfiguration configuration)
{
_configuration = configuration;
}
public DbConnection Create(string connectionStringName)
{
return new SqlConnection(_configuration.GetConnectionString(connectionStringName));
}
}
}
| using System.Data.Common;
using System.Data.SqlClient;
using DapperTesting.Core.Configuration;
namespace DapperTesting.Core.Data
{
public class MsSqlConnectionFactory : IConnectionFactory
{
private readonly IConfiguration _configuration;
public MsSqlConnectionFactory(IConfiguration configuration)
{
_configuration = configuration;
}
public DbConnection Create(string connectionStringName)
{
return new SqlConnection(_configuration.GetConnectionString(connectionStringName));
}
}
}
|
Fix global options for Integration test | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CalDavSynchronizer.Contracts;
using CalDavSynchronizer.DataAccess;
namespace CalDavSynchronizer.IntegrationTests.Infrastructure
{
class InMemoryGeneralOptionsDataAccess : IGeneralOptionsDataAccess
{
private GeneralOptions _options;
public GeneralOptions LoadOptions()
{
return (_options ??
(_options = new GeneralOptions
{
CalDavConnectTimeout = TimeSpan.FromSeconds(10),
MaxReportAgeInDays = 100,
QueryFoldersJustByGetTable = true,
CultureName = System.Threading.Thread.CurrentThread.CurrentUICulture.Name
}))
.Clone();
}
public void SaveOptions(GeneralOptions options)
{
_options = options.Clone();
}
public Version IgnoreUpdatesTilVersion { get; set; }
public int EntityCacheVersion
{
get { return ComponentContainerTestExtension.GetRequiredEntityCacheVersion(); }
set { }
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CalDavSynchronizer.Contracts;
using CalDavSynchronizer.DataAccess;
namespace CalDavSynchronizer.IntegrationTests.Infrastructure
{
class InMemoryGeneralOptionsDataAccess : IGeneralOptionsDataAccess
{
private GeneralOptions _options;
public GeneralOptions LoadOptions()
{
return (_options ??
(_options = new GeneralOptions
{
CalDavConnectTimeout = TimeSpan.FromSeconds(10),
MaxReportAgeInDays = 100,
QueryFoldersJustByGetTable = true,
CultureName = System.Threading.Thread.CurrentThread.CurrentUICulture.Name,
EnableTls12 = true
}))
.Clone();
}
public void SaveOptions(GeneralOptions options)
{
_options = options.Clone();
}
public Version IgnoreUpdatesTilVersion { get; set; }
public int EntityCacheVersion
{
get { return ComponentContainerTestExtension.GetRequiredEntityCacheVersion(); }
set { }
}
}
}
|
Fix inventory trying to update on every frame | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Events;
public class Inventory : MonoBehaviour {
public int[] inventorySlots;
public UnityEvent InventoryChangedEvent;
void Awake()
{
inventorySlots = new int[18];
}
void Start()
{
for (int i = 0; i < inventorySlots.Length; i++) {
inventorySlots[i]= Random.Range (PlayArea.normalBlocksCount+1, PlayArea.totalBlocksCount); // +1 because of the empty block
}
InventoryChangedEvent.Invoke ();
}
}
| using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Events;
public class Inventory : MonoBehaviour {
public int[] inventorySlots;
public UnityEvent InventoryChangedEvent;
protected bool isDirty;
void Awake()
{
inventorySlots = new int[18];
}
void Start()
{
for (int i = 0; i < inventorySlots.Length; i++) {
inventorySlots[i]= Random.Range (PlayArea.normalBlocksCount+1, PlayArea.totalBlocksCount); // +1 because of the empty block
}
isDirty = true;
}
void Update()
{
if (isDirty) {
InventoryChangedEvent.Invoke ();
isDirty = false;
}
}
}
|
Remove `[SuppressMessage]` - build break | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNet.StaticFiles.Infrastructure;
namespace Microsoft.AspNet.StaticFiles
{
/// <summary>
/// Options for selecting default file names.
/// </summary>
public class DefaultFilesOptions : SharedOptionsBase<DefaultFilesOptions>
{
/// <summary>
/// Configuration for the DefaultFilesMiddleware.
/// </summary>
public DefaultFilesOptions()
: this(new SharedOptions())
{
}
/// <summary>
/// Configuration for the DefaultFilesMiddleware.
/// </summary>
/// <param name="sharedOptions"></param>
public DefaultFilesOptions(SharedOptions sharedOptions)
: base(sharedOptions)
{
// Prioritized list
DefaultFileNames = new List<string>()
{
"default.htm",
"default.html",
"index.htm",
"index.html",
};
}
/// <summary>
/// An ordered list of file names to select by default. List length and ordering may affect performance.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Improves usability")]
public IList<string> DefaultFileNames { get; set; }
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using Microsoft.AspNet.StaticFiles.Infrastructure;
namespace Microsoft.AspNet.StaticFiles
{
/// <summary>
/// Options for selecting default file names.
/// </summary>
public class DefaultFilesOptions : SharedOptionsBase<DefaultFilesOptions>
{
/// <summary>
/// Configuration for the DefaultFilesMiddleware.
/// </summary>
public DefaultFilesOptions()
: this(new SharedOptions())
{
}
/// <summary>
/// Configuration for the DefaultFilesMiddleware.
/// </summary>
/// <param name="sharedOptions"></param>
public DefaultFilesOptions(SharedOptions sharedOptions)
: base(sharedOptions)
{
// Prioritized list
DefaultFileNames = new List<string>()
{
"default.htm",
"default.html",
"index.htm",
"index.html",
};
}
/// <summary>
/// An ordered list of file names to select by default. List length and ordering may affect performance.
/// </summary>
public IList<string> DefaultFileNames { get; set; }
}
}
|
Test checkin with new repo | using System.Collections.Generic;
using SecurityConsultantCore.Domain;
using SecurityConsultantCore.Domain.Basic;
namespace SecurityConsultantCore.Factories
{
public static class SecurityObjectFactory
{
private static SecurityObjectContainer _container;
public static SecurityObject Create(string type)
{
return GetContainer().Create(type);
}
public static List<string> GetConstructables()
{
return GetContainer().GetConstructables();
}
private static SecurityObjectContainer GetContainer()
{
return _container ?? (_container = new SecurityObjectContainer());
}
private class SecurityObjectContainer : Container<SecurityObject>
{
protected override string GetKey(string id)
{
return id;
}
protected override Dictionary<string, SecurityObject> GetObjects()
{
return new Dictionary<string, SecurityObject>
{
{
"PressurePlate",
new SecurityObject
{
Type = "PressurePlate",
ObjectLayer = ObjectLayer.GroundPlaceable,
Traits = new[] {"OpenSpace"}
}
},
{
"Guard",
new SecurityObject
{
Type = "Guard",
ObjectLayer = ObjectLayer.LowerPlaceable,
Traits = new[] {"OpenSpace"}
}
}
};
}
}
}
} | using System.Collections.Generic;
using SecurityConsultantCore.Domain;
using SecurityConsultantCore.Domain.Basic;
namespace SecurityConsultantCore.Factories
{
public static class SecurityObjectFactory
{
private static SecurityObjectContainer _container;
public static SecurityObject Create(string type)
{
return GetContainer().Create(type);
}
public static List<string> GetConstructables()
{
return GetContainer().GetConstructables();
}
private static SecurityObjectContainer GetContainer()
{
return _container ?? (_container = new SecurityObjectContainer());
}
private class SecurityObjectContainer : Container<SecurityObject>
{
protected override string GetKey(string id)
{
return id;
}
protected override Dictionary<string, SecurityObject> GetObjects()
{
return new Dictionary<string, SecurityObject>
{
{
"FloorPressurePlate",
new SecurityObject
{
Type = "FloorPressurePlate",
ObjectLayer = ObjectLayer.GroundPlaceable,
Traits = new[] {"OpenSpace"}
}
},
{
"Guard",
new SecurityObject
{
Type = "Guard",
ObjectLayer = ObjectLayer.LowerPlaceable,
Traits = new[] {"OpenSpace"}
}
}
};
}
}
}
} |
Fix algorithm not selected when adding a custom coin | using MultiMiner.Engine.Data;
using MultiMiner.Utility.Forms;
using MultiMiner.Xgminer.Data;
using MultiMiner.Win.Extensions;
using System;
using MultiMiner.Engine;
namespace MultiMiner.Win.Forms
{
public partial class CoinEditForm : MessageBoxFontForm
{
private readonly CryptoCoin cryptoCoin;
public CoinEditForm(CryptoCoin cryptoCoin)
{
InitializeComponent();
this.cryptoCoin = cryptoCoin;
}
private void CoinEditForm_Load(object sender, EventArgs e)
{
PopulateAlgorithmCombo();
LoadSettings();
}
private void PopulateAlgorithmCombo()
{
algorithmCombo.Items.Clear();
System.Collections.Generic.List<CoinAlgorithm> algorithms = MinerFactory.Instance.Algorithms;
foreach (CoinAlgorithm algorithm in algorithms)
algorithmCombo.Items.Add(algorithm.Name.ToSpaceDelimitedWords());
}
private void saveButton_Click(object sender, EventArgs e)
{
if (!ValidateInput())
return;
SaveSettings();
DialogResult = System.Windows.Forms.DialogResult.OK;
}
private bool ValidateInput()
{
//require a symbol be specified, symbol is used throughout the app
if (String.IsNullOrEmpty(cryptoCoin.Symbol))
{
symbolEdit.Focus();
return false;
}
return true;
}
private void LoadSettings()
{
algorithmCombo.Text = cryptoCoin.Algorithm;
cryptoCoinBindingSource.DataSource = cryptoCoin;
}
private void SaveSettings()
{
cryptoCoin.Algorithm = algorithmCombo.Text;
}
}
}
| using MultiMiner.Engine.Data;
using MultiMiner.Utility.Forms;
using MultiMiner.Xgminer.Data;
using MultiMiner.Win.Extensions;
using System;
using MultiMiner.Engine;
namespace MultiMiner.Win.Forms
{
public partial class CoinEditForm : MessageBoxFontForm
{
private readonly CryptoCoin cryptoCoin;
public CoinEditForm(CryptoCoin cryptoCoin)
{
InitializeComponent();
this.cryptoCoin = cryptoCoin;
}
private void CoinEditForm_Load(object sender, EventArgs e)
{
PopulateAlgorithmCombo();
LoadSettings();
}
private void PopulateAlgorithmCombo()
{
algorithmCombo.Items.Clear();
System.Collections.Generic.List<CoinAlgorithm> algorithms = MinerFactory.Instance.Algorithms;
foreach (CoinAlgorithm algorithm in algorithms)
algorithmCombo.Items.Add(algorithm.Name.ToSpaceDelimitedWords());
}
private void saveButton_Click(object sender, EventArgs e)
{
if (!ValidateInput())
return;
SaveSettings();
DialogResult = System.Windows.Forms.DialogResult.OK;
}
private bool ValidateInput()
{
//require a symbol be specified, symbol is used throughout the app
if (String.IsNullOrEmpty(cryptoCoin.Symbol))
{
symbolEdit.Focus();
return false;
}
return true;
}
private void LoadSettings()
{
algorithmCombo.Text = cryptoCoin.Algorithm.ToSpaceDelimitedWords();
cryptoCoinBindingSource.DataSource = cryptoCoin;
}
private void SaveSettings()
{
cryptoCoin.Algorithm = algorithmCombo.Text;
}
}
}
|
Add dataTransferManager to Windows app. | using System;
using wallabag.Common;
using wallabag.ViewModel;
using Windows.ApplicationModel.DataTransfer;
using Windows.System;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace wallabag.Views
{
public sealed partial class ItemPage : basicPage
{
public ItemPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (e.Parameter != null)
this.DataContext = new ItemPageViewModel(e.Parameter as ItemViewModel);
base.OnNavigatedTo(e);
}
void dataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
DataRequest request = args.Request;
request.Data.Properties.Title = ((this.DataContext as ItemPageViewModel).Item as ItemViewModel).Title;
request.Data.SetWebLink(((this.DataContext as ItemPageViewModel).Item as ItemViewModel).Url);
}
private async void webView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
{
// Opens links in the Internet Explorer and not in the webView.
if (args.Uri != null && args.Uri.AbsoluteUri.StartsWith("http"))
{
args.Cancel = true;
await Launcher.LaunchUriAsync(new Uri(args.Uri.AbsoluteUri));
}
}
}
}
| using System;
using wallabag.Common;
using wallabag.ViewModel;
using Windows.ApplicationModel.DataTransfer;
using Windows.System;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace wallabag.Views
{
public sealed partial class ItemPage : basicPage
{
public ItemPage()
{
this.InitializeComponent();
backButton.Command = this.navigationHelper.GoBackCommand;
var dataTransferManager = DataTransferManager.GetForCurrentView();
dataTransferManager.DataRequested += dataTransferManager_DataRequested;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (e.Parameter != null)
this.DataContext = new ItemPageViewModel(e.Parameter as ItemViewModel);
base.OnNavigatedTo(e);
}
void dataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
DataRequest request = args.Request;
request.Data.Properties.Title = ((this.DataContext as ItemPageViewModel).Item as ItemViewModel).Title;
request.Data.SetWebLink(((this.DataContext as ItemPageViewModel).Item as ItemViewModel).Url);
}
private async void webView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
{
// Opens links in the Internet Explorer and not in the webView.
if (args.Uri != null && args.Uri.AbsoluteUri.StartsWith("http"))
{
args.Cancel = true;
await Launcher.LaunchUriAsync(new Uri(args.Uri.AbsoluteUri));
}
}
}
}
|
Use DiplomContext in DI container | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Diploms.WebUI.Configuration;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Diploms.WebUI
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDepartments();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true
});
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
});
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Diploms.DataLayer;
using Diploms.WebUI.Configuration;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Diploms.WebUI
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDepartments();
services.AddDbContext<DiplomContext>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true
});
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
});
}
}
}
|
Add the default constructor, eventually needed for migrations. | using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace HelloWorldApp
{
public class HelloWorldDbContext : DbContext, IHelloWorldDbContext
{
public HelloWorldDbContext(DbContextOptions<HelloWorldDbContext> options)
: base(options)
{ }
public DbSet<Greeting> Greetings { get; set; }
public async Task SaveChangesAsync()
{
await base.SaveChangesAsync();
}
public async Task EnsureCreatedAsync()
{
await Database.EnsureCreatedAsync();
}
}
} | using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace HelloWorldApp
{
public class HelloWorldDbContext : DbContext, IHelloWorldDbContext
{
public HelloWorldDbContext()
{ }
public HelloWorldDbContext(DbContextOptions<HelloWorldDbContext> options)
: base(options)
{ }
public DbSet<Greeting> Greetings { get; set; }
public async Task SaveChangesAsync()
{
await base.SaveChangesAsync();
}
public async Task EnsureCreatedAsync()
{
await Database.EnsureCreatedAsync();
}
}
} |
Set test version to auto increment | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SimpleZipeCode.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SimpleZipeCode.Tests")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ff6363b4-eb03-4a68-9217-ba65deff4f59")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.2")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SimpleZipeCode.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SimpleZipeCode.Tests")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ff6363b4-eb03-4a68-9217-ba65deff4f59")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
Make fullname optional for receiver | using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dragon.Mail.Interfaces;
namespace Dragon.Mail.Impl
{
public class DefaultReceiverMapper : IReceiverMapper
{
public void Map(dynamic receiver, Models.Mail mail)
{
var displayName = receiver.fullname;
var email = receiver.email;
mail.Receiver = new System.Net.Mail.MailAddress(email, displayName);
}
}
}
| using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dragon.Mail.Interfaces;
namespace Dragon.Mail.Impl
{
public class DefaultReceiverMapper : IReceiverMapper
{
public void Map(dynamic receiver, Models.Mail mail)
{
var displayName = (string)null;
if (receiver.GetType().GetProperty("fullname") != null)
{
displayName = receiver.fullname;
}
var email = receiver.email;
mail.Receiver = new System.Net.Mail.MailAddress(email, displayName);
}
}
}
|
Add a default icon when a ruleset isn't present | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using OpenTK;
namespace osu.Game.Beatmaps.Drawables
{
public class DifficultyIcon : DifficultyColouredContainer
{
private readonly BeatmapInfo beatmap;
public DifficultyIcon(BeatmapInfo beatmap) : base(beatmap)
{
this.beatmap = beatmap;
Size = new Vector2(20);
}
[BackgroundDependencyLoader]
private void load()
{
Children = new Drawable[]
{
new SpriteIcon
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
Colour = AccentColour,
Icon = FontAwesome.fa_circle
},
new ConstrainedIconContainer
{
RelativeSizeAxes = Axes.Both,
Icon = beatmap.Ruleset.CreateInstance().CreateIcon()
}
};
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using OpenTK;
namespace osu.Game.Beatmaps.Drawables
{
public class DifficultyIcon : DifficultyColouredContainer
{
private readonly BeatmapInfo beatmap;
public DifficultyIcon(BeatmapInfo beatmap) : base(beatmap)
{
this.beatmap = beatmap;
Size = new Vector2(20);
}
[BackgroundDependencyLoader]
private void load()
{
Children = new Drawable[]
{
new SpriteIcon
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
Colour = AccentColour,
Icon = FontAwesome.fa_circle
},
new ConstrainedIconContainer
{
RelativeSizeAxes = Axes.Both,
// the null coalesce here is only present to make unit tests work (ruleset dlls aren't copied correctly for testing at the moment)
Icon = beatmap.Ruleset?.CreateInstance().CreateIcon() ?? new SpriteIcon { Icon = FontAwesome.fa_question_circle_o }
}
};
}
}
}
|
Use Json.Net type stamping instead of assembly qualified name. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Table;
using Newtonsoft.Json;
namespace SlashTodo.Infrastructure.AzureTables
{
public abstract class ComplexTableEntity<T> : TableEntity
{
public string DataTypeAssemblyQualifiedName { get; set; }
public string SerializedData { get; set; }
protected ComplexTableEntity() { }
protected ComplexTableEntity(T data, Func<T, string> partitionKey, Func<T, string> rowKey)
{
PartitionKey = partitionKey(data);
RowKey = rowKey(data);
SerializedData = JsonConvert.SerializeObject(data);
DataTypeAssemblyQualifiedName = data.GetType().AssemblyQualifiedName;
}
public T GetData()
{
return (T)JsonConvert.DeserializeObject(SerializedData, Type.GetType(DataTypeAssemblyQualifiedName));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Table;
using Newtonsoft.Json;
namespace SlashTodo.Infrastructure.AzureTables
{
public abstract class ComplexTableEntity<T> : TableEntity
{
private static readonly JsonSerializerSettings SerializerSettings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto
};
public string SerializedData { get; set; }
protected ComplexTableEntity() { }
protected ComplexTableEntity(T data, Func<T, string> partitionKey, Func<T, string> rowKey)
{
PartitionKey = partitionKey(data);
RowKey = rowKey(data);
SerializedData = JsonConvert.SerializeObject(data, SerializerSettings);
}
public T GetData()
{
return (T)JsonConvert.DeserializeObject(SerializedData, SerializerSettings);
}
}
}
|
Store an item when it is added to the basket | using NUnit.Framework;
namespace engine.tests
{
[TestFixture]
public class SupermarketAcceptanceTests
{
[Test]
public void EmptyBasket()
{
var till = new Till();
var basket = new Basket();
var total = till.CalculatePrice(basket);
var expected = 0;
Assert.That(total, Is.EqualTo(expected));
}
[Test]
public void SingleItemInBasket()
{
var till = new Till();
var basket = new Basket();
basket.Add("pennySweet", 1);
var total = till.CalculatePrice(basket);
var expected = 1;
Assert.That(total, Is.EqualTo(expected));
}
}
public class Basket
{
public void Add(string item, int unitPrice)
{
}
}
public class Till
{
public int CalculatePrice(Basket basket)
{
return 0;
}
}
} | using NUnit.Framework;
namespace engine.tests
{
[TestFixture]
public class SupermarketAcceptanceTests
{
[Test]
public void EmptyBasket()
{
var till = new Till();
var basket = new Basket();
var total = till.CalculatePrice(basket);
var expected = 0;
Assert.That(total, Is.EqualTo(expected));
}
[Test]
public void SingleItemInBasket()
{
var till = new Till();
var basket = new Basket();
basket.Add("pennySweet", 1);
var total = till.CalculatePrice(basket);
var expected = 1;
Assert.That(total, Is.EqualTo(expected));
}
}
public class Basket
{
private readonly IList<BasketItem> items = new List<BasketItem>();
public void Add(string item, int unitPrice)
{
items.Add(new BasketItem(item, unitPrice));
}
}
public class BasketItem
{
public string Item { get; private set; }
public int UnitPrice { get; private set; }
public BasketItem(string item, int unitPrice)
{
Item = item;
UnitPrice = unitPrice;
}
}
public class Till
{
public int CalculatePrice(Basket basket)
{
return 0;
}
}
} |
Remove website url from product description | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// http://stackoverflow.com/questions/62353/what-are-the-best-practices-for-using-assembly-attributes
[assembly: AssemblyCompany("Mario Guggenberger / protyposis.net")]
[assembly: AssemblyProduct("Aurio Audio Processing, Analysis and Retrieval Library http://protyposis.net")]
//[assembly: AssemblyTrademark("")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0 Alpha")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// http://stackoverflow.com/questions/62353/what-are-the-best-practices-for-using-assembly-attributes
[assembly: AssemblyCompany("Mario Guggenberger / protyposis.net")]
[assembly: AssemblyProduct("Aurio Audio Processing, Analysis and Retrieval Library")]
//[assembly: AssemblyTrademark("")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0 Alpha")]
|
Add Last4 in AU BECS Source and Deprecating Last3 | namespace Stripe
{
using Newtonsoft.Json;
public class SourceAuBecsDebit : StripeEntity
{
[JsonProperty("account_number")]
public string AccountNumber { get; set; }
[JsonProperty("bsb_number")]
public string BsbNumber { get; set; }
[JsonProperty("fingerprint")]
public string Fingerprint { get; set; }
[JsonProperty("last3")]
public string Last3 { get; set; }
}
}
| namespace Stripe
{
using System;
using Newtonsoft.Json;
public class SourceAuBecsDebit : StripeEntity
{
[JsonProperty("account_number")]
public string AccountNumber { get; set; }
[JsonProperty("bsb_number")]
public string BsbNumber { get; set; }
[JsonProperty("fingerprint")]
public string Fingerprint { get; set; }
[Obsolete("This property is deprecated, please use Last4 going forward.")]
[JsonProperty("last3")]
public string Last3 { get; set; }
[JsonProperty("last4")]
public string Last4 { get; set; }
}
}
|
Fix typo in summary comment | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.ComponentModel;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Specifies the C# or VB source code kind.
/// </summary>
public enum SourceCodeKind
{
/// <summary>
/// No scripting. Used for .cs/.vb file parsing.
/// </summary>
Regular = 0,
/// <summary>
/// Allows top-level statementsm, declarations, and optional trailing expression.
/// Used for parsing .csx/.vbx and interactive submissions.
/// </summary>
Script = 1,
/// <summary>
/// The same as <see cref="Script"/>.
/// </summary>
[Obsolete("Use Script instead", error: false)]
[EditorBrowsable(EditorBrowsableState.Never)]
Interactive = 2,
}
internal static partial class SourceCodeKindExtensions
{
internal static bool IsValid(this SourceCodeKind value)
{
return value >= SourceCodeKind.Regular && value <= SourceCodeKind.Script;
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.ComponentModel;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Specifies the C# or VB source code kind.
/// </summary>
public enum SourceCodeKind
{
/// <summary>
/// No scripting. Used for .cs/.vb file parsing.
/// </summary>
Regular = 0,
/// <summary>
/// Allows top-level statements, declarations, and optional trailing expression.
/// Used for parsing .csx/.vbx and interactive submissions.
/// </summary>
Script = 1,
/// <summary>
/// The same as <see cref="Script"/>.
/// </summary>
[Obsolete("Use Script instead", error: false)]
[EditorBrowsable(EditorBrowsableState.Never)]
Interactive = 2,
}
internal static partial class SourceCodeKindExtensions
{
internal static bool IsValid(this SourceCodeKind value)
{
return value >= SourceCodeKind.Regular && value <= SourceCodeKind.Script;
}
}
}
|
Increment the stats counters in bulk | #region Copyright 2014 Exceptionless
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// http://www.gnu.org/licenses/agpl-3.0.html
#endregion
using System;
using Exceptionless.Core.AppStats;
using Exceptionless.Core.Billing;
using Exceptionless.Core.Plugins.EventProcessor;
using Foundatio.Metrics;
namespace Exceptionless.Core.Pipeline {
[Priority(90)]
public class IncrementCountersAction : EventPipelineActionBase {
private readonly IMetricsClient _stats;
public IncrementCountersAction(IMetricsClient stats) {
_stats = stats;
}
protected override bool ContinueOnError { get { return true; } }
public override void Process(EventContext ctx) {
_stats.Counter(MetricNames.EventsProcessed);
if (ctx.Organization.PlanId != BillingManager.FreePlan.Id)
_stats.Counter(MetricNames.EventsPaidProcessed);
}
}
} | #region Copyright 2014 Exceptionless
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// http://www.gnu.org/licenses/agpl-3.0.html
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using Exceptionless.Core.AppStats;
using Exceptionless.Core.Billing;
using Exceptionless.Core.Plugins.EventProcessor;
using Foundatio.Metrics;
namespace Exceptionless.Core.Pipeline {
[Priority(90)]
public class IncrementCountersAction : EventPipelineActionBase {
private readonly IMetricsClient _stats;
public IncrementCountersAction(IMetricsClient stats) {
_stats = stats;
}
protected override bool ContinueOnError { get { return true; } }
public override void ProcessBatch(ICollection<EventContext> contexts) {
_stats.Counter(MetricNames.EventsProcessed, contexts.Count);
if (contexts.First().Organization.PlanId != BillingManager.FreePlan.Id)
_stats.Counter(MetricNames.EventsPaidProcessed, contexts.Count);
}
public override void Process(EventContext ctx) {}
}
} |
Fix for compatibility with AppVeyor | using System;
using Nybus.Configuration;
using Nybus.Logging;
namespace Nybus.MassTransit
{
public class MassTransitOptions
{
public IQueueStrategy CommandQueueStrategy { get; set; } = new AutoGeneratedNameQueueStrategy();
public IErrorStrategy CommandErrorStrategy { get; set; } = new RetryErrorStrategy(5);
public IQueueStrategy EventQueueStrategy { get; set; } = new TemporaryQueueStrategy();
public IErrorStrategy EventErrorStrategy { get; set; } = new RetryErrorStrategy(5);
public IServiceBusFactory ServiceBusFactory { get; set; } = new RabbitMqServiceBusFactory(Environment.ProcessorCount);
public IContextManager ContextManager { get; set; } = new RabbitMqContextManager();
public ILoggerFactory LoggerFactory { get; set; } = Nybus.Logging.LoggerFactory.Default;
}
} | using System;
using Nybus.Configuration;
using Nybus.Logging;
namespace Nybus.MassTransit
{
public class MassTransitOptions
{
public IQueueStrategy CommandQueueStrategy { get; set; } = new AutoGeneratedNameQueueStrategy();
public IErrorStrategy CommandErrorStrategy { get; set; } = new RetryErrorStrategy(5);
public IQueueStrategy EventQueueStrategy { get; set; } = new TemporaryQueueStrategy();
public IErrorStrategy EventErrorStrategy { get; set; } = new RetryErrorStrategy(5);
public IServiceBusFactory ServiceBusFactory { get; set; } = new RabbitMqServiceBusFactory(Math.Max(1, Environment.ProcessorCount));
public IContextManager ContextManager { get; set; } = new RabbitMqContextManager();
public ILoggerFactory LoggerFactory { get; set; } = Nybus.Logging.LoggerFactory.Default;
}
} |
Add comment detailing why this is requried | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osuTK.Graphics;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Extensions.Color4Extensions;
using osuTK;
using osu.Framework.Input.Events;
namespace osu.Game.Graphics.UserInterface
{
public class DimmedLoadingLayer : OverlayContainer
{
private const float transition_duration = 250;
private readonly LoadingAnimation loading;
public DimmedLoadingLayer(float dimAmount = 0.5f, float iconScale = 1f)
{
RelativeSizeAxes = Axes.Both;
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black.Opacity(dimAmount),
},
loading = new LoadingAnimation { Scale = new Vector2(iconScale) },
};
}
protected override void PopIn()
{
this.FadeIn(transition_duration, Easing.OutQuint);
loading.Show();
}
protected override void PopOut()
{
this.FadeOut(transition_duration, Easing.OutQuint);
loading.Hide();
}
protected override bool Handle(UIEvent e)
{
switch (e)
{
case ScrollEvent _:
return false;
}
return base.Handle(e);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osuTK.Graphics;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Extensions.Color4Extensions;
using osuTK;
using osu.Framework.Input.Events;
namespace osu.Game.Graphics.UserInterface
{
public class DimmedLoadingLayer : OverlayContainer
{
private const float transition_duration = 250;
private readonly LoadingAnimation loading;
public DimmedLoadingLayer(float dimAmount = 0.5f, float iconScale = 1f)
{
RelativeSizeAxes = Axes.Both;
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black.Opacity(dimAmount),
},
loading = new LoadingAnimation { Scale = new Vector2(iconScale) },
};
}
protected override void PopIn()
{
this.FadeIn(transition_duration, Easing.OutQuint);
loading.Show();
}
protected override void PopOut()
{
this.FadeOut(transition_duration, Easing.OutQuint);
loading.Hide();
}
protected override bool Handle(UIEvent e)
{
switch (e)
{
// blocking scroll can cause weird behaviour when this layer is used within a ScrollContainer.
case ScrollEvent _:
return false;
}
return base.Handle(e);
}
}
}
|
Fix the broken doc build. | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Utilities
{
/// <summary>
/// A helper class to provide hooks into the Unity camera exclusive Lifecycle events
/// </summary>
public class CameraEventRouter : MonoBehaviour
{
/// <summary>
/// A callback to act upon <see cref="MonoBehaviour.OnPreRender()"/> without a script needing to exist on a <see cref="Camera"/> component
/// </summary>
public event Action<CameraEventRouter> OnCameraPreRender;
private void OnPreRender()
{
OnCameraPreRender?.Invoke(this);
}
}
} | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Utilities
{
/// <summary>
/// A helper class to provide hooks into the Unity camera exclusive Lifecycle events
/// </summary>
public class CameraEventRouter : MonoBehaviour
{
/// <summary>
/// A callback to act upon MonoBehaviour.OnPreRender() without a script needing to exist on a Camera component
/// </summary>
public event Action<CameraEventRouter> OnCameraPreRender;
private void OnPreRender()
{
OnCameraPreRender?.Invoke(this);
}
}
} |
Add problem 4. Photo Gallery | using System;
class PhotoGallery
{
static void Main()
{
}
} | using System;
class PhotoGallery
{
static void Main()
{
int photosNumber = int.Parse(Console.ReadLine());
int day = int.Parse(Console.ReadLine());
int month = int.Parse(Console.ReadLine());
int year = int.Parse(Console.ReadLine());
int hours = int.Parse(Console.ReadLine());
int minutes = int.Parse(Console.ReadLine());
double size = double.Parse(Console.ReadLine());
int width = int.Parse(Console.ReadLine());
int height = int.Parse(Console.ReadLine());
string orientation = "square";
if (width > height)
{
orientation = "landscape";
}
else if (height > width)
{
orientation = "portrait";
}
string formatSize = "B";
if (size >= 1000000)
{
size /= 1000000d;
formatSize = "MB";
}
else if (size >= 100000)
{
size /= 1000;
formatSize = "KB";
}
Console.WriteLine($"Name: DSC_{photosNumber:D4}.jpg");
Console.WriteLine($"Date Taken: {day:D2}/{month:D2}/{year} {hours:D2}:{minutes:D2}");
Console.WriteLine($"Size: {size}{formatSize}");
Console.WriteLine($"Resolution: {width}x{height} ({orientation})");
}
} |
Enable the content type to be editable when there is no result appearing based on the chosen keywords | @model StaticWidget
<div class="rich-text @Model.HtmlClasses" @Html.DxaEntityMarkup()>
@if (Model.TridionDocsItems != null)
{
foreach (TridionDocsItem item in Model.TridionDocsItems)
{
if (Model.DisplayContentAs.ToLower() == "embedded content")
{
<div class="content">
<div @Html.DxaPropertyMarkup(() => Model.TridionDocsItems)>
@Html.Raw(@item.Body)
</div>
</div>
<br />
}
else
{
<div @Html.DxaPropertyMarkup(() => Model.TridionDocsItems)>
<a href="@item.Link">@item.Title</a>
</div>
<br />
}
}
}
</div> | @model StaticWidget
<div class="rich-text @Model.HtmlClasses" @Html.DxaEntityMarkup()>
@if (Model.TridionDocsItems != null && Model.TridionDocsItems.Any())
{
foreach (TridionDocsItem item in Model.TridionDocsItems)
{
if (Model.DisplayContentAs.ToLower() == "embedded content")
{
<div class="content">
<div @Html.DxaPropertyMarkup(() => Model.TridionDocsItems)>
@Html.Raw(@item.Body)
</div>
</div>
<br />
}
else
{
<div @Html.DxaPropertyMarkup(() => Model.TridionDocsItems)>
<a href="@item.Link">@item.Title</a>
</div>
<br />
}
}
}
else
{
<span> </span>
}
</div> |
Add call to Configure() and clean up comments. | using DemoDataAccess;
using DemoDataAccess.Entity;
using NHibernate.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoQueryUtil
{
class Program
{
static void Main(string[] args)
{
// Works, but Area is null
var county = SessionManager.Session.Query<County>().First();
// Crashes
var municipalities = SessionManager.Session.Query<Municipality>()
.Where(m => m.Area.Within(county.Area)).ToList();
}
}
}
| using DemoDataAccess;
using DemoDataAccess.Entity;
using NHibernate.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoQueryUtil
{
class Program
{
static void Main(string[] args)
{
FluentConfiguration.Configure();
// Works, but Area is always null
var county = SessionManager.Session.Query<County>().First();
// Crashes with the error "No persister for: GeoAPI.Geometries.IGeometry"
var municipalities = SessionManager.Session.Query<Municipality>()
.Where(m => m.Area.Within(county.Area)).ToList();
}
}
}
|
Revise unit tests for Actions.Win32Window | using System;
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ThScoreFileConverter.Actions;
using ThScoreFileConverterTests.Models;
namespace ThScoreFileConverterTests.Actions
{
[TestClass]
public class Win32WindowTests
{
[TestMethod]
public void Win32WindowTest()
{
var window = new Window();
var win32window = new Win32Window(window);
Assert.IsNotNull(win32window);
Assert.AreNotEqual(0, win32window.Handle);
}
[SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "win32window")]
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Win32WindowTestNull()
{
var win32window = new Win32Window(null);
Assert.Fail(TestUtils.Unreachable);
}
}
}
| using System;
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using System.Windows.Interop;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ThScoreFileConverter.Actions;
using ThScoreFileConverterTests.Models;
namespace ThScoreFileConverterTests.Actions
{
[TestClass]
public class Win32WindowTests
{
[TestMethod]
public void Win32WindowTest()
{
var window = new Window();
var helper = new WindowInteropHelper(window);
var handle = helper.EnsureHandle();
var win32window = new Win32Window(window);
Assert.AreEqual(handle, win32window.Handle);
}
[TestMethod]
public void Win32WindowTestDefault()
{
var window = new Window();
var win32window = new Win32Window(window);
Assert.AreEqual(IntPtr.Zero, win32window.Handle);
}
[SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "win32window")]
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Win32WindowTestNull()
{
var win32window = new Win32Window(null);
Assert.Fail(TestUtils.Unreachable);
}
}
}
|
Add ShouldSerializeDirectives to pass test ensuring it's only serialized when non-empty | using Newtonsoft.Json;
using System.Collections.Generic;
namespace Alexa.NET.Response
{
public class ResponseBody
{
[JsonProperty("outputSpeech", NullValueHandling = NullValueHandling.Ignore)]
public IOutputSpeech OutputSpeech { get; set; }
[JsonProperty("card", NullValueHandling = NullValueHandling.Ignore)]
public ICard Card { get; set; }
[JsonProperty("reprompt", NullValueHandling = NullValueHandling.Ignore)]
public Reprompt Reprompt { get; set; }
[JsonProperty("shouldEndSession")]
[JsonRequired]
public bool ShouldEndSession { get; set; }
[JsonProperty("directives", NullValueHandling = NullValueHandling.Ignore)]
public IList<IDirective> Directives { get; set; } = new List<IDirective>();
}
} | using Newtonsoft.Json;
using System.Collections.Generic;
namespace Alexa.NET.Response
{
public class ResponseBody
{
[JsonProperty("outputSpeech", NullValueHandling = NullValueHandling.Ignore)]
public IOutputSpeech OutputSpeech { get; set; }
[JsonProperty("card", NullValueHandling = NullValueHandling.Ignore)]
public ICard Card { get; set; }
[JsonProperty("reprompt", NullValueHandling = NullValueHandling.Ignore)]
public Reprompt Reprompt { get; set; }
[JsonProperty("shouldEndSession")]
[JsonRequired]
public bool ShouldEndSession { get; set; }
[JsonProperty("directives", NullValueHandling = NullValueHandling.Ignore)]
public IList<IDirective> Directives { get; set; } = new List<IDirective>();
public bool ShouldSerializeDirectives()
{
return Directives.Count > 0;
}
}
} |
Store car value on grid when car is moved via byte array | // NetGameExtension.cs
// <copyright file="NetGameExtension.cs"> This code is protected under the MIT License. </copyright>
using Tron;
namespace Networking.Extensions
{
/// <summary>
/// An extension class for the game containing useful tools for a networked game of tron.
/// </summary>
public static class NetGameExtension
{
/// <summary>
/// Adjusts a car in the game accordingly to a byte array.
/// </summary>
/// <param name="g"> The game. </param>
/// <param name="byteArray"> The byte array. </param>
public static void SetCarPosFromByteArray(this TronGame g, byte[] byteArray)
{
// Get the index of the car
int index = byteArray[0];
// Adjust the car
g.Cars[index].PosFromByteArray(byteArray);
}
public static void SetCarScoreFromByteArray(this TronGame g, byte[] byteArray)
{
// Get the index of the car
int index = byteArray[0];
// Adjust the car
g.Cars[index].ScoreFromByteArray(byteArray);
}
}
}
| // NetGameExtension.cs
// <copyright file="NetGameExtension.cs"> This code is protected under the MIT License. </copyright>
using Tron;
namespace Networking.Extensions
{
/// <summary>
/// An extension class for the game containing useful tools for a networked game of tron.
/// </summary>
public static class NetGameExtension
{
/// <summary>
/// Adjusts a car in the game accordingly to a byte array.
/// </summary>
/// <param name="g"> The game. </param>
/// <param name="byteArray"> The byte array. </param>
public static void SetCarPosFromByteArray(this TronGame g, byte[] byteArray)
{
// Get the index of the car
int index = byteArray[0];
// Store the value on the grid
g.Grid[g.Cars[index].X][g.Cars[index].Y] = g.Cars[index].Colour;
// Adjust the car
g.Cars[index].PosFromByteArray(byteArray);
}
public static void SetCarScoreFromByteArray(this TronGame g, byte[] byteArray)
{
// Get the index of the car
int index = byteArray[0];
// Adjust the car
g.Cars[index].ScoreFromByteArray(byteArray);
}
}
}
|
Add inline null checks as requested | using System.Web.Http.ExceptionHandling;
using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Logging;
namespace Umbraco.Web.WebApi
{
/// <summary>
/// Used to log unhandled exceptions in webapi controllers
/// </summary>
public class UnhandledExceptionLogger : ExceptionLogger
{
private readonly ILogger _logger;
public UnhandledExceptionLogger()
: this(Current.Logger)
{
}
public UnhandledExceptionLogger(ILogger logger)
{
_logger = logger;
}
public override void Log(ExceptionLoggerContext context)
{
if (context != null && context.ExceptionContext != null
&& context.ExceptionContext.ActionContext != null && context.ExceptionContext.ActionContext.ControllerContext != null
&& context.ExceptionContext.ActionContext.ControllerContext.Controller != null
&& context.Exception != null)
{
var requestUrl = context.ExceptionContext.ControllerContext.Request.RequestUri.AbsoluteUri;
var controllerType = context.ExceptionContext.ActionContext.ControllerContext.Controller.GetType();
_logger.Error(controllerType, context.Exception, "Unhandled controller exception occurred for request '{RequestUrl}'", requestUrl);
}
}
}
}
| using System.Web.Http.ExceptionHandling;
using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Logging;
namespace Umbraco.Web.WebApi
{
/// <summary>
/// Used to log unhandled exceptions in webapi controllers
/// </summary>
public class UnhandledExceptionLogger : ExceptionLogger
{
private readonly ILogger _logger;
public UnhandledExceptionLogger()
: this(Current.Logger)
{
}
public UnhandledExceptionLogger(ILogger logger)
{
_logger = logger;
}
public override void Log(ExceptionLoggerContext context)
{
if (context != null && context.Exception != null)
{
var requestUrl = context.ExceptionContext?.ControllerContext?.Request?.RequestUri?.AbsoluteUri;
var controllerType = context.ExceptionContext?.ActionContext?.ControllerContext?.Controller?.GetType();
_logger.Error(controllerType, context.Exception, "Unhandled controller exception occurred for request '{RequestUrl}'", requestUrl);
}
}
}
}
|
Remove test for "DisableColorCompression" flag. | using System;
using dotless.Core.Parser;
using dotless.Core.Parser.Infrastructure;
namespace dotless.Test.Specs.Compression
{
using NUnit.Framework;
public class ColorsFixture : CompressedSpecFixtureBase
{
[Test]
public void Colors()
{
AssertExpression("#fea", "#fea");
AssertExpression("#0000ff", "#0000ff");
AssertExpression("blue", "blue");
}
[Test]
public void Should_not_compress_IE_ARGB()
{
AssertExpressionUnchanged("#ffaabbcc");
AssertExpressionUnchanged("#aabbccdd");
}
[Test]
public void Overflow()
{
AssertExpression("#000", "#111111 - #444444");
AssertExpression("#fff", "#eee + #fff");
AssertExpression("#fff", "#aaa * 3");
AssertExpression("lime", "#00ee00 + #009900");
AssertExpression("red", "#ee0000 + #990000");
}
[Test]
public void Gray()
{
AssertExpression("#888", "rgb(136, 136, 136)");
AssertExpression("gray", "hsl(50, 0, 50)");
}
[Test]
public void DisableColorCompression()
{
var oldEnv = DefaultEnv();
DefaultEnv = () => new Env(null)
{
Compress = true,
DisableColorCompression = false
};
AssertExpression("#111", "#111111");
DefaultEnv = () => new Env(null)
{
Compress = true,
DisableColorCompression = true
};
AssertExpression("#111111", "#111111");
DefaultEnv = () => oldEnv;
}
}
} | using System;
using dotless.Core.Parser;
using dotless.Core.Parser.Infrastructure;
namespace dotless.Test.Specs.Compression
{
using NUnit.Framework;
public class ColorsFixture : CompressedSpecFixtureBase
{
[Test]
public void Colors()
{
AssertExpression("#fea", "#fea");
AssertExpression("#0000ff", "#0000ff");
AssertExpression("blue", "blue");
}
[Test]
public void Should_not_compress_IE_ARGB()
{
AssertExpressionUnchanged("#ffaabbcc");
AssertExpressionUnchanged("#aabbccdd");
}
[Test]
public void Overflow()
{
AssertExpression("#000", "#111111 - #444444");
AssertExpression("#fff", "#eee + #fff");
AssertExpression("#fff", "#aaa * 3");
AssertExpression("lime", "#00ee00 + #009900");
AssertExpression("red", "#ee0000 + #990000");
}
[Test]
public void Gray()
{
AssertExpression("#888", "rgb(136, 136, 136)");
AssertExpression("gray", "hsl(50, 0, 50)");
}
}
} |
Call ToString() instead of Enum.GetName | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Linq;
using System.Collections.Concurrent;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Utilities;
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.Internal.Log
{
internal static class FunctionIdOptions
{
private static readonly ConcurrentDictionary<FunctionId, Option2<bool>> s_options =
new();
private static readonly Func<FunctionId, Option2<bool>> s_optionCreator = CreateOption;
private static Option2<bool> CreateOption(FunctionId id)
{
var name = Enum.GetName(typeof(FunctionId), id) ?? throw ExceptionUtilities.UnexpectedValue(id);
return new(nameof(FunctionIdOptions), name, defaultValue: false,
storageLocation: new LocalUserProfileStorageLocation(@"Roslyn\Internal\Performance\FunctionId\" + name));
}
private static IEnumerable<FunctionId> GetFunctionIds()
=> Enum.GetValues(typeof(FunctionId)).Cast<FunctionId>();
public static IEnumerable<IOption> GetOptions()
=> GetFunctionIds().Select(GetOption);
public static Option2<bool> GetOption(FunctionId id)
=> s_options.GetOrAdd(id, s_optionCreator);
public static Func<FunctionId, bool> CreateFunctionIsEnabledPredicate(IGlobalOptionService globalOptions)
{
var functionIdOptions = GetFunctionIds().ToDictionary(id => id, id => globalOptions.GetOption(GetOption(id)));
return functionId => functionIdOptions[functionId];
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Linq;
using System.Collections.Concurrent;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Utilities;
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.Internal.Log
{
internal static class FunctionIdOptions
{
private static readonly ConcurrentDictionary<FunctionId, Option2<bool>> s_options =
new();
private static readonly Func<FunctionId, Option2<bool>> s_optionCreator = CreateOption;
private static Option2<bool> CreateOption(FunctionId id)
{
var name = id.ToString();
return new(nameof(FunctionIdOptions), name, defaultValue: false,
storageLocation: new LocalUserProfileStorageLocation(@"Roslyn\Internal\Performance\FunctionId\" + name));
}
private static IEnumerable<FunctionId> GetFunctionIds()
=> Enum.GetValues(typeof(FunctionId)).Cast<FunctionId>();
public static IEnumerable<IOption> GetOptions()
=> GetFunctionIds().Select(GetOption);
public static Option2<bool> GetOption(FunctionId id)
=> s_options.GetOrAdd(id, s_optionCreator);
public static Func<FunctionId, bool> CreateFunctionIsEnabledPredicate(IGlobalOptionService globalOptions)
{
var functionIdOptions = GetFunctionIds().ToDictionary(id => id, id => globalOptions.GetOption(GetOption(id)));
return functionId => functionIdOptions[functionId];
}
}
}
|
Fix namespace issue after refactor of startup | namespace Moya.Runner.Console
{
using System;
using Extensions;
class Program
{
private static void Main(string[] args)
{
try
{
new Startup().Run(args);
}
catch(Exception e)
{
Console.Error.WriteLine("Error: {0}".FormatWith(e.Message));
Environment.Exit(1);
}
}
}
}
| namespace Moya.Runner.Console
{
using System;
using Extensions;
class Program
{
private static void Main(string[] args)
{
try
{
new Startup.Startup().Run(args);
}
catch(Exception e)
{
Console.Error.WriteLine("Error: {0}".FormatWith(e.Message));
Environment.Exit(1);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.