Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Fix showing username when logged in.
@{ var DiscordUser = UserHelper.GetDiscordUser(User); } @if(DiscordUser == null) { <a class="nav-link text-dark" asp-area="" asp-controller="Login" asp-action="Index">Login</a> } else { @DiscordUser }
@{ var DiscordUser = UserHelper.GetDiscordUser(User); } @if(DiscordUser == null) { <a class="nav-link text-dark" asp-area="" asp-controller="Login" asp-action="Index">Login</a> } else { @DiscordUser.User }
Fix hash code to use a tuple.
using System; namespace StructuredLogViewer { public struct ProjectImport : IEquatable<ProjectImport> { public ProjectImport(string importedProject, int line, int column) { ProjectPath = importedProject; Line = line; Column = column; } public string ProjectPath { get; set; } /// <summary> /// 0-based /// </summary> public int Line { get; set; } public int Column { get; set; } public bool Equals(ProjectImport other) { return ProjectPath == other.ProjectPath && Line == other.Line && Column == other.Column; } public override bool Equals(object obj) { if (obj is ProjectImport other) { return Equals(other); } return false; } public override int GetHashCode() { return ProjectPath.GetHashCode() ^ Line.GetHashCode() ^ Column.GetHashCode(); } public override string ToString() { return $"{ProjectPath} ({Line},{Column})"; } } }
using System; namespace StructuredLogViewer { public struct ProjectImport : IEquatable<ProjectImport> { public ProjectImport(string importedProject, int line, int column) { ProjectPath = importedProject; Line = line; Column = column; } public string ProjectPath { get; set; } /// <summary> /// 0-based /// </summary> public int Line { get; set; } public int Column { get; set; } public bool Equals(ProjectImport other) { return ProjectPath == other.ProjectPath && Line == other.Line && Column == other.Column; } public override bool Equals(object obj) { if (obj is ProjectImport other) { return Equals(other); } return false; } public override int GetHashCode() { return (ProjectPath, Line, Column).GetHashCode(); } public override string ToString() { return $"{ProjectPath} ({Line},{Column})"; } } }
Improve test name and assertion
using slang.Compiler.Clr.Compilation.Core.Builders; using slang.Compiler.Clr.Compilation.CSharp; using Xunit; namespace Clr.Tests.Compilation.CSharp { public class CSharpAssemblyGeneratorTests { [Fact] public void Given_a_defined_module_When_compiled_Then_a_CLR_class_is_created() { // Arrange var subject = new CSharpAssemblyGenerator(); var assemblyDefinition = AssemblyDefinitionBuilder .Create("slang") .AsLibrary() .AddModule(m => m .WithName("CSharpAssemblyGeneratorTestModule") .WithNamespace("slang.Clr.Tests")) .Build(); // Act var result = subject.GenerateDynamicAssembly(assemblyDefinition); // Assert result.GetType("slang.Clr.Tests.CSharpAssemblyGeneratorTestModule", true); } } }
using System.Reflection; using FluentAssertions; using slang.Compiler.Clr.Compilation.Core.Builders; using slang.Compiler.Clr.Compilation.CSharp; using Xunit; namespace Clr.Tests.Compilation.CSharp { public class CSharpAssemblyGeneratorTests { [Fact] public void Given_a_defined_module_When_compiled_Then_a_corresponding_public_class_is_created() { // Arrange var subject = new CSharpAssemblyGenerator(); var assemblyDefinition = AssemblyDefinitionBuilder .Create("slang") .AsLibrary() .AddModule(m => m .WithName("CSharpAssemblyGeneratorTestModule") .WithNamespace("slang.Clr.Tests")) .Build(); // Act var result = subject.GenerateDynamicAssembly(assemblyDefinition); // Assert var typeInfo = result.GetType("slang.Clr.Tests.CSharpAssemblyGeneratorTestModule", true).GetTypeInfo(); typeInfo.IsPublic.Should().BeTrue(); } } }
Fix incorrect end date usage in timeshift ready 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 System; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Game.Graphics; using osu.Game.Online.Multiplayer; using osu.Game.Screens.Multi.Components; namespace osu.Game.Screens.Multi.Timeshift { public class TimeshiftReadyButton : ReadyButton { [Resolved(typeof(Room), nameof(Room.EndDate))] private Bindable<DateTimeOffset?> endDate { get; set; } public TimeshiftReadyButton() { Text = "Start"; } [BackgroundDependencyLoader] private void load(OsuColour colours) { BackgroundColour = colours.Green; Triangles.ColourDark = colours.Green; Triangles.ColourLight = colours.GreenLight; } protected override void Update() { base.Update(); Enabled.Value = endDate.Value == null || DateTimeOffset.UtcNow.AddSeconds(30).AddMilliseconds(GameBeatmap.Value.Track.Length) < endDate.Value; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Game.Graphics; using osu.Game.Online.Multiplayer; using osu.Game.Screens.Multi.Components; namespace osu.Game.Screens.Multi.Timeshift { public class TimeshiftReadyButton : ReadyButton { [Resolved(typeof(Room), nameof(Room.EndDate))] private Bindable<DateTimeOffset> endDate { get; set; } public TimeshiftReadyButton() { Text = "Start"; } [BackgroundDependencyLoader] private void load(OsuColour colours) { BackgroundColour = colours.Green; Triangles.ColourDark = colours.Green; Triangles.ColourLight = colours.GreenLight; } protected override void Update() { base.Update(); Enabled.Value = DateTimeOffset.UtcNow.AddSeconds(30).AddMilliseconds(GameBeatmap.Value.Track.Length) < endDate.Value; } } }
Fix lifestyles of job to dispose after each execution
using Castle.MicroKernel.Registration; using Castle.MicroKernel.SubSystems.Configuration; using Castle.Windsor; namespace FineBot.Workers.DI { public class WorkerInstaller : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register(Classes.FromThisAssembly().Pick().WithService.DefaultInterfaces()); } } }
using Castle.MicroKernel.Registration; using Castle.MicroKernel.SubSystems.Configuration; using Castle.Windsor; namespace FineBot.Workers.DI { public class WorkerInstaller : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register(Classes.FromThisAssembly().Pick().WithService.DefaultInterfaces().LifestyleTransient()); } } }
Use BigInteger.Zero instead of implicit conversion
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.ProjectEuler.Puzzles { using System; using System.Globalization; using System.Linq; using System.Numerics; /// <summary> /// A class representing the solution to <c>https://projecteuler.net/problem=48</c>. This class cannot be inherited. /// </summary> internal sealed class Puzzle048 : Puzzle { /// <inheritdoc /> public override string Question => "Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + N^N."; /// <inheritdoc /> protected override int MinimumArguments => 1; /// <inheritdoc /> protected override int SolveCore(string[] args) { int n; if (!TryParseInt32(args[0], out n) || n < 2) { Console.Error.WriteLine("The specified number is invalid."); return -1; } BigInteger value = 0; foreach (int exponent in Enumerable.Range(1, n)) { value += BigInteger.Pow(exponent, exponent); } string result = value.ToString(CultureInfo.InvariantCulture); result = result.Substring(Math.Max(0, result.Length - 10), 10); Answer = result; return 0; } } }
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.ProjectEuler.Puzzles { using System; using System.Globalization; using System.Linq; using System.Numerics; /// <summary> /// A class representing the solution to <c>https://projecteuler.net/problem=48</c>. This class cannot be inherited. /// </summary> internal sealed class Puzzle048 : Puzzle { /// <inheritdoc /> public override string Question => "Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + N^N."; /// <inheritdoc /> protected override int MinimumArguments => 1; /// <inheritdoc /> protected override int SolveCore(string[] args) { int n; if (!TryParseInt32(args[0], out n) || n < 2) { Console.Error.WriteLine("The specified number is invalid."); return -1; } BigInteger value = BigInteger.Zero; foreach (int exponent in Enumerable.Range(1, n)) { value += BigInteger.Pow(exponent, exponent); } string result = value.ToString(CultureInfo.InvariantCulture); result = result.Substring(Math.Max(0, result.Length - 10), 10); Answer = result; return 0; } } }
Change icon for audio settings
// 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.Graphics; using osu.Game.Overlays.Settings.Sections.Audio; namespace osu.Game.Overlays.Settings.Sections { public class AudioSection : SettingsSection { public override string Header => "Audio"; public override FontAwesome Icon => FontAwesome.fa_headphones; public AudioSection() { Children = new Drawable[] { new AudioDevicesSettings(), new VolumeSettings(), new OffsetSettings(), new MainMenuSettings(), }; } } }
// 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.Graphics; using osu.Game.Overlays.Settings.Sections.Audio; namespace osu.Game.Overlays.Settings.Sections { public class AudioSection : SettingsSection { public override string Header => "Audio"; public override FontAwesome Icon => FontAwesome.fa_volume_up; public AudioSection() { Children = new Drawable[] { new AudioDevicesSettings(), new VolumeSettings(), new OffsetSettings(), new MainMenuSettings(), }; } } }
Fix mismatched use of MEF 1 and 2
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Editor.Wpf; using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.Imaging.Interop; namespace Microsoft.CodeAnalysis.Editor.Tags { [ExportImageMonikerService(Name = Name), Shared] internal class DefaultImageMonikerService : IImageMonikerService { public const string Name = nameof(DefaultImageMonikerService); public bool TryGetImageMoniker(ImmutableArray<string> tags, out ImageMoniker imageMoniker) { var glyph = tags.GetFirstGlyph(); // We can't do the compositing of these glyphs at the editor layer. So just map them // to the non-add versions. switch (glyph) { case Glyph.AddReference: glyph = Glyph.Reference; break; } imageMoniker = glyph.GetImageMoniker(); return !imageMoniker.IsNullImage(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Editor.Wpf; using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.Imaging.Interop; namespace Microsoft.CodeAnalysis.Editor.Tags { [ExportImageMonikerService(Name = Name)] internal class DefaultImageMonikerService : IImageMonikerService { public const string Name = nameof(DefaultImageMonikerService); public bool TryGetImageMoniker(ImmutableArray<string> tags, out ImageMoniker imageMoniker) { var glyph = tags.GetFirstGlyph(); // We can't do the compositing of these glyphs at the editor layer. So just map them // to the non-add versions. switch (glyph) { case Glyph.AddReference: glyph = Glyph.Reference; break; } imageMoniker = glyph.GetImageMoniker(); return !imageMoniker.IsNullImage(); } } }
Add closing message to sample console runner
using NSpec; using NSpec.Domain; using NSpec.Domain.Formatters; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace AdHocConsoleRunner { class Program { static void Main(string[] args) { var assemblies = new Assembly[] { typeof(SampleSpecs.DummyPublicClass).Assembly, typeof(ConfigSampleSpecs.DummyPublicClass).Assembly, }; //types that should be considered for testing var types = assemblies.SelectMany(asm => asm.GetTypes()).ToArray(); //now that we have our types, set up a finder so that NSpec //can determine the inheritance hierarchy var finder = new SpecFinder(types); //we've got our inheritance hierarchy, //now we can build our test tree using default conventions var builder = new ContextBuilder(finder, new DefaultConventions()); //create the nspec runner with a //live formatter so we get console output var runner = new ContextRunner( builder, new ConsoleFormatter(), false); //create our final collection of concrete tests var testCollection = builder.Contexts().Build(); //run the tests and get results (to do whatever you want with) var results = runner.Run(testCollection); //console write line to pause the exe System.Console.ReadLine(); } } }
using NSpec; using NSpec.Domain; using NSpec.Domain.Formatters; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace AdHocConsoleRunner { class Program { static void Main(string[] args) { var assemblies = new Assembly[] { typeof(SampleSpecs.DummyPublicClass).Assembly, typeof(ConfigSampleSpecs.DummyPublicClass).Assembly, }; //types that should be considered for testing var types = assemblies.SelectMany(asm => asm.GetTypes()).ToArray(); //now that we have our types, set up a finder so that NSpec //can determine the inheritance hierarchy var finder = new SpecFinder(types); //we've got our inheritance hierarchy, //now we can build our test tree using default conventions var builder = new ContextBuilder(finder, new DefaultConventions()); //create the nspec runner with a //live formatter so we get console output var runner = new ContextRunner( builder, new ConsoleFormatter(), false); //create our final collection of concrete tests var testCollection = builder.Contexts().Build(); //run the tests and get results (to do whatever you want with) var results = runner.Run(testCollection); //console write line to pause the exe Console.WriteLine(Environment.NewLine + "Press <enter> to quit..."); Console.ReadLine(); } } }
Add wrapper for environment variables.
// Copyright Matthias Koch 2017. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; #if NETCORE using System.IO; #endif namespace Nuke.Core { public static partial class EnvironmentInfo { public static string NewLine => Environment.NewLine; public static string MachineName => Environment.MachineName; public static string WorkingDirectory #if NETCORE => Directory.GetCurrentDirectory(); #else => Environment.CurrentDirectory; #endif } }
// Copyright Matthias Koch 2017. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Collections; using System.Collections.Generic; using System.Linq; #if NETCORE using System.IO; #endif namespace Nuke.Core { public static partial class EnvironmentInfo { public static string NewLine => Environment.NewLine; public static string MachineName => Environment.MachineName; public static string WorkingDirectory #if NETCORE => Directory.GetCurrentDirectory(); #else => Environment.CurrentDirectory; #endif public static IReadOnlyDictionary<string, string> Variables { get { var environmentVariables = Environment.GetEnvironmentVariables(); return Environment.GetEnvironmentVariables().Keys.Cast<string>() .ToDictionary(x => x, x => (string) environmentVariables[x], StringComparer.OrdinalIgnoreCase); } } } }
Add ConsoleWhriteLine on Area and Perimeter Methods
using System; using Shapes.Class; namespace Shapes { using Interfaces; class Program { static void Main() { IShape circle = new Circle(4); Console.WriteLine(circle.CalculateArea()); circle.CalculatePerimeter(); IShape triangle = new Triangle(5, 8.4, 6.4, 8.5); triangle.CalculateArea(); triangle.CalculatePerimeter(); IShape rectangle = new Rectangle(8, 5); rectangle.CalculateArea(); rectangle.CalculatePerimeter(); Console.WriteLine(); } } }
using System; using Shapes.Class; namespace Shapes { using Interfaces; class Program { static void Main() { IShape circle = new Circle(4); Console.WriteLine("circle area: " + circle.CalculateArea()); Console.WriteLine("circle perimeter: " + circle.CalculatePerimeter()); IShape triangle = new Triangle(5, 8.4, 6.4, 8.5); Console.WriteLine("triangle area: " + triangle.CalculateArea()); Console.WriteLine("triangle perimeter: " + triangle.CalculatePerimeter()); IShape rectangle = new Rectangle(8, 5); Console.WriteLine("rectangle area: " + rectangle.CalculateArea()); Console.WriteLine("rectangle perimeter: " + rectangle.CalculatePerimeter()); Console.WriteLine(); } } }
Tweak so it'll send for any non-ignored units
using BatteryCommander.Web.Models; using BatteryCommander.Web.Services; using FluentEmail.Core; using FluentEmail.Core.Models; using FluentScheduler; using System.Collections.Generic; using System.IO; namespace BatteryCommander.Web.Jobs { public class PERSTATReportJob : IJob { private static IList<Address> Recipients => new List<Address>(new Address[] { Matt // new Address { Name = "2-116 FA BN TOC", EmailAddress = "ng.fl.flarng.list.ngfl-2-116-fa-bn-toc@mail.mil" } }); internal static Address Matt => new Address { Name = "1LT Wagner", EmailAddress = "MattGWagner@gmail.com" }; private readonly Database db; private readonly IFluentEmail emailSvc; public PERSTATReportJob(Database db, IFluentEmail emailSvc) { this.db = db; this.emailSvc = emailSvc; } public virtual void Execute() { // HACK - Configure the recipients and units that this is going to be wired up for var unit = UnitService.Get(db, unitId: 3).Result; // C Batt emailSvc .To(Recipients) .SetFrom(Matt.EmailAddress, Matt.Name) .Subject($"{unit.Name} | RED 1 PERSTAT") .UsingTemplateFromFile($"{Directory.GetCurrentDirectory()}/Views/Reports/Red1_Perstat.cshtml", unit) .Send(); } } }
using BatteryCommander.Web.Models; using BatteryCommander.Web.Services; using FluentEmail.Core; using FluentEmail.Core.Models; using FluentScheduler; using System.Collections.Generic; using System.IO; namespace BatteryCommander.Web.Jobs { public class PERSTATReportJob : IJob { private static IList<Address> Recipients => new List<Address>(new Address[] { Matt // new Address { Name = "2-116 FA BN TOC", EmailAddress = "ng.fl.flarng.list.ngfl-2-116-fa-bn-toc@mail.mil" } }); internal static Address Matt => new Address { Name = "1LT Wagner", EmailAddress = "MattGWagner@gmail.com" }; private readonly Database db; private readonly IFluentEmail emailSvc; public PERSTATReportJob(Database db, IFluentEmail emailSvc) { this.db = db; this.emailSvc = emailSvc; } public virtual void Execute() { foreach (var unit in UnitService.List(db).GetAwaiter().GetResult()) { // HACK - Configure the recipients and units that this is going to be wired up for emailSvc .To(Recipients) .SetFrom(Matt.EmailAddress, Matt.Name) .Subject($"{unit.Name} | RED 1 PERSTAT") .UsingTemplateFromFile($"{Directory.GetCurrentDirectory()}/Views/Reports/Red1_Perstat.cshtml", unit) .Send(); } } } }
Make as an obsolete class.
#region License // // Copyright (c) 2013, Kooboo team // // Licensed under the BSD License // See the file LICENSE.txt for details. // #endregion using System; using System.Collections.Generic; using System.Linq; namespace Kooboo { /// <summary> /// /// </summary> public static class ApplicationInitialization { #region Fields private class InitializationItem { public Action InitializeMethod { get; set; } public int Priority { get; set; } } private static List<InitializationItem> items = new List<InitializationItem>(); #endregion #region Methods /// <summary> /// Registers the initializer method. /// </summary> /// <param name="method">The method.</param> /// <param name="priority">The priority.</param> public static void RegisterInitializerMethod(Action method, int priority) { items.Add(new InitializationItem() { InitializeMethod = method, Priority = priority }); } /// <summary> /// Executes this instance. /// </summary> public static void Execute() { lock (items) { foreach (var item in items.OrderBy(it => it.Priority)) { item.InitializeMethod(); } items.Clear(); } } #endregion } }
#region License // // Copyright (c) 2013, Kooboo team // // Licensed under the BSD License // See the file LICENSE.txt for details. // #endregion using System; using System.Collections.Generic; using System.Linq; namespace Kooboo { /// <summary> /// /// </summary> [Obsolete] public static class ApplicationInitialization { #region Fields private class InitializationItem { public Action InitializeMethod { get; set; } public int Priority { get; set; } } private static List<InitializationItem> items = new List<InitializationItem>(); #endregion #region Methods /// <summary> /// Registers the initializer method. /// </summary> /// <param name="method">The method.</param> /// <param name="priority">The priority.</param> public static void RegisterInitializerMethod(Action method, int priority) { items.Add(new InitializationItem() { InitializeMethod = method, Priority = priority }); } /// <summary> /// Executes this instance. /// </summary> public static void Execute() { lock (items) { foreach (var item in items.OrderBy(it => it.Priority)) { item.InitializeMethod(); } items.Clear(); } } #endregion } }
Make the text areas bigger on suta edit
@model BatteryCommander.Web.Commands.UpdateSUTARequest @using (Html.BeginForm("Edit", "SUTA", new { Model.Id }, FormMethod.Post, true, new { @class = "form-horizontal", role = "form" })) { @Html.AntiForgeryToken() @Html.ValidationSummary() <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.Supervisor) @Html.DropDownListFor(model => model.Body.Supervisor, (IEnumerable<SelectListItem>)ViewBag.Supervisors) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.StartDate) @Html.EditorFor(model => model.Body.StartDate) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.EndDate) @Html.EditorFor(model => model.Body.EndDate) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.Reasoning) @Html.TextAreaFor(model => model.Body.Reasoning) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.MitigationPlan) @Html.TextAreaFor(model => model.Body.MitigationPlan) </div> <button type="submit">Save</button> }
@model BatteryCommander.Web.Commands.UpdateSUTARequest @using (Html.BeginForm("Edit", "SUTA", new { Model.Id }, FormMethod.Post, true, new { @class = "form-horizontal", role = "form" })) { @Html.AntiForgeryToken() @Html.ValidationSummary() <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.Supervisor) @Html.DropDownListFor(model => model.Body.Supervisor, (IEnumerable<SelectListItem>)ViewBag.Supervisors) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.StartDate) @Html.EditorFor(model => model.Body.StartDate) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.EndDate) @Html.EditorFor(model => model.Body.EndDate) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.Reasoning) @Html.TextAreaFor(model => model.Body.Reasoning, new { cols="40", rows="5" }) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Body.MitigationPlan) @Html.TextAreaFor(model => model.Body.MitigationPlan, new { cols="40", rows="5" }) </div> <button type="submit">Save</button> }
Fix a different error on unit create
using System; using System.ComponentModel.DataAnnotations; using static BatteryCommander.Web.Models.Soldier; namespace BatteryCommander.Web.Models.Reports { public class Stat { public int Assigned { get; set; } public int Passed { get; set; } public int Failed { get; set; } [Display(Name = "Not Tested")] public int NotTested { get; set; } [Display(Name = "Pass %"), DisplayFormat(DataFormatString = SSDStatusModel.PercentFormat)] public Decimal PercentPass => (Decimal)Passed / Assigned; } public class Row { public Rank Rank { get; set; } public int Assigned { get; set; } public int Incomplete => Assigned - Completed; public int Completed { get; set; } [DisplayFormat(DataFormatString = SSDStatusModel.PercentFormat)] public Decimal Percentage => Assigned > 0 ? (Decimal)Completed / Assigned : Decimal.Zero; } }
using System; using System.ComponentModel.DataAnnotations; using static BatteryCommander.Web.Models.Soldier; namespace BatteryCommander.Web.Models.Reports { public class Stat { public int Assigned { get; set; } public int Passed { get; set; } public int Failed { get; set; } [Display(Name = "Not Tested")] public int NotTested { get; set; } [Display(Name = "Pass %"), DisplayFormat(DataFormatString = SSDStatusModel.PercentFormat)] public Decimal PercentPass => (Assigned > 0 ? (Decimal)Passed / Assigned : Decimal.Zero; } public class Row { public Rank Rank { get; set; } public int Assigned { get; set; } public int Incomplete => Assigned - Completed; public int Completed { get; set; } [DisplayFormat(DataFormatString = SSDStatusModel.PercentFormat)] public Decimal Percentage => Assigned > 0 ? (Decimal)Completed / Assigned : Decimal.Zero; } }
Fix the server list update
using UnityEngine; public class OnActivateRefresh : MonoBehaviour { private ServerUI _serverUi; private void Start() { _serverUi = FindObjectOfType<ServerUI>(); } private void OnEnable() { _serverUi.GetServerList(); } }
using UnityEngine; public class OnActivateRefresh : MonoBehaviour { private ServerUI _serverUi; private void Start() { _serverUi = FindObjectOfType<ServerUI>(); _serverUi.GetServerList(); } private void OnEnable() { if(_serverUi)_serverUi.GetServerList(); } }
Add context menu to select the script of a scriptable object
using UnityEditor; namespace BitStrap { public class ScriptableObjectContextMenu { [MenuItem("CONTEXT/ScriptableObject/Select in Project View")] public static void SelectScriptabelObject(MenuCommand menuCommand) { EditorGUIUtility.PingObject(menuCommand.context); } } }
using UnityEditor; using UnityEngine; namespace BitStrap { public class ScriptableObjectContextMenu { [MenuItem("CONTEXT/ScriptableObject/Select Script", false, 10)] public static void SelectScriptabelObjectScript(MenuCommand menuCommand) { var serializedObject = new SerializedObject(menuCommand.context); var scriptProperty = serializedObject.FindProperty("m_Script"); var scriptObject = scriptProperty.objectReferenceValue; Selection.activeObject = scriptObject; } [MenuItem("CONTEXT/ScriptableObject/Show in Project View")] public static void SelectScriptabelObject(MenuCommand menuCommand) { EditorGUIUtility.PingObject(menuCommand.context); } } }
Add None enum member to flags
using System; using JsonApiDotNetCore.Resources; namespace JsonApiDotNetCoreTests.IntegrationTests { /// <summary> /// Lists the various extensibility points on <see cref="IResourceDefinition{TResource,TId}" />. /// </summary> [Flags] public enum ResourceDefinitionExtensibilityPoints { OnApplyIncludes = 1, OnApplyFilter = 1 << 1, OnApplySort = 1 << 2, OnApplyPagination = 1 << 3, OnApplySparseFieldSet = 1 << 4, OnRegisterQueryableHandlersForQueryStringParameters = 1 << 5, GetMeta = 1 << 6, OnPrepareWriteAsync = 1 << 7, OnSetToOneRelationshipAsync = 1 << 8, OnSetToManyRelationshipAsync = 1 << 9, OnAddToRelationshipAsync = 1 << 10, OnRemoveFromRelationshipAsync = 1 << 11, OnWritingAsync = 1 << 12, OnWriteSucceededAsync = 1 << 13, OnDeserialize = 1 << 14, OnSerialize = 1 << 15, Reading = OnApplyIncludes | OnApplyFilter | OnApplySort | OnApplyPagination | OnApplySparseFieldSet | OnRegisterQueryableHandlersForQueryStringParameters | GetMeta, Writing = OnPrepareWriteAsync | OnSetToOneRelationshipAsync | OnSetToManyRelationshipAsync | OnAddToRelationshipAsync | OnRemoveFromRelationshipAsync | OnWritingAsync | OnWriteSucceededAsync, Serialization = OnDeserialize | OnSerialize, All = Reading | Writing | Serialization } }
using System; using JsonApiDotNetCore.Resources; namespace JsonApiDotNetCoreTests.IntegrationTests { /// <summary> /// Lists the various extensibility points on <see cref="IResourceDefinition{TResource,TId}" />. /// </summary> [Flags] public enum ResourceDefinitionExtensibilityPoints { None = 0, OnApplyIncludes = 1, OnApplyFilter = 1 << 1, OnApplySort = 1 << 2, OnApplyPagination = 1 << 3, OnApplySparseFieldSet = 1 << 4, OnRegisterQueryableHandlersForQueryStringParameters = 1 << 5, GetMeta = 1 << 6, OnPrepareWriteAsync = 1 << 7, OnSetToOneRelationshipAsync = 1 << 8, OnSetToManyRelationshipAsync = 1 << 9, OnAddToRelationshipAsync = 1 << 10, OnRemoveFromRelationshipAsync = 1 << 11, OnWritingAsync = 1 << 12, OnWriteSucceededAsync = 1 << 13, OnDeserialize = 1 << 14, OnSerialize = 1 << 15, Reading = OnApplyIncludes | OnApplyFilter | OnApplySort | OnApplyPagination | OnApplySparseFieldSet | OnRegisterQueryableHandlersForQueryStringParameters | GetMeta, Writing = OnPrepareWriteAsync | OnSetToOneRelationshipAsync | OnSetToManyRelationshipAsync | OnAddToRelationshipAsync | OnRemoveFromRelationshipAsync | OnWritingAsync | OnWriteSucceededAsync, Serialization = OnDeserialize | OnSerialize, All = Reading | Writing | Serialization } }
Allow 'data-folder' and 'data-directory' config options
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Reflection; using QuantConnect.Configuration; namespace QuantConnect { /// <summary> /// Provides application level constant values /// </summary> public static class Constants { private static readonly string DataFolderPath = Config.Get("data-folder", @"../../../Data/"); /// <summary> /// The root directory of the data folder for this application /// </summary> public static string DataFolder { get { return DataFolderPath; } } /// <summary> /// The directory used for storing downloaded remote files /// </summary> public const string Cache = "./cache/data"; /// <summary> /// The version of lean /// </summary> public static readonly string Version = Assembly.GetExecutingAssembly().GetName().Version.ToString(); } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Reflection; using QuantConnect.Configuration; namespace QuantConnect { /// <summary> /// Provides application level constant values /// </summary> public static class Constants { private static readonly string DataFolderPath = Config.Get("data-folder", Config.Get("data-directory", @"../../../Data/")); /// <summary> /// The root directory of the data folder for this application /// </summary> public static string DataFolder { get { return DataFolderPath; } } /// <summary> /// The directory used for storing downloaded remote files /// </summary> public const string Cache = "./cache/data"; /// <summary> /// The version of lean /// </summary> public static readonly string Version = Assembly.GetExecutingAssembly().GetName().Version.ToString(); } }
Make querying successors and predeccors fail explicitly
using System; using System.Collections.Generic; using System.Collections.Immutable; namespace Bearded.Utilities.Graphs { class AdjacencyListDirectedGraph<T> : IDirectedGraph<T> where T : IEquatable<T> { private readonly ImmutableList<T> elements; private readonly ImmutableDictionary<T, ImmutableList<T>> directSuccessors; private readonly ImmutableDictionary<T, ImmutableList<T>> directPredecessors; public IEnumerable<T> Elements => elements; public int Count => elements.Count; public AdjacencyListDirectedGraph( ImmutableList<T> elements, ImmutableDictionary<T, ImmutableList<T>> directSuccessors, ImmutableDictionary<T, ImmutableList<T>> directPredecessors) { this.elements = elements; this.directSuccessors = directSuccessors; this.directPredecessors = directPredecessors; } public IEnumerable<T> GetDirectSuccessorsOf(T element) => directSuccessors[element]; public IEnumerable<T> GetDirectPredecessorsOf(T element) => directPredecessors[element]; } }
using System; using System.Collections.Generic; using System.Collections.Immutable; namespace Bearded.Utilities.Graphs { class AdjacencyListDirectedGraph<T> : IDirectedGraph<T> where T : IEquatable<T> { private readonly ImmutableList<T> elements; private readonly ImmutableDictionary<T, ImmutableList<T>> directSuccessors; private readonly ImmutableDictionary<T, ImmutableList<T>> directPredecessors; public IEnumerable<T> Elements => elements; public int Count => elements.Count; public AdjacencyListDirectedGraph( ImmutableList<T> elements, ImmutableDictionary<T, ImmutableList<T>> directSuccessors, ImmutableDictionary<T, ImmutableList<T>> directPredecessors) { this.elements = elements; this.directSuccessors = directSuccessors; this.directPredecessors = directPredecessors; } public IEnumerable<T> GetDirectSuccessorsOf(T element) => directSuccessors.ContainsKey(element) ? directSuccessors[element] : throw new ArgumentOutOfRangeException(nameof(element), "Element not found in graph."); public IEnumerable<T> GetDirectPredecessorsOf(T element) => directPredecessors.ContainsKey(element) ? directPredecessors[element] : throw new ArgumentOutOfRangeException(nameof(element), "Element not found in graph."); } }
Fix type name in exception message for HasUniqueDomainSignature
namespace SharpArch.NHibernate.NHibernateValidator { using System.ComponentModel.DataAnnotations; using SharpArch.Domain; using SharpArch.Domain.DomainModel; using SharpArch.Domain.PersistenceSupport; /// <summary> /// Provides a class level validator for determining if the entity has a unique domain signature /// when compared with other entries in the database. /// /// Due to the fact that .NET does not support generic attributes, this only works for entity /// types having an Id of type int. /// </summary> public class HasUniqueDomainSignatureAttribute : ValidationAttribute { public override bool IsValid(object value) { var entityToValidate = value as IEntityWithTypedId<int>; Check.Require( entityToValidate != null, "This validator must be used at the class level of an IDomainWithTypedId<int>. The type you provided was " + value.GetType()); var duplicateChecker = SafeServiceLocator<IEntityDuplicateChecker>.GetService(); return ! duplicateChecker.DoesDuplicateExistWithTypedIdOf(entityToValidate); } public override string FormatErrorMessage(string name) { return "Provided values matched an existing, duplicate entity"; } } }
namespace SharpArch.NHibernate.NHibernateValidator { using System.ComponentModel.DataAnnotations; using SharpArch.Domain; using SharpArch.Domain.DomainModel; using SharpArch.Domain.PersistenceSupport; /// <summary> /// Provides a class level validator for determining if the entity has a unique domain signature /// when compared with other entries in the database. /// /// Due to the fact that .NET does not support generic attributes, this only works for entity /// types having an Id of type int. /// </summary> public class HasUniqueDomainSignatureAttribute : ValidationAttribute { public override bool IsValid(object value) { var entityToValidate = value as IEntityWithTypedId<int>; Check.Require( entityToValidate != null, "This validator must be used at the class level of an IEntityWithTypedId<int>. The type you provided was " + value.GetType()); var duplicateChecker = SafeServiceLocator<IEntityDuplicateChecker>.GetService(); return ! duplicateChecker.DoesDuplicateExistWithTypedIdOf(entityToValidate); } public override string FormatErrorMessage(string name) { return "Provided values matched an existing, duplicate entity"; } } }
Increase the precision of speed multiplier to match osu-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 osu.Framework.Bindables; using osu.Game.Graphics; using osuTK.Graphics; namespace osu.Game.Beatmaps.ControlPoints { public class DifficultyControlPoint : ControlPoint { public static readonly DifficultyControlPoint DEFAULT = new DifficultyControlPoint { SpeedMultiplierBindable = { Disabled = true }, }; /// <summary> /// The speed multiplier at this control point. /// </summary> public readonly BindableDouble SpeedMultiplierBindable = new BindableDouble(1) { Precision = 0.1, Default = 1, MinValue = 0.1, MaxValue = 10 }; public override Color4 GetRepresentingColour(OsuColour colours) => colours.GreenDark; /// <summary> /// The speed multiplier at this control point. /// </summary> public double SpeedMultiplier { get => SpeedMultiplierBindable.Value; set => SpeedMultiplierBindable.Value = value; } public override bool IsRedundant(ControlPoint existing) => existing is DifficultyControlPoint existingDifficulty && SpeedMultiplier == existingDifficulty.SpeedMultiplier; public override void CopyFrom(ControlPoint other) { SpeedMultiplier = ((DifficultyControlPoint)other).SpeedMultiplier; base.CopyFrom(other); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Bindables; using osu.Game.Graphics; using osuTK.Graphics; namespace osu.Game.Beatmaps.ControlPoints { public class DifficultyControlPoint : ControlPoint { public static readonly DifficultyControlPoint DEFAULT = new DifficultyControlPoint { SpeedMultiplierBindable = { Disabled = true }, }; /// <summary> /// The speed multiplier at this control point. /// </summary> public readonly BindableDouble SpeedMultiplierBindable = new BindableDouble(1) { Precision = 0.01, Default = 1, MinValue = 0.1, MaxValue = 10 }; public override Color4 GetRepresentingColour(OsuColour colours) => colours.GreenDark; /// <summary> /// The speed multiplier at this control point. /// </summary> public double SpeedMultiplier { get => SpeedMultiplierBindable.Value; set => SpeedMultiplierBindable.Value = value; } public override bool IsRedundant(ControlPoint existing) => existing is DifficultyControlPoint existingDifficulty && SpeedMultiplier == existingDifficulty.SpeedMultiplier; public override void CopyFrom(ControlPoint other) { SpeedMultiplier = ((DifficultyControlPoint)other).SpeedMultiplier; base.CopyFrom(other); } } }
Add the accumulator addressing mode.
namespace Mos6510.Instructions { public enum AddressingMode { Implied, Immediate, Absolute, AbsoluteX, AbsoluteY, Zeropage, ZeropageX, ZeropageY, IndirectX, IndirectY } }
namespace Mos6510.Instructions { public enum AddressingMode { Absolute, AbsoluteX, AbsoluteY, Accumulator, Immediate, Implied, IndirectX, IndirectY, Zeropage, ZeropageX, ZeropageY, } }
Fix failing when passing null
using System.Collections.Generic; namespace RetailStore { public class RetailStore { private readonly Screen m_Screen; private readonly Dictionary<string, string> m_Products; public RetailStore(Screen screen, Dictionary<string, string> products) { m_Screen = screen; m_Products = products; } public void OnBarcode(string barcode) { if (barcode == null || !m_Products.ContainsKey(barcode)) { m_Screen.ShowText("Product Not Found"); return; } var product = m_Products[barcode]; m_Screen.ShowText(product); } } }
using System.Collections.Generic; namespace RetailStore { public class RetailStore { private readonly Screen m_Screen; private readonly Dictionary<string, string> m_Products; public RetailStore(Screen screen, Dictionary<string, string> products) { m_Screen = screen; m_Products = products ?? new Dictionary<string, string>(); } public void OnBarcode(string barcode) { if (barcode == null || !m_Products.ContainsKey(barcode)) { m_Screen.ShowText("Product Not Found"); return; } var product = m_Products[barcode]; m_Screen.ShowText(product); } } }
Move back to list link
@model alert_roster.web.Models.Message @{ ViewBag.Title = "Create New Message"; } <h2>@ViewBag.Title</h2> @using (Html.BeginForm("New", "Home", FormMethod.Post)) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Message</h4> <hr /> @Html.ValidationSummary(true) <div class="form-group"> @Html.LabelFor(model => model.Content, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Content) @Html.ValidationMessageFor(model => model.Content) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Create" class="btn btn-default" /> </div> </div> </div> } <div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
@model alert_roster.web.Models.Message @{ ViewBag.Title = "Create New Message"; } <h2>@ViewBag.Title</h2> <div> @Html.ActionLink("Back to List", "Index") </div> @using (Html.BeginForm("New", "Home", FormMethod.Post)) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Message</h4> <hr /> @Html.ValidationSummary(true) <div class="form-group"> @Html.LabelFor(model => model.Content, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.Content) @Html.ValidationMessageFor(model => model.Content) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Create" class="btn btn-default" /> </div> </div> </div> }
Change OrderDetails table name from 'OrderDetails' to 'Order Details' in the mapping.
using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; namespace Northwind.Model.Mapping { public class OrderDetailMap : EntityTypeConfiguration<OrderDetail> { public OrderDetailMap() { // Primary Key HasKey(t => new { t.OrderId, t.ProductId }); // Properties Property(t => t.OrderId) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); Property(t => t.ProductId) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); // Table & Column Mappings ToTable("OrderDetails"); Property(t => t.OrderId).HasColumnName("OrderID"); Property(t => t.ProductId).HasColumnName("ProductID"); Property(t => t.UnitPrice).HasColumnName("UnitPrice"); Property(t => t.Quantity).HasColumnName("Quantity"); Property(t => t.Discount).HasColumnName("Discount"); // Relationships HasRequired(t => t.Order) .WithMany(t => t.OrderDetails) .HasForeignKey(d => d.OrderId); HasRequired(t => t.Product) .WithMany(t => t.OrderDetails) .HasForeignKey(d => d.ProductId); } } }
using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; namespace Northwind.Model.Mapping { public class OrderDetailMap : EntityTypeConfiguration<OrderDetail> { public OrderDetailMap() { // Primary Key HasKey(t => new { t.OrderId, t.ProductId }); // Properties Property(t => t.OrderId) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); Property(t => t.ProductId) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); // Table & Column Mappings ToTable("Order Details"); Property(t => t.OrderId).HasColumnName("OrderID"); Property(t => t.ProductId).HasColumnName("ProductID"); Property(t => t.UnitPrice).HasColumnName("UnitPrice"); Property(t => t.Quantity).HasColumnName("Quantity"); Property(t => t.Discount).HasColumnName("Discount"); // Relationships HasRequired(t => t.Order) .WithMany(t => t.OrderDetails) .HasForeignKey(d => d.OrderId); HasRequired(t => t.Product) .WithMany(t => t.OrderDetails) .HasForeignKey(d => d.ProductId); } } }
Remove this test as the API is broken
using Machine.Specifications; namespace Stripe.Tests { [Behaviors] public class account_behaviors { protected static StripeAccountSharedOptions CreateOrUpdateOptions; protected static StripeAccount StripeAccount; //It should_have_the_correct_email_address = () => // StripeAccount.Email.ShouldEqual(CreateOrUpdateOptions.Email); It should_have_the_correct_business_info = () => { StripeAccount.BusinessName.ShouldEqual(CreateOrUpdateOptions.BusinessName); StripeAccount.BusinessPrimaryColor.ShouldEqual(CreateOrUpdateOptions.BusinessPrimaryColor); StripeAccount.BusinessUrl.ShouldEqual(CreateOrUpdateOptions.BusinessUrl); }; It should_have_the_correct_debit_negative_balances = () => StripeAccount.DebitNegativeBalances.ShouldEqual(CreateOrUpdateOptions.DebitNegativeBalances.Value); It should_have_the_correct_decline_charge_values = () => { StripeAccount.DeclineChargeOn.AvsFailure.ShouldEqual(CreateOrUpdateOptions.DeclineChargeOnAvsFailure.Value); StripeAccount.DeclineChargeOn.CvcFailure.ShouldEqual(CreateOrUpdateOptions.DeclineChargeOnCvcFailure.Value); }; It should_have_the_correct_default_currency = () => StripeAccount.DefaultCurrency.ShouldEqual(CreateOrUpdateOptions.DefaultCurrency); } }
using Machine.Specifications; namespace Stripe.Tests { [Behaviors] public class account_behaviors { protected static StripeAccountSharedOptions CreateOrUpdateOptions; protected static StripeAccount StripeAccount; //It should_have_the_correct_email_address = () => // StripeAccount.Email.ShouldEqual(CreateOrUpdateOptions.Email); It should_have_the_correct_business_info = () => { StripeAccount.BusinessName.ShouldEqual(CreateOrUpdateOptions.BusinessName); StripeAccount.BusinessPrimaryColor.ShouldEqual(CreateOrUpdateOptions.BusinessPrimaryColor); StripeAccount.BusinessUrl.ShouldEqual(CreateOrUpdateOptions.BusinessUrl); }; It should_have_the_correct_debit_negative_balances = () => StripeAccount.DebitNegativeBalances.ShouldEqual(CreateOrUpdateOptions.DebitNegativeBalances.Value); It should_have_the_correct_default_currency = () => StripeAccount.DefaultCurrency.ShouldEqual(CreateOrUpdateOptions.DefaultCurrency); } }
Revert "Revert "Force fix for new databases""
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Threading; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Newtonsoft.Json; using VotingApplication.Data.Context; using VotingApplication.Web.Api.Migrations; namespace VotingApplication.Web.Api { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // Fix the infinite recursion of Session.OptionSet.Options[0].OptionSets[0].Options[0].[...] // by not populating the Option.OptionSets after already encountering Session.OptionSet GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //Enable automatic migrations Database.SetInitializer(new MigrateDatabaseToLatestVersion<VotingContext, Configuration>()); new VotingContext().Database.Initialize(false); } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Threading; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Newtonsoft.Json; using VotingApplication.Data.Context; using VotingApplication.Web.Api.Migrations; namespace VotingApplication.Web.Api { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // Fix the infinite recursion of Session.OptionSet.Options[0].OptionSets[0].Options[0].[...] // by not populating the Option.OptionSets after already encountering Session.OptionSet GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //Enable automatic migrations //Database.SetInitializer(new MigrateDatabaseToLatestVersion<VotingContext, Configuration>()); //new VotingContext().Database.Initialize(false); } } }
Fix NPE where saveData was accessed before being initialized
namespace RedBlueGames.ToolsExamples { using UnityEngine; using System.Collections; using System.Collections.Generic; public class PrimitiveCreatorSaveData : ScriptableObject { public List<PrimitiveCreator.Config> ConfigPresets; public bool HasConfigForIndex(int index) { if (this.ConfigPresets == null || this.ConfigPresets.Count == 0) { return false; } return index >= 0 && index < this.ConfigPresets.Count; } } }
namespace RedBlueGames.ToolsExamples { using UnityEngine; using System.Collections; using System.Collections.Generic; public class PrimitiveCreatorSaveData : ScriptableObject { public List<PrimitiveCreator.Config> ConfigPresets; private void OnEnable() { if (this.ConfigPresets == null) { this.ConfigPresets = new List<PrimitiveCreator.Config>(); } } public bool HasConfigForIndex(int index) { if (this.ConfigPresets == null || this.ConfigPresets.Count == 0) { return false; } return index >= 0 && index < this.ConfigPresets.Count; } } }
Allow Eye Dropper to be used as macro parameter editor
using Microsoft.Extensions.Logging; using Umbraco.Cms.Core.IO; using Umbraco.Cms.Core.Serialization; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Strings; namespace Umbraco.Cms.Core.PropertyEditors { [DataEditor( Constants.PropertyEditors.Aliases.ColorPickerEyeDropper, "Eye Dropper Color Picker", "eyedropper", Icon = "icon-colorpicker", Group = Constants.PropertyEditors.Groups.Pickers)] public class EyeDropperColorPickerPropertyEditor : DataEditor { private readonly IIOHelper _ioHelper; public EyeDropperColorPickerPropertyEditor( IDataValueEditorFactory dataValueEditorFactory, IIOHelper ioHelper, EditorType type = EditorType.PropertyValue) : base(dataValueEditorFactory, type) { _ioHelper = ioHelper; } /// <inheritdoc /> protected override IConfigurationEditor CreateConfigurationEditor() => new EyeDropperColorPickerConfigurationEditor(_ioHelper); } }
using Microsoft.Extensions.Logging; using Umbraco.Cms.Core.IO; using Umbraco.Cms.Core.Serialization; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Strings; namespace Umbraco.Cms.Core.PropertyEditors { [DataEditor( Constants.PropertyEditors.Aliases.ColorPickerEyeDropper, EditorType.PropertyValue | EditorType.MacroParameter, "Eye Dropper Color Picker", "eyedropper", Icon = "icon-colorpicker", Group = Constants.PropertyEditors.Groups.Pickers)] public class EyeDropperColorPickerPropertyEditor : DataEditor { private readonly IIOHelper _ioHelper; public EyeDropperColorPickerPropertyEditor( IDataValueEditorFactory dataValueEditorFactory, IIOHelper ioHelper, EditorType type = EditorType.PropertyValue) : base(dataValueEditorFactory, type) { _ioHelper = ioHelper; } /// <inheritdoc /> protected override IConfigurationEditor CreateConfigurationEditor() => new EyeDropperColorPickerConfigurationEditor(_ioHelper); } }
Fix test datacard path case
using System; using System.IO; using System.IO.Compression; using System.Reflection; namespace TestUtilities { public static class DatacardUtility { public static string WriteDatacard(string name) { var directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(directory); WriteDatacard(name, directory); return directory; } public static void WriteDatacard(string name, string directory) { var bytes = GetDatacard(name); Directory.CreateDirectory(directory); var zipFilePath = Path.Combine(directory, "DataCard.zip"); File.WriteAllBytes(zipFilePath, bytes); ZipFile.ExtractToDirectory(zipFilePath, directory); } public static byte[] GetDatacard(string name) { var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DataCards", Path.ChangeExtension(name.Replace(" ", "_"), ".zip")); return File.ReadAllBytes(path); } } }
using System; using System.IO; using System.IO.Compression; using System.Reflection; namespace TestUtilities { public static class DatacardUtility { public static string WriteDatacard(string name) { var directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(directory); WriteDatacard(name, directory); return directory; } public static void WriteDatacard(string name, string directory) { var bytes = GetDatacard(name); Directory.CreateDirectory(directory); var zipFilePath = Path.Combine(directory, "Datacard.zip"); File.WriteAllBytes(zipFilePath, bytes); ZipFile.ExtractToDirectory(zipFilePath, directory); } public static byte[] GetDatacard(string name) { var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Datacards", Path.ChangeExtension(name.Replace(" ", "_"), ".zip")); return File.ReadAllBytes(path); } } }
Use correct claims in case UserPrincipal has more than one identity
using System; using System.Collections.Generic; using System.Linq; using System.Security; using System.Security.Claims; using System.Security.Principal; using System.Web; namespace Bonobo.Git.Server { public static class UserExtensions { public static string GetClaim(this IPrincipal user, string claimName) { string result = null; ClaimsIdentity claimsIdentity = user.Identity as ClaimsIdentity; if (claimsIdentity != null) { try { result = claimsIdentity.FindFirst(claimName).Value; } catch { } } return result; } public static string Id(this IPrincipal user) { return user.GetClaim(ClaimTypes.Upn); } public static string Name(this IPrincipal user) { return user.GetClaim(ClaimTypes.Name); } public static string[] Roles(this IPrincipal user) { string[] result = null; ClaimsIdentity claimsIdentity = user.Identity as ClaimsIdentity; if (claimsIdentity != null) { try { result = claimsIdentity.FindAll(ClaimTypes.Role).Select(x => x.Value).ToArray(); } catch { } } return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security; using System.Security.Claims; using System.Security.Principal; using System.Web; namespace Bonobo.Git.Server { public static class UserExtensions { public static string GetClaim(this IPrincipal user, string claimName) { string result = null; try { ClaimsIdentity claimsIdentity = GetClaimsIdentity(user); if (claimsIdentity != null) { result = claimsIdentity.FindFirst(claimName).Value; } } catch { } return result; } public static string Id(this IPrincipal user) { return user.GetClaim(ClaimTypes.Upn); } public static string Name(this IPrincipal user) { return user.GetClaim(ClaimTypes.Name); } public static bool IsWindowsPrincipal(this IPrincipal user) { return user.Identity is WindowsIdentity; } public static string[] Roles(this IPrincipal user) { string[] result = null; try { ClaimsIdentity claimsIdentity = GetClaimsIdentity(user); if (claimsIdentity != null) { result = claimsIdentity.FindAll(ClaimTypes.Role).Select(x => x.Value).ToArray(); } } catch { } return result; } private static ClaimsIdentity GetClaimsIdentity(this IPrincipal user) { ClaimsIdentity result = null; ClaimsPrincipal claimsPrincipal = user as ClaimsPrincipal; if (claimsPrincipal != null) { result = claimsPrincipal.Identities.FirstOrDefault(x => x is ClaimsIdentity); } return result; } } }
Optimize element and text rendering for modern Windows versions
namespace Inspiring.Mvvm.Views { using System.Windows; using System.Windows.Media; using Inspiring.Mvvm.Common; using Inspiring.Mvvm.Screens; public class WindowService : IWindowService { public static readonly Event<InitializeWindowEventArgs> InitializeWindowEvent = new Event<InitializeWindowEventArgs>(); public virtual Window CreateWindow(Window owner, string title, bool modal) { Window window = new Window(); if (title != null) { window.Title = title; } if (owner != null) { window.Owner = owner; } if (modal) { window.ShowInTaskbar = false; } // Needed for sharp text rendering. TextOptions.SetTextFormattingMode(window, TextFormattingMode.Display); TextOptions.SetTextRenderingMode(window, TextRenderingMode.Aliased); return window; } public virtual void ShowWindow(Window window, bool modal) { if (modal) { window.ShowDialog(); } else { window.Show(); } } } public sealed class InitializeWindowEventArgs : ScreenEventArgs { public InitializeWindowEventArgs(IScreenBase target, Window window) : base(target) { Window = window; } public Window Window { get; private set; } } }
namespace Inspiring.Mvvm.Views { using System.Windows; using System.Windows.Media; using Inspiring.Mvvm.Common; using Inspiring.Mvvm.Screens; public class WindowService : IWindowService { public static readonly Event<InitializeWindowEventArgs> InitializeWindowEvent = new Event<InitializeWindowEventArgs>(); public virtual Window CreateWindow(Window owner, string title, bool modal) { var window = new Window(); if (title != null) { window.Title = title; } if (owner != null) { window.Owner = owner; } if (modal) { window.ShowInTaskbar = false; } // Needed for sharp element rendering. window.UseLayoutRounding = true; // Needed for sharp text rendering. TextOptions.SetTextFormattingMode(window, TextFormattingMode.Display); return window; } public virtual void ShowWindow(Window window, bool modal) { if (modal) { window.ShowDialog(); } else { window.Show(); } } } public sealed class InitializeWindowEventArgs : ScreenEventArgs { public InitializeWindowEventArgs(IScreenBase target, Window window) : base(target) { Window = window; } public Window Window { get; private set; } } }
Replace any API endpoint [::] for localhost when configuring HttpClient base address
using System; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Hosting.Server.Features; using Microsoft.Extensions.Hosting; namespace Duracellko.PlanningPoker.Web { public class HttpClientSetupService : BackgroundService { private readonly HttpClient _httpClient; private readonly IServer _server; public HttpClientSetupService(HttpClient httpClient, IServer server) { _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); _server = server ?? throw new ArgumentNullException(nameof(server)); } protected override Task ExecuteAsync(CancellationToken stoppingToken) { var serverAddresses = _server.Features.Get<IServerAddressesFeature>(); var address = serverAddresses.Addresses.FirstOrDefault(); if (address == null) { // Default ASP.NET Core Kestrel endpoint address = "http://localhost:5000"; } else { address = address.Replace("*", "localhost", StringComparison.Ordinal); address = address.Replace("+", "localhost", StringComparison.Ordinal); } _httpClient.BaseAddress = new Uri(address); return Task.CompletedTask; } } }
using System; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Hosting.Server.Features; using Microsoft.Extensions.Hosting; namespace Duracellko.PlanningPoker.Web { public class HttpClientSetupService : BackgroundService { private readonly HttpClient _httpClient; private readonly IServer _server; public HttpClientSetupService(HttpClient httpClient, IServer server) { _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); _server = server ?? throw new ArgumentNullException(nameof(server)); } protected override Task ExecuteAsync(CancellationToken stoppingToken) { var serverAddresses = _server.Features.Get<IServerAddressesFeature>(); var address = serverAddresses.Addresses.FirstOrDefault(); if (address == null) { // Default ASP.NET Core Kestrel endpoint address = "http://localhost:5000"; } else { address = address.Replace("*", "localhost", StringComparison.Ordinal); address = address.Replace("+", "localhost", StringComparison.Ordinal); address = address.Replace("[::]", "localhost", StringComparison.Ordinal); } _httpClient.BaseAddress = new Uri(address); return Task.CompletedTask; } } }
Add Uri Path Extension - constraints: new { ext = @"|json|xml|csv" }
using System; using System.Web.Http; using DataBooster.DbWebApi; namespace MyDbWebApi { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DbWebApi", routeTemplate: "{sp}", defaults: new { controller = "DbWebApi" } ); config.SupportCsvMediaType(); DbWebApiOptions.DerivedParametersCacheExpireInterval = new TimeSpan(0, 15, 0); } } }
using System; using System.Web.Http; using DataBooster.DbWebApi; namespace MyDbWebApi { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DbWebApi", routeTemplate: "{sp}/{ext}", defaults: new { controller = "DbWebApi", ext = RouteParameter.Optional }, constraints: new { ext = @"|json|xml|csv" } ); config.SupportCsvMediaType(); DbWebApiOptions.DerivedParametersCacheExpireInterval = new TimeSpan(0, 15, 0); } } }
Remove OpCode and Task from mapping
using System.Collections.Generic; using System.Linq; using Microsoft.Practices.EnterpriseLibrary.SemanticLogging; using MongoDB.Bson; namespace TIMEmSYSTEM.SemanticLogging.Mongo { internal static class EventEntryExtensions { internal static BsonDocument AsBsonDocument(this EventEntry eventEntry) { var payload = eventEntry.Schema.Payload.Zip(eventEntry.Payload, (key, value) => new KeyValuePair<string, object>(key, value)).ToDictionary(x => x.Key, y => y.Value); var dictionary = new Dictionary<string, object> { {"event", eventEntry.EventId}, {"message", eventEntry.FormattedMessage}, {"timestamp", eventEntry.Timestamp.LocalDateTime}, {"provider", eventEntry.ProviderId}, {"activity", eventEntry.ActivityId}, {"process", eventEntry.ProcessId}, {"thread", eventEntry.ThreadId}, {"level", (int) eventEntry.Schema.Level}, {"task", (int) eventEntry.Schema.Task}, {"ocode", (int) eventEntry.Schema.Opcode}, {"keywords", (long) eventEntry.Schema.Keywords}, {"payload", new BsonDocument(payload)} }; return new BsonDocument(dictionary); } internal static BsonDocument[] AsBsonDocuments(this IEnumerable<EventEntry> eventEntries) { return eventEntries.Select(AsBsonDocument).ToArray(); } } }
using System.Collections.Generic; using System.Linq; using Microsoft.Practices.EnterpriseLibrary.SemanticLogging; using MongoDB.Bson; namespace TIMEmSYSTEM.SemanticLogging.Mongo { internal static class EventEntryExtensions { internal static BsonDocument AsBsonDocument(this EventEntry eventEntry) { var payload = eventEntry.Schema.Payload.Zip(eventEntry.Payload, (key, value) => new KeyValuePair<string, object>(key, value)).ToDictionary(x => x.Key, y => y.Value); var dictionary = new Dictionary<string, object> { {"event", eventEntry.EventId}, {"message", eventEntry.FormattedMessage}, {"timestamp", eventEntry.Timestamp.LocalDateTime}, {"provider", eventEntry.ProviderId}, {"activity", eventEntry.ActivityId}, {"process", eventEntry.ProcessId}, {"thread", eventEntry.ThreadId}, {"level", (int) eventEntry.Schema.Level}, {"keywords", (long) eventEntry.Schema.Keywords}, {"payload", new BsonDocument(payload)} }; return new BsonDocument(dictionary); } internal static BsonDocument[] AsBsonDocuments(this IEnumerable<EventEntry> eventEntries) { return eventEntries.Select(AsBsonDocument).ToArray(); } } }
Add new option to redirect to output from command line
using CommandLine; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IdunnSql.Console { [Verb("execute", HelpText = "Execute the permission checks defined in a file")] public class ExecuteOptions { [Option('s', "source", Required = true, HelpText = "Name of the file containing information about the permissions to check")] public string Source { get; set; } [Option('p', "principal", Required = false, HelpText = "Name of the principal to impersonate.")] public string Principal { get; set; } } }
using CommandLine; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IdunnSql.Console { [Verb("execute", HelpText = "Execute the permission checks defined in a file")] public class ExecuteOptions { [Option('s', "source", Required = true, HelpText = "Name of the file containing information about the permissions to check")] public string Source { get; set; } [Option('p', "principal", Required = false, HelpText = "Name of the principal to impersonate.")] public string Principal { get; set; } [Option('o', "output", Required = false, HelpText = "Name of the file to redirect the output of the console.")] public string Output { get; set; } } }
Deploy as well as trim
using System; using System.IO; using NuGet; namespace NugetPackageTrimmer { class Program { static void Main(string[] args) { var repoUrl = args.Length > 2 ? args[1] : "https://packages.nuget.org/api/v2"; Console.WriteLine($"Checking if packages in [{args[0]}] exist in {repoUrl} and deleting any that dont need deploying..."); var repo = PackageRepositoryFactory.Default.CreateRepository(repoUrl); foreach (var nupkg in Directory.EnumerateFiles(args[0], "*.nupkg")) { Console.WriteLine($"Checking nuget package : {nupkg}"); var package = new ZipPackage(nupkg); if (repo.Exists(package)) { Console.WriteLine("That package already exists, deleting..."); File.Delete(nupkg); } else { Console.WriteLine("That package isnt in nuget yet, skipping..."); } } } } }
using System; using System.Globalization; using System.IO; using NuGet; namespace NugetPackageTrimmer { class Program { static void Main(string[] args) { var repoUrl = args.Length > 3 ? args[2] : "https://packages.nuget.org/api/v2"; Console.WriteLine($"Checking if packages in [{args[0]}] exist in {repoUrl} and deleting any that dont need deploying..."); var repo = PackageRepositoryFactory.Default.CreateRepository(repoUrl); var packageServer = new PackageServer(repoUrl, "NuGet Command Line"); packageServer.SendingRequest += (sender, e) => { Console.WriteLine(String.Format(CultureInfo.CurrentCulture, "{0} {1}", e.Request.Method, e.Request.RequestUri)); }; foreach (var nupkg in Directory.EnumerateFiles(args[0], "*.nupkg")) { Console.WriteLine($"Checking nuget package : {nupkg}"); var package = new OptimizedZipPackage(nupkg); if (repo.Exists(package)) { Console.WriteLine("That package already exists, skipping..."); File.Delete(nupkg); } else { Console.WriteLine("That package isnt in nuget yet, pushing..."); // Push the package to the server var sourceUri = new Uri(repoUrl); packageServer.PushPackage( args[1], package, new FileInfo(nupkg).Length, Convert.ToInt32(new TimeSpan(0, 0, 1, 0, 0).TotalMilliseconds), false); Console.WriteLine("Pushed"); } } } } }
Use deprecated method for older Unity support
using Oxide.Core; using UnityEngine; namespace Oxide.Unity { /// <summary> /// The main MonoBehaviour which calls OxideMod.OnFrame /// </summary> public class UnityScript : MonoBehaviour { public static GameObject Instance { get; private set; } public static void Create() { Instance = new GameObject("Oxide.Ext.Unity"); Object.DontDestroyOnLoad(Instance); Instance.AddComponent<UnityScript>(); } private OxideMod oxideMod; void Awake() { oxideMod = Interface.GetMod(); Application.logMessageReceived += HandleException; } void Update() { oxideMod.OnFrame(Time.deltaTime); } void OnDestroy() { if (oxideMod.IsShuttingDown) return; oxideMod.LogWarning("The Oxide Unity Script was destroyed (creating a new instance)"); oxideMod.NextTick(Create); } void HandleException(string message, string stack_trace, LogType type) { if (type == LogType.Exception && stack_trace.Contains("Oxide")) RemoteLogger.Exception(message, stack_trace); } } }
using Oxide.Core; using UnityEngine; namespace Oxide.Unity { /// <summary> /// The main MonoBehaviour which calls OxideMod.OnFrame /// </summary> public class UnityScript : MonoBehaviour { public static GameObject Instance { get; private set; } public static void Create() { Instance = new GameObject("Oxide.Ext.Unity"); Object.DontDestroyOnLoad(Instance); Instance.AddComponent<UnityScript>(); } private OxideMod oxideMod; void Awake() { oxideMod = Interface.GetMod(); Application.RegisterLogCallback(HandleException); } void Update() { oxideMod.OnFrame(Time.deltaTime); } void OnDestroy() { if (oxideMod.IsShuttingDown) return; oxideMod.LogWarning("The Oxide Unity Script was destroyed (creating a new instance)"); oxideMod.NextTick(Create); } void HandleException(string message, string stack_trace, LogType type) { if (type == LogType.Exception && stack_trace.Contains("Oxide")) RemoteLogger.Exception(message, stack_trace); } } }
Tweak raw sql data update
using Microsoft.EntityFrameworkCore.Migrations; using System; using System.Collections.Generic; namespace BatteryCommander.Web.Migrations { public partial class CanLogin : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<bool>( name: "CanLogin", table: "Soldiers", nullable: false, defaultValue: false); migrationBuilder.Sql("UPDATE dbo.Soldiers SET CanLogin = 1 WHERE CivilianEmail IS NOT NULL"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "CanLogin", table: "Soldiers"); } } }
using Microsoft.EntityFrameworkCore.Migrations; using System; using System.Collections.Generic; namespace BatteryCommander.Web.Migrations { public partial class CanLogin : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<bool>( name: "CanLogin", table: "Soldiers", nullable: false, defaultValue: false); migrationBuilder.Sql("UPDATE Soldiers SET CanLogin = 1 WHERE CivilianEmail IS NOT NULL"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "CanLogin", table: "Soldiers"); } } }
Set assembly version to 5.0.0.0
using System.Reflection; [assembly: AssemblyVersion("3.1.0.0")] [assembly: AssemblyFileVersion("3.1.0.0")] //// [assembly: AssemblyInformationalVersion("3.1.0.0 Release")]
using System.Reflection; [assembly: AssemblyVersion("5.0.0.0")] [assembly: AssemblyFileVersion("5.0.0.0")] //// [assembly: AssemblyInformationalVersion("3.1.0.0 Release")]
Add way to get HTTP error code
using System; namespace IvionWebSoft { public abstract class WebResource { public Uri Location { get; private set; } public bool Success { get; private set; } public Exception Exception { get; private set; } public WebResource(Uri uri) { if (uri == null) throw new ArgumentNullException("uri"); Location = uri; Success = true; Exception = null; } public WebResource(Exception ex) : this(null, ex) {} public WebResource(Uri uri, Exception ex) { if (ex == null) throw new ArgumentNullException("ex"); Location = uri; Success = false; Exception = ex; } public WebResource(WebResource resource) { if (resource == null) throw new ArgumentNullException("resource"); Location = resource.Location; Success = resource.Success; Exception = resource.Exception; } } }
using System; using System.Net; namespace IvionWebSoft { public abstract class WebResource { public Uri Location { get; private set; } public bool Success { get; private set; } public Exception Exception { get; private set; } public WebResource(Uri uri) { if (uri == null) throw new ArgumentNullException("uri"); Location = uri; Success = true; Exception = null; } public WebResource(Exception ex) : this(null, ex) {} public WebResource(Uri uri, Exception ex) { if (ex == null) throw new ArgumentNullException("ex"); Location = uri; Success = false; Exception = ex; } public WebResource(WebResource resource) { if (resource == null) throw new ArgumentNullException("resource"); Location = resource.Location; Success = resource.Success; Exception = resource.Exception; } public bool TryGetHttpError(out HttpStatusCode error) { var webEx = Exception as WebException; if (webEx != null && webEx.Status == WebExceptionStatus.ProtocolError) { var resp = webEx.Response as HttpWebResponse; if (resp != null) { error = resp.StatusCode; return true; } } error = default(HttpStatusCode); return false; } public bool HttpErrorIs(HttpStatusCode error) { HttpStatusCode status; if (TryGetHttpError(out status)) return status == error; return false; } } }
Use linq to simplify enumeration
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Web; namespace SettingsAPISample.Models { public class ARMListEntry<T> where T : INamedObject { public static ARMListEntry<T> Create(IEnumerable<T> objects, HttpRequestMessage request) { return new ARMListEntry<T> { Value = CreateList(objects, request) }; } private static IEnumerable<ARMEntry<T>> CreateList(IEnumerable<T> objects, HttpRequestMessage request) { foreach (var entry in objects) { yield return ARMEntry<T>.Create(entry, request, isChild: true); } } public IEnumerable<ARMEntry<T>> Value { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Web; namespace SettingsAPISample.Models { public class ARMListEntry<T> where T : INamedObject { public static ARMListEntry<T> Create(IEnumerable<T> objects, HttpRequestMessage request) { return new ARMListEntry<T> { Value = objects.Select(entry => ARMEntry<T>.Create(entry, request, isChild: true)) }; } public IEnumerable<ARMEntry<T>> Value { get; set; } } }
Align with Nuget Package Version 1.0.7
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("ElmahExtensions")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CustomErrorSignal")] [assembly: AssemblyCopyright("Copyright © 2013")] [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("5ffd977a-b2cf-4f08-a7f9-c5fc0fd3e5c1")] // 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.6.0")] [assembly: AssemblyFileVersion("1.0.6.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("ElmahExtensions")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CustomErrorSignal")] [assembly: AssemblyCopyright("Copyright © 2013")] [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("5ffd977a-b2cf-4f08-a7f9-c5fc0fd3e5c1")] // 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.7.0")] [assembly: AssemblyFileVersion("1.0.7.0")]
Use regular test steps rather than one-time set up and scheduling
// 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.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Utils; using osu.Game.Beatmaps; using osu.Game.Screens.Ranking.Expanded; namespace osu.Game.Tests.Visual.Ranking { public class TestSceneStarRatingDisplay : OsuTestScene { [SetUp] public void SetUp() => Schedule(() => { StarRatingDisplay changingStarRating; Child = new FillFlowContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, Children = new Drawable[] { new StarRatingDisplay(new StarDifficulty(1.23, 0)), new StarRatingDisplay(new StarDifficulty(2.34, 0)), new StarRatingDisplay(new StarDifficulty(3.45, 0)), new StarRatingDisplay(new StarDifficulty(4.56, 0)), new StarRatingDisplay(new StarDifficulty(5.67, 0)), new StarRatingDisplay(new StarDifficulty(6.78, 0)), new StarRatingDisplay(new StarDifficulty(10.11, 0)), changingStarRating = new StarRatingDisplay(), } }; Scheduler.AddDelayed(() => { changingStarRating.Current.Value = new StarDifficulty(RNG.NextDouble(0, 10), RNG.Next()); }, 500, 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 NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Utils; using osu.Game.Beatmaps; using osu.Game.Screens.Ranking.Expanded; namespace osu.Game.Tests.Visual.Ranking { public class TestSceneStarRatingDisplay : OsuTestScene { [Test] public void TestDisplay() { StarRatingDisplay changingStarRating = null; AddStep("load displays", () => Child = new FillFlowContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, Children = new Drawable[] { new StarRatingDisplay(new StarDifficulty(1.23, 0)), new StarRatingDisplay(new StarDifficulty(2.34, 0)), new StarRatingDisplay(new StarDifficulty(3.45, 0)), new StarRatingDisplay(new StarDifficulty(4.56, 0)), new StarRatingDisplay(new StarDifficulty(5.67, 0)), new StarRatingDisplay(new StarDifficulty(6.78, 0)), new StarRatingDisplay(new StarDifficulty(10.11, 0)), changingStarRating = new StarRatingDisplay(), } }); AddRepeatStep("change bottom rating", () => { changingStarRating.Current.Value = new StarDifficulty(RNG.NextDouble(0, 10), RNG.Next()); }, 10); } } }
Correct names for http verbs
//----------------------------------------------------------------------- // <copyright file="HttpVerb.cs" company="Bremus Solutions"> // Copyright (c) Bremus Solutions. All rights reserved. // </copyright> // <author>Timm Bremus</author> // <license> // Licensed to the Apache Software Foundation(ASF) under one // or more contributor license agreements.See the NOTICE file // distributed with this work for additional information // regarding copyright ownership.The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // </license> //----------------------------------------------------------------------- namespace BSolutions.Brecons.Core.Enumerations { using BSolutions.Brecons.Core.Attributes.Enumerations; public enum HttpVerb { [EnumInfo("get")] Get, [EnumInfo("Post")] Post, [EnumInfo("Put")] Put, [EnumInfo("Delete")] Delete } }
//----------------------------------------------------------------------- // <copyright file="HttpVerb.cs" company="Bremus Solutions"> // Copyright (c) Bremus Solutions. All rights reserved. // </copyright> // <author>Timm Bremus</author> // <license> // Licensed to the Apache Software Foundation(ASF) under one // or more contributor license agreements.See the NOTICE file // distributed with this work for additional information // regarding copyright ownership.The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // </license> //----------------------------------------------------------------------- namespace BSolutions.Brecons.Core.Enumerations { using BSolutions.Brecons.Core.Attributes.Enumerations; public enum HttpVerb { [EnumInfo("GET")] Get, [EnumInfo("POST")] Post, [EnumInfo("PUT")] Put, [EnumInfo("DELETE")] Delete } }
Mark the "Auto" variable scope as not expensive
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // namespace Microsoft.PowerShell.EditorServices.Protocol.DebugAdapter { public class Scope { /// <summary> /// Gets or sets the name of the scope (as such 'Arguments', 'Locals') /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets the variables of this scope can be retrieved by passing the /// value of variablesReference to the VariablesRequest. /// </summary> public int VariablesReference { get; set; } /// <summary> /// Gets or sets a boolean value indicating if number of variables in /// this scope is large or expensive to retrieve. /// </summary> public bool Expensive { get; set; } public static Scope Create(VariableScope scope) { return new Scope { Name = scope.Name, VariablesReference = scope.Id, // Temporary fix for #95 to get debug hover tips to work well at least for the local scope. Expensive = (scope.Name != VariableContainerDetails.LocalScopeName) }; } } }
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // namespace Microsoft.PowerShell.EditorServices.Protocol.DebugAdapter { public class Scope { /// <summary> /// Gets or sets the name of the scope (as such 'Arguments', 'Locals') /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets the variables of this scope can be retrieved by passing the /// value of variablesReference to the VariablesRequest. /// </summary> public int VariablesReference { get; set; } /// <summary> /// Gets or sets a boolean value indicating if number of variables in /// this scope is large or expensive to retrieve. /// </summary> public bool Expensive { get; set; } public static Scope Create(VariableScope scope) { return new Scope { Name = scope.Name, VariablesReference = scope.Id, // Temporary fix for #95 to get debug hover tips to work well at least for the local scope. Expensive = ((scope.Name != VariableContainerDetails.LocalScopeName) && (scope.Name != VariableContainerDetails.AutoVariablesName)) }; } } }
Add property to identity a Channel Notice
using System.Collections.Generic; namespace NetIRC.Messages { public class NoticeMessage : IRCMessage, IServerMessage, IClientMessage { public string From { get; } public string Target { get; } public string Message { get; } public NoticeMessage(ParsedIRCMessage parsedMessage) { From = parsedMessage.Prefix.From; Target = parsedMessage.Parameters[0]; Message = parsedMessage.Trailing; } public NoticeMessage(string target, string text) { Target = target; Message = text; } public IEnumerable<string> Tokens => new[] { "NOTICE", Target, Message }; } }
using System.Collections.Generic; namespace NetIRC.Messages { public class NoticeMessage : IRCMessage, IServerMessage, IClientMessage { public string From { get; } public string Target { get; } public string Message { get; } public NoticeMessage(ParsedIRCMessage parsedMessage) { From = parsedMessage.Prefix.From; Target = parsedMessage.Parameters[0]; Message = parsedMessage.Trailing; } public NoticeMessage(string target, string text) { Target = target; Message = text; } public bool IsChannelMessage => Target[0] == '#'; public IEnumerable<string> Tokens => new[] { "NOTICE", Target, Message }; } }
Add animation path curves to the debug component
using UnityEngine; using System.Collections; using ATP.AnimationPathTools; [ExecuteInEditMode] public class AnimationPathCurvesDebug : MonoBehaviour { private AnimationPathAnimator animator; [Header("Rotation curves")] public AnimationCurve curveX; public AnimationCurve curveY; public AnimationCurve curveZ; [Header("Ease curve")] public AnimationCurve easeCurve; // Use this for initialization void Awake() { } void OnEnable() { animator = GetComponent<AnimationPathAnimator>(); curveX = animator.RotationCurves[0]; curveY = animator.RotationCurves[1]; curveZ = animator.RotationCurves[2]; easeCurve = animator.EaseCurve; } void Start() { } // Update is called once per frame void Update() { } }
using UnityEngine; using System.Collections; using ATP.AnimationPathTools; [ExecuteInEditMode] public class AnimationPathCurvesDebug : MonoBehaviour { private AnimationPathAnimator animator; private AnimationPath animationPath; [Header("Animation Path")] public AnimationCurve pathCurveX; public AnimationCurve pathCurveY; public AnimationCurve pathCurveZ; [Header("Rotation curves")] public AnimationCurve rotationCurveX; public AnimationCurve rotationCurveY; public AnimationCurve rotationCurveZ; [Header("Ease curve")] public AnimationCurve easeCurve; // Use this for initialization void Awake() { } void OnEnable() { animator = GetComponent<AnimationPathAnimator>(); animationPath = GetComponent<AnimationPath>(); rotationCurveX = animator.RotationCurves[0]; rotationCurveY = animator.RotationCurves[1]; rotationCurveZ = animator.RotationCurves[2]; pathCurveX = animationPath.AnimationCurves[0]; pathCurveY = animationPath.AnimationCurves[1]; pathCurveZ = animationPath.AnimationCurves[2]; easeCurve = animator.EaseCurve; } void Start() { } // Update is called once per frame void Update() { } }
Make the monitor tool build again
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System.Reflection; using System.Runtime.CompilerServices; //[assembly: AssemblyVersion("0.0.0.*")] [assembly: AssemblyTitle ("NDesk.DBus")] [assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")] [assembly: AssemblyCopyright ("Copyright (C) Alp Toker")] [assembly: AssemblyCompany ("NDesk")] [assembly: InternalsVisibleTo ("NDesk.DBus.GLib, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")] //[assembly: InternalsVisibleTo ("dbus-monitor")] //[assembly: InternalsVisibleTo ("dbus-daemon")]
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System.Reflection; using System.Runtime.CompilerServices; //[assembly: AssemblyVersion("0.0.0.*")] [assembly: AssemblyTitle ("NDesk.DBus")] [assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")] [assembly: AssemblyCopyright ("Copyright (C) Alp Toker")] [assembly: AssemblyCompany ("NDesk")] [assembly: InternalsVisibleTo ("dbus-monitor, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")] [assembly: InternalsVisibleTo ("NDesk.DBus.GLib, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
Move Settings tab just after OfflinePayment settings
using Orchard.Localization; using Orchard.UI.Navigation; using OShop.Permissions; namespace OShop.PayPal.Navigation { public class AdminMenu : INavigationProvider { public Localizer T { get; set; } public AdminMenu() { T = NullLocalizer.Instance; } public string MenuName { get { return "admin"; } } public void GetNavigation(NavigationBuilder builder) { builder .AddImageSet("oshop") .Add(menu => menu .Caption(T("OShop")) .Add(subMenu => subMenu .Caption(T("Settings")) .Add(tab => tab .Caption(T("PayPal")) .Position("7") .Action("Settings", "Admin", new { area = "OShop.PayPal" }) .Permission(OShopPermissions.ManageShopSettings) .LocalNav() ) ) ); } } }
using Orchard.Localization; using Orchard.UI.Navigation; using OShop.Permissions; namespace OShop.PayPal.Navigation { public class AdminMenu : INavigationProvider { public Localizer T { get; set; } public AdminMenu() { T = NullLocalizer.Instance; } public string MenuName { get { return "admin"; } } public void GetNavigation(NavigationBuilder builder) { builder .AddImageSet("oshop") .Add(menu => menu .Caption(T("OShop")) .Add(subMenu => subMenu .Caption(T("Settings")) .Add(tab => tab .Caption(T("PayPal")) .Position("7.1") .Action("Settings", "Admin", new { area = "OShop.PayPal" }) .Permission(OShopPermissions.ManageShopSettings) .LocalNav() ) ) ); } } }
Check if image is supported before uploading in the validation tag
using ImageSharp; using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; using System.Linq; namespace CollAction.ValidationAttributes { public class MaxImageDimensionsAttribute : ValidationAttribute { private readonly int _maxWidth; private readonly int _maxHeight; public MaxImageDimensionsAttribute(int width, int height) { _maxWidth = width; _maxHeight = height; } public override bool IsValid(object value) { if (value == null) return true; using (Stream imageStream = (value as IFormFile).OpenReadStream()) { using (MemoryStream ms = new MemoryStream()) { imageStream.CopyTo(ms); using (Image image = Image.Load(ms.ToArray())) { return image.Width <= _maxWidth && image.Height <= _maxHeight; } } } } public override string FormatErrorMessage(string name) { return string.Format("Only images with dimensions of or smaller than {0}x{1}px are accepted.", _maxWidth, _maxHeight); } } }
using ImageSharp; using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; using System.Linq; namespace CollAction.ValidationAttributes { public class MaxImageDimensionsAttribute : ValidationAttribute { private readonly int _maxWidth; private readonly int _maxHeight; public MaxImageDimensionsAttribute(int width, int height) { _maxWidth = width; _maxHeight = height; } public override bool IsValid(object value) { if (value == null) return true; using (Stream imageStream = (value as IFormFile).OpenReadStream()) { using (MemoryStream ms = new MemoryStream()) { imageStream.CopyTo(ms); try { using (Image image = Image.Load(ms.ToArray())) { return image.Width <= _maxWidth && image.Height <= _maxHeight; } } catch (NotSupportedException) { return false; } } } } public override string FormatErrorMessage(string name) { return string.Format("Only images with dimensions of or smaller than {0}x{1}px are accepted.", _maxWidth, _maxHeight); } } }
Implement random walk for 3D
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace RandomWalkConsole { class Program { static void Main(string[] args) { var unfinished = Enumerable.Range(0, 1000) .Select(_ => Walk2()) .Aggregate(0, (u, t) => u + (t.HasValue ? 0 : 1)); Console.WriteLine(unfinished); } static readonly Random random = new Random(); static readonly Int32Vector3[] Directions2 = new[] { Int32Vector3.XBasis, Int32Vector3.YBasis, -Int32Vector3.XBasis, -Int32Vector3.YBasis }; static int? Walk2() { var current = Int32Vector3.Zero; for (var i = 1; i <= 1000000; i++) { current += Directions2[random.Next(0, Directions2.Length)]; if (current == Int32Vector3.Zero) return i; } Console.WriteLine(current); return null; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using static System.Console; using static System.Math; namespace RandomWalkConsole { class Program { const int Trials = 1 * 1000; const int MaxSteps = 100 * 1000 * 1000; const int MaxDistance = 10 * 1000; static void Main(string[] args) { var returned = Enumerable.Range(0, Trials) .Select(_ => Walk(Directions2)) .Aggregate(0, (u, t) => u + (t.HasValue ? 1 : 0)); WriteLine($"Returned Rate: {(double)returned / Trials}"); } static readonly Random random = new Random(); static readonly Int32Vector3[] Directions2 = new[] { Int32Vector3.XBasis, Int32Vector3.YBasis, -Int32Vector3.XBasis, -Int32Vector3.YBasis }; static readonly Int32Vector3[] Directions3 = new[] { Int32Vector3.XBasis, Int32Vector3.YBasis, Int32Vector3.ZBasis, -Int32Vector3.XBasis, -Int32Vector3.YBasis, -Int32Vector3.ZBasis }; static int? Walk(Int32Vector3[] directions) { var current = Int32Vector3.Zero; for (var i = 1; i <= MaxSteps; i++) { current += directions[random.Next(0, directions.Length)]; if (current == Int32Vector3.Zero) { WriteLine($"{i:N0}"); return i; } else if (Abs(current.X) >= MaxDistance || Abs(current.Y) >= MaxDistance || Abs(current.Z) >= MaxDistance) { WriteLine(current); return null; } } WriteLine(current); return null; } } }
Fix incorrect hit object type.
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; namespace osu.Game.Modes.Objects.Types { [Flags] public enum HitObjectType { Circle = 1 << 0, Slider = 1 << 1, NewCombo = 1 << 2, Spinner = 1 << 3, ColourHax = 122, Hold = 1 << 7, SliderTick = 1 << 8, } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; namespace osu.Game.Modes.Objects.Types { [Flags] public enum HitObjectType { Circle = 1 << 0, Slider = 1 << 1, NewCombo = 1 << 2, Spinner = 1 << 3, ColourHax = 112, Hold = 1 << 7 } }
Add a test to confirm down migrations are run in reverse order of up migrations
using NUnit.Framework; using FluentMigrator.Infrastructure; namespace FluentMigrator.Tests.Unit { using System.Collections.ObjectModel; using System.Linq; using FluentMigrator.Expressions; using Moq; [TestFixture] public class AutoReversingMigrationTests { private Mock<IMigrationContext> context; [SetUp] public void SetUp() { context = new Mock<IMigrationContext>(); context.SetupAllProperties(); } [Test] public void CreateTableUpAutoReversingMigrationGivesDeleteTableDown() { var autoReversibleMigration = new TestAutoReversingMigrationCreateTable(); context.Object.Expressions = new Collection<IMigrationExpression>(); autoReversibleMigration.GetDownExpressions(context.Object); Assert.True(context.Object.Expressions.Any(me => me is DeleteTableExpression && ((DeleteTableExpression)me).TableName == "Foo")); } } internal class TestAutoReversingMigrationCreateTable : AutoReversingMigration { public override void Up() { Create.Table("Foo"); } } }
using NUnit.Framework; using FluentMigrator.Infrastructure; namespace FluentMigrator.Tests.Unit { using System.Collections.ObjectModel; using System.Linq; using FluentMigrator.Expressions; using Moq; [TestFixture] public class AutoReversingMigrationTests { private Mock<IMigrationContext> context; [SetUp] public void SetUp() { context = new Mock<IMigrationContext>(); context.SetupAllProperties(); } [Test] public void CreateTableUpAutoReversingMigrationGivesDeleteTableDown() { var autoReversibleMigration = new TestAutoReversingMigrationCreateTable(); context.Object.Expressions = new Collection<IMigrationExpression>(); autoReversibleMigration.GetDownExpressions(context.Object); Assert.True(context.Object.Expressions.Any(me => me is DeleteTableExpression && ((DeleteTableExpression)me).TableName == "Foo")); } [Test] public void DownMigrationsAreInReverseOrderOfUpMigrations() { var autoReversibleMigration = new TestAutoReversingMigrationCreateTable(); context.Object.Expressions = new Collection<IMigrationExpression>(); autoReversibleMigration.GetDownExpressions(context.Object); Assert.IsAssignableFrom(typeof(RenameTableExpression), context.Object.Expressions.ToList()[0]); Assert.IsAssignableFrom(typeof(DeleteTableExpression), context.Object.Expressions.ToList()[1]); } } internal class TestAutoReversingMigrationCreateTable : AutoReversingMigration { public override void Up() { Create.Table("Foo"); Rename.Table("Foo").InSchema("FooSchema").To("Bar"); } } }
Change Pad-Palettes behavior to be more like the old version.
using LibPixelPet; using System; namespace PixelPet.CLI.Commands { internal class PadPalettesCmd : CliCommand { public PadPalettesCmd() : base("Pad-Palettes", new Parameter(true, new ParameterValue("width", "0")) ) { } public override void Run(Workbench workbench, ILogger logger) { int width = FindUnnamedParameter(0).Values[0].ToInt32(); if (width < 1) { logger?.Log("Invalid palette width.", LogLevel.Error); return; } int addedColors = 0; foreach (PaletteEntry pe in workbench.PaletteSet) { while (pe.Palette.Count % width != 0) { pe.Palette.Add(0); addedColors++; } } logger?.Log("Padded palettes to width " + width + " (added " + addedColors + " colors).", LogLevel.Information); } } }
using LibPixelPet; using System; namespace PixelPet.CLI.Commands { internal class PadPalettesCmd : CliCommand { public PadPalettesCmd() : base("Pad-Palettes", new Parameter(true, new ParameterValue("width", "0")) ) { } public override void Run(Workbench workbench, ILogger logger) { int width = FindUnnamedParameter(0).Values[0].ToInt32(); if (width < 1) { logger?.Log("Invalid palette width.", LogLevel.Error); return; } if (workbench.PaletteSet.Count == 0) { logger?.Log("No palettes to pad. Creating 1 palette based on current bitmap format.", LogLevel.Information); Palette pal = new Palette(workbench.BitmapFormat, -1); workbench.PaletteSet.Add(pal); } int addedColors = 0; foreach (PaletteEntry pe in workbench.PaletteSet) { while (pe.Palette.Count < width) { pe.Palette.Add(0); addedColors++; } } logger?.Log("Padded palettes to width " + width + " (added " + addedColors + " colors).", LogLevel.Information); } } }
Add LocationViewTypes repo to unit of work
///////////////////////////////////////////////////////////////// // Created by : Caesar Moussalli // // TimeStamp : 31-1-2016 // // Content : Associate Repositories to the Unit of Work // // Notes : Send DB context to repositories to reduce DB // // connectivity sessions count // ///////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DynThings.Data.Models; namespace DynThings.Data.Repositories { public static class UnitOfWork { #region Repositories public static LocationViewsRepository repoLocationViews = new LocationViewsRepository(); public static LocationsRepository repoLocations = new LocationsRepository(); public static EndpointsRepository repoEndpoints = new EndpointsRepository(); public static EndpointIOsRepository repoEndpointIOs = new EndpointIOsRepository(); public static EndPointTypesRepository repoEndpointTypes = new EndPointTypesRepository(); public static DevicesRepositories repoDevices = new DevicesRepositories(); #endregion #region Enums public enum RepositoryMethodResultType { Ok = 1, Failed = 2 } #endregion } }
///////////////////////////////////////////////////////////////// // Created by : Caesar Moussalli // // TimeStamp : 31-1-2016 // // Content : Associate Repositories to the Unit of Work // // Notes : Send DB context to repositories to reduce DB // // connectivity sessions count // ///////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DynThings.Data.Models; namespace DynThings.Data.Repositories { public static class UnitOfWork { #region Repositories public static LocationViewsRepository repoLocationViews = new LocationViewsRepository(); public static LocationViewTypesRepository repoLocationViewTypes = new LocationViewTypesRepository(); public static LocationsRepository repoLocations = new LocationsRepository(); public static EndpointsRepository repoEndpoints = new EndpointsRepository(); public static EndpointIOsRepository repoEndpointIOs = new EndpointIOsRepository(); public static EndPointTypesRepository repoEndpointTypes = new EndPointTypesRepository(); public static DevicesRepositories repoDevices = new DevicesRepositories(); #endregion #region Enums public enum RepositoryMethodResultType { Ok = 1, Failed = 2 } #endregion } }
Make sure daemon password console works on Windows 7
using System; using System.Collections.Generic; using System.Text; namespace WalletWasabi.Helpers { public static class PasswordConsole { /// <summary> /// Gets the console password. /// </summary> public static string ReadPassword() { var sb = new StringBuilder(); while (true) { ConsoleKeyInfo cki = Console.ReadKey(true); if (cki.Key == ConsoleKey.Enter) { Console.WriteLine(); break; } if (cki.Key == ConsoleKey.Backspace) { if (sb.Length > 0) { Console.Write("\b \b"); sb.Length--; } continue; } Console.Write('*'); sb.Append(cki.KeyChar); } return sb.ToString(); } } }
using System; using System.Collections.Generic; using System.Text; namespace WalletWasabi.Helpers { public static class PasswordConsole { /// <summary> /// Gets the console password. /// </summary> public static string ReadPassword() { try { var sb = new StringBuilder(); while (true) { ConsoleKeyInfo cki = Console.ReadKey(true); if (cki.Key == ConsoleKey.Enter) { Console.WriteLine(); break; } if (cki.Key == ConsoleKey.Backspace) { if (sb.Length > 0) { Console.Write("\b \b"); sb.Length--; } continue; } Console.Write('*'); sb.Append(cki.KeyChar); } return sb.ToString(); } catch (InvalidOperationException) { return Console.ReadLine(); } } } }
Remove never-run code in WriteHost.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Management.Automation; using Extensions.String; namespace Microsoft.PowerShell.Commands.Utility { [Cmdlet("Write", "Host")] public sealed class WriteHostCommand : ConsoleColorCmdlet { [Parameter(Position = 0, ValueFromRemainingArguments = true, ValueFromPipeline = true)] public PSObject Object { get; set; } [Parameter] public SwitchParameter NoNewline { get; set; } [Parameter] public Object Separator { get; set; } protected override void ProcessRecord() { Action<ConsoleColor, ConsoleColor, string> writeAction; if (NoNewline) writeAction = Host.UI.Write; else writeAction = Host.UI.WriteLine; if (Object == null) { writeAction(ForegroundColor, BackgroundColor, ""); } else if (Object.BaseObject is Enumerable) { throw new NotImplementedException(); } else { writeAction(ForegroundColor, BackgroundColor, Object.ToString()); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Management.Automation; using Extensions.String; using System.Collections; namespace Microsoft.PowerShell.Commands.Utility { [Cmdlet("Write", "Host")] public sealed class WriteHostCommand : ConsoleColorCmdlet { [Parameter(Position = 0, ValueFromRemainingArguments = true, ValueFromPipeline = true)] public PSObject Object { get; set; } [Parameter] public SwitchParameter NoNewline { get; set; } [Parameter] public Object Separator { get; set; } protected override void ProcessRecord() { Action<ConsoleColor, ConsoleColor, string> writeAction; if (NoNewline) writeAction = Host.UI.Write; else writeAction = Host.UI.WriteLine; if (Object == null) { writeAction(ForegroundColor, BackgroundColor, ""); } else { writeAction(ForegroundColor, BackgroundColor, Object.ToString()); } } } }
Add filter property to most collected movies request.
namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common { using Base.Get; using Enums; using Objects.Basic; using Objects.Get.Movies.Common; using System.Collections.Generic; internal class TraktMoviesMostCollectedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostCollectedMovie>, TraktMostCollectedMovie> { internal TraktMoviesMostCollectedRequest(TraktClient client) : base(client) { Period = TraktPeriod.Weekly; } internal TraktPeriod? Period { get; set; } protected override IDictionary<string, object> GetUriPathParameters() { var uriParams = base.GetUriPathParameters(); if (Period.HasValue && Period.Value != TraktPeriod.Unspecified) uriParams.Add("period", Period.Value.AsString()); return uriParams; } protected override string UriTemplate => "movies/collected{/period}{?extended,page,limit}"; protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired; protected override bool SupportsPagination => true; protected override bool IsListResult => true; } }
namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common { using Base; using Base.Get; using Enums; using Objects.Basic; using Objects.Get.Movies.Common; using System.Collections.Generic; internal class TraktMoviesMostCollectedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostCollectedMovie>, TraktMostCollectedMovie> { internal TraktMoviesMostCollectedRequest(TraktClient client) : base(client) { Period = TraktPeriod.Weekly; } internal TraktPeriod? Period { get; set; } protected override IDictionary<string, object> GetUriPathParameters() { var uriParams = base.GetUriPathParameters(); if (Period.HasValue && Period.Value != TraktPeriod.Unspecified) uriParams.Add("period", Period.Value.AsString()); return uriParams; } protected override string UriTemplate => "movies/collected{/period}{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications}"; protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired; internal TraktMovieFilter Filter { get; set; } protected override bool SupportsPagination => true; protected override bool IsListResult => true; } }
Update wear command to work with the new appearance maanger.
using System; using OpenMetaverse; namespace OpenMetaverse.TestClient { public class WearCommand : Command { public WearCommand(TestClient testClient) { Client = testClient; Name = "wear"; Description = "Wear an outfit folder from inventory. Usage: wear [outfit name] [nobake]"; Category = CommandCategory.Appearance; } public override string Execute(string[] args, UUID fromAgentID) { if (args.Length < 1) return "Usage: wear [outfit name] eg: 'wear /My Outfit/Dance Party"; string target = String.Empty; bool bake = true; for (int ct = 0; ct < args.Length; ct++) { if (args[ct].Equals("nobake")) bake = false; else target = target + args[ct] + " "; } target = target.TrimEnd(); //Client.Appearance.WearOutfit(target.Split('/'), bake); return "FIXME: Implement this"; } } }
using System; using System.Collections.Generic; using OpenMetaverse; namespace OpenMetaverse.TestClient { public class WearCommand : Command { public WearCommand(TestClient testClient) { Client = testClient; Name = "wear"; Description = "Wear an outfit folder from inventory. Usage: wear [outfit name]"; Category = CommandCategory.Appearance; } public override string Execute(string[] args, UUID fromAgentID) { if (args.Length < 1) return "Usage: wear [outfit name] eg: 'wear Clothing/My Outfit"; string target = String.Empty; for (int ct = 0; ct < args.Length; ct++) { target += args[ct] + " "; } target = target.TrimEnd(); UUID folder = Client.Inventory.FindObjectByPath(Client.Inventory.Store.RootFolder.UUID, Client.Self.AgentID, target, 20 * 1000); if (folder == UUID.Zero) { return "Outfit path " + target + " not found"; } List<InventoryBase> contents = Client.Inventory.FolderContents(folder, Client.Self.AgentID, true, true, InventorySortOrder.ByName, 20 * 1000); List<InventoryItem> items = new List<InventoryItem>(); if (contents == null) { return "Failed to get contents of " + target; } foreach (InventoryBase item in contents) { if (item is InventoryItem) items.Add((InventoryItem)item); } Client.Appearance.ReplaceOutfit(items); return "Starting to change outfit to " + target; } } }
Add correct guid/date generation for messages
using System; namespace Glimpse { public class BaseMessage : IMessage { public BaseMessage() { Id = new Guid(); Time = new DateTime(); } public Guid Id { get; } public DateTime Time { get; } } }
using System; namespace Glimpse { public class BaseMessage : IMessage { public BaseMessage() { Id = Guid.NewGuid(); Time = DateTime.Now; } public Guid Id { get; } public DateTime Time { get; } } }
Remove unused code & add comment
using System; using System.Net.Http; namespace Glimpse.Agent { public class RemoteHttpMessagePublisher : IMessagePublisher, IDisposable { private readonly HttpClient _httpClient; private readonly HttpClientHandler _httpHandler; public RemoteHttpMessagePublisher() { _httpHandler = new HttpClientHandler(); _httpClient = new HttpClient(_httpHandler); } public void PublishMessage(IMessage message) { var content = new StringContent("Hello"); // TODO: Try shifting to async and await // TODO: Find out what happened to System.Net.Http.Formmating - PostAsJsonAsync _httpClient.PostAsJsonAsync("http://localhost:15999/Glimpse/Agent", message) .ContinueWith(requestTask => { // Get HTTP response from completed task. HttpResponseMessage response = requestTask.Result; // Check that response was successful or throw exception response.EnsureSuccessStatusCode(); // Read response asynchronously as JsonValue and write out top facts for each country var result = response.Content.ReadAsStringAsync().Result; }); } public void Dispose() { _httpClient.Dispose(); _httpHandler.Dispose(); } } }
using System; using System.Net.Http; namespace Glimpse.Agent { public class RemoteHttpMessagePublisher : IMessagePublisher, IDisposable { private readonly HttpClient _httpClient; private readonly HttpClientHandler _httpHandler; public RemoteHttpMessagePublisher() { _httpHandler = new HttpClientHandler(); _httpClient = new HttpClient(_httpHandler); } public void PublishMessage(IMessage message) { // TODO: Try shifting to async and await // TODO: Needs error handelling // TODO: Find out what happened to System.Net.Http.Formmating - PostAsJsonAsync _httpClient.PostAsJsonAsync("http://localhost:15999/Glimpse/Agent", message) .ContinueWith(requestTask => { // Get HTTP response from completed task. HttpResponseMessage response = requestTask.Result; // Check that response was successful or throw exception response.EnsureSuccessStatusCode(); // Read response asynchronously as JsonValue and write out top facts for each country var result = response.Content.ReadAsStringAsync().Result; }); } public void Dispose() { _httpClient.Dispose(); _httpHandler.Dispose(); } } }
Set Geolocator to accuracy of 500m, 5min age and 10 second timeout
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using Windows.Devices.Geolocation; using AirQualityInfo.DataClient.Models; using AirQualityInfo.DataClient.Services; namespace AirQualityInfo.WP.Services { // http://msdn.microsoft.com/en-us/library/windows/apps/hh465148.aspx public class LocationService : ILocationService { public async Task<LocationResult> GetCurrentPosition() { try { var geolocator = new Geolocator() { DesiredAccuracyInMeters = 50 }; Geoposition pos = await geolocator.GetGeopositionAsync( maximumAge: TimeSpan.FromMinutes(1), timeout: TimeSpan.FromSeconds(10) ); return new LocationResult(new GeoCoordinate(pos.Coordinate.Latitude, pos.Coordinate.Longitude)); } catch (UnauthorizedAccessException) { return new LocationResult("Die aktuelle Position ist zur Berechnung der Distanz zur Messstation notwendig, Zugriff wurde verweigert."); } catch (Exception) { } return new LocationResult("Aktuelle Position konnte nicht ermittelt werden"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using Windows.Devices.Geolocation; using AirQualityInfo.DataClient.Models; using AirQualityInfo.DataClient.Services; namespace AirQualityInfo.WP.Services { // http://msdn.microsoft.com/en-us/library/windows/apps/hh465148.aspx public class LocationService : ILocationService { public async Task<LocationResult> GetCurrentPosition() { try { var geolocator = new Geolocator() { DesiredAccuracyInMeters = 500 }; Geoposition pos = await geolocator.GetGeopositionAsync( maximumAge: TimeSpan.FromMinutes(5), timeout: TimeSpan.FromSeconds(10) ); return new LocationResult(new GeoCoordinate(pos.Coordinate.Latitude, pos.Coordinate.Longitude)); } catch (UnauthorizedAccessException) { return new LocationResult("Die aktuelle Position ist zur Berechnung der Distanz zur Messstation notwendig, Zugriff wurde verweigert."); } catch (Exception) { } return new LocationResult("Aktuelle Position konnte nicht ermittelt werden"); } } }
Fix crash with legacy import from incomplete installs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using System.Collections.Generic; using System.Linq; using osu.Framework.IO.Stores; using osu.Framework.Platform; using osu.Game.Beatmaps; using osu.Game.IO; namespace osu.Game.Database { public class LegacyBeatmapImporter : LegacyModelImporter<BeatmapSetInfo> { protected override string ImportFromStablePath => "."; protected override Storage PrepareStableStorage(StableStorage stableStorage) => stableStorage.GetSongStorage(); protected override IEnumerable<string> GetStableImportPaths(Storage storage) { foreach (string directory in storage.GetDirectories(string.Empty)) { var directoryStorage = storage.GetStorageForDirectory(directory); if (!directoryStorage.GetFiles(string.Empty).ExcludeSystemFileNames().Any()) { // if a directory doesn't contain files, attempt looking for beatmaps inside of that directory. // this is a special behaviour in stable for beatmaps only, see https://github.com/ppy/osu/issues/18615. foreach (string subDirectory in GetStableImportPaths(directoryStorage)) yield return subDirectory; } else yield return storage.GetFullPath(directory); } } public LegacyBeatmapImporter(IModelImporter<BeatmapSetInfo> importer) : base(importer) { } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using System.Collections.Generic; using System.Linq; using osu.Framework.IO.Stores; using osu.Framework.Platform; using osu.Game.Beatmaps; using osu.Game.IO; namespace osu.Game.Database { public class LegacyBeatmapImporter : LegacyModelImporter<BeatmapSetInfo> { protected override string ImportFromStablePath => "."; protected override Storage PrepareStableStorage(StableStorage stableStorage) => stableStorage.GetSongStorage(); protected override IEnumerable<string> GetStableImportPaths(Storage storage) { // make sure the directory exists if (!storage.ExistsDirectory(string.Empty)) yield break; foreach (string directory in storage.GetDirectories(string.Empty)) { var directoryStorage = storage.GetStorageForDirectory(directory); if (!directoryStorage.GetFiles(string.Empty).ExcludeSystemFileNames().Any()) { // if a directory doesn't contain files, attempt looking for beatmaps inside of that directory. // this is a special behaviour in stable for beatmaps only, see https://github.com/ppy/osu/issues/18615. foreach (string subDirectory in GetStableImportPaths(directoryStorage)) yield return subDirectory; } else yield return storage.GetFullPath(directory); } } public LegacyBeatmapImporter(IModelImporter<BeatmapSetInfo> importer) : base(importer) { } } }
Remove "Default" from Destination VNet for migration
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; namespace Microsoft.WindowsAzure.Management.Compute.Models { /// <summary> /// Known values for Destination Virtual Network. /// </summary> public static partial class DestinationVirtualNetwork { public const string Default = "Default"; public const string New = "New"; public const string Existing = "Existing"; } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; namespace Microsoft.WindowsAzure.Management.Compute.Models { /// <summary> /// Known values for Destination Virtual Network. /// </summary> public static partial class DestinationVirtualNetwork { public const string New = "New"; public const string Existing = "Existing"; } }
Use AssemblyName to portably obtain version number
using System.Reflection; namespace EvilDICOM.Core.Helpers { public static class Constants { public static string EVIL_DICOM_IMP_UID = "1.2.598.0.1.2851334.2.1865.1"; public static string EVIL_DICOM_IMP_VERSION = Assembly.GetCallingAssembly().GetName().Version.ToString(); //APPLICATION CONTEXT public static string DEFAULT_APPLICATION_CONTEXT = "1.2.840.10008.3.1.1.1"; } }
using System.Reflection; namespace EvilDICOM.Core.Helpers { public static class Constants { public static string EVIL_DICOM_IMP_UID = "1.2.598.0.1.2851334.2.1865.1"; public static string EVIL_DICOM_IMP_VERSION = new AssemblyName(Assembly.GetCallingAssembly().FullName).Version.ToString(); //APPLICATION CONTEXT public static string DEFAULT_APPLICATION_CONTEXT = "1.2.840.10008.3.1.1.1"; } }
Remove 0.75 scale from osu! playfield in the editor
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics.Cursor; using osu.Game.Beatmaps; using osu.Game.Rulesets.Osu.UI; using osu.Game.Rulesets.UI; namespace osu.Game.Rulesets.Osu.Edit { public class OsuEditRulesetContainer : OsuRulesetContainer { public OsuEditRulesetContainer(Ruleset ruleset, WorkingBeatmap beatmap, bool isForCurrentRuleset) : base(ruleset, beatmap, isForCurrentRuleset) { } protected override Playfield CreatePlayfield() => new OsuEditPlayfield(); protected override CursorContainer CreateCursor() => null; } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics.Cursor; using osu.Game.Beatmaps; using osu.Game.Rulesets.Osu.UI; using osu.Game.Rulesets.UI; using OpenTK; namespace osu.Game.Rulesets.Osu.Edit { public class OsuEditRulesetContainer : OsuRulesetContainer { public OsuEditRulesetContainer(Ruleset ruleset, WorkingBeatmap beatmap, bool isForCurrentRuleset) : base(ruleset, beatmap, isForCurrentRuleset) { } protected override Playfield CreatePlayfield() => new OsuEditPlayfield(); protected override Vector2 GetAspectAdjustedSize() { var aspectSize = DrawSize.X * 0.75f < DrawSize.Y ? new Vector2(DrawSize.X, DrawSize.X * 0.75f) : new Vector2(DrawSize.Y * 4f / 3f, DrawSize.Y); return new Vector2(aspectSize.X / DrawSize.X, aspectSize.Y / DrawSize.Y); } protected override CursorContainer CreateCursor() => null; } }
Implement a simple executor that just reads the file directly
using System.Diagnostics; using System.IO; using System.Reflection; namespace DanTup.TestAdapters.Xml { public class XmlExternalTestExecutor : ExternalTestExecutor { static readonly string extensionFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); public override string ExtensionFolder { get { return extensionFolder; } } static readonly string luaExecutable = Path.Combine(extensionFolder, "lua52.exe"); static readonly string testFrameworkFile = Path.Combine(extensionFolder, "TestFramework.lua"); protected override ProcessStartInfo CreateProcessStartInfo(string source, string args) { args = string.Format("\"{0}\" \"{1}\" {2}", testFrameworkFile.Replace("\"", "\\\""), source.Replace("\"", "\\\""), args); return new ProcessStartInfo(luaExecutable, args) { WorkingDirectory = Path.GetDirectoryName(source), UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; } } }
using System; using System.Collections.Generic; using System.IO; using System.Reflection; namespace DanTup.TestAdapters.Xml { public class XmlExternalTestExecutor : ExternalTestExecutor { static readonly string extensionFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); public override string ExtensionFolder { get { return extensionFolder; } } /// <summary> /// Reads the results XML file directly. /// </summary> public override IEnumerable<GenericTest> GetTestCases(string source, Action<string> logger) { return ParseTestOutput(File.ReadAllText(source)); } /// <summary> /// Reads the results XML file directly. /// </summary> public override IEnumerable<GenericTest> GetTestResults(string source, Action<string> logger) { return ParseTestOutput(File.ReadAllText(source)); } } }
Add typing state to inspiro command
using Discord; using Discord.Commands; using NadekoBot.Extensions; using Newtonsoft.Json; using System.Net.Http; using System.Threading.Tasks; using NadekoBot.Common; using NadekoBot.Common.Attributes; namespace NadekoBot.Modules.Searches { public partial class Searches { [Group] public class InspiroCommands : NadekoSubmodule { private const string _xkcdUrl = "https://xkcd.com"; private readonly IHttpClientFactory _httpFactory; public InspiroCommands(IHttpClientFactory factory) { _httpFactory = factory; } [NadekoCommand, Usage, Description, Aliases] [Priority(0)] public async Task Inspiro() { using (var http = _httpFactory.CreateClient()) { var response = await http.GetStringAsync("http://inspirobot.me/api?generate=true").ConfigureAwait(false); if (response == null || string.IsNullOrWhiteSpace(response)) return; await ctx.Channel.EmbedAsync(new EmbedBuilder() .WithOkColor() .WithImageUrl(response) .WithDescription(response.Replace(@"https://generated.inspirobot.me/", @"http://inspirobot.me/share?iuid="))); } } } } }
using Discord; using Discord.Commands; using NadekoBot.Extensions; using Newtonsoft.Json; using System.Net.Http; using System.Threading.Tasks; using NadekoBot.Common; using NadekoBot.Common.Attributes; namespace NadekoBot.Modules.Searches { public partial class Searches { [Group] public class InspiroCommands : NadekoSubmodule { private readonly IHttpClientFactory _httpFactory; public InspiroCommands(IHttpClientFactory factory) { _httpFactory = factory; } [NadekoCommand, Usage, Description, Aliases] [Priority(0)] public async Task Inspiro() { using (ctx.Channel.EnterTypingState()) { using (var http = _httpFactory.CreateClient()) { var response = await http.GetStringAsync("http://inspirobot.me/api?generate=true").ConfigureAwait(false); if (response == null || string.IsNullOrWhiteSpace(response)) return; await ctx.Channel.EmbedAsync(new EmbedBuilder() .WithOkColor() .WithImageUrl(response) .WithDescription(response.Replace(@"https://generated.inspirobot.me/", @"http://inspirobot.me/share?iuid="))); } } } } } }
Remove extraneous info in assembly info
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 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("Eto.Platform.Wpf")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Picoe")] [assembly: AssemblyProduct("Eto.Platform.Wpf")] [assembly: AssemblyCopyright("Copyright © Curtis Wensley 2012")] [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("256ea788-fb5e-46b1-a4f3-acad21c1fbbf")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: ThemeInfo ( ResourceDictionaryLocation.SourceAssembly, ResourceDictionaryLocation.SourceAssembly )]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; [assembly: AssemblyTitle("Eto.Platform.Wpf")] [assembly: AssemblyDescription("")] [assembly: ThemeInfo ( ResourceDictionaryLocation.SourceAssembly, ResourceDictionaryLocation.SourceAssembly )]
Hide the Manage Content admin menu item
using System.Linq; using Orchard.ContentManagement; using Orchard.ContentManagement.MetaData; using Orchard.Localization; using Orchard.UI.Navigation; namespace Orchard.Core.Contents { public class AdminMenu : INavigationProvider { private readonly IContentDefinitionManager _contentDefinitionManager; private readonly IContentManager _contentManager; public AdminMenu(IContentDefinitionManager contentDefinitionManager, IContentManager contentManager) { _contentDefinitionManager = contentDefinitionManager; _contentManager = contentManager; } public Localizer T { get; set; } public string MenuName { get { return "admin"; } } public void GetNavigation(NavigationBuilder builder) { var contentTypeDefinitions = _contentDefinitionManager.ListTypeDefinitions().OrderBy(d => d.Name); builder.Add(T("Content"), "1", menu => { menu.Add(T("Manage Content"), "1.2", item => item.Action("List", "Admin", new {area = "Orchard.ContentTypes"})); //foreach (var contentTypeDefinition in contentTypeDefinitions) { // var ci = _contentManager.New(contentTypeDefinition.Name); // var cim = _contentManager.GetItemMetadata(ci); // var createRouteValues = cim.CreateRouteValues; // if (createRouteValues.Any()) // menu.Add(T("Create New {0}", contentTypeDefinition.DisplayName), "1.3", item => item.Action(cim.CreateRouteValues["Action"] as string, cim.CreateRouteValues["Controller"] as string, cim.CreateRouteValues)); //} }); } } }
using System.Linq; using Orchard.ContentManagement; using Orchard.ContentManagement.MetaData; using Orchard.Localization; using Orchard.UI.Navigation; namespace Orchard.Core.Contents { public class AdminMenu : INavigationProvider { private readonly IContentDefinitionManager _contentDefinitionManager; private readonly IContentManager _contentManager; public AdminMenu(IContentDefinitionManager contentDefinitionManager, IContentManager contentManager) { _contentDefinitionManager = contentDefinitionManager; _contentManager = contentManager; } public Localizer T { get; set; } public string MenuName { get { return "admin"; } } public void GetNavigation(NavigationBuilder builder) { //var contentTypeDefinitions = _contentDefinitionManager.ListTypeDefinitions().OrderBy(d => d.Name); //builder.Add(T("Content"), "1", menu => { // menu.Add(T("Manage Content"), "1.2", item => item.Action("List", "Admin", new {area = "Orchard.ContentTypes"})); //foreach (var contentTypeDefinition in contentTypeDefinitions) { // var ci = _contentManager.New(contentTypeDefinition.Name); // var cim = _contentManager.GetItemMetadata(ci); // var createRouteValues = cim.CreateRouteValues; // if (createRouteValues.Any()) // menu.Add(T("Create New {0}", contentTypeDefinition.DisplayName), "1.3", item => item.Action(cim.CreateRouteValues["Action"] as string, cim.CreateRouteValues["Controller"] as string, cim.CreateRouteValues)); //} //}); } } }
Remove old red 1 reference
using BatteryCommander.Web.Models; using BatteryCommander.Web.Models.Reports; using BatteryCommander.Web.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers { [Authorize, ApiExplorerSettings(IgnoreApi = true)] public class ReportsController : Controller { private readonly Database db; public ReportsController(Database db) { this.db = db; } // Generate HTML/PDF version // Email to configurable address on request / on schedule // GREEN 3 -- Sensitive Items // CONVOY MANIFEST? // TAN 1 -- Comstat // YELLOW 1 -- LOGSTAT public async Task<IActionResult> Red1(SoldierService.Query query) { var model = new Red1_Perstat { Soldiers = await SoldierService.Filter(db, query) }; return Json(model); } public async Task<IActionResult> SadPerstat(SoldierService.Query query) { var model = new StateActiveDuty_Perstat { Soldiers = await SoldierService.Filter(db, query) }; return Json(model); } public async Task<IActionResult> DscaReady() { var soldiers = await SoldierService.Filter(db, new SoldierService.Query { IWQ = true, DSCA = true }); return View(soldiers); } } }
using BatteryCommander.Web.Models; using BatteryCommander.Web.Models.Reports; using BatteryCommander.Web.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers { [Authorize, ApiExplorerSettings(IgnoreApi = true)] public class ReportsController : Controller { private readonly Database db; public ReportsController(Database db) { this.db = db; } // TAN 1 -- Comstat // YELLOW 1 -- LOGSTAT public async Task<IActionResult> SadPerstat(SoldierService.Query query) { var model = new StateActiveDuty_Perstat { Soldiers = await SoldierService.Filter(db, query) }; return Json(model); } public async Task<IActionResult> DscaReady() { var soldiers = await SoldierService.Filter(db, new SoldierService.Query { IWQ = true, DSCA = true }); return View(soldiers); } } }
Copy file to temp folder as long as document is not saved
using MyDocs.Common.Contract.Service; using MyDocs.Common.Model.View; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Windows.Storage; using Windows.Storage.Pickers; namespace MyDocs.WindowsStore.Service { public class FileOpenPickerService : IFileOpenPickerService { public async Task<IEnumerable<StorageFile>> PickSubDocuments() { var filePicker = new FileOpenPicker(); filePicker.FileTypeFilter.Add("*"); filePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary; filePicker.ViewMode = PickerViewMode.List; var files = await filePicker.PickMultipleFilesAsync(); var folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(document.Id.ToString(), CreationCollisionOption.OpenIfExists); var tasks = files.Select(file => file.CopyAsync(folder, file.Name, NameCollisionOption.GenerateUniqueName).AsTask()); return await Task.WhenAll(tasks); } public async Task<StorageFile> PickImportFile() { var filePicker = new FileOpenPicker(); filePicker.FileTypeFilter.Add(".zip"); return await filePicker.PickSingleFileAsync(); } } }
using MyDocs.Common.Contract.Service; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Windows.Storage; using Windows.Storage.Pickers; namespace MyDocs.WindowsStore.Service { public class FileOpenPickerService : IFileOpenPickerService { public async Task<IEnumerable<StorageFile>> PickSubDocuments() { var filePicker = new FileOpenPicker(); filePicker.FileTypeFilter.Add("*"); filePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary; filePicker.ViewMode = PickerViewMode.List; var files = await filePicker.PickMultipleFilesAsync(); var folder = ApplicationData.Current.TemporaryFolder; var tasks = files.Select(file => { var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.Name); return file.CopyAsync(folder, fileName).AsTask(); }); return await Task.WhenAll(tasks); } public async Task<StorageFile> PickImportFile() { var filePicker = new FileOpenPicker(); filePicker.FileTypeFilter.Add(".zip"); return await filePicker.PickSingleFileAsync(); } } }
Edit comment. Token is not required.
using System; using System.Linq; namespace Elasticsearch.Net.Aws { /// <summary> /// Encapsulates /// </summary> public class AwsSettings { /// <summary> /// Gets or sets the region. e.g. us-east-1. Required. /// </summary> public string Region { get; set; } /// <summary> /// Gets or sets the AWS access key. Required. /// </summary> public string AccessKey { get; set; } /// <summary> /// Gets or sets the AWS secret key. e.g. wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY /// Required. /// </summary> public string SecretKey { get; set; } /// <summary> /// Gets or sets the security token /// Required. /// </summary> public string Token { get; set; } } }
using System; using System.Linq; namespace Elasticsearch.Net.Aws { /// <summary> /// Encapsulates /// </summary> public class AwsSettings { /// <summary> /// Gets or sets the region. e.g. us-east-1. Required. /// </summary> public string Region { get; set; } /// <summary> /// Gets or sets the AWS access key. Required. /// </summary> public string AccessKey { get; set; } /// <summary> /// Gets or sets the AWS secret key. e.g. wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY /// Required. /// </summary> public string SecretKey { get; set; } /// <summary> /// Gets or sets the security token. /// </summary> public string Token { get; set; } } }
Raise Ping timeout for tests slightly
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace System.Net.Utilities.Tests { internal static class TestSettings { public static readonly string LocalHost = "localhost"; public const int PingTimeout = 200; public const string PayloadAsString = "'Post hoc ergo propter hoc'. 'After it, therefore because of it'. It means one thing follows the other, therefore it was caused by the other. But it's not always true. In fact it's hardly ever true."; public static readonly byte[] PayloadAsBytes = Encoding.UTF8.GetBytes(TestSettings.PayloadAsString); public static Task<IPAddress> GetLocalIPAddress() { return ResolveHost(LocalHost); } private static async Task<IPAddress> ResolveHost(string host) { IPHostEntry hostEntry = await Dns.GetHostEntryAsync(host); IPAddress ret = null; foreach (IPAddress address in hostEntry.AddressList) { if (address.AddressFamily == AddressFamily.InterNetworkV6) { ret = address; } } // If there's no IPv6 addresses, just take the first (IPv4) address. if (ret == null) { ret = hostEntry.AddressList[0]; } if (ret != null) { return ret; } throw new InvalidOperationException("Unable to discover any addresses for host " + host); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace System.Net.Utilities.Tests { internal static class TestSettings { public static readonly string LocalHost = "localhost"; public const int PingTimeout = 1000; public const string PayloadAsString = "'Post hoc ergo propter hoc'. 'After it, therefore because of it'. It means one thing follows the other, therefore it was caused by the other. But it's not always true. In fact it's hardly ever true."; public static readonly byte[] PayloadAsBytes = Encoding.UTF8.GetBytes(TestSettings.PayloadAsString); public static Task<IPAddress> GetLocalIPAddress() { return ResolveHost(LocalHost); } private static async Task<IPAddress> ResolveHost(string host) { IPHostEntry hostEntry = await Dns.GetHostEntryAsync(host); IPAddress ret = null; foreach (IPAddress address in hostEntry.AddressList) { if (address.AddressFamily == AddressFamily.InterNetworkV6) { ret = address; } } // If there's no IPv6 addresses, just take the first (IPv4) address. if (ret == null) { ret = hostEntry.AddressList[0]; } if (ret != null) { return ret; } throw new InvalidOperationException("Unable to discover any addresses for host " + host); } } }
Add comment and make constructor protected internal
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using osu.Framework.Input.Handlers; using osu.Framework.Input.StateChanges.Events; using osu.Framework.Platform; using osuTK; namespace osu.Framework.Input { public class UserInputManager : PassThroughInputManager { protected override IEnumerable<InputHandler> InputHandlers => Host.AvailableInputHandlers; protected override bool HandleHoverEvents => Host.Window?.CursorInWindow ?? true; public UserInputManager() { IsAlive = true; UseParentInput = false; } public override void HandleInputStateChange(InputStateChangeEvent inputStateChange) { switch (inputStateChange) { case MousePositionChangeEvent mousePositionChange: var mouse = mousePositionChange.State.Mouse; // confine cursor if (Host.Window != null && Host.Window.CursorState.HasFlag(CursorState.Confined)) mouse.Position = Vector2.Clamp(mouse.Position, Vector2.Zero, new Vector2(Host.Window.Width, Host.Window.Height)); break; case MouseScrollChangeEvent _: if (Host.Window != null && !Host.Window.CursorInWindow) return; break; } base.HandleInputStateChange(inputStateChange); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using osu.Framework.Input.Handlers; using osu.Framework.Input.StateChanges.Events; using osu.Framework.Platform; using osuTK; namespace osu.Framework.Input { public class UserInputManager : PassThroughInputManager { protected override IEnumerable<InputHandler> InputHandlers => Host.AvailableInputHandlers; protected override bool HandleHoverEvents => Host.Window?.CursorInWindow ?? true; protected internal UserInputManager() { // IsAlive is being forced to true here as UserInputManager is at the very top of the Draw Hierarchy, which means it never becomes alive normally. IsAlive = true; UseParentInput = false; } public override void HandleInputStateChange(InputStateChangeEvent inputStateChange) { switch (inputStateChange) { case MousePositionChangeEvent mousePositionChange: var mouse = mousePositionChange.State.Mouse; // confine cursor if (Host.Window != null && Host.Window.CursorState.HasFlag(CursorState.Confined)) mouse.Position = Vector2.Clamp(mouse.Position, Vector2.Zero, new Vector2(Host.Window.Width, Host.Window.Height)); break; case MouseScrollChangeEvent _: if (Host.Window != null && !Host.Window.CursorInWindow) return; break; } base.HandleInputStateChange(inputStateChange); } } }
Add missing file offset registration.
using System; namespace AsmResolver.PE.Debug { /// <summary> /// Provides an implementation of a debug data entry that was stored in a PE file. /// </summary> public class SerializedDebugDataEntry : DebugDataEntry { private readonly IDebugDataReader _dataReader; private readonly DebugDataType _type; private readonly uint _sizeOfData; private readonly uint _addressOfRawData; private readonly uint _pointerToRawData; /// <summary> /// Reads a single debug data entry from an input stream. /// </summary> /// <param name="reader">The input stream.</param> /// <param name="dataReader">The object responsible for reading the contents.</param> public SerializedDebugDataEntry(IBinaryStreamReader reader, IDebugDataReader dataReader) { if (reader == null) throw new ArgumentNullException(nameof(reader)); _dataReader = dataReader ?? throw new ArgumentNullException(nameof(dataReader)); Characteristics = reader.ReadUInt32(); TimeDateStamp = reader.ReadUInt32(); MajorVersion = reader.ReadUInt16(); MinorVersion = reader.ReadUInt16(); _type = (DebugDataType) reader.ReadUInt32(); _sizeOfData = reader.ReadUInt32(); _addressOfRawData = reader.ReadUInt32(); _pointerToRawData = reader.ReadUInt32(); } /// <inheritdoc /> protected override IDebugDataSegment GetContents() => _dataReader.ReadDebugData(_type, _addressOfRawData, _sizeOfData); } }
using System; namespace AsmResolver.PE.Debug { /// <summary> /// Provides an implementation of a debug data entry that was stored in a PE file. /// </summary> public class SerializedDebugDataEntry : DebugDataEntry { private readonly IDebugDataReader _dataReader; private readonly DebugDataType _type; private readonly uint _sizeOfData; private readonly uint _addressOfRawData; private readonly uint _pointerToRawData; /// <summary> /// Reads a single debug data entry from an input stream. /// </summary> /// <param name="reader">The input stream.</param> /// <param name="dataReader">The object responsible for reading the contents.</param> public SerializedDebugDataEntry(IBinaryStreamReader reader, IDebugDataReader dataReader) { if (reader == null) throw new ArgumentNullException(nameof(reader)); _dataReader = dataReader ?? throw new ArgumentNullException(nameof(dataReader)); FileOffset = reader.FileOffset; Rva = reader.Rva; Characteristics = reader.ReadUInt32(); TimeDateStamp = reader.ReadUInt32(); MajorVersion = reader.ReadUInt16(); MinorVersion = reader.ReadUInt16(); _type = (DebugDataType) reader.ReadUInt32(); _sizeOfData = reader.ReadUInt32(); _addressOfRawData = reader.ReadUInt32(); _pointerToRawData = reader.ReadUInt32(); } /// <inheritdoc /> protected override IDebugDataSegment GetContents() => _dataReader.ReadDebugData(_type, _addressOfRawData, _sizeOfData); } }
Use default build & revision numbers
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("SqlServerHelpers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SqlServerHelpers")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5595bad6-6335-4e57-b4ac-bb5b9e77fbaa")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.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("SqlServerHelpers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SqlServerHelpers")] [assembly: AssemblyCopyright("Copyright © Josh Keegan 2015-2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5595bad6-6335-4e57-b4ac-bb5b9e77fbaa")] // 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.*")]
Add the product name and the assembly title custom attributes
using System; using System.Reflection; // TODO: Automate this [assembly: AssemblyInformationalVersion ("1.1.0")] namespace Tomboy { public class Defines { public const string VERSION = "1.1.0"; public static readonly string DATADIR = System.IO.Path.GetDirectoryName (Assembly.GetExecutingAssembly ().Location); public static readonly string GNOME_LOCALE_DIR = System.IO.Path.Combine (DATADIR, "locale"); public const string GNOME_HELP_DIR = "@datadir@/gnome/help/tomboy"; public const string PKGLIBDIR = "@pkglibdir@"; public static readonly string SYS_ADDINS_DIR = DATADIR; public const string TOMBOY_WEBSITE = "http://www.gnome.org/projects/tomboy/"; } }
using System; using System.Reflection; // TODO: Automate this [assembly: AssemblyInformationalVersion ("1.1.0")] [assembly: AssemblyProduct("Tomboy")] [assembly: AssemblyTitle("Tomboy Notes")] namespace Tomboy { public class Defines { public const string VERSION = "1.1.0"; public static readonly string DATADIR = System.IO.Path.GetDirectoryName (Assembly.GetExecutingAssembly ().Location); public static readonly string GNOME_LOCALE_DIR = System.IO.Path.Combine (DATADIR, "locale"); public const string GNOME_HELP_DIR = "@datadir@/gnome/help/tomboy"; public const string PKGLIBDIR = "@pkglibdir@"; public static readonly string SYS_ADDINS_DIR = DATADIR; public const string TOMBOY_WEBSITE = "http://www.gnome.org/projects/tomboy/"; } }
Align side-by-side comments in SampleSpecs.Bug test
using System.Collections.Generic; using NSpec; namespace SampleSpecs.Bug { class grandparents_run_first : nspec { List<int> ints = null; void describe_NSpec() //describe RSpec do { before = () => ints = new List<int>(); // before(:each) { @array = Array.new } context["something that works in rspec but not nspec"] = () => // context "something that works in rspec but not nspec" do { before = () => ints.Add(1); describe["sibling context"] = () => // context "sibling context" do { before = () => ints.Add(1); // before(:each) { @array << "sibling 1" } specify = () => ints.Count.should_be(1); // it { @array.count.should == 1 } }; // end describe["another sibling context"] = () => // context "another sibling context" do { before = () => ints.Add(1); // before(:each) { @array << "sibling 2" } specify = () => ints.Count.should_be(1); // it { @array.count.should == 1 } }; // end }; // end } //end } }
using System.Collections.Generic; using NSpec; namespace SampleSpecs.Bug { class grandparents_run_first : nspec { List<int> ints = null; void describe_NSpec() //describe RSpec do { before = () => ints = new List<int>(); // before(:each) { @array = Array.new } context["something that works in rspec but not nspec"] = () => // context "something that works in rspec but not nspec" do { before = () => ints.Add(1); describe["sibling context"] = () => // context "sibling context" do { before = () => ints.Add(1); // before(:each) { @array << "sibling 1" } specify = () => ints.Count.should_be(1); // it { @array.count.should == 1 } }; // end describe["another sibling context"] = () => // context "another sibling context" do { before = () => ints.Add(1); // before(:each) { @array << "sibling 2" } specify = () => ints.Count.should_be(1); // it { @array.count.should == 1 } }; // end }; // end } //end } }
Fix for a compile error in the QuickStart.
using System.Xml; using FluentNHibernate; using FluentNHibernate.Mapping; namespace FluentNHibernate.QuickStart.Domain.Mapping { public class CatMap : ClassMap<Cat>, IMapGenerator { public CatMap() { //set up our generator as UUID.HEX Id(x => x.Id) .GeneratedBy .UuidHex("B"); //non-nullable string with a length of 16 Map(x => x.Name) .WithLengthOf(16) .CanNotBeNull(); //simple properties Map(x => x.Sex); Map(x => x.Weight); } #region IMapGenerator Members public XmlDocument Generate() { return CreateMapping(new MappingVisitor()); } #endregion } }
using System.Xml; using FluentNHibernate; using FluentNHibernate.Mapping; namespace FluentNHibernate.QuickStart.Domain.Mapping { public class CatMap : ClassMap<Cat>, IMapGenerator { public CatMap() { //set up our generator as UUID.HEX Id(x => x.Id) .GeneratedBy .UuidHex("B"); //non-nullable string with a length of 16 Map(x => x.Name) .WithLengthOf(16) .Not.Nullable(); //simple properties Map(x => x.Sex); Map(x => x.Weight); } #region IMapGenerator Members public XmlDocument Generate() { return CreateMapping(new MappingVisitor()); } #endregion } }
Revert "Fix of previous commit"
using System.IO; using System; namespace Bari.Core.Generic { public class LocalFileSystemDirectoryWatcher: IFileSystemDirectoryWatcher { private readonly FileSystemWatcher watcher; private readonly string path; public event EventHandler<FileSystemChangedEventArgs> Changed; public LocalFileSystemDirectoryWatcher(string path) { this.path = path; watcher = new FileSystemWatcher(path) { IncludeSubdirectories = true, NotifyFilter = NotifyFilters.FileName }; watcher.Changed += OnChanged; watcher.Created += OnChanged; watcher.Deleted += OnChanged; watcher.Renamed += OnChanged; watcher.EnableRaisingEvents = true; } public void Stop() { watcher.Dispose(); } public void Dispose() { Stop(); } private void OnChanged(object sender, FileSystemEventArgs e) { if (Changed != null) { Changed(this, new FileSystemChangedEventArgs(e.FullPath.Substring(path.Length).TrimStart(Path.DirectorySeparatorChar))); } } } }
using System.IO; using System; namespace Bari.Core.Generic { public class LocalFileSystemDirectoryWatcher: IFileSystemDirectoryWatcher { private readonly FileSystemWatcher watcher; private readonly string path; public event EventHandler<FileSystemChangedEventArgs> Changed; public LocalFileSystemDirectoryWatcher(string path) { this.path = path; watcher = new FileSystemWatcher(path); watcher.IncludeSubdirectories = true; watcher.Changed += OnChanged; watcher.Created += OnChanged; watcher.Deleted += OnChanged; watcher.Renamed += OnChanged; watcher.EnableRaisingEvents = true; } public void Stop() { watcher.Dispose(); } public void Dispose() { Stop(); } private void OnChanged(object sender, FileSystemEventArgs e) { if (Changed != null) { Changed(this, new FileSystemChangedEventArgs(e.FullPath.Substring(path.Length).TrimStart(Path.DirectorySeparatorChar))); } } } }
Add test for incrementing with negative number
using System.Linq; using FluentAssertions; using Xunit; namespace Okanshi.Test { public class CounterTest { private readonly Counter counter; public CounterTest() { counter = new Counter(MonitorConfig.Build("Test")); } [Fact] public void Initial_peak_is_zero() { var value = counter.GetValues(); value.First().Value.Should().Be(0); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(110)] public void Incrementing_value_updates_peak(int amount) { counter.Increment(amount); counter.GetValues().First().Value.Should().Be(amount); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(110)] public void Get_and_reset_returns_the_peak(int amount) { counter.Increment(amount); counter.GetValuesAndReset().First().Value.Should().Be(amount); } [Fact] public void Peak_is_reset_after_get_and_reset() { counter.Increment(); counter.GetValuesAndReset(); var value = counter.GetValues(); value.First().Value.Should().Be(0); } [Fact] public void Value_is_called_value() { counter.GetValues().Single().Name.Should().Be("value"); } } }
using System.Linq; using FluentAssertions; using Xunit; namespace Okanshi.Test { public class CounterTest { private readonly Counter counter; public CounterTest() { counter = new Counter(MonitorConfig.Build("Test")); } [Fact] public void Initial_peak_is_zero() { var value = counter.GetValues(); value.First().Value.Should().Be(0); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(110)] public void Incrementing_value_updates_peak(int amount) { counter.Increment(amount); counter.GetValues().First().Value.Should().Be(amount); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(110)] public void Get_and_reset_returns_the_peak(int amount) { counter.Increment(amount); counter.GetValuesAndReset().First().Value.Should().Be(amount); } [Fact] public void Peak_is_reset_after_get_and_reset() { counter.Increment(); counter.GetValuesAndReset(); var value = counter.GetValues(); value.First().Value.Should().Be(0); } [Fact] public void Value_is_called_value() { counter.GetValues().Single().Name.Should().Be("value"); } [Fact] public void Increment_with_negative_values_works() { counter.Increment(-1); counter.GetValues().Single().Value.Should().Be(-1); } } }
Add a namespace reference for System
using System.IO; using System.Security.Cryptography; using Mono.Security; using Mono.Security.Cryptography; namespace Xpdm.PurpleOnion { class Program { private static void Main() { long count = 0; while (true) { RSA pki = RSA.Create(); ASN1 asn = RSAExtensions.ToAsn1Key(pki); byte[] hash = SHA1CryptoServiceProvider.Create().ComputeHash(asn.GetBytes()); string onion = ConvertExtensions.FromBytesToBase32String(hash).Substring(0,16).ToLowerInvariant(); if (onion.Contains("tor") || onion.Contains("mirror")) { System.Console.WriteLine("Found: " + onion); Directory.CreateDirectory(onion); File.WriteAllText(Path.Combine(onion, "pki.xml"), pki.ToXmlString(true)); File.WriteAllText(Path.Combine(onion, "private_key"), System.Convert.ToBase64String(PKCS8.PrivateKeyInfo.Encode(pki))); File.WriteAllText(Path.Combine(onion, "hostname"), onion + ".onion"); } System.Console.WriteLine(onion + " " + ++count); } } } }
using System; using System.IO; using System.Security.Cryptography; using Mono.Security; using Mono.Security.Cryptography; namespace Xpdm.PurpleOnion { class Program { private static void Main() { long count = 0; while (true) { RSA pki = RSA.Create(); ASN1 asn = RSAExtensions.ToAsn1Key(pki); byte[] hash = SHA1CryptoServiceProvider.Create().ComputeHash(asn.GetBytes()); string onion = ConvertExtensions.FromBytesToBase32String(hash).Substring(0,16).ToLowerInvariant(); if (onion.Contains("tor") || onion.Contains("mirror")) { Console.WriteLine("Found: " + onion); Directory.CreateDirectory(onion); File.WriteAllText(Path.Combine(onion, "pki.xml"), pki.ToXmlString(true)); File.WriteAllText(Path.Combine(onion, "private_key"), System.Convert.ToBase64String(PKCS8.PrivateKeyInfo.Encode(pki))); File.WriteAllText(Path.Combine(onion, "hostname"), onion + ".onion"); } Console.WriteLine(onion + " " + ++count); } } } }
Revert "Remove ignore attribute from now fixed test scene"
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Graphics.Containers; using osu.Framework.Screens; using osu.Framework.Testing; using osu.Game.Screens.Play.HUD; using osu.Game.Skinning; using osu.Game.Tests.Visual; using osuTK; namespace osu.Game.Rulesets.Catch.Tests { [TestFixture] public class TestSceneCatchPlayerLegacySkin : LegacySkinPlayerTestScene { protected override Ruleset CreatePlayerRuleset() => new CatchRuleset(); [Test] public void TestLegacyHUDComboCounterHidden([Values] bool withModifiedSkin) { if (withModifiedSkin) { AddStep("change component scale", () => Player.ChildrenOfType<LegacyScoreCounter>().First().Scale = new Vector2(2f)); AddStep("update target", () => Player.ChildrenOfType<SkinnableTargetContainer>().ForEach(LegacySkin.UpdateDrawableTarget)); AddStep("exit player", () => Player.Exit()); CreateTest(null); } AddAssert("legacy HUD combo counter hidden", () => { return Player.ChildrenOfType<LegacyComboCounter>().All(c => c.ChildrenOfType<Container>().Single().Alpha == 0f); }); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Graphics.Containers; using osu.Framework.Screens; using osu.Framework.Testing; using osu.Game.Screens.Play.HUD; using osu.Game.Skinning; using osu.Game.Tests.Visual; using osuTK; namespace osu.Game.Rulesets.Catch.Tests { [TestFixture] public class TestSceneCatchPlayerLegacySkin : LegacySkinPlayerTestScene { protected override Ruleset CreatePlayerRuleset() => new CatchRuleset(); [Test] [Ignore("HUD components broken, remove when fixed.")] public void TestLegacyHUDComboCounterHidden([Values] bool withModifiedSkin) { if (withModifiedSkin) { AddStep("change component scale", () => Player.ChildrenOfType<LegacyScoreCounter>().First().Scale = new Vector2(2f)); AddStep("update target", () => Player.ChildrenOfType<SkinnableTargetContainer>().ForEach(LegacySkin.UpdateDrawableTarget)); AddStep("exit player", () => Player.Exit()); CreateTest(null); } AddAssert("legacy HUD combo counter hidden", () => { return Player.ChildrenOfType<LegacyComboCounter>().All(c => !c.ChildrenOfType<Container>().Single().IsPresent); }); } } }
Fix NRE if null array.
using System.Data.SqlClient; using System.Management.Automation; namespace PSql { [Cmdlet(VerbsCommunications.Disconnect, "Sql")] public class DisconnectSqlCommand : Cmdlet { // -Connection [Alias("c", "cn")] [Parameter(Position = 0, ValueFromPipeline = true, ValueFromRemainingArguments = true)] public SqlConnection[] Connection { get; set; } protected override void ProcessRecord() { foreach (var connection in Connection) { if (connection == null) continue; ConnectionInfo.Get(connection).IsDisconnecting = true; connection.Dispose(); } } } }
using System.Data.SqlClient; using System.Management.Automation; namespace PSql { [Cmdlet(VerbsCommunications.Disconnect, "Sql")] public class DisconnectSqlCommand : Cmdlet { // -Connection [Alias("c", "cn")] [Parameter(Position = 0, ValueFromPipeline = true, ValueFromRemainingArguments = true)] public SqlConnection[] Connection { get; set; } protected override void ProcessRecord() { var connections = Connection; if (connections == null) return; foreach (var connection in connections) { if (connection == null) continue; ConnectionInfo.Get(connection).IsDisconnecting = true; connection.Dispose(); } } } }
Add extension method for using version header middleware.
using System; using Microsoft.AspNetCore.Hosting; using TwentyTwenty.Mvc; using TwentyTwenty.Mvc.ErrorHandling; using TwentyTwenty.Mvc.HealthCheck; using TwentyTwenty.Mvc.ReadOnlyMode; namespace Microsoft.AspNetCore.Builder { public static class ErrorHandling { public static void UseErrorHandling(this IApplicationBuilder app, ICodeMap codeMap) => app.UseErrorHandling(codeMap.MapErrorCode); public static void UseErrorHandling(this IApplicationBuilder app, Func<int, int> codeMap = null) { app.UseMiddleware<ErrorHandlerMiddleware>(codeMap); } public static void UseHealthCheck(this IApplicationBuilder app) => app.UseHealthCheck("/status/health-check"); public static void UseHealthCheck(this IApplicationBuilder app, string path) { app.Map(path, builder => { builder.UseMiddleware<HealthCheckMiddleware>(); }); } public static void UseReadOnlyMode(this IApplicationBuilder app) { app.UseMiddleware<ReadOnlyModeMiddleware>(); } } }
using System; using Microsoft.AspNetCore.Hosting; using TwentyTwenty.Mvc; using TwentyTwenty.Mvc.ErrorHandling; using TwentyTwenty.Mvc.HealthCheck; using TwentyTwenty.Mvc.ReadOnlyMode; using TwentyTwenty.Mvc.Version; namespace Microsoft.AspNetCore.Builder { public static class ErrorHandling { public static void UseErrorHandling(this IApplicationBuilder app, ICodeMap codeMap) => app.UseErrorHandling(codeMap.MapErrorCode); public static void UseErrorHandling(this IApplicationBuilder app, Func<int, int> codeMap = null) { app.UseMiddleware<ErrorHandlerMiddleware>(codeMap); } public static void UseHealthCheck(this IApplicationBuilder app) => app.UseHealthCheck("/status/health-check"); public static void UseHealthCheck(this IApplicationBuilder app, string path) { app.Map(path, builder => { builder.UseMiddleware<HealthCheckMiddleware>(); }); } public static void UseReadOnlyMode(this IApplicationBuilder app) { app.UseMiddleware<ReadOnlyModeMiddleware>(); } public static void UseVersionHeader(this IApplicationBuilder app, string headerName = "api-version") { app.UseMiddleware<VersionHeaderMiddleware>(headerName); } } }
Change SMA assembly info for DNX xUnit runner
using System.Runtime.CompilerServices; using System.Reflection; [assembly:InternalsVisibleTo("Microsoft.PowerShell.Commands.Management")] [assembly:InternalsVisibleTo("Microsoft.PowerShell.Commands.Utility")] [assembly:InternalsVisibleTo("Microsoft.PowerShell.Security")] [assembly:InternalsVisibleTo("Microsoft.PowerShell.Linux.Host")] [assembly:InternalsVisibleTo("PowerShell.Linux.Test")] [assembly:InternalsVisibleTo("powershell")] [assembly:AssemblyFileVersionAttribute("1.0.0.0")] [assembly:AssemblyVersion("1.0.0.0")] namespace System.Management.Automation { internal class NTVerpVars { internal const int PRODUCTMAJORVERSION = 10; internal const int PRODUCTMINORVERSION = 0; internal const int PRODUCTBUILD = 10032; internal const int PRODUCTBUILD_QFE = 0; internal const int PACKAGEBUILD_QFE = 814; } }
using System.Runtime.CompilerServices; using System.Reflection; [assembly:InternalsVisibleTo("Microsoft.PowerShell.Commands.Management")] [assembly:InternalsVisibleTo("Microsoft.PowerShell.Commands.Utility")] [assembly:InternalsVisibleTo("Microsoft.PowerShell.Security")] [assembly:InternalsVisibleTo("Microsoft.PowerShell.Linux.Host")] [assembly:InternalsVisibleTo("Microsoft.PowerShell.Linux.UnitTests")] [assembly:InternalsVisibleTo("powershell")] [assembly:AssemblyFileVersionAttribute("1.0.0.0")] [assembly:AssemblyVersion("1.0.0.0")] namespace System.Management.Automation { internal class NTVerpVars { internal const int PRODUCTMAJORVERSION = 10; internal const int PRODUCTMINORVERSION = 0; internal const int PRODUCTBUILD = 10032; internal const int PRODUCTBUILD_QFE = 0; internal const int PACKAGEBUILD_QFE = 814; } }
Fix time zone name on non windows platforms
using System; namespace Stranne.VasttrafikNET.Extensions { internal static class DateTimeOffsetExtension { private const string TimeZoneName = "W. Europe Standard Time"; public static TimeSpan GetVasttrafikTimeOffset(this DateTimeOffset dateTimeOffset) { return TimeZoneInfo.FindSystemTimeZoneById(TimeZoneName).GetUtcOffset(dateTimeOffset); } public static DateTimeOffset AddVasttrafikTimeSpan(this DateTimeOffset dateTimeOffset) { var timeOffset = dateTimeOffset.GetVasttrafikTimeOffset(); return new DateTimeOffset(dateTimeOffset.DateTime, timeOffset); } public static DateTimeOffset ConvertToVasttrafikTimeZone(this DateTimeOffset dateTimeOffset) { return TimeZoneInfo.ConvertTime(dateTimeOffset, TimeZoneInfo.FindSystemTimeZoneById(TimeZoneName)); } } }
using System; using System.Runtime.InteropServices; namespace Stranne.VasttrafikNET.Extensions { internal static class DateTimeOffsetExtension { public static TimeSpan GetVasttrafikTimeOffset(this DateTimeOffset dateTimeOffset) { return TimeZoneInfo.FindSystemTimeZoneById(GetTimeZoneName()).GetUtcOffset(dateTimeOffset); } public static DateTimeOffset AddVasttrafikTimeSpan(this DateTimeOffset dateTimeOffset) { var timeOffset = dateTimeOffset.GetVasttrafikTimeOffset(); return new DateTimeOffset(dateTimeOffset.DateTime, timeOffset); } public static DateTimeOffset ConvertToVasttrafikTimeZone(this DateTimeOffset dateTimeOffset) { return TimeZoneInfo.ConvertTime(dateTimeOffset, TimeZoneInfo.FindSystemTimeZoneById(GetTimeZoneName())); } private static string GetTimeZoneName() { var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); return isWindows ? "W. Europe Standard Time" : "Europe/Stockholm"; } } }
Check if a phone call is possible on Andriod
using System; using Android.Content; using Android.Telephony; using Uri = Android.Net.Uri; namespace Plugin.Messaging { internal class PhoneCallTask : IPhoneCallTask { public PhoneCallTask() { } #region IPhoneCallTask Members public bool CanMakePhoneCall { get { return true; } } public void MakePhoneCall(string number, string name = null) { if (string.IsNullOrWhiteSpace(number)) throw new ArgumentException("number"); if (CanMakePhoneCall) { var phoneNumber = PhoneNumberUtils.FormatNumber(number); Uri telUri = Uri.Parse("tel:" + phoneNumber); var dialIntent = new Intent(Intent.ActionDial, telUri); dialIntent.StartNewActivity(); } } #endregion } }
using System; using Android.Content; using Android.Telephony; using Uri = Android.Net.Uri; namespace Plugin.Messaging { internal class PhoneCallTask : IPhoneCallTask { public PhoneCallTask() { } #region IPhoneCallTask Members public bool CanMakePhoneCall { get { var packageManager = Android.App.Application.Context.PackageManager; var dialIntent = new Intent(Intent.ActionDial); return null != dialIntent.ResolveActivity(packageManager); } } public void MakePhoneCall(string number, string name = null) { if (string.IsNullOrWhiteSpace(number)) throw new ArgumentException("number"); if (CanMakePhoneCall) { var phoneNumber = PhoneNumberUtils.FormatNumber(number); Uri telUri = Uri.Parse("tel:" + phoneNumber); var dialIntent = new Intent(Intent.ActionDial, telUri); dialIntent.StartNewActivity(); } } #endregion } }
Fix bad key in Context.Items.
using CK.AspNet.Auth; using CK.Auth; using System; using System.Collections.Generic; using System.Text; namespace Microsoft.AspNetCore.Http { /// <summary> /// Exposes <see cref="WebFrontAuthenticate"/> extension method on <see cref="HttpContext"/>. /// </summary> static public class CKAspNetAuthHttpContextExtensions { /// <summary> /// Obtains the current <see cref="IAuthenticationInfo"/>, either because it is already /// in <see cref="HttpContext.Items"/> or by extracting authentication from request. /// It is never null, but can be <see cref="IAuthenticationInfoType.None"/>. /// </summary> /// <param name="this">This context.</param> /// <returns>Never null, can be <see cref="IAuthenticationInfoType.None"/>.</returns> static public IAuthenticationInfo WebFrontAuthenticate( this HttpContext @this ) { IAuthenticationInfo authInfo = null; object o; if( @this.Items.TryGetValue( typeof( IAuthenticationInfo ), out o ) ) { authInfo = (IAuthenticationInfo)o; } else { WebFrontAuthService s = (WebFrontAuthService)@this.RequestServices.GetService( typeof( WebFrontAuthService ) ); if( s == null ) throw new InvalidOperationException( "Missing WebFrontAuthService registration in Services." ); authInfo = s.ReadAndCacheAuthenticationHeader( @this ).Info; } return authInfo; } } }
using CK.AspNet.Auth; using CK.Auth; using System; using System.Collections.Generic; using System.Text; namespace Microsoft.AspNetCore.Http { /// <summary> /// Exposes <see cref="WebFrontAuthenticate"/> extension method on <see cref="HttpContext"/>. /// </summary> static public class CKAspNetAuthHttpContextExtensions { /// <summary> /// Obtains the current <see cref="IAuthenticationInfo"/>, either because it is already /// in <see cref="HttpContext.Items"/> or by extracting authentication from request. /// It is never null, but can be <see cref="IAuthenticationInfoType.None"/>. /// </summary> /// <param name="this">This context.</param> /// <returns>Never null, can be <see cref="IAuthenticationInfoType.None"/>.</returns> static public IAuthenticationInfo WebFrontAuthenticate( this HttpContext @this ) { IAuthenticationInfo authInfo = null; object o; if( @this.Items.TryGetValue( typeof( FrontAuthenticationInfo ), out o ) ) { authInfo = ((FrontAuthenticationInfo)o).Info; } else { WebFrontAuthService s = (WebFrontAuthService)@this.RequestServices.GetService( typeof( WebFrontAuthService ) ); if( s == null ) throw new InvalidOperationException( "Missing WebFrontAuthService registration in Services." ); authInfo = s.ReadAndCacheAuthenticationHeader( @this ).Info; } return authInfo; } } }
Fix for entity not loading from db.
using System.ComponentModel.DataAnnotations; namespace BoozeHoundCloud.Models.Core { public class Account { //------------------------------------------------------------------------- public const int NameMaxLength = 64; //------------------------------------------------------------------------- public int Id { get; set; } [MaxLength(NameMaxLength)] public string Name { get; set; } public AccountType AccountType { get; set; } public int AccountTypeId { get; set; } public decimal Balance { get; set; } //------------------------------------------------------------------------- } }
using System.ComponentModel.DataAnnotations; namespace BoozeHoundCloud.Models.Core { public class Account { //------------------------------------------------------------------------- public const int NameMaxLength = 64; //------------------------------------------------------------------------- public int Id { get; set; } [MaxLength(NameMaxLength)] public string Name { get; set; } // Virtual so entity framework can lazy load. public virtual AccountType AccountType { get; set; } public int AccountTypeId { get; set; } public decimal Balance { get; set; } //------------------------------------------------------------------------- } }
Create a new claims principal everytime if jabbr authenticated.
using System; using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; using JabbR.Infrastructure; using JabbR.Services; namespace JabbR.Middleware { using AppFunc = Func<IDictionary<string, object>, Task>; public class AuthorizationHandler { private readonly AppFunc _next; private readonly IAuthenticationTokenService _authenticationTokenService; public AuthorizationHandler(AppFunc next, IAuthenticationTokenService authenticationTokenService) { _next = next; _authenticationTokenService = authenticationTokenService; } public Task Invoke(IDictionary<string, object> env) { var request = new Gate.Request(env); string userToken; string userId; if (request.Cookies.TryGetValue(Constants.UserTokenCookie, out userToken) && _authenticationTokenService.TryGetUserId(userToken, out userId)) { // Add the JabbR user id claim var claims = new List<Claim>(); claims.Add(new Claim(ClaimTypes.NameIdentifier, userId)); var identity = new ClaimsIdentity(claims, Constants.JabbRAuthType); var principal = (ClaimsPrincipal)env["server.User"]; if (principal == null) { principal = new ClaimsPrincipal(identity); } else { // Add the jabbr identity to the current claims principal principal.AddIdentity(identity); } env["server.User"] = principal; } return _next(env); } } }
using System; using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; using JabbR.Infrastructure; using JabbR.Services; namespace JabbR.Middleware { using AppFunc = Func<IDictionary<string, object>, Task>; public class AuthorizationHandler { private readonly AppFunc _next; private readonly IAuthenticationTokenService _authenticationTokenService; public AuthorizationHandler(AppFunc next, IAuthenticationTokenService authenticationTokenService) { _next = next; _authenticationTokenService = authenticationTokenService; } public Task Invoke(IDictionary<string, object> env) { var request = new Gate.Request(env); string userToken; string userId; if (request.Cookies.TryGetValue(Constants.UserTokenCookie, out userToken) && _authenticationTokenService.TryGetUserId(userToken, out userId)) { // Add the JabbR user id claim var claims = new List<Claim>(); claims.Add(new Claim(ClaimTypes.NameIdentifier, userId)); var identity = new ClaimsIdentity(claims, Constants.JabbRAuthType); env["server.User"] = new ClaimsPrincipal(identity); } return _next(env); } } }
Remove forcefield from fist movement
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FistForceApply : MonoBehaviour { public static float forceAmount = 10000000f; public forceField forceField; public GameObject movingParentObj; public Vector3 oldPosition; void Start(){ oldPosition = (movingParentObj.transform.position); } void FixedUpdate(){ //Debug.Log ("VELO - "+GetComponent<Rigidbody>().velocity.magnitude); if((movingParentObj.transform.position - oldPosition).magnitude/Time.fixedDeltaTime >1f){ forceField.turnOnForceField((movingParentObj.transform.position - oldPosition).normalized); } oldPosition = (movingParentObj.transform.position); } void OnCollisionEnter(Collision col) { if (col.gameObject.tag == "Fish") { Debug.Log ("COLLIDED - "+col.gameObject.name); col.rigidbody.AddForce (gameObject.GetComponent<Rigidbody>().velocity.normalized * Time.deltaTime * forceAmount); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FistForceApply : MonoBehaviour { public static float forceAmount = 10000000f; void OnCollisionEnter(Collision col) { if (col.gameObject.tag == "Fish") { Debug.Log ("COLLIDED - "+col.gameObject.name); col.rigidbody.AddForce (gameObject.GetComponent<Rigidbody>().velocity.normalized * Time.deltaTime * forceAmount); } } }
Adjust default entity rendering layer.
using BearLib; using Roguelike.Entities; using Roguelike.World; using System.Collections.Generic; namespace Roguelike.Render { public abstract class Renderer : IRenderer { public const int MapLayer = 0; public const int EntityLayer = 5; public abstract void RenderEntities(IEnumerable<Entity> entities, Camera camera); public void RenderMap(Map map, Camera camera) { Terminal.Layer(MapLayer); for (int x = camera.Left; x < camera.Right; x++) { for (int y = camera.Top; y < camera.Bottom; y++) { RenderTile(map, x, y, camera); } } } protected abstract void RenderTile(Map map, int x, int y, Camera camera); } }
using BearLib; using Roguelike.Entities; using Roguelike.World; using System.Collections.Generic; namespace Roguelike.Render { public abstract class Renderer : IRenderer { public const int MapLayer = 0; public const int EntityLayer = 10; public abstract void RenderEntities(IEnumerable<Entity> entities, Camera camera); public void RenderMap(Map map, Camera camera) { Terminal.Layer(MapLayer); for (int x = camera.Left; x < camera.Right; x++) { for (int y = camera.Top; y < camera.Bottom; y++) { RenderTile(map, x, y, camera); } } } protected abstract void RenderTile(Map map, int x, int y, Camera camera); } }
Return IServiceCollection from AddDirectoryBrowser extension methods
// 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; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Extension methods for adding directory browser services. /// </summary> public static class DirectoryBrowserServiceExtensions { /// <summary> /// Adds directory browser middleware services. /// </summary> /// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param> public static void AddDirectoryBrowser(this IServiceCollection services) { if (services == null) { throw new ArgumentNullException(nameof(services)); } services.AddWebEncoders(); } } }
// 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; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Extension methods for adding directory browser services. /// </summary> public static class DirectoryBrowserServiceExtensions { /// <summary> /// Adds directory browser middleware services. /// </summary> /// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param> /// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns> public static IServiceCollection AddDirectoryBrowser(this IServiceCollection services) { if (services == null) { throw new ArgumentNullException(nameof(services)); } services.AddWebEncoders(); return services; } } }
Add Identity namespace to view imports
@using System.Globalization @using Microsoft.Extensions.Configuration @using MartinCostello.LondonTravel.Site @using MartinCostello.LondonTravel.Site.Extensions @using MartinCostello.LondonTravel.Site.Models @using MartinCostello.LondonTravel.Site.Options @addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" @addTagHelper "*, LondonTravel.Site" @inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet
@using System.Globalization @using Microsoft.Extensions.Configuration @using MartinCostello.LondonTravel.Site @using MartinCostello.LondonTravel.Site.Extensions @using MartinCostello.LondonTravel.Site.Identity @using MartinCostello.LondonTravel.Site.Models @using MartinCostello.LondonTravel.Site.Options @addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" @addTagHelper "*, LondonTravel.Site" @inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet
Add tests for constructors of MuffinClient
using System; using System.ComponentModel.Composition.Hosting; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace MuffinFramework.Tests { [TestClass] public class MuffinClientTests { [TestMethod] public void DoubleStartTest() { // arrange InvalidOperationException expectedException = null; var client = new MuffinClient(new AggregateCatalog()); client.Start(); // act try { // try to start the client a second time... client.Start(); } catch (InvalidOperationException ex) { expectedException = ex; } // assert Assert.IsNotNull(expectedException); } } }
using System; using System.ComponentModel.Composition.Hosting; using System.ComponentModel.Composition.Primitives; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace MuffinFramework.Tests { [TestClass] public class MuffinClientTests { [TestMethod] public void DoubleStartTest() { // arrange InvalidOperationException expectedException = null; var client = new MuffinClient(new AggregateCatalog()); client.Start(); // act try { // try to start the client a second time... client.Start(); } catch (InvalidOperationException ex) { expectedException = ex; } // assert Assert.IsNotNull(expectedException); } [TestMethod] public void Constructor1Test() { // arrange // act var client = new MuffinClient(); // assert Assert.IsNotNull(client.MuffinLoader); Assert.IsNotNull(client.ServiceLoader); Assert.IsNotNull(client.PlatformLoader); Assert.IsNotNull(client.AggregateCatalog); Assert.AreEqual(1, client.AggregateCatalog.Catalogs.Count); } [TestMethod] public void Constructor2Test() { // arrange var catalog = new AggregateCatalog(); // act var client = new MuffinClient(catalog); // assert Assert.IsNotNull(client.MuffinLoader); Assert.IsNotNull(client.ServiceLoader); Assert.IsNotNull(client.PlatformLoader); Assert.AreSame(catalog, client.AggregateCatalog); } [TestMethod] public void Constructor3Test() { // arrange var catalog1 = new TypeCatalog(); var catalog2 = new TypeCatalog(); // act var client = new MuffinClient(catalog1, catalog2); // assert Assert.IsNotNull(client.MuffinLoader); Assert.IsNotNull(client.ServiceLoader); Assert.IsNotNull(client.PlatformLoader); Assert.IsNotNull(client.AggregateCatalog); Assert.AreEqual(2, client.AggregateCatalog.Catalogs.Count); } [TestMethod] public void Constructor4Test() { // arrange // act var client = new MuffinClient(new ComposablePartCatalog[] {}); // assert Assert.IsNotNull(client.MuffinLoader); Assert.IsNotNull(client.ServiceLoader); Assert.IsNotNull(client.PlatformLoader); Assert.IsNotNull(client.AggregateCatalog); Assert.AreEqual(0, client.AggregateCatalog.Catalogs.Count); } } }
Update vehicle data set mime type version to 2.2
using System.Collections.Generic; namespace NFleet.Data { public class VehicleDataSet : IResponseData, IVersioned { public static string MIMEType = "application/vnd.jyu.nfleet.vehicleset"; public static string MIMEVersion = "2.0"; int IVersioned.VersionNumber { get; set; } public List<VehicleData> Items { get; set; } public List<Link> Meta { get; set; } public VehicleDataSet() { Items = new List<VehicleData>(); Meta = new List<Link>(); } } }
using System.Collections.Generic; namespace NFleet.Data { public class VehicleDataSet : IResponseData, IVersioned { public static string MIMEType = "application/vnd.jyu.nfleet.vehicleset"; public static string MIMEVersion = "2.2"; int IVersioned.VersionNumber { get; set; } public List<VehicleData> Items { get; set; } public List<Link> Meta { get; set; } public VehicleDataSet() { Items = new List<VehicleData>(); Meta = new List<Link>(); } } }