Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add cropping options into Generate-Tilemap directly.
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace PixelPet.Commands { internal class GenerateTilemapCmd : CliCommand { public GenerateTilemapCmd() : base("Generate-Tilemap", new Parameter[] { new Parameter("palette-size", "ps", false, new ParameterValue("count", "16")), new Parameter("no-reduce", "nr", false), }) { } public override void Run(Workbench workbench, Cli cli) { cli.Log("Generating tilemap..."); int palSize = FindNamedParameter("--palette-size").Values[0].ToInt32(); bool noReduce = FindNamedParameter("--no-reduce").IsPresent; workbench.Tilemap = new Tilemap(workbench.Bitmap, workbench.Tileset, workbench.Palette, palSize, !noReduce); } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace PixelPet.Commands { internal class GenerateTilemapCmd : CliCommand { public GenerateTilemapCmd() : base("Generate-Tilemap", new Parameter("palette-size", "ps", false, new ParameterValue("count", "16")), new Parameter("no-reduce", "nr", false), new Parameter("x", "x", false, new ParameterValue("pixels", "0")), new Parameter("y", "y", false, new ParameterValue("pixels", "0")), new Parameter("width", "w", false, new ParameterValue("pixels", "-1")), new Parameter("height", "h", false, new ParameterValue("pixels", "-1")) ) { } public override void Run(Workbench workbench, Cli cli) { cli.Log("Generating tilemap..."); int palSize = FindNamedParameter("--palette-size").Values[0].ToInt32(); bool noReduce = FindNamedParameter("--no-reduce" ).IsPresent; int x = FindNamedParameter("--x" ).Values[0].ToInt32(); int y = FindNamedParameter("--y" ).Values[0].ToInt32(); int w = FindNamedParameter("--width" ).Values[0].ToInt32(); int h = FindNamedParameter("--height" ).Values[0].ToInt32(); using (Bitmap bmp = workbench.GetCroppedBitmap(x, y, w, h, cli)) { workbench.Tilemap = new Tilemap(bmp, workbench.Tileset, workbench.Palette, palSize, !noReduce); } } } }
Add ability to set text halo color.
using System.Drawing; namespace TileSharp.Symbolizers { /// <summary> /// https://github.com/mapnik/mapnik/wiki/TextSymbolizer /// </summary> public class TextSymbolizer : Symbolizer { public readonly string LabelAttribute; public readonly PlacementType Placement; public readonly ContentAlignment Alignment; public readonly int FontSize; public readonly Color TextColor; public readonly Color TextHaloColor; /// <summary> /// The distance between repeated labels. /// 0: A single label is placed in the center. /// Based on Mapnik Spacing /// </summary> public readonly int Spacing; public TextSymbolizer(string labelAttribute, PlacementType placement, int fontSize, ContentAlignment alignment = ContentAlignment.MiddleCenter, int spacing = 0, Color? textColor = null) { LabelAttribute = labelAttribute; Placement = placement; Alignment = alignment; Spacing = spacing; FontSize = fontSize; TextColor = textColor ?? Color.Black; TextHaloColor = Color.White; } public enum PlacementType { Line, Point } } }
using System.Drawing; namespace TileSharp.Symbolizers { /// <summary> /// https://github.com/mapnik/mapnik/wiki/TextSymbolizer /// </summary> public class TextSymbolizer : Symbolizer { public readonly string LabelAttribute; public readonly PlacementType Placement; public readonly ContentAlignment Alignment; public readonly int FontSize; public readonly Color TextColor; public readonly Color TextHaloColor; /// <summary> /// The distance between repeated labels. /// 0: A single label is placed in the center. /// Based on Mapnik Spacing /// </summary> public readonly int Spacing; public TextSymbolizer(string labelAttribute, PlacementType placement, int fontSize, ContentAlignment alignment = ContentAlignment.MiddleCenter, int spacing = 0, Color? textColor = null, Color? textHaloColor = null) { LabelAttribute = labelAttribute; Placement = placement; Alignment = alignment; Spacing = spacing; FontSize = fontSize; TextColor = textColor ?? Color.Black; TextHaloColor = textHaloColor ?? Color.White; } public enum PlacementType { Line, Point } } }
Fix an animation bug with Mice to Snuffboxes
using System.Collections.Generic; using HarryPotterUnity.Cards.Generic; using JetBrains.Annotations; namespace HarryPotterUnity.Cards.Spells.Transfigurations { [UsedImplicitly] public class MiceToSnuffboxes : GenericSpell { public override List<GenericCard> GetValidTargets() { var validCards = Player.InPlay.GetCreaturesInPlay(); validCards.AddRange(Player.OppositePlayer.InPlay.GetCreaturesInPlay()); return validCards; } protected override void SpellAction(List<GenericCard> selectedCards) { foreach(var card in selectedCards) { card.Player.Hand.Add(card, false); card.Player.InPlay.Remove(card); } } } }
using System.Collections.Generic; using HarryPotterUnity.Cards.Generic; using JetBrains.Annotations; namespace HarryPotterUnity.Cards.Spells.Transfigurations { [UsedImplicitly] public class MiceToSnuffboxes : GenericSpell { public override List<GenericCard> GetValidTargets() { var validCards = Player.InPlay.GetCreaturesInPlay(); validCards.AddRange(Player.OppositePlayer.InPlay.GetCreaturesInPlay()); return validCards; } protected override void SpellAction(List<GenericCard> selectedCards) { int i = 0; foreach(var card in selectedCards) { card.Player.Hand.Add(card, preview: false, adjustSpacing: card.Player.IsLocalPlayer && i == 1); card.Player.InPlay.Remove(card); i++; } } } }
Save feature added for testing.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows; using ProjectMarkdown.Annotations; namespace ProjectMarkdown.ViewModels { public class MainWindowViewModel : INotifyPropertyChanged { private string _currentDocumentPath; public string CurrentDocumentPath { get { return _currentDocumentPath; } set { if (value == _currentDocumentPath) return; _currentDocumentPath = value; OnPropertyChanged(nameof(CurrentDocumentPath)); } } public event PropertyChangedEventHandler PropertyChanged; public MainWindowViewModel() { if (DesignerProperties.GetIsInDesignMode(new DependencyObject())) { return; } CurrentDocumentPath = "Untitled.md"; } [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Documents; using System.Windows.Input; using ProjectMarkdown.Annotations; namespace ProjectMarkdown.ViewModels { public class MainWindowViewModel : INotifyPropertyChanged { private string _currentDocumentPath; private string _currentText; private string _currentHtml; public string CurrentDocumentPath { get { return _currentDocumentPath; } set { if (value == _currentDocumentPath) return; _currentDocumentPath = value; OnPropertyChanged(nameof(CurrentDocumentPath)); } } public string CurrentText { get { return _currentText; } set { if (value == _currentText) return; _currentText = value; OnPropertyChanged(nameof(CurrentText)); } } public string CurrentHtml { get { return _currentHtml; } set { if (value == _currentHtml) return; _currentHtml = value; OnPropertyChanged(nameof(CurrentHtml)); } } public event PropertyChangedEventHandler PropertyChanged; public ICommand SaveDocumentCommand { get; set; } public MainWindowViewModel() { if (DesignerProperties.GetIsInDesignMode(new DependencyObject())) { return; } using (var sr = new StreamReader("Example.html")) { CurrentHtml = sr.ReadToEnd(); } LoadCommands(); CurrentDocumentPath = "Untitled.md"; } private void LoadCommands() { SaveDocumentCommand = new RelayCommand(SaveDocument, CanSaveDocument); } public void SaveDocument(object obj) { using (var sr = new StreamReader("Example.html")) { CurrentHtml = sr.ReadToEnd(); } } public bool CanSaveDocument(object obj) { return true; } [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
Make sure the decimal field value converter can handle double values when converting
using System; using System.Globalization; using Umbraco.Core.Models.PublishedContent; namespace Umbraco.Core.PropertyEditors.ValueConverters { [DefaultPropertyValueConverter] public class DecimalValueConverter : PropertyValueConverterBase { public override bool IsConverter(PublishedPropertyType propertyType) => Constants.PropertyEditors.Aliases.Decimal.Equals(propertyType.EditorAlias); public override Type GetPropertyValueType(PublishedPropertyType propertyType) => typeof (decimal); public override PropertyCacheLevel GetPropertyCacheLevel(PublishedPropertyType propertyType) => PropertyCacheLevel.Element; public override object ConvertSourceToIntermediate(IPublishedElement owner, PublishedPropertyType propertyType, object source, bool preview) { if (source == null) return 0M; // in XML a decimal is a string if (source is string sourceString) { return decimal.TryParse(sourceString, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out decimal d) ? d : 0M; } // in the database an a decimal is an a decimal // default value is zero return source is decimal ? source : 0M; } } }
using System; using System.Globalization; using Umbraco.Core.Models.PublishedContent; namespace Umbraco.Core.PropertyEditors.ValueConverters { [DefaultPropertyValueConverter] public class DecimalValueConverter : PropertyValueConverterBase { public override bool IsConverter(PublishedPropertyType propertyType) => Constants.PropertyEditors.Aliases.Decimal.Equals(propertyType.EditorAlias); public override Type GetPropertyValueType(PublishedPropertyType propertyType) => typeof (decimal); public override PropertyCacheLevel GetPropertyCacheLevel(PublishedPropertyType propertyType) => PropertyCacheLevel.Element; public override object ConvertSourceToIntermediate(IPublishedElement owner, PublishedPropertyType propertyType, object source, bool preview) { if (source == null) { return 0M; } // is it already a decimal? if(source is decimal) { return source; } // is it a double? if(source is double sourceDouble) { return Convert.ToDecimal(sourceDouble); } // is it a string? if (source is string sourceString) { return decimal.TryParse(sourceString, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out decimal d) ? d : 0M; } // couldn't convert the source value - default to zero return 0M; } } }
Make key entry case insensitive
using System; using System.IO; namespace Hangman { public class Hangman { public static void Main(string[] args) { var game = new Game("HANG THE MAN"); while (true) { string titleText = File.ReadAllText("title.txt"); Cell[] title = { new Cell(titleText, Cell.CentreAlign) }; string shownWord = game.ShownWord(); Cell[] word = { new Cell(shownWord, Cell.CentreAlign) }; Cell[] stats = { new Cell("Incorrect letters:\n A B I U"), new Cell("Lives remaining:\n 11/15", Cell.RightAlign) }; Cell[] status = { new Cell("Press any letter to guess!", Cell.CentreAlign) }; Row[] rows = { new Row(title), new Row(word), new Row(stats), new Row(status) }; var table = new Table( Math.Min(81, Console.WindowWidth), 2, rows ); var tableOutput = table.Draw(); Console.WriteLine(tableOutput); char key = Console.ReadKey(true).KeyChar; bool wasCorrect = game.GuessLetter(key); Console.Clear(); } } } }
using System; using System.IO; namespace Hangman { public class Hangman { public static void Main(string[] args) { var game = new Game("HANG THE MAN"); while (true) { string titleText = File.ReadAllText("title.txt"); Cell[] title = { new Cell(titleText, Cell.CentreAlign) }; string shownWord = game.ShownWord(); Cell[] word = { new Cell(shownWord, Cell.CentreAlign) }; Cell[] stats = { new Cell("Incorrect letters:\n A B I U"), new Cell("Lives remaining:\n 11/15", Cell.RightAlign) }; Cell[] status = { new Cell("Press any letter to guess!", Cell.CentreAlign) }; Row[] rows = { new Row(title), new Row(word), new Row(stats), new Row(status) }; var table = new Table( Math.Min(81, Console.WindowWidth), 2, rows ); var tableOutput = table.Draw(); Console.WriteLine(tableOutput); char key = Console.ReadKey(true).KeyChar; bool wasCorrect = game.GuessLetter(Char.ToUpper(key)); Console.Clear(); } } } }
Add a catch all route
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace CatchAllRule { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace CatchAllRule { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Everything", "{*url}", new { controller = "Everything", action = "Index" } ); } } }
Rename service collection extensions to be correct
using Microsoft.Framework.ConfigurationModel; using Microsoft.Framework.DependencyInjection; using System; namespace Glimpse { public static class GlimpseServiceCollectionExtensions { public static IServiceCollection AddMvc(this IServiceCollection services) { return services.Add(GlimpseServices.GetDefaultServices()); } public static IServiceCollection AddMvc(this IServiceCollection services, IConfiguration configuration) { return services.Add(GlimpseServices.GetDefaultServices(configuration)); } } }
using Microsoft.Framework.ConfigurationModel; using Microsoft.Framework.DependencyInjection; using System; namespace Glimpse { public static class GlimpseServiceCollectionExtensions { public static IServiceCollection AddGlimpse(this IServiceCollection services) { return services.Add(GlimpseServices.GetDefaultServices()); } public static IServiceCollection AddGlimpse(this IServiceCollection services, IConfiguration configuration) { return services.Add(GlimpseServices.GetDefaultServices(configuration)); } } }
Fix element3d presenter binding issue.
using HelixToolkit.Wpf.SharpDX.Model.Scene; using HelixToolkit.Wpf.SharpDX.Render; using SharpDX; using System.Collections.Generic; using System.Windows; using System.Windows.Markup; namespace HelixToolkit.Wpf.SharpDX { [ContentProperty("Content")] public class Element3DPresenter : Element3D { /// <summary> /// Gets or sets the content. /// </summary> /// <value> /// The content. /// </value> public Element3D Content { get { return (Element3D)GetValue(ContentProperty); } set { SetValue(ContentProperty, value); } } /// <summary> /// The content property /// </summary> public static readonly DependencyProperty ContentProperty = DependencyProperty.Register("Content", typeof(Element3D), typeof(Element3DPresenter), new PropertyMetadata(null, (d,e)=> { var model = d as Element3DPresenter; if(e.OldValue != null) { model.RemoveLogicalChild(e.OldValue); (model.SceneNode as GroupNode).RemoveChildNode(e.OldValue as Element3D); } if(e.NewValue != null) { model.AddLogicalChild(e.NewValue); (model.SceneNode as GroupNode).AddChildNode(e.NewValue as Element3D); } })); protected override SceneNode OnCreateSceneNode() { return new GroupNode(); } } }
using HelixToolkit.Wpf.SharpDX.Model.Scene; using HelixToolkit.Wpf.SharpDX.Render; using SharpDX; using System.Collections.Generic; using System.Windows; using System.Windows.Markup; namespace HelixToolkit.Wpf.SharpDX { [ContentProperty("Content")] public class Element3DPresenter : Element3D { /// <summary> /// Gets or sets the content. /// </summary> /// <value> /// The content. /// </value> public Element3D Content { get { return (Element3D)GetValue(ContentProperty); } set { SetValue(ContentProperty, value); } } /// <summary> /// The content property /// </summary> public static readonly DependencyProperty ContentProperty = DependencyProperty.Register("Content", typeof(Element3D), typeof(Element3DPresenter), new PropertyMetadata(null, (d,e)=> { var model = d as Element3DPresenter; if(e.OldValue != null) { model.RemoveLogicalChild(e.OldValue); (model.SceneNode as GroupNode).RemoveChildNode(e.OldValue as Element3D); } if(e.NewValue != null) { model.AddLogicalChild(e.NewValue); (model.SceneNode as GroupNode).AddChildNode(e.NewValue as Element3D); } })); public Element3DPresenter() { Loaded += Element3DPresenter_Loaded; } protected override SceneNode OnCreateSceneNode() { return new GroupNode(); } private void Element3DPresenter_Loaded(object sender, RoutedEventArgs e) { if (Content != null) { RemoveLogicalChild(Content); AddLogicalChild(Content); } } } }
Fix up the test to return correct type
using System; using System.Threading.Tasks; using NSubstitute; using Octokit.Tests.Helpers; using Xunit; namespace Octokit.Tests.Clients { /// <summary> /// Client tests mostly just need to make sure they call the IApiConnection with the correct /// relative Uri. No need to fake up the response. All *those* tests are in ApiConnectionTests.cs. /// </summary> public class TeamsClientTests { public class TheConstructor { [Fact] public void EnsuresNonNullArguments() { Assert.Throws<ArgumentNullException>(() => new TeamsClient(null)); } } public class TheGetAllMethod { [Fact] public void RequestsTheCorrectUrl() { var client = Substitute.For<IApiConnection>(); var orgs = new TeamsClient(client); orgs.GetAllTeams("username"); client.Received().GetAll<Team>(Arg.Is<Uri>(u => u.ToString() == "users/username/orgs")); } [Fact] public async Task EnsuresNonNullArguments() { var teams = new TeamsClient(Substitute.For<IApiConnection>()); AssertEx.Throws<ArgumentNullException>(async () => await teams.GetAllTeams(null)); } } } }
using System; using System.Threading.Tasks; using NSubstitute; using Octokit.Tests.Helpers; using Xunit; namespace Octokit.Tests.Clients { /// <summary> /// Client tests mostly just need to make sure they call the IApiConnection with the correct /// relative Uri. No need to fake up the response. All *those* tests are in ApiConnectionTests.cs. /// </summary> public class TeamsClientTests { public class TheConstructor { [Fact] public void EnsuresNonNullArguments() { Assert.Throws<ArgumentNullException>(() => new TeamsClient(null)); } } public class TheGetAllMethod { [Fact] public void RequestsTheCorrectUrl() { var client = Substitute.For<IApiConnection>(); var orgs = new TeamsClient(client); orgs.GetAllTeams("username"); client.Received().GetAll<TeamItem>(Arg.Is<Uri>(u => u.ToString() == "users/username/orgs")); } [Fact] public async Task EnsuresNonNullArguments() { var teams = new TeamsClient(Substitute.For<IApiConnection>()); AssertEx.Throws<ArgumentNullException>(async () => await teams.GetAllTeams(null)); } } } }
Replace age with date of birth
using System.Collections.Generic; using System.Net.Mail; namespace StressMeasurementSystem.Models { public class Patient { #region Structs public struct Name { public string Prefix { get; set; } public string First { get; set; } public string Middle { get; set; } public string Last { get; set; } public string Suffix { get; set; } } public struct Organization { public string Company { get; set; } public string JobTitle { get; set; } } public struct PhoneNumber { public enum Type { Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other } public string Number { get; set; } public Type T { get; set; } } public struct Email { public enum Type { Home, Work, Other } public MailAddress Address { get; set; } public Type T { get; set; } } #endregion #region Fields private Name? _name; private uint? _age; private Organization? _organization; private List<PhoneNumber> _phoneNumbers; private List<Email> _emails; #endregion #region Constructors public Patient(Name? name, uint? age, Organization? organization, List<PhoneNumber> phoneNumbers, List<Email> emails) { _name = name; _age = age; _organization = organization; _phoneNumbers = phoneNumbers; _emails = emails; } #endregion } }
using System; using System.Collections.Generic; using System.Net.Mail; namespace StressMeasurementSystem.Models { public class Patient { #region Structs public struct Name { public string Prefix { get; set; } public string First { get; set; } public string Middle { get; set; } public string Last { get; set; } public string Suffix { get; set; } } public struct Organization { public string Company { get; set; } public string JobTitle { get; set; } } public struct PhoneNumber { public enum Type { Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other } public string Number { get; set; } public Type T { get; set; } } public struct Email { public enum Type { Home, Work, Other } public MailAddress Address { get; set; } public Type T { get; set; } } #endregion #region Fields private Name? _name; private DateTime _dateOfBirth; private Organization? _organization; private List<PhoneNumber> _phoneNumbers; private List<Email> _emails; #endregion #region Constructors public Patient(Name? name, DateTime dateOfBirth, Organization? organization, List<PhoneNumber> phoneNumbers, List<Email> emails) { _name = name; _dateOfBirth = dateOfBirth; _organization = organization; _phoneNumbers = phoneNumbers; _emails = emails; } #endregion } }
Use default getters and setters
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Core2D.Shapes.Interfaces; namespace Core2D.UnitTests { public class TestPointShape : TestBaseShape, IPointShape { public double X { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } public double Y { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } public PointAlignment Alignment { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } public IBaseShape Shape { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Core2D.Shapes.Interfaces; namespace Core2D.UnitTests { public class TestPointShape : TestBaseShape, IPointShape { public double X { get; set; } public double Y { get; set; } public PointAlignment Alignment { get; set; } public IBaseShape Shape { get; set; } } }
Fix path separator on Linux
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using System.Runtime.InteropServices; using Microsoft.NET.TestFramework; using Microsoft.NET.TestFramework.Assertions; using Microsoft.NET.TestFramework.Commands; using Xunit; using static Microsoft.NET.TestFramework.Commands.MSBuildTest; namespace Microsoft.NET.Build.Tests { public class GivenThatWeWantToBuildASolutionWithNonAnyCPUPlatform { private TestAssetsManager _testAssetsManager = TestAssetsManager.TestProjectsAssetsManager; [Fact] public void It_builds_solusuccessfully() { var testAsset = _testAssetsManager .CopyTestAsset("x64SolutionBuild") .WithSource() .Restore(); var buildCommand = new BuildCommand(Stage0MSBuild, testAsset.TestRoot, "x64SolutionBuild.sln"); buildCommand .Execute() .Should() .Pass(); buildCommand.GetOutputDirectory("netcoreapp1.0", @"x64\Debug") .Should() .OnlyHaveFiles(new[] { "x64SolutionBuild.runtimeconfig.dev.json", "x64SolutionBuild.runtimeconfig.json", "x64SolutionBuild.deps.json", "x64SolutionBuild.dll", "x64SolutionBuild.pdb" }); } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using System.Runtime.InteropServices; using Microsoft.NET.TestFramework; using Microsoft.NET.TestFramework.Assertions; using Microsoft.NET.TestFramework.Commands; using Xunit; using static Microsoft.NET.TestFramework.Commands.MSBuildTest; namespace Microsoft.NET.Build.Tests { public class GivenThatWeWantToBuildASolutionWithNonAnyCPUPlatform { private TestAssetsManager _testAssetsManager = TestAssetsManager.TestProjectsAssetsManager; [Fact] public void It_builds_solusuccessfully() { var testAsset = _testAssetsManager .CopyTestAsset("x64SolutionBuild") .WithSource() .Restore(); var buildCommand = new BuildCommand(Stage0MSBuild, testAsset.TestRoot, "x64SolutionBuild.sln"); buildCommand .Execute() .Should() .Pass(); buildCommand.GetOutputDirectory("netcoreapp1.0", Path.Combine("x64", "Debug")) .Should() .OnlyHaveFiles(new[] { "x64SolutionBuild.runtimeconfig.dev.json", "x64SolutionBuild.runtimeconfig.json", "x64SolutionBuild.deps.json", "x64SolutionBuild.dll", "x64SolutionBuild.pdb" }); } } }
Update starting solution with correct namespaces.
@using Tracker @using Tracker.Models @using Tracker.ViewModels.Account @using Tracker.ViewModels.Manage @using Microsoft.AspNet.Identity @addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"
@using ShatteredTemple.LegoDimensions.Tracker @using ShatteredTemple.LegoDimensions.Tracker.Models @using ShatteredTemple.LegoDimensions.Tracker.ViewModels.Account @using ShatteredTemple.LegoDimensions.Tracker.ViewModels.Manage @using Microsoft.AspNet.Identity @addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"
Update assembly version per feedback
// // Copyright (c) Microsoft. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft Azure Batch Management Library")] [assembly: AssemblyDescription("Provides management functions for Microsoft Azure Batch services.")] [assembly: AssemblyVersion("2.1.0.0")] [assembly: AssemblyFileVersion("2.1.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")]
// // Copyright (c) Microsoft. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft Azure Batch Management Library")] [assembly: AssemblyDescription("Provides management functions for Microsoft Azure Batch services.")] [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.1.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")]
Fix event factory parsing of documents
using StockportWebapp.Models; using StockportWebapp.Parsers; using StockportWebapp.Utils; namespace StockportWebapp.ContentFactory { public class EventFactory { private readonly ISimpleTagParserContainer _simpleTagParserContainer; private readonly MarkdownWrapper _markdownWrapper; private readonly IDynamicTagParser<Document> _documentTagParser; public EventFactory(ISimpleTagParserContainer simpleTagParserContainer, MarkdownWrapper markdownWrapper, IDynamicTagParser<Document> documentTagParser) { _simpleTagParserContainer = simpleTagParserContainer; _markdownWrapper = markdownWrapper; _documentTagParser = documentTagParser; } public virtual ProcessedEvents Build(Event eventItem) { var description = _simpleTagParserContainer.ParseAll(eventItem.Description, eventItem.Title); description = _documentTagParser.Parse(description, eventItem.Documents); description = _markdownWrapper.ConvertToHtml(description ?? ""); return new ProcessedEvents(eventItem.Title, eventItem.Slug, eventItem.Teaser, eventItem.ImageUrl, eventItem.ThumbnailImageUrl, description, eventItem.Fee, eventItem.Location, eventItem.SubmittedBy, eventItem.EventDate, eventItem.StartTime, eventItem.EndTime, eventItem.Breadcrumbs); } } }
using StockportWebapp.Models; using StockportWebapp.Parsers; using StockportWebapp.Utils; namespace StockportWebapp.ContentFactory { public class EventFactory { private readonly ISimpleTagParserContainer _simpleTagParserContainer; private readonly MarkdownWrapper _markdownWrapper; private readonly IDynamicTagParser<Document> _documentTagParser; public EventFactory(ISimpleTagParserContainer simpleTagParserContainer, MarkdownWrapper markdownWrapper, IDynamicTagParser<Document> documentTagParser) { _simpleTagParserContainer = simpleTagParserContainer; _markdownWrapper = markdownWrapper; _documentTagParser = documentTagParser; } public virtual ProcessedEvents Build(Event eventItem) { var description = _simpleTagParserContainer.ParseAll(eventItem.Description, eventItem.Title); description = _markdownWrapper.ConvertToHtml(description ?? ""); description = _documentTagParser.Parse(description, eventItem.Documents); return new ProcessedEvents(eventItem.Title, eventItem.Slug, eventItem.Teaser, eventItem.ImageUrl, eventItem.ThumbnailImageUrl, description, eventItem.Fee, eventItem.Location, eventItem.SubmittedBy, eventItem.EventDate, eventItem.StartTime, eventItem.EndTime, eventItem.Breadcrumbs); } } }
Use non-guest user ID for non-guest user
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Bindables; using osu.Game.Users; namespace osu.Game.Online.API { public class DummyAPIAccess : IAPIProvider { public Bindable<User> LocalUser { get; } = new Bindable<User>(new User { Username = @"Dummy", Id = 1001, }); public bool IsLoggedIn => true; public string ProvidedUsername => LocalUser.Value.Username; public string Endpoint => "http://localhost"; public APIState State => LocalUser.Value.Id == 1 ? APIState.Offline : APIState.Online; public virtual void Queue(APIRequest request) { } public void Register(IOnlineComponent component) { // todo: add support } public void Unregister(IOnlineComponent component) { // todo: add support } public void Login(string username, string password) { LocalUser.Value = new User { Username = @"Dummy", Id = 1, }; } public void Logout() { LocalUser.Value = new GuestUser(); } public RegistrationRequest.RegistrationRequestErrors CreateAccount(string email, string username, string password) => null; } }
// 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.Users; namespace osu.Game.Online.API { public class DummyAPIAccess : IAPIProvider { public Bindable<User> LocalUser { get; } = new Bindable<User>(new User { Username = @"Dummy", Id = 1001, }); public bool IsLoggedIn => true; public string ProvidedUsername => LocalUser.Value.Username; public string Endpoint => "http://localhost"; public APIState State => LocalUser.Value.Id == 1 ? APIState.Offline : APIState.Online; public virtual void Queue(APIRequest request) { } public void Register(IOnlineComponent component) { // todo: add support } public void Unregister(IOnlineComponent component) { // todo: add support } public void Login(string username, string password) { LocalUser.Value = new User { Username = @"Dummy", Id = 1001, }; } public void Logout() { LocalUser.Value = new GuestUser(); } public RegistrationRequest.RegistrationRequestErrors CreateAccount(string email, string username, string password) => null; } }
Add overload SerializeToXml with object type
using System.IO; using System.Linq; using System.Text; using System.Xml; using System.Xml.Serialization; using JetBrains.Annotations; namespace Diadoc.Api { public static class XmlSerializerExtensions { public static byte[] SerializeToXml<T>(this T @object) { var serializer = new XmlSerializer(typeof(T)); using (var ms = new MemoryStream()) { using (var sw = new StreamWriter(ms, Encoding.UTF8)) { XmlSerializerNamespaces namespaces = null; var ns = FindXmlNamespace<T>(); if (!IsNullOrWhiteSpace(ns)) { namespaces = new XmlSerializerNamespaces(); namespaces.Add("", ns); } serializer.Serialize(sw, @object, namespaces ?? new XmlSerializerNamespaces(new[] {new XmlQualifiedName(string.Empty)})); } return ms.ToArray(); } } [CanBeNull] private static string FindXmlNamespace<T>() { var root = typeof(T).GetCustomAttributes(typeof(XmlRootAttribute), true).Cast<XmlRootAttribute>().FirstOrDefault(); return root != null && !IsNullOrWhiteSpace(root.Namespace) ? root.Namespace : null; } private static bool IsNullOrWhiteSpace(string value) => string.IsNullOrEmpty(value) || value.Trim().Length == 0; } }
using System.IO; using System.Linq; using System.Text; using System.Xml; using System.Xml.Serialization; using JetBrains.Annotations; namespace Diadoc.Api { public static class XmlSerializerExtensions { public static byte[] SerializeToXml<T>(this T @object) { var serializer = new XmlSerializer(typeof(T)); return SerializeToXml(@object, serializer); } public static byte[] SerializeToXml(object @object) { var serializer = new XmlSerializer(@object.GetType()); return SerializeToXml(@object, serializer); } private static byte[] SerializeToXml<T>(T @object, XmlSerializer serializer) { using (var ms = new MemoryStream()) { using (var sw = new StreamWriter(ms, Encoding.UTF8)) { XmlSerializerNamespaces namespaces = null; var ns = FindXmlNamespace<T>(); if (!IsNullOrWhiteSpace(ns)) { namespaces = new XmlSerializerNamespaces(); namespaces.Add("", ns); } serializer.Serialize(sw, @object, namespaces ?? new XmlSerializerNamespaces(new[] {new XmlQualifiedName(string.Empty)})); } return ms.ToArray(); } } [CanBeNull] private static string FindXmlNamespace<T>() { var root = typeof(T).GetCustomAttributes(typeof(XmlRootAttribute), true).Cast<XmlRootAttribute>().FirstOrDefault(); return root != null && !IsNullOrWhiteSpace(root.Namespace) ? root.Namespace : null; } private static bool IsNullOrWhiteSpace(string value) => string.IsNullOrEmpty(value) || value.Trim().Length == 0; } }
Add assembly attribute to get rid of warnings
using System.Reflection; [assembly: AssemblyTitle("GraphQL")] [assembly: AssemblyProduct("GraphQL")] [assembly: AssemblyDescription("GraphQL for .NET")] [assembly: AssemblyCopyright("Copyright 2015-2016 Joseph T. McBride, et al. All rights reserved.")] [assembly: AssemblyVersion("0.8.2.0")] [assembly: AssemblyFileVersion("0.8.2.0")]
using System; using System.Reflection; [assembly: AssemblyTitle("GraphQL")] [assembly: AssemblyProduct("GraphQL")] [assembly: AssemblyDescription("GraphQL for .NET")] [assembly: AssemblyCopyright("Copyright 2015-2016 Joseph T. McBride, et al. All rights reserved.")] [assembly: AssemblyVersion("0.8.2.0")] [assembly: AssemblyFileVersion("0.8.2.0")] [assembly: CLSCompliant(false)]
Add deploy experiment function to left-click on button
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.UI; using BetterNotes.NoteClasses; namespace BetterNotes.NoteUIObjects { public class NoteExpButton : NoteUIObjectBase { private NotesExperiment expObject; private bool highlight; private void Start() { highlight = NotesMainMenu.Settings.HighLightPart; } protected override void OnLeftClick() { //Run Experiment } protected override void OnRightClick() { //Part Right-Click menu } protected override void OnMouseIn() { if (highlight) expObject.RootPart.SetHighlight(true, false); } protected override void OnMouseOut() { if (highlight) expObject.RootPart.SetHighlight(false, false); } protected override void ToolTip() { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.UI; using BetterNotes.NoteClasses; namespace BetterNotes.NoteUIObjects { public class NoteExpButton : NoteUIObjectBase { private NotesExperiment expObject; private bool highlight; private void Start() { highlight = NotesMainMenu.Settings.HighLightPart; } protected override bool assignObject(object obj) { if (obj == null || obj.GetType() != typeof(NotesExperiment)) { return false; } expObject = (NotesExperiment)obj; return true; } protected override void OnLeftClick() { if (expObject.deployExperiment()) { //log success } else { //log fail } } protected override void OnRightClick() { //Part Right-Click menu } protected override void OnMouseIn() { if (highlight) expObject.RootPart.SetHighlight(true, false); } protected override void OnMouseOut() { if (highlight) expObject.RootPart.SetHighlight(false, false); } protected override void ToolTip() { throw new NotImplementedException(); } } }
Remove apostrophe in parse error description
using System.Collections.Generic; namespace Esprima { public class ErrorHandler : IErrorHandler { public IList<ParserException> Errors { get; } public bool Tolerant { get; set; } public string Source { get; set; } public ErrorHandler() { Errors = new List<ParserException>(); Tolerant = false; } public void RecordError(ParserException error) { Errors.Add(error); } public void Tolerate(ParserException error) { if (Tolerant) { RecordError(error); } else { throw error; } } public ParserException CreateError(int index, int line, int col, string description) { var msg = $"Line {line}': {description}"; var error = new ParserException(msg) { Index = index, Column = col, LineNumber = line, Description = description, Source = Source }; return error; } public void TolerateError(int index, int line, int col, string description) { var error = this.CreateError(index, line, col, description); if (Tolerant) { this.RecordError(error); } else { throw error; } } } }
using System.Collections.Generic; namespace Esprima { public class ErrorHandler : IErrorHandler { public IList<ParserException> Errors { get; } public bool Tolerant { get; set; } public string Source { get; set; } public ErrorHandler() { Errors = new List<ParserException>(); Tolerant = false; } public void RecordError(ParserException error) { Errors.Add(error); } public void Tolerate(ParserException error) { if (Tolerant) { RecordError(error); } else { throw error; } } public ParserException CreateError(int index, int line, int col, string description) { var msg = $"Line {line}: {description}"; var error = new ParserException(msg) { Index = index, Column = col, LineNumber = line, Description = description, Source = Source }; return error; } public void TolerateError(int index, int line, int col, string description) { var error = this.CreateError(index, line, col, description); if (Tolerant) { this.RecordError(error); } else { throw error; } } } }
Add helper WebRequest extensions, useful when playing with REST-ful APIs
using System.IO; using System.Net; namespace ServiceStack.Text { public static class WebRequestExtensions { public static string GetJsonFromUrl(this string url) { return url.GetStringFromUrl("application/json"); } public static string GetStringFromUrl(this string url, string acceptContentType) { var webReq = (HttpWebRequest)WebRequest.Create(url); webReq.Accept = acceptContentType; using (var webRes = webReq.GetResponse()) using (var stream = webRes.GetResponseStream()) using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } } }
using System; using System.IO; using System.Net; namespace ServiceStack.Text { public static class WebRequestExtensions { public static string GetJsonFromUrl(this string url) { return url.GetStringFromUrl("application/json"); } public static string GetStringFromUrl(this string url, string acceptContentType="*/*") { var webReq = (HttpWebRequest)WebRequest.Create(url); webReq.Accept = acceptContentType; using (var webRes = webReq.GetResponse()) using (var stream = webRes.GetResponseStream()) using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } public static bool Is404(this Exception ex) { return HasStatus(ex as WebException, HttpStatusCode.NotFound); } public static HttpStatusCode? GetResponseStatus(this string url) { try { var webReq = (HttpWebRequest)WebRequest.Create(url); using (var webRes = webReq.GetResponse()) { var httpRes = webRes as HttpWebResponse; return httpRes != null ? httpRes.StatusCode : (HttpStatusCode?)null; } } catch (Exception ex) { return ex.GetStatus(); } } public static HttpStatusCode? GetStatus(this Exception ex) { return GetStatus(ex as WebException); } public static HttpStatusCode? GetStatus(this WebException webEx) { if (webEx == null) return null; var httpRes = webEx.Response as HttpWebResponse; return httpRes != null ? httpRes.StatusCode : (HttpStatusCode?) null; } public static bool HasStatus(this WebException webEx, HttpStatusCode statusCode) { return GetStatus(webEx) == statusCode; } } }
Read sound until the end of file correctly
using System; using System.IO; using System.Text; namespace ValveResourceFormat.ResourceTypes { public class Sound : Blocks.ResourceData { private BinaryReader Reader; private long DataOffset; private NTRO NTROBlock; public override void Read(BinaryReader reader, Resource resource) { Reader = reader; reader.BaseStream.Position = Offset; if (resource.Blocks.ContainsKey(BlockType.NTRO)) { NTROBlock = new NTRO(); NTROBlock.Offset = Offset; NTROBlock.Size = Size; NTROBlock.Read(reader, resource); } DataOffset = Offset + Size; } public byte[] GetSound() { Reader.BaseStream.Position = DataOffset; return Reader.ReadBytes((int)Reader.BaseStream.Length); } public override string ToString() { if (NTROBlock != null) { return NTROBlock.ToString(); } return "This is a sound."; } } }
using System; using System.IO; using System.Text; namespace ValveResourceFormat.ResourceTypes { public class Sound : Blocks.ResourceData { private BinaryReader Reader; private NTRO NTROBlock; public override void Read(BinaryReader reader, Resource resource) { Reader = reader; reader.BaseStream.Position = Offset; if (resource.Blocks.ContainsKey(BlockType.NTRO)) { NTROBlock = new NTRO(); NTROBlock.Offset = Offset; NTROBlock.Size = Size; NTROBlock.Read(reader, resource); } } public byte[] GetSound() { Reader.BaseStream.Position = Offset + Size; return Reader.ReadBytes((int)(Reader.BaseStream.Length - Reader.BaseStream.Position)); } public override string ToString() { if (NTROBlock != null) { return NTROBlock.ToString(); } return "This is a sound."; } } }
Revert "Fix error when launching missing files"
#region using System.Diagnostics; using System.IO; using DesktopWidgets.Classes; #endregion namespace DesktopWidgets.Helpers { internal static class ProcessHelper { public static void Launch(string path, string args = "", string startIn = "", ProcessWindowStyle style = ProcessWindowStyle.Normal) { Launch(new ProcessFile {Path = path, Arguments = args, StartInFolder = startIn, WindowStyle = style}); } public static void Launch(ProcessFile file) { if (string.IsNullOrWhiteSpace(file.Path) || !File.Exists(file.Path)) return; Process.Start(new ProcessStartInfo { FileName = file.Path, Arguments = file.Arguments, WorkingDirectory = file.StartInFolder, WindowStyle = file.WindowStyle }); } public static void OpenFolder(string path) { if (File.Exists(path) || Directory.Exists(path)) Launch("explorer.exe", "/select," + path); } } }
#region using System.Diagnostics; using System.IO; using DesktopWidgets.Classes; #endregion namespace DesktopWidgets.Helpers { internal static class ProcessHelper { public static void Launch(string path, string args = "", string startIn = "", ProcessWindowStyle style = ProcessWindowStyle.Normal) { Launch(new ProcessFile {Path = path, Arguments = args, StartInFolder = startIn, WindowStyle = style}); } public static void Launch(ProcessFile file) { Process.Start(new ProcessStartInfo { FileName = file.Path, Arguments = file.Arguments, WorkingDirectory = file.StartInFolder, WindowStyle = file.WindowStyle }); } public static void OpenFolder(string path) { if (File.Exists(path) || Directory.Exists(path)) Launch("explorer.exe", "/select," + path); } } }
Add a `lib` prefix to the DllImport so it works with mono
using System; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace Dbus { public partial class Connection { private static async Task authenticate(Stream stream) { using (var writer = new StreamWriter(stream, Encoding.ASCII, 32, true)) using (var reader = new StreamReader(stream, Encoding.ASCII, false, 32, true)) { writer.NewLine = "\r\n"; await writer.WriteAsync("\0AUTH EXTERNAL ").ConfigureAwait(false); var uid = getuid(); var stringUid = $"{uid}"; var uidBytes = Encoding.ASCII.GetBytes(stringUid); foreach (var b in uidBytes) await writer.WriteAsync($"{b:X}").ConfigureAwait(false); await writer.WriteLineAsync().ConfigureAwait(false); await writer.FlushAsync().ConfigureAwait(false); var response = await reader.ReadLineAsync().ConfigureAwait(false); if (!response.StartsWith("OK ")) throw new InvalidOperationException("Authentication failed: " + response); await writer.WriteLineAsync("BEGIN").ConfigureAwait(false); await writer.FlushAsync().ConfigureAwait(false); } } [DllImport("c")] private static extern int getuid(); } }
using System; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace Dbus { public partial class Connection { private static async Task authenticate(Stream stream) { using (var writer = new StreamWriter(stream, Encoding.ASCII, 32, true)) using (var reader = new StreamReader(stream, Encoding.ASCII, false, 32, true)) { writer.NewLine = "\r\n"; await writer.WriteAsync("\0AUTH EXTERNAL ").ConfigureAwait(false); var uid = getuid(); var stringUid = $"{uid}"; var uidBytes = Encoding.ASCII.GetBytes(stringUid); foreach (var b in uidBytes) await writer.WriteAsync($"{b:X}").ConfigureAwait(false); await writer.WriteLineAsync().ConfigureAwait(false); await writer.FlushAsync().ConfigureAwait(false); var response = await reader.ReadLineAsync().ConfigureAwait(false); if (!response.StartsWith("OK ")) throw new InvalidOperationException("Authentication failed: " + response); await writer.WriteLineAsync("BEGIN").ConfigureAwait(false); await writer.FlushAsync().ConfigureAwait(false); } } [DllImport("libc")] private static extern int getuid(); } }
Use properties in example code
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using System.Collections.Generic; using NDesk.DBus; using org.freedesktop.DBus; public class ManagedDBusTestObjects { public static void Main () { Bus bus = Bus.Session; ObjectPath myPath = new ObjectPath ("/org/ndesk/test"); string myName = "org.ndesk.test"; //TODO: write the rest of this demo and implement } } public class Device : IDevice { public string GetName () { return "Some device"; } } public class DeviceManager : IDeviceManager { public IDevice GetCurrentDevice () { return new Device (); } } public interface IDevice { string GetName (); } public interface IDeviceManager { IDevice GetCurrentDevice (); } public interface IUglyDeviceManager { ObjectPath GetCurrentDevice (); }
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using System.Collections.Generic; using NDesk.DBus; using org.freedesktop.DBus; public class ManagedDBusTestObjects { public static void Main () { Bus bus = Bus.Session; ObjectPath myPath = new ObjectPath ("/org/ndesk/test"); string myName = "org.ndesk.test"; //TODO: write the rest of this demo and implement } } public class Device : IDevice { public string Name { get { return "Some device"; } } } public class DeviceManager : IDeviceManager { public IDevice CurrentDevice { get { return new Device (); } } } public interface IDevice { string Name { get; } } public interface IDeviceManager { IDevice CurrentDevice { get; } } public interface IUglyDeviceManager { ObjectPath CurrentDevice { get; } }
Correct year when development started.
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Sandra")] [assembly: AssemblyDescription("Hosted on https://github.com/PenguinF/sandra-three")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Sandra")] [assembly: AssemblyCopyright("Copyright © 2002-2016 - Henk Nicolai")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Sandra")] [assembly: AssemblyDescription("Hosted on https://github.com/PenguinF/sandra-three")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Sandra")] [assembly: AssemblyCopyright("Copyright © 2004-2016 - Henk Nicolai")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Fix radius calculation and lower sigma.
using System; namespace Mpdn.CustomLinearScaler { namespace Example { public class Gaussian : ICustomLinearScaler { public Guid Guid { get { return new Guid("647351FF-7FEC-4EAB-86C7-CE1BEF43EFD4"); } } public string Name { get { return "Gaussian"; } } public bool AllowDeRing { get { return false; } } public ScalerTaps MaxTapCount { get { return ScalerTaps.Eight; } } public float GetWeight(float n, int width) { return (float) GaussianKernel(n, width); } private static double GaussianKernel(double x, double radius) { var sigma = radius/6; return Math.Exp(-(x*x/(2*sigma*sigma))); } } } }
using System; namespace Mpdn.CustomLinearScaler { namespace Example { public class Gaussian : ICustomLinearScaler { public Guid Guid { get { return new Guid("647351FF-7FEC-4EAB-86C7-CE1BEF43EFD4"); } } public string Name { get { return "Gaussian"; } } public bool AllowDeRing { get { return false; } } public ScalerTaps MaxTapCount { get { return ScalerTaps.Eight; } } public float GetWeight(float n, int width) { return (float) GaussianKernel(n, width / 2); } private static double GaussianKernel(double x, double radius) { var sigma = radius / 4; return Math.Exp(-(x*x/(2*sigma*sigma))); } } } }
Store messages in list to future filter; Clear method;
using UnityEngine; using UnityEngine.UI; using System.Collections; namespace UDBase.Components.Log { public class Log_Visual_Behaviour : MonoBehaviour { public Text Text; public void Init() { Text.text = ""; } public void AddMessage(string msg) { Text.text += msg + "\n"; } } }
using UnityEngine; using UnityEngine.UI; using System.Collections; using System.Collections.Generic; namespace UDBase.Components.Log { public class Log_Visual_Behaviour : MonoBehaviour { public Text Text; List<string> _messages = new List<string>(); public void Init() { Clear(); } public void Clear() { Text.text = ""; } public void AddMessage(string msg) { _messages.Add(msg); ApplyMessage(msg); } void ApplyMessage(string msg) { Text.text += msg + "\n"; } } }
Remove hack to load correct version of Splat.
using System; using System.Linq; using System.Reflection; using NUnit.Framework; [SetUpFixture] public class SplatModeDetectorSetUp { static SplatModeDetectorSetUp() { // HACK: Force .NET 4.5 version of Splat to load when executing inside NCrunch var ncrunchAsms = Environment.GetEnvironmentVariable("NCrunch.AllAssemblyLocations")?.Split(';'); if (ncrunchAsms != null) { ncrunchAsms.Where(x => x.EndsWith(@"\Net45\Splat.dll")).Select(Assembly.LoadFrom).FirstOrDefault(); } } [OneTimeSetUp] public void RunBeforeAnyTests() { Splat.ModeDetector.Current.SetInUnitTestRunner(true); } }
using System; using System.Linq; using System.Reflection; using NUnit.Framework; [SetUpFixture] public class SplatModeDetectorSetUp { [OneTimeSetUp] public void RunBeforeAnyTests() { Splat.ModeDetector.Current.SetInUnitTestRunner(true); } }
Clean up how IHttpContextAccessor is added
using System; using System.Collections.Generic; using System.Text; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.NodeServices; using Microsoft.AspNetCore.SpaServices.Prerendering; using Microsoft.Extensions.DependencyInjection.Extensions; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Extension methods for setting up prerendering features in an <see cref="IServiceCollection" />. /// </summary> public static class PrerenderingServiceCollectionExtensions { /// <summary> /// Configures the dependency injection system to supply an implementation /// of <see cref="ISpaPrerenderer"/>. /// </summary> /// <param name="serviceCollection">The <see cref="IServiceCollection"/>.</param> public static void AddSpaPrerenderer(this IServiceCollection serviceCollection) { serviceCollection.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>(); serviceCollection.AddSingleton<ISpaPrerenderer, DefaultSpaPrerenderer>(); } } }
using Microsoft.AspNetCore.SpaServices.Prerendering; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Extension methods for setting up prerendering features in an <see cref="IServiceCollection" />. /// </summary> public static class PrerenderingServiceCollectionExtensions { /// <summary> /// Configures the dependency injection system to supply an implementation /// of <see cref="ISpaPrerenderer"/>. /// </summary> /// <param name="serviceCollection">The <see cref="IServiceCollection"/>.</param> public static void AddSpaPrerenderer(this IServiceCollection serviceCollection) { serviceCollection.AddHttpContextAccessor(); serviceCollection.AddSingleton<ISpaPrerenderer, DefaultSpaPrerenderer>(); } } }
Update copyright year to 2018
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("WpfAboutView")] [assembly: AssemblyDescription("Simple About control with app name, icon, version, and credits")] [assembly: AssemblyCompany("Daniel Chalmers")] [assembly: AssemblyProduct("WpfAboutView")] [assembly: AssemblyCopyright("© Daniel Chalmers 2017")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.1.0.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("WpfAboutView")] [assembly: AssemblyDescription("Simple About control with app name, icon, version, and credits")] [assembly: AssemblyCompany("Daniel Chalmers")] [assembly: AssemblyProduct("WpfAboutView")] [assembly: AssemblyCopyright("© Daniel Chalmers 2018")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.1.0.0")]
Add autosize coverage to spinning boxes benchmark
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using BenchmarkDotNet.Attributes; using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osuTK.Graphics; namespace osu.Framework.Benchmarks { public class BenchmarkManySpinningBoxes : GameBenchmark { [Test] [Benchmark] public void RunFrame() => RunSingleFrame(); protected override Game CreateGame() => new TestGame(); private class TestGame : Game { protected override void LoadComplete() { base.LoadComplete(); for (int i = 0; i < 1000; i++) { var box = new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.Black }; Add(box); box.Spin(200, RotationDirection.Clockwise); } } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using BenchmarkDotNet.Attributes; using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osuTK; using osuTK.Graphics; namespace osu.Framework.Benchmarks { public class BenchmarkManySpinningBoxes : GameBenchmark { private TestGame game; [Test] [Benchmark] public void RunFrame() { game.MainContent.AutoSizeAxes = Axes.None; game.MainContent.RelativeSizeAxes = Axes.Both; RunSingleFrame(); } [Test] [Benchmark] public void RunFrameWithAutoSize() { game.MainContent.RelativeSizeAxes = Axes.None; game.MainContent.AutoSizeAxes = Axes.Both; RunSingleFrame(); } [Test] [Benchmark] public void RunFrameWithAutoSizeDuration() { game.MainContent.RelativeSizeAxes = Axes.None; game.MainContent.AutoSizeAxes = Axes.Both; game.MainContent.AutoSizeDuration = 100; RunSingleFrame(); } protected override Game CreateGame() => game = new TestGame(); private class TestGame : Game { public Container MainContent; protected override void LoadComplete() { base.LoadComplete(); Add(MainContent = new Container()); for (int i = 0; i < 1000; i++) { var box = new Box { Size = new Vector2(100), Colour = Color4.Black }; MainContent.Add(box); box.Spin(200, RotationDirection.Clockwise); } } } } }
Use new logo name for showcase screen
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; namespace osu.Game.Tournament.Screens.Showcase { public class TournamentLogo : CompositeDrawable { public TournamentLogo() { RelativeSizeAxes = Axes.X; Margin = new MarginPadding { Vertical = 5 }; Height = 100; } [BackgroundDependencyLoader] private void load(TextureStore textures) { InternalChild = new Sprite { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, FillMode = FillMode.Fit, RelativeSizeAxes = Axes.Both, Texture = textures.Get("game-screen-logo"), }; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; namespace osu.Game.Tournament.Screens.Showcase { public class TournamentLogo : CompositeDrawable { public TournamentLogo() { RelativeSizeAxes = Axes.X; Margin = new MarginPadding { Vertical = 5 }; Height = 100; } [BackgroundDependencyLoader] private void load(TextureStore textures) { InternalChild = new Sprite { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, FillMode = FillMode.Fit, RelativeSizeAxes = Axes.Both, Texture = textures.Get("header-logo"), }; } } }
Remove unsupported column attribute convention with no sql connection.
using EntityCore.DynamicEntity; using EntityCore.Utils; using System.Configuration; using System.Data.Common; using System.Data.Entity; using System.Data.Entity.Infrastructure; namespace EntityCore { public static class Context { public static DynamicEntityContext New(string nameOrConnectionString) { Check.NotEmpty(nameOrConnectionString, "nameOrConnectionString"); var connnection = DbHelpers.GetDbConnection(nameOrConnectionString); DbCompiledModel model = GetCompiledModel(connnection); return new DynamicEntityContext(nameOrConnectionString, model); } public static DynamicEntityContext New(DbConnection existingConnection) { Check.NotNull(existingConnection, "existingConnection"); DbCompiledModel model = GetCompiledModel(existingConnection); return new DynamicEntityContext(existingConnection, model, false); } private static DbCompiledModel GetCompiledModel(DbConnection connection) { var builder = new DbModelBuilder(DbModelBuilderVersion.Latest); foreach (var entity in EntityTypeCache.GetEntitiesTypes(connection)) builder.RegisterEntityType(entity); var model = builder.Build(connection); return model.Compile(); } } }
using EntityCore.DynamicEntity; using EntityCore.Utils; using System.Data.Common; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Data.Entity.ModelConfiguration.Conventions; using System.Data.SqlClient; using System.Linq; namespace EntityCore { public static class Context { public static DynamicEntityContext New(string nameOrConnectionString) { Check.NotEmpty(nameOrConnectionString, "nameOrConnectionString"); var connection = DbHelpers.GetDbConnection(nameOrConnectionString); DbCompiledModel model = GetCompiledModel(connection); return new DynamicEntityContext(nameOrConnectionString, model); } public static DynamicEntityContext New(DbConnection existingConnection) { Check.NotNull(existingConnection, "existingConnection"); DbCompiledModel model = GetCompiledModel(existingConnection); return new DynamicEntityContext(existingConnection, model, false); } private static DbCompiledModel GetCompiledModel(DbConnection connection) { var builder = new DbModelBuilder(DbModelBuilderVersion.Latest); foreach (var entity in EntityTypeCache.GetEntitiesTypes(connection)) builder.RegisterEntityType(entity); if (!(connection is SqlConnection)) // Compatible Effort. See https://effort.codeplex.com/workitem/678 builder.Conventions.Remove<ColumnAttributeConvention>(); var model = builder.Build(connection); return model.Compile(); } } }
Support more polygon trigger types
using System.IO; using OpenZH.Data.Utilities.Extensions; namespace OpenZH.Data.Map { public sealed class PolygonTrigger { public string Name { get; private set; } public string LayerName { get; private set; } public uint UniqueId { get; private set; } public PolygonTriggerType TriggerType { get; private set; } public MapVector3i[] Points { get; private set; } public static PolygonTrigger Parse(BinaryReader reader) { var name = reader.ReadUInt16PrefixedAsciiString(); var layerName = reader.ReadUInt16PrefixedAsciiString(); var uniqueId = reader.ReadUInt32(); var triggerType = reader.ReadUInt32AsEnum<PolygonTriggerType>(); var unknown = reader.ReadUInt16(); if (unknown != 0) { throw new InvalidDataException(); } var numPoints = reader.ReadUInt32(); var points = new MapVector3i[numPoints]; for (var i = 0; i < numPoints; i++) { points[i] = MapVector3i.Parse(reader); } return new PolygonTrigger { Name = name, LayerName = layerName, UniqueId = uniqueId, TriggerType = triggerType, Points = points }; } } public enum PolygonTriggerType : uint { Area = 0, Water = 1 } }
using System; using System.IO; using OpenZH.Data.Utilities.Extensions; namespace OpenZH.Data.Map { public sealed class PolygonTrigger { public string Name { get; private set; } public string LayerName { get; private set; } public uint UniqueId { get; private set; } public PolygonTriggerType TriggerType { get; private set; } public MapVector3i[] Points { get; private set; } public static PolygonTrigger Parse(BinaryReader reader) { var name = reader.ReadUInt16PrefixedAsciiString(); var layerName = reader.ReadUInt16PrefixedAsciiString(); var uniqueId = reader.ReadUInt32(); var triggerType = reader.ReadUInt32AsEnum<PolygonTriggerType>(); var unknown = reader.ReadUInt16(); if (unknown != 0) { throw new InvalidDataException(); } var numPoints = reader.ReadUInt32(); var points = new MapVector3i[numPoints]; for (var i = 0; i < numPoints; i++) { points[i] = MapVector3i.Parse(reader); } return new PolygonTrigger { Name = name, LayerName = layerName, UniqueId = uniqueId, TriggerType = triggerType, Points = points }; } } [Flags] public enum PolygonTriggerType : uint { Area = 0, Water = 1, River = 256, Unknown = 65536, WaterAndRiver = Water | River, WaterAndUnknown = Water | Unknown, } }
Add tests for the status flags set by iny.
using NUnit.Framework; using Mos6510.Instructions; namespace Mos6510.Tests.Instructions { [TestFixture] public class InyTests { [Test] public void IncrementsTheValueInRegisterY() { const int initialValue = 42; var model = new ProgrammingModel(); model.GetRegister(RegisterName.Y).SetValue(initialValue); var instruction = new Iny(); instruction.Execute(model); Assert.That(model.GetRegister(RegisterName.Y).GetValue(), Is.EqualTo(initialValue + 1)); } } }
using NUnit.Framework; using Mos6510.Instructions; namespace Mos6510.Tests.Instructions { [TestFixture] public class InyTests { [Test] public void IncrementsTheValueInRegisterY() { const int initialValue = 42; var model = new ProgrammingModel(); model.GetRegister(RegisterName.Y).SetValue(initialValue); var instruction = new Iny(); instruction.Execute(model); Assert.That(model.GetRegister(RegisterName.Y).GetValue(), Is.EqualTo(initialValue + 1)); } [TestCase(0x7F, true)] [TestCase(0x7E, false)] public void VerifyValuesOfNegativeFlag(int initialValue, bool expectedResult) { var model = new ProgrammingModel(); model.GetRegister(RegisterName.Y).SetValue(initialValue); model.NegativeFlag = !expectedResult; var instruction = new Iny(); instruction.Execute(model); Assert.That(model.NegativeFlag, Is.EqualTo(expectedResult)); } [TestCase(0xFF, true)] [TestCase(0x00, false)] public void VerifyValuesOfZeroFlag(int initialValue, bool expectedResult) { var model = new ProgrammingModel(); model.GetRegister(RegisterName.Y).SetValue(initialValue); model.ZeroFlag = !expectedResult; var instruction = new Iny(); instruction.Execute(model); Assert.That(model.ZeroFlag, Is.EqualTo(expectedResult)); } } }
Rename document to shard in item edges
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph { /// <summary> /// Represents a single item that points to a range from a result. See https://github.com/Microsoft/language-server-protocol/blob/master/indexFormat/specification.md#request-textdocumentreferences /// for an example of item edges. /// </summary> internal sealed class Item : Edge { public Id<LsifDocument> Document { get; } public string? Property { get; } public Item(Id<Vertex> outVertex, Id<Range> range, Id<LsifDocument> document, IdFactory idFactory, string? property = null) : base(label: "item", outVertex, new[] { range.As<Range, Vertex>() }, idFactory) { Document = document; Property = property; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph { /// <summary> /// Represents a single item that points to a range from a result. See https://github.com/Microsoft/language-server-protocol/blob/master/indexFormat/specification.md#request-textdocumentreferences /// for an example of item edges. /// </summary> internal sealed class Item : Edge { public Id<LsifDocument> Shard { get; } public string? Property { get; } public Item(Id<Vertex> outVertex, Id<Range> range, Id<LsifDocument> document, IdFactory idFactory, string? property = null) : base(label: "item", outVertex, new[] { range.As<Range, Vertex>() }, idFactory) { Shard = document; Property = property; } } }
Make point factory method internal.
// ReSharper disable InconsistentNaming #pragma warning disable namespace Gu.Wpf.UiAutomation.WindowsAPI { using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows; [DebuggerDisplay("({X}, {Y})")] [StructLayout(LayoutKind.Sequential)] public struct POINT : IEquatable<POINT> { public int X; public int Y; public POINT(int x, int y) { this.X = x; this.Y = y; } public static bool operator ==(POINT left, POINT right) { return left.Equals(right); } public static bool operator !=(POINT left, POINT right) { return !left.Equals(right); } public static POINT Create(Point p) { return new POINT { X = (int)p.X, Y = (int)p.Y, }; } /// <inheritdoc /> public bool Equals(POINT other) { return this.X == other.X && this.Y == other.Y; } /// <inheritdoc /> public override bool Equals(object obj) => obj is POINT other && this.Equals(other); /// <inheritdoc /> public override int GetHashCode() { unchecked { return (this.X * 397) ^ this.Y; } } } }
// ReSharper disable InconsistentNaming #pragma warning disable namespace Gu.Wpf.UiAutomation.WindowsAPI { using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows; [DebuggerDisplay("({X}, {Y})")] [StructLayout(LayoutKind.Sequential)] public struct POINT : IEquatable<POINT> { public int X; public int Y; public POINT(int x, int y) { this.X = x; this.Y = y; } public static bool operator ==(POINT left, POINT right) { return left.Equals(right); } public static bool operator !=(POINT left, POINT right) { return !left.Equals(right); } /// <inheritdoc /> public bool Equals(POINT other) { return this.X == other.X && this.Y == other.Y; } /// <inheritdoc /> public override bool Equals(object obj) => obj is POINT other && this.Equals(other); /// <inheritdoc /> public override int GetHashCode() { unchecked { return (this.X * 397) ^ this.Y; } } internal static POINT Create(Point p) { return new POINT { X = (int)p.X, Y = (int)p.Y, }; } } }
Add OUTPUT chain to raw, remove POSTROUTING
using System; using System.Collections.Generic; using System.Linq; using System.Text; using IPTables.Net.Exceptions; namespace IPTables.Net.Iptables { /// <summary> /// Data to define the default IPTables tables and chains /// </summary> internal class IPTablesTables { static internal Dictionary<String, List<String>> Tables = new Dictionary<string, List<string>> { { "filter", new List<string>{"INPUT", "FORWARD", "OUTPUT"} }, { "nat", new List<string>{"PREROUTING", "POSTROUTING", "OUTPUT"} }, { "raw", new List<string>{"PREROUTING", "POSTROUTING"} }, { "mangle", new List<string>{"INPUT", "FORWARD", "OUTPUT", "PREROUTING", "POSTROUTING"} }, }; internal static List<String> GetInternalChains(String table) { if (!Tables.ContainsKey(table)) { throw new IpTablesNetException(String.Format("Unknown Table: {0}", table)); } return Tables[table]; } internal static bool IsInternalChain(String table, String chain) { return GetInternalChains(table).Contains(chain); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using IPTables.Net.Exceptions; namespace IPTables.Net.Iptables { /// <summary> /// Data to define the default IPTables tables and chains /// </summary> internal class IPTablesTables { static internal Dictionary<String, List<String>> Tables = new Dictionary<string, List<string>> { { "filter", new List<string>{"INPUT", "FORWARD", "OUTPUT"} }, { "nat", new List<string>{"PREROUTING", "POSTROUTING", "OUTPUT"} }, { "raw", new List<string>{"PREROUTING", "POSTROUTING", "OUTPUT"} }, { "mangle", new List<string>{"INPUT", "FORWARD", "OUTPUT", "PREROUTING", "POSTROUTING"} }, }; internal static List<String> GetInternalChains(String table) { if (!Tables.ContainsKey(table)) { throw new IpTablesNetException(String.Format("Unknown Table: {0}", table)); } return Tables[table]; } internal static bool IsInternalChain(String table, String chain) { return GetInternalChains(table).Contains(chain); } } }
Remove redundant line from mod usage
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Rulesets.Mods { /// <summary> /// The usage of this mod to determine whether it's playable in such context. /// </summary> public enum ModUsage { /// <summary> /// Used for a per-user gameplay session. /// Determines whether the mod is playable by an end user. /// </summary> User, /// <summary> /// Used in multiplayer but must be applied to all users. /// This is generally the case for mods which affect the length of gameplay. /// </summary> MultiplayerRoomWide, /// <summary> /// Used in multiplayer either at a room or per-player level (i.e. "free mod"). /// </summary> MultiplayerPerPlayer, } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Rulesets.Mods { /// <summary> /// The usage of this mod to determine whether it's playable in such context. /// </summary> public enum ModUsage { /// <summary> /// Used for a per-user gameplay session. /// </summary> User, /// <summary> /// Used in multiplayer but must be applied to all users. /// This is generally the case for mods which affect the length of gameplay. /// </summary> MultiplayerRoomWide, /// <summary> /// Used in multiplayer either at a room or per-player level (i.e. "free mod"). /// </summary> MultiplayerPerPlayer, } }
Save as consistent filename to make other scripting easier.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Diagnostics; namespace MatterHackers.MatterControl.Testing { public class TestingDispatch { string errorLogFileName = null; public TestingDispatch() { errorLogFileName = string.Format("ErrorLog - {0:yyyy-MM-dd hh-mmtt}.txt", DateTime.Now); string firstLine = string.Format("MatterControl Errors: {0:yyyy-MM-dd hh:mm:ss tt}", DateTime.Now); using (StreamWriter file = new StreamWriter(errorLogFileName)) { file.WriteLine(errorLogFileName, firstLine); } } public void RunTests(string[] testCommands) { try { ReleaseTests.AssertDebugNotDefined(); } catch (Exception e) { DumpException(e); } try { MatterHackers.GCodeVisualizer.GCodeFile.AssertDebugNotDefined(); } catch (Exception e) { DumpException(e); } } void DumpException(Exception e) { using (StreamWriter w = File.AppendText(errorLogFileName)) { w.WriteLine(e.Message); w.Write(e.StackTrace); w.WriteLine(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Diagnostics; namespace MatterHackers.MatterControl.Testing { public class TestingDispatch { string errorLogFileName = null; public TestingDispatch() { errorLogFileName = "ErrorLog.txt"; string firstLine = string.Format("MatterControl Errors: {0:yyyy-MM-dd hh:mm:ss tt}", DateTime.Now); using (StreamWriter file = new StreamWriter(errorLogFileName)) { file.WriteLine(errorLogFileName, firstLine); } } public void RunTests(string[] testCommands) { try { ReleaseTests.AssertDebugNotDefined(); } catch (Exception e) { DumpException(e); } try { MatterHackers.GCodeVisualizer.GCodeFile.AssertDebugNotDefined(); } catch (Exception e) { DumpException(e); } } void DumpException(Exception e) { using (StreamWriter w = File.AppendText(errorLogFileName)) { w.WriteLine(e.Message); w.Write(e.StackTrace); w.WriteLine(); } } } }
Use double instead of float
using System; namespace UnhelpfulDebugger { class Program { static void Main() { string awkward1 = "Foo\\Bar"; string awkward2 = "FindEle‌​ment"; float awkward3 = 4.9999995f; Console.WriteLine(awkward1); PrintString(awkward1); Console.WriteLine(awkward2); PrintString(awkward2); Console.WriteLine(awkward3); PrintDouble(awkward3); } static void PrintString(string text) { Console.WriteLine($"Text: '{text}'"); Console.WriteLine($"Length: {text.Length}"); for (int i = 0; i < text.Length; i++) { Console.WriteLine($"{i,2} U+{((int)text[i]):0000} '{text[i]}'"); } } static void PrintDouble(double value) => Console.WriteLine(DoubleConverter.ToExactString(value)); } }
using System; namespace UnhelpfulDebugger { class Program { static void Main() { string awkward1 = "Foo\\Bar"; string awkward2 = "FindEle‌​ment"; double awkward3 = 4.9999999999999995d; Console.WriteLine(awkward1); PrintString(awkward1); Console.WriteLine(awkward2); PrintString(awkward2); Console.WriteLine(awkward3); PrintDouble(awkward3); } static void PrintString(string text) { Console.WriteLine($"Text: '{text}'"); Console.WriteLine($"Length: {text.Length}"); for (int i = 0; i < text.Length; i++) { Console.WriteLine($"{i,2} U+{((int)text[i]):0000} '{text[i]}'"); } } static void PrintDouble(double value) => Console.WriteLine(DoubleConverter.ToExactString(value)); } }
Use empty accessor for unimplemented events.
// 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 Foundation; using osu.Framework.Input; namespace osu.Framework.iOS.Input { public class IOSTextInput : ITextInputSource { private readonly IOSGameView view; private string pending = string.Empty; public IOSTextInput(IOSGameView view) { this.view = view; } public bool ImeActive => false; public string GetPendingText() { try { return pending; } finally { pending = string.Empty; } } private void handleShouldChangeCharacters(NSRange range, string text) { if (text == " " || text.Trim().Length > 0) pending += text; } public void Deactivate(object sender) { view.KeyboardTextField.HandleShouldChangeCharacters -= handleShouldChangeCharacters; view.KeyboardTextField.UpdateFirstResponder(false); } public void Activate(object sender) { view.KeyboardTextField.HandleShouldChangeCharacters += handleShouldChangeCharacters; view.KeyboardTextField.UpdateFirstResponder(true); } public event Action<string> OnNewImeComposition; public event Action<string> OnNewImeResult; } }
// 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 Foundation; using osu.Framework.Input; namespace osu.Framework.iOS.Input { public class IOSTextInput : ITextInputSource { private readonly IOSGameView view; private string pending = string.Empty; public IOSTextInput(IOSGameView view) { this.view = view; } public bool ImeActive => false; public string GetPendingText() { try { return pending; } finally { pending = string.Empty; } } private void handleShouldChangeCharacters(NSRange range, string text) { if (text == " " || text.Trim().Length > 0) pending += text; } public void Deactivate(object sender) { view.KeyboardTextField.HandleShouldChangeCharacters -= handleShouldChangeCharacters; view.KeyboardTextField.UpdateFirstResponder(false); } public void Activate(object sender) { view.KeyboardTextField.HandleShouldChangeCharacters += handleShouldChangeCharacters; view.KeyboardTextField.UpdateFirstResponder(true); } public event Action<string> OnNewImeComposition { add { } remove { } } public event Action<string> OnNewImeResult { add { } remove { } } } }
Convert vertical scroll to horizontal when shift is held
// 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.Input.StateChanges.Events; using osu.Framework.Input.States; using osuTK; namespace osu.Framework.Input.StateChanges { /// <summary> /// Denotes a relative change of mouse scroll. /// Pointing devices such as mice provide relative scroll input. /// </summary> public class MouseScrollRelativeInput : IInput { /// <summary> /// The change in scroll. This is added to the current scroll. /// </summary> public Vector2 Delta; /// <summary> /// Whether the change came from a device supporting precision scrolling. /// </summary> /// <remarks> /// In cases this is true, scroll events will generally map 1:1 to user's input, rather than incrementing in large "notches" (as expected of traditional scroll wheels). /// </remarks> public bool IsPrecise; public void Apply(InputState state, IInputStateChangeHandler handler) { var mouse = state.Mouse; if (Delta != Vector2.Zero) { var lastScroll = mouse.Scroll; mouse.Scroll += Delta; mouse.LastSource = this; handler.HandleInputStateChange(new MouseScrollChangeEvent(state, this, lastScroll, IsPrecise)); } } } }
// 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.Input.StateChanges.Events; using osu.Framework.Input.States; using osuTK; namespace osu.Framework.Input.StateChanges { /// <summary> /// Denotes a relative change of mouse scroll. /// Pointing devices such as mice provide relative scroll input. /// </summary> public class MouseScrollRelativeInput : IInput { /// <summary> /// The change in scroll. This is added to the current scroll. /// </summary> public Vector2 Delta; /// <summary> /// Whether the change came from a device supporting precision scrolling. /// </summary> /// <remarks> /// In cases this is true, scroll events will generally map 1:1 to user's input, rather than incrementing in large "notches" (as expected of traditional scroll wheels). /// </remarks> public bool IsPrecise; public void Apply(InputState state, IInputStateChangeHandler handler) { var mouse = state.Mouse; if (Delta != Vector2.Zero) { if (!IsPrecise && Delta.X == 0 && state.Keyboard.ShiftPressed) Delta = new Vector2(Delta.Y, 0); var lastScroll = mouse.Scroll; mouse.Scroll += Delta; mouse.LastSource = this; handler.HandleInputStateChange(new MouseScrollChangeEvent(state, this, lastScroll, IsPrecise)); } } } }
Hide or show button in sample application
 @{ ViewBag.Title = "Employees Overview"; } <h2>Employees Overview</h2> You can only see this page if you have the <strong>employee_read</strong> permissions.
@using System.Security.Claims @{ ViewBag.Title = "Employees Overview"; } <h2>Employees Overview</h2> You can only see this page if you have the <strong>employee_read</strong> permissions. <br/> <br/> @if (ClaimsPrincipal.Current.HasClaim(ClaimTypes.Role, "employee_create")) { <a href="@Url.Action("Create", "Employee")" class="btn btn-info btn-lg">Create a new employee</a> }
Save settings.txt to same folder as the assembly
using System.Collections.Generic; using System.Drawing; using System.IO; using ValveKeyValue; namespace GUI.Utils { internal static class Settings { public class AppConfig { public List<string> GameSearchPaths { get; set; } = new List<string>(); public string BackgroundColor { get; set; } = string.Empty; public string OpenDirectory { get; set; } = string.Empty; public string SaveDirectory { get; set; } = string.Empty; } private const string SettingsFilePath = "settings.txt"; public static AppConfig Config { get; set; } = new AppConfig(); public static Color BackgroundColor { get; set; } = Color.FromArgb(60, 60, 60); public static void Load() { if (!File.Exists(SettingsFilePath)) { Save(); return; } using (var stream = new FileStream(SettingsFilePath, FileMode.Open, FileAccess.Read)) { Config = KVSerializer.Create(KVSerializationFormat.KeyValues1Text).Deserialize<AppConfig>(stream, KVSerializerOptions.DefaultOptions); } BackgroundColor = ColorTranslator.FromHtml(Config.BackgroundColor); } public static void Save() { Config.BackgroundColor = ColorTranslator.ToHtml(BackgroundColor); using (var stream = new FileStream(SettingsFilePath, FileMode.Create, FileAccess.Write, FileShare.None)) { KVSerializer.Create(KVSerializationFormat.KeyValues1Text).Serialize(stream, Config, nameof(ValveResourceFormat)); } } } }
using System.Collections.Generic; using System.Drawing; using System.IO; using ValveKeyValue; namespace GUI.Utils { internal static class Settings { public class AppConfig { public List<string> GameSearchPaths { get; set; } = new List<string>(); public string BackgroundColor { get; set; } = string.Empty; public string OpenDirectory { get; set; } = string.Empty; public string SaveDirectory { get; set; } = string.Empty; } private static string SettingsFilePath; public static AppConfig Config { get; set; } = new AppConfig(); public static Color BackgroundColor { get; set; } = Color.FromArgb(60, 60, 60); public static void Load() { SettingsFilePath = Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location), "settings.txt"); if (!File.Exists(SettingsFilePath)) { Save(); return; } using (var stream = new FileStream(SettingsFilePath, FileMode.Open, FileAccess.Read)) { Config = KVSerializer.Create(KVSerializationFormat.KeyValues1Text).Deserialize<AppConfig>(stream, KVSerializerOptions.DefaultOptions); } BackgroundColor = ColorTranslator.FromHtml(Config.BackgroundColor); } public static void Save() { Config.BackgroundColor = ColorTranslator.ToHtml(BackgroundColor); using (var stream = new FileStream(SettingsFilePath, FileMode.Create, FileAccess.Write, FileShare.None)) { KVSerializer.Create(KVSerializationFormat.KeyValues1Text).Serialize(stream, Config, nameof(ValveResourceFormat)); } } } }
Fix logic in home index to go to a slug if provided
using System; using System.Linq; using downr.Services; using Microsoft.AspNetCore.Mvc; namespace downr.Controllers { public class HomeController : Controller { IYamlIndexer _indexer; public HomeController(IYamlIndexer indexer) { _indexer = indexer; } [Route("{id?}")] public IActionResult Index(string id) { // if no slug was provided show the last one if (string.IsNullOrEmpty(id)) return RedirectToAction("Index", "Posts", new { slug = _indexer.Metadata.ElementAt(0).Slug }); // if the slug was provided AND found, redirect to it if (_indexer.Metadata.Any(x => x.Slug == id)) return RedirectToAction("Index", "Posts", new { slug = _indexer.Metadata.ElementAt(0).Slug }); else // no match was found, show the last one return RedirectToAction("Index", "Posts", new { slug = _indexer.Metadata.ElementAt(0).Slug }); } } }
using System; using System.Linq; using downr.Services; using Microsoft.AspNetCore.Mvc; namespace downr.Controllers { public class HomeController : Controller { IYamlIndexer _indexer; public HomeController(IYamlIndexer indexer) { _indexer = indexer; } [Route("{id?}")] public IActionResult Index(string id) { //Go to a slug if provided otherwise go to latest. var slug = _indexer.Metadata.FirstOrDefault(x => x.Slug == id)?.Slug; return RedirectToAction("Index", "Posts", new { slug = slug ?? _indexer.Metadata.ElementAt(0).Slug }); } } }
Change GC Handicapping sticky note
<div class="sticky-notes"> <div class="sticky-note"> <i class="pin"></i> <div class="content green"> <h1> GC Handicapping System </h1> <p> New <a href="/disciplines/golf-croquet/resources">GC Handicapping System</a> comes into effect 3 April, 2017 </p> </div> </div> </div>
<div class="sticky-notes"> <div class="sticky-note"> <i class="pin"></i> <div class="content green"> <h1> GC Handicapping System </h1> <p> New <a href="/disciplines/golf-croquet/resources">GC Handicapping System</a> came into effect 3 April, 2017 </p> </div> </div> </div>
Update tests to pass new required title parameter.
// 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.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServer.CustomProtocol; using Newtonsoft.Json.Linq; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests { public class RunCodeActionsHandlerTests : AbstractLiveShareRequestHandlerTests { [WpfFact] public async Task TestRunCodeActionsAsync() { var markup = @"class A { void M() { {|caret:|}int i = 1; } }"; var (solution, ranges) = CreateTestSolution(markup); var codeActionLocation = ranges["caret"].First(); var results = await TestHandleAsync<LSP.ExecuteCommandParams, object>(solution, CreateExecuteCommandParams(codeActionLocation)); Assert.True((bool)results); } private static LSP.ExecuteCommandParams CreateExecuteCommandParams(LSP.Location location) => new LSP.ExecuteCommandParams() { Command = "_liveshare.remotecommand.Roslyn", Arguments = new object[] { JObject.FromObject(new LSP.Command() { CommandIdentifier = "Roslyn.RunCodeAction", Arguments = new RunCodeActionParams[] { CreateRunCodeActionParams("Use implicit type", location) } }) } }; } }
// 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.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServer.CustomProtocol; using Newtonsoft.Json.Linq; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests { public class RunCodeActionsHandlerTests : AbstractLiveShareRequestHandlerTests { [WpfFact] public async Task TestRunCodeActionsAsync() { var markup = @"class A { void M() { {|caret:|}int i = 1; } }"; var (solution, ranges) = CreateTestSolution(markup); var codeActionLocation = ranges["caret"].First(); var results = await TestHandleAsync<LSP.ExecuteCommandParams, object>(solution, CreateExecuteCommandParams(codeActionLocation, "Use implicit type")); Assert.True((bool)results); } private static LSP.ExecuteCommandParams CreateExecuteCommandParams(LSP.Location location, string title) => new LSP.ExecuteCommandParams() { Command = "_liveshare.remotecommand.Roslyn", Arguments = new object[] { JObject.FromObject(new LSP.Command() { CommandIdentifier = "Roslyn.RunCodeAction", Arguments = new RunCodeActionParams[] { CreateRunCodeActionParams(title, location) }, Title = title }) } }; } }
Correct extension definition configuration value
using Loupe.Extensibility; using Loupe.Extensibility.Client; namespace Loupe.Extension.Export { /// <summary> /// Top-level class for integrating with the Loupe framework /// </summary> [LoupeExtension(ConfigurationEditor = typeof(ExportConfigurationDialog), MachineConfiguration = typeof(ExportAddInConfiguration))] public class ExtentionDefinition : IExtensionDefinition { /// <summary> /// Called to register the extension. /// </summary> /// <param name="context">A standard interface to the hosting environment for the Extension, provided to all the different extensions that get loaded.</param><param name="definitionContext">Used to register the various types used by the extension.</param> /// <remarks> /// <para> /// If any exception is thrown during this call this Extension will not be loaded. /// </para> /// <para> /// Register each of the other extension types that should be available to end users through appropriate calls to /// the definitionContext. These objects will be created and initialized as required and provided the same IExtensionContext object instance provided to this /// method to enable coordination between all of the components. /// </para> /// <para> /// After registration the extension definition object is unloaded and disposed. /// </para> /// </remarks> public void Register(IGlobalContext context, IExtensionDefinitionContext definitionContext) { //we have to register all of our types during this call or they won't be used at all. definitionContext.RegisterSessionAnalyzer(typeof(SessionExporter)); definitionContext.RegisterSessionCommand(typeof(SessionExporter)); } } }
using Loupe.Extensibility; using Loupe.Extensibility.Client; namespace Loupe.Extension.Export { /// <summary> /// Top-level class for integrating with the Loupe framework /// </summary> [LoupeExtension(ConfigurationEditor = typeof(ExportConfigurationDialog), CommonConfiguration = typeof(ExportAddInConfiguration))] public class ExtentionDefinition : IExtensionDefinition { /// <summary> /// Called to register the extension. /// </summary> /// <param name="context">A standard interface to the hosting environment for the Extension, provided to all the different extensions that get loaded.</param><param name="definitionContext">Used to register the various types used by the extension.</param> /// <remarks> /// <para> /// If any exception is thrown during this call this Extension will not be loaded. /// </para> /// <para> /// Register each of the other extension types that should be available to end users through appropriate calls to /// the definitionContext. These objects will be created and initialized as required and provided the same IExtensionContext object instance provided to this /// method to enable coordination between all of the components. /// </para> /// <para> /// After registration the extension definition object is unloaded and disposed. /// </para> /// </remarks> public void Register(IGlobalContext context, IExtensionDefinitionContext definitionContext) { //we have to register all of our types during this call or they won't be used at all. definitionContext.RegisterSessionAnalyzer(typeof(SessionExporter)); definitionContext.RegisterSessionCommand(typeof(SessionExporter)); } } }
Add separate log file for debugging service
using Microsoft.PowerShell.EditorServices.Session; using Microsoft.PowerShell.EditorServices.Transport.Stdio.Event; using Microsoft.PowerShell.EditorServices.Transport.Stdio.Message; using Microsoft.PowerShell.EditorServices.Transport.Stdio.Response; using Nito.AsyncEx; using System.Threading.Tasks; namespace Microsoft.PowerShell.EditorServices.Transport.Stdio.Request { [MessageTypeName("initialize")] public class InitializeRequest : RequestBase<InitializeRequestArguments> { public override async Task ProcessMessage( EditorSession editorSession, MessageWriter messageWriter) { // Send the Initialized event first so that we get breakpoints await messageWriter.WriteMessage( new InitializedEvent()); // Now send the Initialize response to continue setup await messageWriter.WriteMessage( this.PrepareResponse( new InitializeResponse())); } } public class InitializeRequestArguments { public string AdapterId { get; set; } public bool LinesStartAt1 { get; set; } public string PathFormat { get; set; } public bool SourceMaps { get; set; } public string GeneratedCodeDirectory { get; set; } } }
using Microsoft.PowerShell.EditorServices.Session; using Microsoft.PowerShell.EditorServices.Transport.Stdio.Event; using Microsoft.PowerShell.EditorServices.Transport.Stdio.Message; using Microsoft.PowerShell.EditorServices.Transport.Stdio.Response; using Microsoft.PowerShell.EditorServices.Utility; using Nito.AsyncEx; using System.Threading.Tasks; namespace Microsoft.PowerShell.EditorServices.Transport.Stdio.Request { [MessageTypeName("initialize")] public class InitializeRequest : RequestBase<InitializeRequestArguments> { public override async Task ProcessMessage( EditorSession editorSession, MessageWriter messageWriter) { // TODO: Remove this behavior in the near future -- // Create the debug service log in a separate file // so that there isn't a conflict with the default // log file. Logger.Initialize("DebugService.log", LogLevel.Verbose); // Send the Initialized event first so that we get breakpoints await messageWriter.WriteMessage( new InitializedEvent()); // Now send the Initialize response to continue setup await messageWriter.WriteMessage( this.PrepareResponse( new InitializeResponse())); } } public class InitializeRequestArguments { public string AdapterId { get; set; } public bool LinesStartAt1 { get; set; } public string PathFormat { get; set; } public bool SourceMaps { get; set; } public string GeneratedCodeDirectory { get; set; } } }
Check username for null too.
using System.Collections.Generic; using System.Web.Http; using System.Web.Http.Cors; namespace CORS.Controllers { public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "This is a CORS request.", "That works from any origin." }; } // GET api/values/another [HttpGet] [EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")] public IEnumerable<string> Another() { return new string[] { "This is a CORS request.", "It works only from www.bigfont.ca." }; } public class EstimateQuery { public string username { get; set; } } public IHttpActionResult GetTitleEstimate([FromUri] EstimateQuery query) { // All the values in "query" are null or zero // Do some stuff with query if there were anything to do if(query != null) { return Ok(query.username); } else { return Ok("Add a username!"); } } } }
using System.Collections.Generic; using System.Web.Http; using System.Web.Http.Cors; namespace CORS.Controllers { public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "This is a CORS request.", "That works from any origin." }; } // GET api/values/another [HttpGet] [EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")] public IEnumerable<string> Another() { return new string[] { "This is a CORS request.", "It works only from www.bigfont.ca." }; } public class EstimateQuery { public string username { get; set; } } public IHttpActionResult GetTitleEstimate([FromUri] EstimateQuery query) { // All the values in "query" are null or zero // Do some stuff with query if there were anything to do if(query != null && query.username != null) { return Ok(query.username); } else { return Ok("Add a username!"); } } } }
Add the writer to the interface.
using System; using System.Text; namespace Manos.Server { public interface IHttpResponse { IHttpTransaction Transaction { get; } HttpHeaders Headers { get; } HttpResponseStream Stream { get; } Encoding Encoding { get; } int StatusCode { get; set; } bool WriteStatusLine { get; set; } bool WriteHeaders { get; set; } void Write (string str); void Write (string str, params object [] prms); void WriteLine (string str); void WriteLine (string str, params object [] prms); void Write (byte [] data); void SendFile (string file); void Finish (); void SetHeader (string name, string value); void SetCookie (string name, HttpCookie cookie); HttpCookie SetCookie (string name, string value); HttpCookie SetCookie (string name, string value, string domain); HttpCookie SetCookie (string name, string value, DateTime expires); HttpCookie SetCookie (string name, string value, string domain, DateTime expires); HttpCookie SetCookie (string name, string value, TimeSpan max_age); HttpCookie SetCookie (string name, string value, string domain, TimeSpan max_age); void Redirect (string url); } }
using System; using System.IO; using System.Text; namespace Manos.Server { public interface IHttpResponse { IHttpTransaction Transaction { get; } HttpHeaders Headers { get; } HttpResponseStream Stream { get; } StreamWriter Writer { get; } Encoding Encoding { get; } int StatusCode { get; set; } bool WriteStatusLine { get; set; } bool WriteHeaders { get; set; } void Write (string str); void Write (string str, params object [] prms); void WriteLine (string str); void WriteLine (string str, params object [] prms); void Write (byte [] data); void SendFile (string file); void Finish (); void SetHeader (string name, string value); void SetCookie (string name, HttpCookie cookie); HttpCookie SetCookie (string name, string value); HttpCookie SetCookie (string name, string value, string domain); HttpCookie SetCookie (string name, string value, DateTime expires); HttpCookie SetCookie (string name, string value, string domain, DateTime expires); HttpCookie SetCookie (string name, string value, TimeSpan max_age); HttpCookie SetCookie (string name, string value, string domain, TimeSpan max_age); void Redirect (string url); } }
Make sure there is a space between the -* and the filtered namespace to prevent any accidental replacements
using System; using System.Collections.Generic; using System.Linq; namespace Giles.Core.Configuration { [Serializable] public class Filter { public Filter() { } public Filter(string convertToFilter) { foreach (var entry in FilterLookUp.Where(entry => convertToFilter.Contains(entry.Key))) { Type = entry.Value; Name = convertToFilter.Replace(entry.Key, string.Empty).Trim(); break; } if (!string.IsNullOrWhiteSpace(Name)) return; Name = convertToFilter.Trim(); Type = FilterType.Inclusive; } public string Name { get; set; } public FilterType Type { get; set; } public string NameDll { get { return Name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ? Name : String.Format("{0}.dll", Name); } } public static readonly IDictionary<string, FilterType> FilterLookUp = new Dictionary<string, FilterType> { {"-i", FilterType.Inclusive}, {"-e", FilterType.Exclusive} }; } public enum FilterType { Inclusive, Exclusive } }
using System; using System.Collections.Generic; using System.Linq; namespace Giles.Core.Configuration { [Serializable] public class Filter { public Filter() { } public Filter(string convertToFilter) { foreach (var entry in FilterLookUp.Where(entry => convertToFilter.Contains(string.Format(" {0}" ,entry.Key)))) { Type = entry.Value; Name = convertToFilter.Replace(string.Format(" {0}", entry.Key), string.Empty).Trim(); break; } if (!string.IsNullOrWhiteSpace(Name)) return; Name = convertToFilter.Trim(); Type = FilterType.Inclusive; } public string Name { get; set; } public FilterType Type { get; set; } public string NameDll { get { return Name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ? Name : String.Format("{0}.dll", Name); } } public static readonly IDictionary<string, FilterType> FilterLookUp = new Dictionary<string, FilterType> { {"-i", FilterType.Inclusive}, {"-e", FilterType.Exclusive} }; } public enum FilterType { Inclusive, Exclusive } }
Fix merge conflict with maitisoumyajit
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVCLibraryManagementSystem.Controllers { public class HomeController : Controller { // GET: Home public ActionResult Index() { return View(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVCLibraryManagementSystem.Controllers { public class HomeController : Controller { // GET: Home public ActionResult Index() { return View(); } } }
Use dispatcher begininvoke for textbox scroll
using System; using System.Windows; using System.Windows.Controls; using vmPing.Classes; namespace vmPing.Views { /// <summary> /// Interaction logic for IsolatedPingWindow.xaml /// </summary> public partial class IsolatedPingWindow : Window { private int SelStart = 0; private int SelLength = 0; public IsolatedPingWindow(Probe pingItem) { InitializeComponent(); pingItem.IsolatedWindow = this; DataContext = pingItem; } private void History_TextChanged(object sender, TextChangedEventArgs e) { History.SelectionStart = SelStart; History.SelectionLength = SelLength; History.ScrollToEnd(); } private void History_SelectionChanged(object sender, RoutedEventArgs e) { SelStart = History.SelectionStart; SelLength = History.SelectionLength; } private void Window_Closed(object sender, EventArgs e) { (DataContext as Probe).IsolatedWindow = null; DataContext = null; } } }
using System; using System.Windows; using System.Windows.Controls; using vmPing.Classes; namespace vmPing.Views { /// <summary> /// Interaction logic for IsolatedPingWindow.xaml /// </summary> public partial class IsolatedPingWindow : Window { private int SelStart = 0; private int SelLength = 0; public IsolatedPingWindow(Probe pingItem) { InitializeComponent(); pingItem.IsolatedWindow = this; DataContext = pingItem; } private void History_TextChanged(object sender, TextChangedEventArgs e) { History.SelectionStart = SelStart; History.SelectionLength = SelLength; Application.Current.Dispatcher.BeginInvoke( new Action(() => History.ScrollToEnd())); } private void History_SelectionChanged(object sender, RoutedEventArgs e) { SelStart = History.SelectionStart; SelLength = History.SelectionLength; } private void Window_Closed(object sender, EventArgs e) { (DataContext as Probe).IsolatedWindow = null; DataContext = null; } } }
Initialize a WindowsContainer when program starts
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AppHarbor { class Program { static void Main(string[] args) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Castle.Windsor; namespace AppHarbor { class Program { static void Main(string[] args) { var container = new WindsorContainer(); } } }
Save game settings on close.
using System.Windows; using Dogstar.Properties; namespace Dogstar { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App { void Application_Startup(object sender, StartupEventArgs e) { if (Settings.Default.UpgradeCheck) { Settings.Default.Upgrade(); Settings.Default.UpgradeCheck = false; Settings.Default.Save(); } foreach (var arg in e.Args) { switch (arg) { case "-pso2": Helper.LaunchGame(); Shutdown(); break; } } } private void Application_Exit(object sender, ExitEventArgs e) { if (e.ApplicationExitCode == 0) { Settings.Default.Save(); } } } }
using System.Windows; using Dogstar.Properties; namespace Dogstar { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App { void Application_Startup(object sender, StartupEventArgs e) { if (Settings.Default.UpgradeCheck) { Settings.Default.Upgrade(); Settings.Default.UpgradeCheck = false; Settings.Default.Save(); } foreach (var arg in e.Args) { switch (arg) { case "-pso2": Helper.LaunchGame(); Shutdown(); break; } } } private void Application_Exit(object sender, ExitEventArgs e) { if (e.ApplicationExitCode == 0) { Settings.Default.Save(); if (Settings.Default.IsGameInstalled) { PsoSettings.Save(); } } } } }
Fix spinner bonus ticks samples not actually playing
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Rulesets.Osu.Judgements; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Osu.Objects.Drawables { public class DrawableSpinnerTick : DrawableOsuHitObject { private bool hasBonusPoints; /// <summary> /// Whether this judgement has a bonus of 1,000 points additional to the numeric result. /// Set when a spin occured after the spinner has completed. /// </summary> public bool HasBonusPoints { get => hasBonusPoints; internal set { hasBonusPoints = value; Samples.Volume.Value = ((OsuSpinnerTickJudgement)Result.Judgement).HasBonusPoints ? 1 : 0; } } public override bool DisplayResult => false; public DrawableSpinnerTick(SpinnerTick spinnerTick) : base(spinnerTick) { } /// <summary> /// Apply a judgement result. /// </summary> /// <param name="hit">Whether to apply a <see cref="HitResult.Great"/> result, <see cref="HitResult.Miss"/> otherwise.</param> internal void TriggerResult(bool hit) { HitObject.StartTime = Time.Current; ApplyResult(r => r.Type = hit ? HitResult.Great : HitResult.Miss); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Rulesets.Osu.Judgements; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Osu.Objects.Drawables { public class DrawableSpinnerTick : DrawableOsuHitObject { private bool hasBonusPoints; /// <summary> /// Whether this judgement has a bonus of 1,000 points additional to the numeric result. /// Set when a spin occured after the spinner has completed. /// </summary> public bool HasBonusPoints { get => hasBonusPoints; internal set { hasBonusPoints = value; ((OsuSpinnerTickJudgement)Result.Judgement).HasBonusPoints = value; Samples.Volume.Value = value ? 1 : 0; } } public override bool DisplayResult => false; public DrawableSpinnerTick(SpinnerTick spinnerTick) : base(spinnerTick) { } /// <summary> /// Apply a judgement result. /// </summary> /// <param name="hit">Whether to apply a <see cref="HitResult.Great"/> result, <see cref="HitResult.Miss"/> otherwise.</param> internal void TriggerResult(bool hit) { HitObject.StartTime = Time.Current; ApplyResult(r => r.Type = hit ? HitResult.Great : HitResult.Miss); } } }
Reword options item to include "screenshot"
// 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.Allocation; using osu.Framework.Graphics; using osu.Game.Configuration; namespace osu.Game.Overlays.Settings.Sections.Graphics { public class DetailSettings : SettingsSubsection { protected override string Header => "Detail Settings"; [BackgroundDependencyLoader] private void load(OsuConfigManager config) { Children = new Drawable[] { new SettingsCheckbox { LabelText = "Storyboards", Bindable = config.GetBindable<bool>(OsuSetting.ShowStoryboard) }, new SettingsCheckbox { LabelText = "Rotate cursor when dragging", Bindable = config.GetBindable<bool>(OsuSetting.CursorRotation) }, new SettingsEnumDropdown<ScreenshotFormat> { LabelText = "Screenshot format", Bindable = config.GetBindable<ScreenshotFormat>(OsuSetting.ScreenshotFormat) }, new SettingsCheckbox { LabelText = "Capture menu cursor", Bindable = config.GetBindable<bool>(OsuSetting.ScreenshotCaptureMenuCursor) } }; } } }
// 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.Allocation; using osu.Framework.Graphics; using osu.Game.Configuration; namespace osu.Game.Overlays.Settings.Sections.Graphics { public class DetailSettings : SettingsSubsection { protected override string Header => "Detail Settings"; [BackgroundDependencyLoader] private void load(OsuConfigManager config) { Children = new Drawable[] { new SettingsCheckbox { LabelText = "Storyboards", Bindable = config.GetBindable<bool>(OsuSetting.ShowStoryboard) }, new SettingsCheckbox { LabelText = "Rotate cursor when dragging", Bindable = config.GetBindable<bool>(OsuSetting.CursorRotation) }, new SettingsEnumDropdown<ScreenshotFormat> { LabelText = "Screenshot format", Bindable = config.GetBindable<ScreenshotFormat>(OsuSetting.ScreenshotFormat) }, new SettingsCheckbox { LabelText = "Show menu cursor in screenshots", Bindable = config.GetBindable<bool>(OsuSetting.ScreenshotCaptureMenuCursor) } }; } } }
Add worker resolve and start Start
using System; using GAIT.Utilities.Logging; using NLog; using Topshelf; using static GAIT.Utilities.GeneralBootstrapper; namespace Rik.CodeCamp.Host { internal class CodeCampControl : ServiceControl { private Bootstrapper _bootstrapper; private readonly ILogger _logger; public CodeCampControl() { _logger = LoggingFactory.Create(GetType()); } public bool Start(HostControl hostControl) { try { _bootstrapper = new Bootstrapper(); //var worker = _bootstrapper.Resolve<IWorker>(); //return worker.Start(); } catch (Exception exception) { _logger.Fatal(exception, "Start failed!!! "); } return false; } public bool Stop(HostControl hostControl) { try { _bootstrapper?.Dispose(); CancelAll.Cancel(); } catch (Exception exception) { _logger.Fatal(exception, "Stop failed!!! "); } return false; } } }
using System; using GAIT.Utilities.Logging; using NLog; using Rik.CodeCamp.Core; using Topshelf; using static GAIT.Utilities.GeneralBootstrapper; namespace Rik.CodeCamp.Host { internal class CodeCampControl : ServiceControl { private Bootstrapper _bootstrapper; private readonly ILogger _logger; public CodeCampControl() { _logger = LoggingFactory.Create(GetType()); } public bool Start(HostControl hostControl) { try { _bootstrapper = new Bootstrapper(); var worker = _bootstrapper.Resolve<IWorker>(); return worker.Start(); } catch (Exception exception) { _logger.Fatal(exception, "Start failed!!! "); } return false; } public bool Stop(HostControl hostControl) { try { _bootstrapper?.Dispose(); CancelAll.Cancel(); } catch (Exception exception) { _logger.Fatal(exception, "Stop failed!!! "); } return false; } } }
Set DialogResult to false on Options cancel
using System; using System.Windows; using SteamAccountSwitcher.Properties; namespace SteamAccountSwitcher { /// <summary> /// Interaction logic for Options.xaml /// </summary> public partial class Options : Window { public Options() { InitializeComponent(); Settings.Default.Save(); } private void menuItemImport_OnClick(object sender, EventArgs e) { AccountDataHelper.ImportAccounts(); } private void menuItemExport_OnClick(object sender, EventArgs e) { AccountDataHelper.ExportAccounts(); } private void btnOK_Click(object sender, RoutedEventArgs e) { SettingsHelper.SaveSettings(); DialogResult = true; } private void btnCancel_Click(object sender, RoutedEventArgs e) { Settings.Default.Reload(); DialogResult = true; } } }
using System; using System.Windows; using SteamAccountSwitcher.Properties; namespace SteamAccountSwitcher { /// <summary> /// Interaction logic for Options.xaml /// </summary> public partial class Options : Window { public Options() { InitializeComponent(); Settings.Default.Save(); } private void menuItemImport_OnClick(object sender, EventArgs e) { AccountDataHelper.ImportAccounts(); } private void menuItemExport_OnClick(object sender, EventArgs e) { AccountDataHelper.ExportAccounts(); } private void btnOK_Click(object sender, RoutedEventArgs e) { SettingsHelper.SaveSettings(); DialogResult = true; } private void btnCancel_Click(object sender, RoutedEventArgs e) { Settings.Default.Reload(); DialogResult = false; } } }
Add more one catch block for ArgumentException
using System; namespace FractionCalculator { using Class; public class TestProgram { public static void Main() { try { Fraction fraction1 = new Fraction(22, 7); Fraction fraction2 = new Fraction(40, 4); Fraction result = fraction1 + fraction2; Console.WriteLine(result.Numerator); Console.WriteLine(result.Denominator); Console.WriteLine(result); } catch (DivideByZeroException ex) { Console.WriteLine(ex.Message); } } } }
using System; namespace FractionCalculator { using Class; public class TestProgram { public static void Main() { try { Fraction fraction1 = new Fraction(22, 7); Fraction fraction2 = new Fraction(40, 4); Fraction result = fraction1 + fraction2; Console.WriteLine(result.Numerator); Console.WriteLine(result.Denominator); Console.WriteLine(result); } catch (DivideByZeroException ex) { Console.WriteLine(ex.Message); } catch (ArgumentException ex) { Console.WriteLine(ex.Message); } } } }
Set result in enumerator and break completes sync
//----------------------------------------------------------------------- // <copyright file="AsyncOperationTest.cs" company="Brian Rogers"> // Copyright (c) Brian Rogers. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace AsyncEnum35Sample.Test.Unit { using System; using System.Collections.Generic; using Xunit; public class AsyncOperationTest { public AsyncOperationTest() { } [Fact] public void Set_result_in_ctor_and_break_completes_sync() { SetResultInCtorOperation op = new SetResultInCtorOperation(1234); IAsyncResult result = op.Start(null, null); Assert.True(result.IsCompleted); Assert.True(result.CompletedSynchronously); Assert.Equal(1234, SetResultInCtorOperation.End(result)); } private abstract class TestAsyncOperation : AsyncOperation<int> { protected TestAsyncOperation() { } } private sealed class SetResultInCtorOperation : TestAsyncOperation { public SetResultInCtorOperation(int result) { this.Result = result; } protected override IEnumerator<Step> Steps() { yield break; } } } }
//----------------------------------------------------------------------- // <copyright file="AsyncOperationTest.cs" company="Brian Rogers"> // Copyright (c) Brian Rogers. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace AsyncEnum35Sample.Test.Unit { using System; using System.Collections.Generic; using Xunit; public class AsyncOperationTest { public AsyncOperationTest() { } [Fact] public void Set_result_in_ctor_and_break_completes_sync() { SetResultInCtorOperation op = new SetResultInCtorOperation(1234); IAsyncResult result = op.Start(null, null); Assert.True(result.IsCompleted); Assert.True(result.CompletedSynchronously); Assert.Equal(1234, SetResultInCtorOperation.End(result)); } [Fact] public void Set_result_in_enumerator_and_break_completes_sync() { SetResultInEnumeratorOperation op = new SetResultInEnumeratorOperation(1234); IAsyncResult result = op.Start(null, null); Assert.True(result.IsCompleted); Assert.True(result.CompletedSynchronously); Assert.Equal(1234, SetResultInEnumeratorOperation.End(result)); } private abstract class TestAsyncOperation : AsyncOperation<int> { protected TestAsyncOperation() { } } private sealed class SetResultInCtorOperation : TestAsyncOperation { public SetResultInCtorOperation(int result) { this.Result = result; } protected override IEnumerator<Step> Steps() { yield break; } } private sealed class SetResultInEnumeratorOperation : TestAsyncOperation { private readonly int result; public SetResultInEnumeratorOperation(int result) { this.result = result; } protected override IEnumerator<Step> Steps() { this.Result = this.result; yield break; } } } }
Change high lighting crash to NFW
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Highlighting { [Export(typeof(IHighlightingService))] [Shared] internal class HighlightingService : IHighlightingService { private readonly List<Lazy<IHighlighter, LanguageMetadata>> _highlighters; [ImportingConstructor] public HighlightingService( [ImportMany] IEnumerable<Lazy<IHighlighter, LanguageMetadata>> highlighters) { _highlighters = highlighters.ToList(); } public IEnumerable<TextSpan> GetHighlights( SyntaxNode root, int position, CancellationToken cancellationToken) { return _highlighters.Where(h => h.Metadata.Language == root.Language) .Select(h => h.Value.GetHighlights(root, position, cancellationToken)) .WhereNotNull() .Flatten() .Distinct(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Highlighting { [Export(typeof(IHighlightingService))] [Shared] internal class HighlightingService : IHighlightingService { private readonly List<Lazy<IHighlighter, LanguageMetadata>> _highlighters; [ImportingConstructor] public HighlightingService( [ImportMany] IEnumerable<Lazy<IHighlighter, LanguageMetadata>> highlighters) { _highlighters = highlighters.ToList(); } public IEnumerable<TextSpan> GetHighlights( SyntaxNode root, int position, CancellationToken cancellationToken) { try { return _highlighters.Where(h => h.Metadata.Language == root.Language) .Select(h => h.Value.GetHighlights(root, position, cancellationToken)) .WhereNotNull() .Flatten() .Distinct(); } catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e)) { // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/763988 // We still couldn't identify the root cause for the linked bug above. // Since high lighting failure is not important enough to crash VS, change crash to NFW. return SpecializedCollections.EmptyEnumerable<TextSpan>(); } } } }
Include company logo in email
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Mail; using System.Net.Mime; using System.Text; using System.Threading.Tasks; namespace SendEmailWithLogo { class Program { static void Main(string[] args) { var toAddress = "somewhere@mailinator.com"; var fromAddress = "you@host.com"; var message = "your message goes here"; // create the email var mailMessage = new MailMessage(); mailMessage.To.Add(toAddress); mailMessage.Subject = "Sending emails is easy"; mailMessage.From = new MailAddress(fromAddress); mailMessage.Body = message; // send it (settings in web.config / app.config) var smtp = new SmtpClient(); smtp.Send(mailMessage); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Mail; using System.Net.Mime; using System.Text; using System.Threading.Tasks; namespace SendEmailWithLogo { class Program { static void Main(string[] args) { var toAddress = "somewhere@mailinator.com"; var fromAddress = "you@host.com"; var pathToLogo = @"Content\logo.png"; var pathToTemplate = @"Content\Template.html"; var messageText = File.ReadAllText(pathToTemplate); // replace placeholder messageText = ReplacePlaceholdersWithValues(messageText); // create the email var mailMessage = new MailMessage(); mailMessage.To.Add(toAddress); mailMessage.Subject = "Sending emails is easy"; mailMessage.From = new MailAddress(fromAddress); mailMessage.IsBodyHtml = true; mailMessage.AlternateViews.Add(CreateHtmlMessage(messageText, pathToLogo)); // send it (settings in web.config / app.config) var smtp = new SmtpClient(); smtp.Send(mailMessage); } private static AlternateView CreateHtmlMessage(string messageText, string pathToLogo) { LinkedResource inline = new LinkedResource(pathToLogo); inline.ContentId = "companyLogo"; AlternateView alternateView = AlternateView.CreateAlternateViewFromString(messageText, null, MediaTypeNames.Text.Html); alternateView.LinkedResources.Add(inline); return alternateView; } private static string ReplacePlaceholdersWithValues(string messageText) { // use the dynamic values instead of the hardcoded ones in this example messageText = messageText.Replace("$AMOUNT$", "$12.50"); messageText = messageText.Replace("$DATE$", DateTime.Now.ToShortDateString()); messageText = messageText.Replace("$INVOICE$", "25639"); messageText = messageText.Replace("$TRANSACTION$", "TRX2017-WEB-01"); return messageText; } } }
Check Environment.UserInteractive instead of /c argument.
using System; using System.Linq; using System.ServiceProcess; namespace PolymeliaDeployController { using System.Configuration; using System.Data.Entity; using Microsoft.Owin.Hosting; using PolymeliaDeploy; using PolymeliaDeploy.Controller; using PolymeliaDeploy.Data; using PolymeliaDeploy.Network; static class Program { static void Main(string[] args) { Database.SetInitializer<PolymeliaDeployDbContext>(null); DeployServices.ReportClient = new ReportLocalClient(); var service = new Service(); if (args.Any(arg => arg == "/c")) { using (CreateServiceHost()) { Console.WriteLine("Started"); Console.ReadKey(); Console.WriteLine("Stopping"); return; } } ServiceBase.Run(service); } internal static IDisposable CreateServiceHost() { var localIpAddress = IPAddressRetriever.LocalIPAddress(); var portNumber = ConfigurationManager.AppSettings["ControllerPort"]; var controllUri = string.Format("http://{0}:{1}", localIpAddress, portNumber); return WebApplication.Start<Startup>(controllUri); } } }
using System; using System.Linq; using System.ServiceProcess; namespace PolymeliaDeployController { using System.Configuration; using System.Data.Entity; using Microsoft.Owin.Hosting; using PolymeliaDeploy; using PolymeliaDeploy.Controller; using PolymeliaDeploy.Data; using PolymeliaDeploy.Network; static class Program { static void Main(string[] args) { Database.SetInitializer<PolymeliaDeployDbContext>(null); DeployServices.ReportClient = new ReportLocalClient(); var service = new Service(); if (Environment.UserInteractive) { using (CreateServiceHost()) { Console.WriteLine("Started"); Console.ReadKey(); Console.WriteLine("Stopping"); return; } } ServiceBase.Run(service); } internal static IDisposable CreateServiceHost() { var localIpAddress = IPAddressRetriever.LocalIPAddress(); var portNumber = ConfigurationManager.AppSettings["ControllerPort"]; var controllUri = string.Format("http://{0}:{1}", localIpAddress, portNumber); return WebApplication.Start<Startup>(controllUri); } } }
Fix error that aborted sync when invalid XML was present in an XML formatted field (e.g. a malformed rules field in the stock master db)
using System; using System.Xml; using System.Xml.Linq; using Rainbow.Model; namespace Rainbow.Diff.Fields { public class XmlComparison : FieldTypeBasedComparison { public override bool AreEqual(IItemFieldValue field1, IItemFieldValue field2) { if (string.IsNullOrWhiteSpace(field1.Value) && string.IsNullOrWhiteSpace(field2.Value)) return true; if (string.IsNullOrWhiteSpace(field1.Value) || string.IsNullOrWhiteSpace(field2.Value)) return false; try { var x1 = XElement.Parse(field1.Value); var x2 = XElement.Parse(field2.Value); return XNode.DeepEquals(x1, x2); } catch (XmlException xe) { throw new InvalidOperationException($"Unable to compare {field1.NameHint ?? field2.NameHint} field due to invalid XML value.", xe); } } public override string[] SupportedFieldTypes => new[] { "Layout", "Tracking", "Rules" }; } }
using System.Xml; using System.Xml.Linq; using Rainbow.Model; using Sitecore.Diagnostics; namespace Rainbow.Diff.Fields { public class XmlComparison : FieldTypeBasedComparison { public override bool AreEqual(IItemFieldValue field1, IItemFieldValue field2) { if (string.IsNullOrWhiteSpace(field1.Value) && string.IsNullOrWhiteSpace(field2.Value)) return true; if (string.IsNullOrWhiteSpace(field1.Value) || string.IsNullOrWhiteSpace(field2.Value)) return false; try { var x1 = XElement.Parse(field1.Value); var x2 = XElement.Parse(field2.Value); return XNode.DeepEquals(x1, x2); } catch (XmlException xe) { Log.Error($"Field {field1.NameHint ?? field2.NameHint} contained an invalid XML value. Falling back to string comparison.", xe, this); return new DefaultComparison().AreEqual(field1, field2); } } public override string[] SupportedFieldTypes => new[] { "Layout", "Tracking", "Rules" }; } }
Fix increase connections to transport
using System; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using Serilog.Core; using Serilog.Debugging; using Serilog.Events; using Serilog.Sinks.Graylog.Core; using Serilog.Sinks.Graylog.Core.Transport; namespace Serilog.Sinks.Graylog { public class GraylogSink : ILogEventSink { private readonly Lazy<IGelfConverter> _converter; private readonly Lazy<ITransport> _transport; public GraylogSink(GraylogSinkOptions options) { ISinkComponentsBuilder sinkComponentsBuilder = new SinkComponentsBuilder(options); _transport = new Lazy<ITransport>(() => sinkComponentsBuilder.MakeTransport()); _converter = new Lazy<IGelfConverter>(() => sinkComponentsBuilder.MakeGelfConverter()); } public void Emit(LogEvent logEvent) { try { Task.Run(() => EmitAsync(logEvent)).GetAwaiter().GetResult(); } catch (Exception exc) { SelfLog.WriteLine("Oops something going wrong {0}", exc); } } private Task EmitAsync(LogEvent logEvent) { JObject json = _converter.Value.GetGelfJson(logEvent); string payload = json.ToString(Newtonsoft.Json.Formatting.None); return _transport.Value.Send(payload); } } }
using System; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using Serilog.Core; using Serilog.Debugging; using Serilog.Events; using Serilog.Sinks.Graylog.Core; using Serilog.Sinks.Graylog.Core.Transport; namespace Serilog.Sinks.Graylog { public class GraylogSink : ILogEventSink, IDisposable { private readonly Lazy<IGelfConverter> _converter; private readonly Lazy<ITransport> _transport; public GraylogSink(GraylogSinkOptions options) { ISinkComponentsBuilder sinkComponentsBuilder = new SinkComponentsBuilder(options); _transport = new Lazy<ITransport>(() => sinkComponentsBuilder.MakeTransport()); _converter = new Lazy<IGelfConverter>(() => sinkComponentsBuilder.MakeGelfConverter()); } public void Dispose() { _transport.Value.Dispose(); } public void Emit(LogEvent logEvent) { try { Task.Run(() => EmitAsync(logEvent)).GetAwaiter().GetResult(); } catch (Exception exc) { SelfLog.WriteLine("Oops something going wrong {0}", exc); } } private Task EmitAsync(LogEvent logEvent) { JObject json = _converter.Value.GetGelfJson(logEvent); string payload = json.ToString(Newtonsoft.Json.Formatting.None); return _transport.Value.Send(payload); } } }
Fix exception on clipboard access contention
using System.Windows; using System.Windows.Controls; namespace Certify.UI.Controls.ManagedCertificate { public partial class TestProgress : UserControl { protected Certify.UI.ViewModel.ManagedCertificateViewModel ItemViewModel => UI.ViewModel.ManagedCertificateViewModel.Current; protected Certify.UI.ViewModel.AppViewModel AppViewModel => UI.ViewModel.AppViewModel.Current; public TestProgress() { InitializeComponent(); DataContext = ItemViewModel; } private void TextBlock_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e) { // copy text to clipboard if (sender != null) { var text = (sender as TextBlock).Text; Clipboard.SetText(text); MessageBox.Show("Copied to clipboard"); } } } }
using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; namespace Certify.UI.Controls.ManagedCertificate { public partial class TestProgress : UserControl { protected Certify.UI.ViewModel.ManagedCertificateViewModel ItemViewModel => UI.ViewModel.ManagedCertificateViewModel.Current; protected Certify.UI.ViewModel.AppViewModel AppViewModel => UI.ViewModel.AppViewModel.Current; public TestProgress() { InitializeComponent(); DataContext = ItemViewModel; } private async Task<bool> WaitForClipboard(string text) { // if running under terminal services etc the clipboard can take multiple attempts to set // https://stackoverflow.com/questions/68666/clipbrd-e-cant-open-error-when-setting-the-clipboard-from-net for (var i = 0; i < 10; i++) { try { Clipboard.SetText(text); return true; } catch { } await Task.Delay(50); } return false; } private async void TextBlock_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e) { // copy text to clipboard if (sender != null) { var text = (sender as TextBlock).Text; var copiedOK = await WaitForClipboard(text); if (copiedOK) { MessageBox.Show("Copied to clipboard"); } else { MessageBox.Show("Another process is preventing access to the clipboard. Please try again."); } } } } }
Use GherkinDialectProvider instead of I18n
#region License /* Copyright [2011] [Jeffrey Cameron] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using System; using System.Globalization; using gherkin; namespace PicklesDoc.Pickles { public class LanguageServices { private readonly CultureInfo currentCulture; public LanguageServices(Configuration configuration) { if (!string.IsNullOrEmpty(configuration.Language)) this.currentCulture = CultureInfo.GetCultureInfo(configuration.Language); } private java.util.List GetKeywords(string key) { return this.GetLanguage().keywords(key); } public string GetKeyword(string key) { var keywords = this.GetKeywords("background"); if (keywords != null && !keywords.isEmpty()) { return keywords.get(0).ToString(); } return null; } private I18n GetLanguage() { if (this.currentCulture == null) return new I18n("en"); return new I18n(this.currentCulture.TwoLetterISOLanguageName); } } }
#region License /* Copyright [2011] [Jeffrey Cameron] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using System; using System.Globalization; using System.Linq; using Gherkin3; namespace PicklesDoc.Pickles { public class LanguageServices { private readonly CultureInfo currentCulture; private readonly GherkinDialectProvider dialectProvider; public LanguageServices(Configuration configuration) { if (!string.IsNullOrEmpty(configuration.Language)) this.currentCulture = CultureInfo.GetCultureInfo(configuration.Language); this.dialectProvider = new GherkinDialectProvider(); } private string[] GetBackgroundKeywords() { return this.GetLanguage().BackgroundKeywords; } public string GetKeyword(string key) { var keywords = this.GetBackgroundKeywords(); return keywords.FirstOrDefault(); } private GherkinDialect GetLanguage() { if (this.currentCulture == null) return this.dialectProvider.GetDialect("en", null); return this.dialectProvider.GetDialect(this.currentCulture.TwoLetterISOLanguageName, null); } } }
Fix new expression with dot name
namespace BScript.Expressions { using System; using System.Collections.Generic; using System.Linq; using System.Text; using BScript.Language; public class NewExpression : IExpression { private IExpression expression; private IList<IExpression> argexprs; public NewExpression(IExpression expression, IList<IExpression> argexprs) { this.expression = expression; this.argexprs = argexprs; } public IExpression Expression { get { return this.expression; } } public IList<IExpression> ArgumentExpressions { get { return this.argexprs; } } public object Evaluate(Context context) { var type = (Type)this.expression.Evaluate(context); IList<object> args = new List<object>(); foreach (var argexpr in this.argexprs) args.Add(argexpr.Evaluate(context)); return Activator.CreateInstance(type, args.ToArray()); } } }
namespace BScript.Expressions { using System; using System.Collections.Generic; using System.Linq; using System.Text; using BScript.Language; using BScript.Utilities; public class NewExpression : IExpression { private IExpression expression; private IList<IExpression> argexprs; public NewExpression(IExpression expression, IList<IExpression> argexprs) { this.expression = expression; this.argexprs = argexprs; } public IExpression Expression { get { return this.expression; } } public IList<IExpression> ArgumentExpressions { get { return this.argexprs; } } public object Evaluate(Context context) { Type type; if (this.expression is DotExpression) type = TypeUtilities.GetType(((DotExpression)this.expression).FullName); else type = (Type)this.expression.Evaluate(context); IList<object> args = new List<object>(); foreach (var argexpr in this.argexprs) args.Add(argexpr.Evaluate(context)); return Activator.CreateInstance(type, args.ToArray()); } } }
Update view of all answers
@model System.Linq.IQueryable<ForumSystem.Web.ViewModels.Answers.AnswerViewModel> @using ForumSystem.Web.ViewModels.Answers; @foreach (var answer in Model) { <div class="panel panel-success"> <div class="panel-heading"> <h3> @answer.Post.Title </h3> </div> <div class="panel-body"> <div class="panel-body"> <p>@Html.Raw(answer.Content)</p> @if (@answer.Author != null) { <p>@answer.Author.Email</p> } else { @Html.Display("Anonymous") } </div> <button type="button" class="btn btn-secondary" data-toggle="tooltip" data-placement="bottom" title="Tooltip on left"> @Html.ActionLink("Delete", "Delete", "Answer", new { id = answer.Id }, null) </button> </div> </div> }
@model System.Linq.IQueryable<ForumSystem.Web.ViewModels.Answers.AnswerViewModel> @using ForumSystem.Web.ViewModels.Answers; <div class="panel panel-success"> <div class="panel-heading"> <h3> @Html.ActionLink(Model.FirstOrDefault().Post.Title, "Display", "Questions", new { id = Model.FirstOrDefault().PostId, url = "new" }, null) </h3> </div> <div class="panel-body"> @foreach (var answer in Model) { <div class="panel-body"> <span class="glyphicon glyphicon-user" aria-hidden="true"></span> <p>@Html.Raw(answer.Content)</p> @if (@answer.Author != null) { <p>@answer.Author.Email</p> } else { @Html.Display("Anonymous") } </div> <button type="button" class="btn btn-secondary" data-toggle="tooltip" data-placement="bottom" title="Tooltip on left"> @Html.ActionLink("Delete", "Delete", "Answer", new { id = answer.Id }, null) </button> } </div> </div>
Fix incorrect skin version case
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Beatmaps.Formats; namespace osu.Game.Skinning { public class LegacySkinDecoder : LegacyDecoder<LegacySkinConfiguration> { public LegacySkinDecoder() : base(1) { } protected override void ParseLine(LegacySkinConfiguration skin, Section section, string line) { if (section != Section.Colours) { line = StripComments(line); var pair = SplitKeyVal(line); switch (section) { case Section.General: switch (pair.Key) { case @"Name": skin.SkinInfo.Name = pair.Value; return; case @"Author": skin.SkinInfo.Creator = pair.Value; return; case @"Version": if (pair.Value == "latest" || pair.Value == "User") skin.LegacyVersion = LegacySkinConfiguration.LATEST_VERSION; else if (decimal.TryParse(pair.Value, out var version)) skin.LegacyVersion = version; return; } break; } if (!string.IsNullOrEmpty(pair.Key)) skin.ConfigDictionary[pair.Key] = pair.Value; } base.ParseLine(skin, section, line); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Beatmaps.Formats; namespace osu.Game.Skinning { public class LegacySkinDecoder : LegacyDecoder<LegacySkinConfiguration> { public LegacySkinDecoder() : base(1) { } protected override void ParseLine(LegacySkinConfiguration skin, Section section, string line) { if (section != Section.Colours) { line = StripComments(line); var pair = SplitKeyVal(line); switch (section) { case Section.General: switch (pair.Key) { case @"Name": skin.SkinInfo.Name = pair.Value; return; case @"Author": skin.SkinInfo.Creator = pair.Value; return; case @"Version": if (pair.Value == "latest") skin.LegacyVersion = LegacySkinConfiguration.LATEST_VERSION; else if (decimal.TryParse(pair.Value, out var version)) skin.LegacyVersion = version; return; } break; } if (!string.IsNullOrEmpty(pair.Key)) skin.ConfigDictionary[pair.Key] = pair.Value; } base.ParseLine(skin, section, line); } } }
Fix fake not replicating actual behaviour
using KafkaNet; using KafkaNet.Protocol; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace kafka_tests.Fakes { public class FakeKafkaConnection : IKafkaConnection { private Uri _address; public Func<ProduceResponse> ProduceResponseFunction; public Func<MetadataResponse> MetadataResponseFunction; public FakeKafkaConnection(Uri address) { _address = address; } public int MetadataRequestCallCount { get; set; } public int ProduceRequestCallCount { get; set; } public Uri KafkaUri { get { return _address; } } public bool ReadPolling { get { return true; } } public Task SendAsync(byte[] payload) { throw new NotImplementedException(); } public Task<List<T>> SendAsync<T>(IKafkaRequest<T> request) { var tcs = new TaskCompletionSource<List<T>>(); if (typeof(T) == typeof(ProduceResponse)) { ProduceRequestCallCount++; tcs.SetResult(new List<T> { (T)(object)ProduceResponseFunction() }); } else if (typeof(T) == typeof(MetadataResponse)) { MetadataRequestCallCount++; tcs.SetResult(new List<T> { (T)(object)MetadataResponseFunction() }); } return tcs.Task; } public void Dispose() { } } }
using KafkaNet; using KafkaNet.Protocol; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace kafka_tests.Fakes { public class FakeKafkaConnection : IKafkaConnection { private Uri _address; public Func<ProduceResponse> ProduceResponseFunction; public Func<MetadataResponse> MetadataResponseFunction; public FakeKafkaConnection(Uri address) { _address = address; } public int MetadataRequestCallCount { get; set; } public int ProduceRequestCallCount { get; set; } public Uri KafkaUri { get { return _address; } } public bool ReadPolling { get { return true; } } public Task SendAsync(byte[] payload) { throw new NotImplementedException(); } public Task<List<T>> SendAsync<T>(IKafkaRequest<T> request) { var task = new Task<List<T>>(() => { if (typeof(T) == typeof(ProduceResponse)) { ProduceRequestCallCount++; return new List<T> { (T)(object)ProduceResponseFunction() }; } else if (typeof(T) == typeof(MetadataResponse)) { MetadataRequestCallCount++; return new List<T> { (T)(object)MetadataResponseFunction() }; } return null; }); task.Start(); return task; } public void Dispose() { } } }
Append .json to end of filename when outputting JSON
using System; using System.IO; using DataTool.ToolLogic.List; using Utf8Json; using Utf8Json.Resolvers; using static DataTool.Helper.IO; using static DataTool.Helper.Logger; namespace DataTool.JSON { public class JSONTool { internal void OutputJSON(object jObj, ListFlags toolFlags) { CompositeResolver.RegisterAndSetAsDefault(new IJsonFormatter[] { new ResourceGUIDFormatter() }, new[] { StandardResolver.Default }); byte[] json = JsonSerializer.NonGeneric.Serialize(jObj.GetType(), jObj); if (!string.IsNullOrWhiteSpace(toolFlags.Output)) { byte[] pretty = JsonSerializer.PrettyPrintByteArray(json); Log("Writing to {0}", toolFlags.Output); CreateDirectoryFromFile(toolFlags.Output); using (Stream file = File.OpenWrite(toolFlags.Output)) { file.SetLength(0); file.Write(pretty, 0, pretty.Length); } } else { Console.Error.WriteLine(JsonSerializer.PrettyPrint(json)); } } } }
using System; using System.IO; using DataTool.ToolLogic.List; using Utf8Json; using Utf8Json.Resolvers; using static DataTool.Helper.IO; using static DataTool.Helper.Logger; namespace DataTool.JSON { public class JSONTool { internal void OutputJSON(object jObj, ListFlags toolFlags) { CompositeResolver.RegisterAndSetAsDefault(new IJsonFormatter[] { new ResourceGUIDFormatter() }, new[] { StandardResolver.Default }); byte[] json = JsonSerializer.NonGeneric.Serialize(jObj.GetType(), jObj); if (!string.IsNullOrWhiteSpace(toolFlags.Output)) { byte[] pretty = JsonSerializer.PrettyPrintByteArray(json); Log("Writing to {0}", toolFlags.Output); CreateDirectoryFromFile(toolFlags.Output); var fileName = !toolFlags.Output.EndsWith(".json") ? $"{toolFlags.Output}.json" : toolFlags.Output; using (Stream file = File.OpenWrite(fileName)) { file.SetLength(0); file.Write(pretty, 0, pretty.Length); } } else { Console.Error.WriteLine(JsonSerializer.PrettyPrint(json)); } } } }
Add test for delegation in obsolete property
// Copyright 2013 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System.Linq; using NUnit.Framework; namespace NodaTime.Test { /// <summary> /// Tests for DateTimeZoneProviders. /// </summary> public class DateTimeZoneProvidersTest { [Test] public void TzdbProviderUsesTzdbSource() { Assert.IsTrue(DateTimeZoneProviders.Tzdb.VersionId.StartsWith("TZDB: ")); } [Test] public void AllTzdbTimeZonesLoad() { var allZones = DateTimeZoneProviders.Tzdb.Ids.Select(id => DateTimeZoneProviders.Tzdb[id]).ToList(); // Just to stop the variable from being lonely. In reality, it's likely there'll be a breakpoint here to inspect a particular zone... Assert.IsTrue(allZones.Count > 50); } [Test] public void BclProviderUsesTimeZoneInfoSource() { Assert.IsTrue(DateTimeZoneProviders.Bcl.VersionId.StartsWith("TimeZoneInfo: ")); } } }
// Copyright 2013 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System.Linq; using NodaTime.Testing.TimeZones; using NodaTime.Xml; using NUnit.Framework; namespace NodaTime.Test { /// <summary> /// Tests for DateTimeZoneProviders. /// </summary> public class DateTimeZoneProvidersTest { [Test] public void TzdbProviderUsesTzdbSource() { Assert.IsTrue(DateTimeZoneProviders.Tzdb.VersionId.StartsWith("TZDB: ")); } [Test] public void AllTzdbTimeZonesLoad() { var allZones = DateTimeZoneProviders.Tzdb.Ids.Select(id => DateTimeZoneProviders.Tzdb[id]).ToList(); // Just to stop the variable from being lonely. In reality, it's likely there'll be a breakpoint here to inspect a particular zone... Assert.IsTrue(allZones.Count > 50); } [Test] public void BclProviderUsesTimeZoneInfoSource() { Assert.IsTrue(DateTimeZoneProviders.Bcl.VersionId.StartsWith("TimeZoneInfo: ")); } [Test] public void SerializationDelegatesToXmlSerializerSettings() { var original = XmlSerializationSettings.DateTimeZoneProvider; try { #pragma warning disable CS0618 // Type or member is obsolete var provider1 = new FakeDateTimeZoneSource.Builder().Build().ToProvider(); DateTimeZoneProviders.Serialization = provider1; Assert.AreSame(provider1, XmlSerializationSettings.DateTimeZoneProvider); var provider2 = new FakeDateTimeZoneSource.Builder().Build().ToProvider(); XmlSerializationSettings.DateTimeZoneProvider = provider2; Assert.AreSame(provider2, DateTimeZoneProviders.Serialization); #pragma warning restore CS0618 // Type or member is obsolete } finally { XmlSerializationSettings.DateTimeZoneProvider = original; } } } }
Support drivers without a date of birth
using System; using Newtonsoft.Json; namespace ErgastApi.Responses.Models { public class Driver { [JsonProperty("driverId")] public string DriverId { get; private set; } /// <summary> /// Drivers who participated in the 2014 season onwards have a permanent driver number. /// However, this may differ from the value of the number attribute of the Result element in earlier seasons /// or where the reigning champion has chosen to use "1" rather than his permanent driver number. /// </summary> [JsonProperty("permanentNumber")] public int? PermanentNumber { get; private set; } [JsonProperty("code")] public string Code { get; private set; } [JsonProperty("url")] public string WikiUrl { get; private set; } public string FullName => $"{FirstName} {LastName}"; [JsonProperty("givenName")] public string FirstName { get; private set; } [JsonProperty("familyName")] public string LastName { get; private set; } [JsonProperty("dateOfBirth")] public DateTime DateOfBirth { get; private set; } [JsonProperty("nationality")] public string Nationality { get; private set; } } }
using System; using Newtonsoft.Json; namespace ErgastApi.Responses.Models { public class Driver { [JsonProperty("driverId")] public string DriverId { get; private set; } /// <summary> /// Drivers who participated in the 2014 season onwards have a permanent driver number. /// However, this may differ from the value of the number attribute of the Result element in earlier seasons /// or where the reigning champion has chosen to use "1" rather than his permanent driver number. /// </summary> [JsonProperty("permanentNumber")] public int? PermanentNumber { get; private set; } [JsonProperty("code")] public string Code { get; private set; } [JsonProperty("url")] public string WikiUrl { get; private set; } public string FullName => $"{FirstName} {LastName}"; [JsonProperty("givenName")] public string FirstName { get; private set; } [JsonProperty("familyName")] public string LastName { get; private set; } [JsonProperty("dateOfBirth")] public DateTime? DateOfBirth { get; private set; } [JsonProperty("nationality")] public string Nationality { get; private set; } } }
Fix typo in last commit
using System.Linq.Expressions; using Remotion.Linq.Parsing.ExpressionTreeVisitors.Transformation; namespace NHibernate.Linq.ExpressionTransformers { /// <summary> /// Remove redundant casts to the same type or to superclass (upcast) in <see cref="ExpressionType.Convert"/>, <see cref=" ExpressionType.ConvertChecked"/> /// and <see cref="ExpressionType.TypeAs"/> <see cref="UnaryExpression"/>s /// </summary> public class RemoveRedundantCast : IExpressionTransformer<UnaryExpression> { private static readonly ExpressionType[] _supportedExpressionTypes = new[] { ExpressionType.TypeAs, ExpressionType.Convert, ExpressionType.ConvertChecked, }; public Expression Transform(UnaryExpression expression) { if (expression.Type != typeof(object) && expression.Type.IsAssignableFrom(expression.Operand.Type) && expression.Method != null && !expression.IsLiftedToNull) { return expression.Operand; } return expression; } public ExpressionType[] SupportedExpressionTypes { get { return _supportedExpressionTypes; } } } }
using System.Linq.Expressions; using Remotion.Linq.Parsing.ExpressionTreeVisitors.Transformation; namespace NHibernate.Linq.ExpressionTransformers { /// <summary> /// Remove redundant casts to the same type or to superclass (upcast) in <see cref="ExpressionType.Convert"/>, <see cref=" ExpressionType.ConvertChecked"/> /// and <see cref="ExpressionType.TypeAs"/> <see cref="UnaryExpression"/>s /// </summary> public class RemoveRedundantCast : IExpressionTransformer<UnaryExpression> { private static readonly ExpressionType[] _supportedExpressionTypes = new[] { ExpressionType.TypeAs, ExpressionType.Convert, ExpressionType.ConvertChecked, }; public Expression Transform(UnaryExpression expression) { if (expression.Type != typeof(object) && expression.Type.IsAssignableFrom(expression.Operand.Type) && expression.Method == null && !expression.IsLiftedToNull) { return expression.Operand; } return expression; } public ExpressionType[] SupportedExpressionTypes { get { return _supportedExpressionTypes; } } } }
Support EventHub Consumer Groups in Script
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using Microsoft.Azure.WebJobs.ServiceBus; namespace Microsoft.Azure.WebJobs.Script.Description { public class EventHubBindingMetadata : BindingMetadata { [AllowNameResolution] public string Path { get; set; } public override void ApplyToConfig(JobHostConfigurationBuilder configBuilder) { if (configBuilder == null) { throw new ArgumentNullException("configBuilder"); } EventHubConfiguration eventHubConfig = configBuilder.EventHubConfiguration; string connectionString = null; if (!string.IsNullOrEmpty(Connection)) { connectionString = Utility.GetAppSettingOrEnvironmentValue(Connection); } if (this.IsTrigger) { string eventProcessorHostName = Guid.NewGuid().ToString(); string storageConnectionString = configBuilder.Config.StorageConnectionString; var eventProcessorHost = new Microsoft.ServiceBus.Messaging.EventProcessorHost( eventProcessorHostName, this.Path, Microsoft.ServiceBus.Messaging.EventHubConsumerGroup.DefaultGroupName, connectionString, storageConnectionString); eventHubConfig.AddEventProcessorHost(this.Path, eventProcessorHost); } else { var client = Microsoft.ServiceBus.Messaging.EventHubClient.CreateFromConnectionString( connectionString, this.Path); eventHubConfig.AddEventHubClient(this.Path, client); } } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using Microsoft.Azure.WebJobs.ServiceBus; namespace Microsoft.Azure.WebJobs.Script.Description { public class EventHubBindingMetadata : BindingMetadata { [AllowNameResolution] public string Path { get; set; } // Optional Consumer group public string ConsumerGroup { get; set; } public override void ApplyToConfig(JobHostConfigurationBuilder configBuilder) { if (configBuilder == null) { throw new ArgumentNullException("configBuilder"); } EventHubConfiguration eventHubConfig = configBuilder.EventHubConfiguration; string connectionString = null; if (!string.IsNullOrEmpty(Connection)) { connectionString = Utility.GetAppSettingOrEnvironmentValue(Connection); } if (this.IsTrigger) { string eventProcessorHostName = Guid.NewGuid().ToString(); string storageConnectionString = configBuilder.Config.StorageConnectionString; string consumerGroup = this.ConsumerGroup; if (consumerGroup == null) { consumerGroup = Microsoft.ServiceBus.Messaging.EventHubConsumerGroup.DefaultGroupName; } var eventProcessorHost = new Microsoft.ServiceBus.Messaging.EventProcessorHost( eventProcessorHostName, this.Path, consumerGroup, connectionString, storageConnectionString); eventHubConfig.AddEventProcessorHost(this.Path, eventProcessorHost); } else { var client = Microsoft.ServiceBus.Messaging.EventHubClient.CreateFromConnectionString( connectionString, this.Path); eventHubConfig.AddEventHubClient(this.Path, client); } } } }
Fix mono support on startup. Bypass TopShelf service framework.
using Topshelf; namespace MiNET.Service { public class MiNetService { private MiNetServer _server; private void Start() { _server = new MiNetServer(); _server.StartServer(); } private void Stop() { _server.StopServer(); } private static void Main(string[] args) { HostFactory.Run(host => { host.Service<MiNetService>(s => { s.ConstructUsing(construct => new MiNetService()); s.WhenStarted(service => service.Start()); s.WhenStopped(service => service.Stop()); }); host.RunAsLocalService(); host.SetDisplayName("MiNET Service"); host.SetDescription("MiNET MineCraft Pocket Edition server."); host.SetServiceName("MiNET"); }); } } }
using System; using Topshelf; namespace MiNET.Service { public class MiNetService { private MiNetServer _server; private void Start() { _server = new MiNetServer(); _server.StartServer(); } private void Stop() { _server.StopServer(); } private static void Main(string[] args) { if (IsRunningOnMono()) { var service = new MiNetService(); service.Start(); Console.WriteLine("MiNET runing. Press <enter> to stop service.."); Console.ReadLine(); service.Stop(); } HostFactory.Run(host => { host.Service<MiNetService>(s => { s.ConstructUsing(construct => new MiNetService()); s.WhenStarted(service => service.Start()); s.WhenStopped(service => service.Stop()); }); host.RunAsLocalService(); host.SetDisplayName("MiNET Service"); host.SetDescription("MiNET MineCraft Pocket Edition server."); host.SetServiceName("MiNET"); }); } public static bool IsRunningOnMono() { return Type.GetType("Mono.Runtime") != null; } } }
Fix NRE when copying nodes when the ToString() is null
using System.Text; namespace Microsoft.Build.Logging.StructuredLogger { public class StringWriter { public static string GetString(object rootNode) { var sb = new StringBuilder(); WriteNode(rootNode, sb, 0); return sb.ToString(); } private static void WriteNode(object rootNode, StringBuilder sb, int indent = 0) { Indent(sb, indent); var text = rootNode.ToString(); // when we injest strings we normalize on \n to save space. // when the strings leave our app via clipboard, bring \r\n back so that notepad works text = text.Replace("\n", "\r\n"); sb.AppendLine(text); var treeNode = rootNode as TreeNode; if (treeNode != null && treeNode.HasChildren) { if (treeNode.HasChildren) { foreach (var child in treeNode.Children) { WriteNode(child, sb, indent + 1); } } } } private static void Indent(StringBuilder sb, int indent) { for (int i = 0; i < indent * 4; i++) { sb.Append(' '); } } } }
using System.Text; namespace Microsoft.Build.Logging.StructuredLogger { public class StringWriter { public static string GetString(object rootNode) { var sb = new StringBuilder(); WriteNode(rootNode, sb, 0); return sb.ToString(); } private static void WriteNode(object rootNode, StringBuilder sb, int indent = 0) { Indent(sb, indent); var text = rootNode.ToString() ?? ""; // when we injest strings we normalize on \n to save space. // when the strings leave our app via clipboard, bring \r\n back so that notepad works text = text.Replace("\n", "\r\n"); sb.AppendLine(text); var treeNode = rootNode as TreeNode; if (treeNode != null && treeNode.HasChildren) { if (treeNode.HasChildren) { foreach (var child in treeNode.Children) { WriteNode(child, sb, indent + 1); } } } } private static void Indent(StringBuilder sb, int indent) { for (int i = 0; i < indent * 4; i++) { sb.Append(' '); } } } }
Remove stray default value specification
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osuTK; using osuTK.Graphics; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Effects; using osu.Framework.Graphics.Shapes; using osu.Game.Skinning; namespace osu.Game.Rulesets.Osu.Objects.Drawables.Connections { /// <summary> /// A single follow point positioned between two adjacent <see cref="DrawableOsuHitObject"/>s. /// </summary> public class FollowPoint : Container, IAnimationTimeReference { private const float width = 8; public override bool RemoveWhenNotAlive => false; public FollowPoint() { Origin = Anchor.Centre; Child = new SkinnableDrawable(new OsuSkinComponent(OsuSkinComponents.FollowPoint), _ => new CircularContainer { Masking = true, AutoSizeAxes = Axes.Both, EdgeEffect = new EdgeEffectParameters { Type = EdgeEffectType.Glow, Colour = Color4.White.Opacity(0.2f), Radius = 4, }, Child = new Box { Size = new Vector2(width), Blending = BlendingParameters.Additive, Origin = Anchor.Centre, Anchor = Anchor.Centre, Alpha = 0.5f, } }, confineMode: ConfineMode.NoScaling); } public double AnimationStartTime { get; set; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osuTK; using osuTK.Graphics; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Effects; using osu.Framework.Graphics.Shapes; using osu.Game.Skinning; namespace osu.Game.Rulesets.Osu.Objects.Drawables.Connections { /// <summary> /// A single follow point positioned between two adjacent <see cref="DrawableOsuHitObject"/>s. /// </summary> public class FollowPoint : Container, IAnimationTimeReference { private const float width = 8; public override bool RemoveWhenNotAlive => false; public FollowPoint() { Origin = Anchor.Centre; Child = new SkinnableDrawable(new OsuSkinComponent(OsuSkinComponents.FollowPoint), _ => new CircularContainer { Masking = true, AutoSizeAxes = Axes.Both, EdgeEffect = new EdgeEffectParameters { Type = EdgeEffectType.Glow, Colour = Color4.White.Opacity(0.2f), Radius = 4, }, Child = new Box { Size = new Vector2(width), Blending = BlendingParameters.Additive, Origin = Anchor.Centre, Anchor = Anchor.Centre, Alpha = 0.5f, } }); } public double AnimationStartTime { get; set; } } }
Update verbiage on user registration email
Hello @ViewData.Model.FirstName,<br /><br /> Thank you for signing up for Rambla! You have taken the first step towards expanding your rentability.<br /><br /> @{ string URL = Url.Action("activateaccount", "Account", new RouteValueDictionary(new { id = ViewData.Model.ActivationId }), Request.Url.Scheme.ToString(), Request.Url.Host); } Please click <a href="@URL">here</a> to activate your account.<br /><br /> Regards,<br /> Rambla Team
@{ string URL = Url.Action("activateaccount", "Account", new RouteValueDictionary(new { id = ViewData.Model.ActivationId }), Request.Url.Scheme.ToString(), Request.Url.Host); } <p>Hi @ViewData.Model.FirstName,</p> <p>Welcome to <strong>Rambla</strong>, a marketplace that facilitates sharing of items between you and your community members. We're excited to have you as a member and can't wait to see what you have to share.</p> <p>As a new member, here are a few suggestions to get you started with Rambla:</p> <ul> <li> Dig out that hammer drill that you do not need right now or that snowboard that you do not use too often and post it on <strong>Rambla</strong>. In fact, any unused item in your house can be of use to someone belonging to your community. </li> <li> Need a sleeping bag for your annual camping trip or an outdoor patio heater for your Christmas party? Search for it on <strong>Rambla</strong> There is always someone who has an item you are looking for and is willing to share it with you. </li> <li> Help your fellow community members find your stuff by using big images, writing thoughtful descriptions and addressing their queries promptly. You might just get rewarded for your exceptional conduct with a small gift from us. :-) </li> </ul> <p>To get started with your <strong>Rambla</strong> experience, please click <a href="@URL">here</a> to activate your account.</p> <p>Thanks for joining and happy sharing!</p> <p>- The Rambla Team</p>
Support completion of parens and indexes too.
using System.ComponentModel.Composition; using Microsoft.VisualStudio.Text.BraceCompletion; using Microsoft.VisualStudio.Utilities; namespace DanTup.DartVS { [Export(typeof(IBraceCompletionDefaultProvider))] [ContentType(DartContentTypeDefinition.DartContentType)] [BracePair('{', '}')] class BraceCompletionProvider : IBraceCompletionDefaultProvider { } }
using System.ComponentModel.Composition; using Microsoft.VisualStudio.Text.BraceCompletion; using Microsoft.VisualStudio.Utilities; namespace DanTup.DartVS { [Export(typeof(IBraceCompletionDefaultProvider))] [ContentType(DartContentTypeDefinition.DartContentType)] [BracePair('{', '}')] [BracePair('(', ')')] [BracePair('[', ']')] class BraceCompletionProvider : IBraceCompletionDefaultProvider { } }
Fix SD not failing for the first note
// 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; using osu.Game.Graphics; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Mods { public abstract class ModSuddenDeath : Mod, IApplicableToScoreProcessor { public override string Name => "Sudden Death"; public override string ShortenedName => "SD"; public override FontAwesome Icon => FontAwesome.fa_osu_mod_suddendeath; public override ModType Type => ModType.DifficultyIncrease; public override string Description => "Miss a note and fail."; public override double ScoreMultiplier => 1; public override bool Ranked => true; public override Type[] IncompatibleMods => new[] { typeof(ModNoFail), typeof(ModRelax), typeof(ModAutoplay) }; public void ApplyToScoreProcessor(ScoreProcessor scoreProcessor) { scoreProcessor.FailConditions += FailCondition; } protected virtual bool FailCondition(ScoreProcessor scoreProcessor) => scoreProcessor.Combo.Value != scoreProcessor.HighestCombo.Value; } }
// 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; using osu.Game.Graphics; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Mods { public abstract class ModSuddenDeath : Mod, IApplicableToScoreProcessor { public override string Name => "Sudden Death"; public override string ShortenedName => "SD"; public override FontAwesome Icon => FontAwesome.fa_osu_mod_suddendeath; public override ModType Type => ModType.DifficultyIncrease; public override string Description => "Miss a note and fail."; public override double ScoreMultiplier => 1; public override bool Ranked => true; public override Type[] IncompatibleMods => new[] { typeof(ModNoFail), typeof(ModRelax), typeof(ModAutoplay) }; public void ApplyToScoreProcessor(ScoreProcessor scoreProcessor) { scoreProcessor.FailConditions += FailCondition; } protected virtual bool FailCondition(ScoreProcessor scoreProcessor) => scoreProcessor.Combo.Value == 0; } }
Add help for -t switch
using System; using System.Collections.Generic; namespace LessMsi.Cli { internal class ShowHelpCommand : LessMsiCommand { public override void Run(List<string> args) { ShowHelp(""); } public static void ShowHelp(string errorMessage) { string helpString = @"Usage: lessmsi <command> [options] <msi_name> [<path_to_extract\>] [file_names] Commands: x Extracts all or specified files from the specified msi_name. l Lists the contents of the specified msi table as CSV to stdout. v Lists the value of the ProductVersion Property in the msi (typically this is the version of the MSI). o Opens the specified msi_name in the GUI. h Shows this help page. For more information see http://lessmsi.activescott.com "; if (!string.IsNullOrEmpty(errorMessage)) { helpString = "\r\nError: " + errorMessage + "\r\n\r\n" + helpString; } Console.WriteLine(helpString); } } }
using System; using System.Collections.Generic; namespace LessMsi.Cli { internal class ShowHelpCommand : LessMsiCommand { public override void Run(List<string> args) { ShowHelp(""); } public static void ShowHelp(string errorMessage) { string helpString = @"Usage: lessmsi <command> [options] <msi_name> [<path_to_extract\>] [file_names] Commands: x Extracts all or specified files from the specified msi_name. l Lists the contents of the specified msi table as CSV to stdout. Table is specified with -t switch. Example: lessmsi l -t Component c:\foo.msi v Lists the value of the ProductVersion Property in the msi (typically this is the version of the MSI). o Opens the specified msi_name in the GUI. h Shows this help page. For more information see http://lessmsi.activescott.com "; if (!string.IsNullOrEmpty(errorMessage)) { helpString = "\r\nError: " + errorMessage + "\r\n\r\n" + helpString; } Console.WriteLine(helpString); } } }
Fix context menu not running any actions in notification Form
using CefSharp; namespace TweetDck.Core.Handling{ class ContextMenuNotification : ContextMenuBase{ public override void OnBeforeContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model){ model.Clear(); base.OnBeforeContextMenu(browserControl,browser,frame,parameters,model); RemoveSeparatorIfLast(model); } public override bool OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags){ return false; } } }
using CefSharp; namespace TweetDck.Core.Handling{ class ContextMenuNotification : ContextMenuBase{ public override void OnBeforeContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model){ model.Clear(); base.OnBeforeContextMenu(browserControl,browser,frame,parameters,model); RemoveSeparatorIfLast(model); } } }
Increment version number for new build.
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MonoGameUtils")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MonoGameUtils")] [assembly: AssemblyCopyright("")] [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("4ecedc75-1f2d-4915-9efe-368a5d104e41")] // 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.4.0")] [assembly: AssemblyFileVersion("1.0.4.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MonoGameUtils")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MonoGameUtils")] [assembly: AssemblyCopyright("")] [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("4ecedc75-1f2d-4915-9efe-368a5d104e41")] // 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.5.0")] [assembly: AssemblyFileVersion("1.0.5.0")]
Copy interactions from the given object
using UnityEngine; namespace Pear.InteractionEngine.Interactions { /// <summary> /// Copies interactions from the current object to the supplied objects /// </summary> public class CopyInteractions: MonoBehaviour { [Tooltip("Objects that interactions will be copied to")] public GameObject[] CopyTo; private void Awake() { if (CopyTo != null) { //Copy alkl interactions from the current object to the specified object foreach (GameObject copyTo in CopyTo) Interaction.CopyAll(gameObject, copyTo); } } } }
using UnityEngine; namespace Pear.InteractionEngine.Interactions { /// <summary> /// Copies interactions from the current object to the supplied objects /// </summary> public class CopyInteractions: MonoBehaviour { [Tooltip("Objects that interactions will be copied to")] public GameObject[] CopyTo; [Tooltip("Objects that the interactions will be copied from")] public GameObject[] CopyFrom; private void Awake() { if (CopyTo != null) { // Copy all interactions from the current object to the specified object foreach (GameObject copyTo in CopyTo) Interaction.CopyAll(gameObject, copyTo); } if(CopyFrom != null) { // Copy all interactions from the specified objects to this game object foreach (GameObject copyFrom in CopyFrom) Interaction.CopyAll(copyFrom, gameObject); } } } }
Hide game type for now
@model WebEditor.Models.Create @{ ViewBag.Title = "New Game"; } @section scripts { <script src="@Url.Content("~/Scripts/GameNew.js")" type="text/javascript"></script> } @using (Html.BeginForm()) { @Html.ValidationSummary(true, "Unable to create game. Please correct the errors below.") <div> <div class="editor-label"> @Html.LabelFor(m => m.GameName) </div> <div class="editor-field"> @Html.TextBoxFor(m => m.GameName, new { style = "width: 300px" }) @Html.ValidationMessageFor(m => m.GameName) </div> <div class="editor-label"> @Html.LabelFor(m => m.SelectedType) </div> <div class="editor-field"> @Html.DropDownListFor(m => m.SelectedType, new SelectList(Model.AllTypes, Model.SelectedType)) @Html.ValidationMessageFor(m => m.SelectedType) </div> <div class="editor-label"> @Html.LabelFor(m => m.SelectedTemplate) </div> <div class="editor-field"> @Html.DropDownListFor(m => m.SelectedTemplate, new SelectList(Model.AllTemplates, Model.SelectedTemplate)) @Html.ValidationMessageFor(m => m.SelectedTemplate) </div> <p> <button id="submit-button" type="submit">Create</button> </p> </div> }
@model WebEditor.Models.Create @{ ViewBag.Title = "New Game"; } @section scripts { <script src="@Url.Content("~/Scripts/GameNew.js")" type="text/javascript"></script> } @using (Html.BeginForm()) { @Html.ValidationSummary(true, "Unable to create game. Please correct the errors below.") <div> <div class="editor-label"> @Html.LabelFor(m => m.GameName): </div> <div class="editor-field"> @Html.TextBoxFor(m => m.GameName, new { style = "width: 300px" }) @Html.ValidationMessageFor(m => m.GameName) </div> <div style="display: none"> <div class="editor-label"> @Html.LabelFor(m => m.SelectedType): </div> <div class="editor-field"> @Html.DropDownListFor(m => m.SelectedType, new SelectList(Model.AllTypes, Model.SelectedType)) @Html.ValidationMessageFor(m => m.SelectedType) </div> </div> <div class="editor-label"> @Html.LabelFor(m => m.SelectedTemplate): </div> <div class="editor-field"> @Html.DropDownListFor(m => m.SelectedTemplate, new SelectList(Model.AllTemplates, Model.SelectedTemplate)) @Html.ValidationMessageFor(m => m.SelectedTemplate) </div> <p> <button id="submit-button" type="submit">Create</button> </p> </div> }
Allow for multiple phone numbers and email addresses
using System.Net.Mail; namespace StressMeasurementSystem.Models { public class Patient { #region Structs public struct Name { public string Prefix { get; set; } public string First { get; set; } public string Middle { get; set; } public string Last { get; set; } public string Suffix { get; set; } } public struct Organization { public string Company { get; set; } public string JobTitle { get; set; } } public struct PhoneNumber { public enum Type {Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other} public string Number { get; set; } public Type T { get; set; } } public struct Email { public enum Type {Home, Work, Other} public MailAddress Address { get; set; } public Type T { get; set; } } #endregion #region Fields private Name _name; private uint _age; private Organization _organization; private PhoneNumber _phoneNumber; private Email _email; #endregion #region Constructors public Patient(Name name, uint age, Organization organization, PhoneNumber phoneNumber, Email email) { _name = name; _age = age; _organization = organization; _phoneNumber = phoneNumber; _email = email; } #endregion } }
using System.Collections.Generic; using System.Net.Mail; namespace StressMeasurementSystem.Models { public class Patient { #region Structs public struct Name { public string Prefix { get; set; } public string First { get; set; } public string Middle { get; set; } public string Last { get; set; } public string Suffix { get; set; } } public struct Organization { public string Company { get; set; } public string JobTitle { get; set; } } public struct PhoneNumber { public enum Type {Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other} public string Number { get; set; } public Type T { get; set; } } public struct Email { public enum Type {Home, Work, Other} public MailAddress Address { get; set; } public Type T { get; set; } } #endregion #region Fields private Name _name; private uint _age; private Organization _organization; private List<PhoneNumber> _phoneNumbers; private List<Email> _emails; #endregion #region Constructors public Patient(Name name, uint age, Organization organization, List<PhoneNumber> phoneNumbers, List<Email> emails) { _name = name; _age = age; _organization = organization; _phoneNumbers = phoneNumbers; _emails = emails; } #endregion } }
Allow debugging without running as a service.
using System; using System.Collections.Generic; using System.Linq; using System.ServiceProcess; using System.Text; namespace Leeroy { static class Program { /// <summary> /// The main entry point for the application. /// </summary> static void Main() { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new Service() }; ServiceBase.Run(ServicesToRun); } } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading; namespace Leeroy { static class Program { /// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { if (args.FirstOrDefault() == "/test") { Overseer overseer = new Overseer(new CancellationTokenSource().Token, "BradleyGrainger", "Configuration", "master"); overseer.Run(null); } else { ServiceBase.Run(new ServiceBase[] { new Service() }); } } } }
Change version number to 0.6.5
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("TextMatch")] [assembly: AssemblyDescription("A library for matching texts with Lucene query expressions")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TextMatch")] [assembly: AssemblyCopyright("Copyright © 2015 Cris Almodovar")] [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("2fe43f0a-b8c0-4de3-b2d5-6fc207385f7c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.7.0.0")] [assembly: AssemblyFileVersion("0.7.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("TextMatch")] [assembly: AssemblyDescription("A library for matching texts with Lucene query expressions")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TextMatch")] [assembly: AssemblyCopyright("Copyright © 2015 Cris Almodovar")] [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("2fe43f0a-b8c0-4de3-b2d5-6fc207385f7c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.6.5.0")] [assembly: AssemblyFileVersion("0.6.5.0")]
Revert change that broke tests on Windows PowerShell.
/* Copyright 2018 Jeremy Herbison This file is part of AudioWorks. AudioWorks is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. AudioWorks is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with AudioWorks. If not, see <https://www.gnu.org/licenses/>. */ using System; using System.IO; using System.Management.Automation; using System.Management.Automation.Runspaces; using JetBrains.Annotations; namespace AudioWorks.Commands.Tests { [UsedImplicitly] public sealed class ModuleFixture : IDisposable { const string _moduleProject = "AudioWorks.Commands"; [NotNull] internal Runspace Runspace { get; } public ModuleFixture() { var state = InitialSessionState.CreateDefault(); // This bypasses the execution policy (InitialSessionState.ExecutionPolicy isn't available with PowerShell 5) state.AuthorizationManager = new AuthorizationManager("Microsoft.PowerShell"); state.ImportPSModule( Path.Combine(new DirectoryInfo(Directory.GetCurrentDirectory()).FullName, _moduleProject)); Runspace = RunspaceFactory.CreateRunspace(state); Runspace.Open(); } public void Dispose() { Runspace.Close(); } } }
/* Copyright 2018 Jeremy Herbison This file is part of AudioWorks. AudioWorks is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. AudioWorks is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with AudioWorks. If not, see <https://www.gnu.org/licenses/>. */ using System; using System.IO; using System.Management.Automation; using System.Management.Automation.Runspaces; using JetBrains.Annotations; namespace AudioWorks.Commands.Tests { [UsedImplicitly] public sealed class ModuleFixture : IDisposable { const string _moduleProject = "AudioWorks.Commands"; [NotNull] internal Runspace Runspace { get; } public ModuleFixture() { var state = InitialSessionState.CreateDefault(); // This bypasses the execution policy (InitialSessionState.ExecutionPolicy isn't available with PowerShell 5) state.AuthorizationManager = new AuthorizationManager("Microsoft.PowerShell"); state.ImportPSModule(new[] { Path.Combine(new DirectoryInfo(Directory.GetCurrentDirectory()).FullName, _moduleProject) }); Runspace = RunspaceFactory.CreateRunspace(state); Runspace.Open(); } public void Dispose() { Runspace.Close(); } } }
Add static methods for building XML data strings
using Xunit.Abstractions; namespace Cascara.Tests { public abstract class CascaraTestFramework { public CascaraTestFramework(ITestOutputHelper output) { Output = output; } protected ITestOutputHelper Output { get; } } }
using System; using System.Xml.Linq; using Xunit.Abstractions; namespace Cascara.Tests { public abstract class CascaraTestFramework { protected static string BuildXmlElement(string name, params Tuple<string, string>[] attrs) { return BuildXmlElement(name, "", attrs); } protected static string BuildXmlElement(string name, string innerData, params Tuple<string, string>[] attrs) { string attrString = ""; foreach (Tuple<string, string> t in attrs) { attrString += string.Format(" {0}='{1}'", t.Item1, t.Item2); } return string.Format("<{0}{1}>{2}</{0}>", name, attrString, innerData); } protected static XElement ParseXmlElement(string data) { XDocument doc = XDocument.Parse(data, LoadOptions.SetLineInfo); return doc.Root; } public CascaraTestFramework(ITestOutputHelper output) { Output = output; } protected ITestOutputHelper Output { get; } } }
Fix intro settings "Hide On Finish" option name
using System.ComponentModel; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; namespace DesktopWidgets.Classes { [ExpandableObject] [DisplayName("Intro Settings")] public class IntroData { [DisplayName("Duration")] public int Duration { get; set; } = -1; [DisplayName("Reversable")] public bool Reversable { get; set; } = false; [DisplayName("Activate")] public bool Activate { get; set; } = false; [DisplayName("Stay Open")] public bool HideOnFinish { get; set; } = true; [DisplayName("Execute Finish Action")] public bool ExecuteFinishAction { get; set; } = true; } }
using System.ComponentModel; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; namespace DesktopWidgets.Classes { [ExpandableObject] [DisplayName("Intro Settings")] public class IntroData { [DisplayName("Duration")] public int Duration { get; set; } = -1; [DisplayName("Reversable")] public bool Reversable { get; set; } = false; [DisplayName("Activate")] public bool Activate { get; set; } = false; [DisplayName("Hide On Finish")] public bool HideOnFinish { get; set; } = true; [DisplayName("Execute Finish Action")] public bool ExecuteFinishAction { get; set; } = true; } }
Implement Equals/GetHashCode to comply with Distinct
using IO = System.IO; namespace dokas.EncodingConverter.Logic { internal sealed class FileData { public string Path { get; private set; } public string Name { get; private set; } public string Extension { get; private set; } public FileData(string path) { Path = path; Name = IO.Path.GetFileName(path); Extension = IO.Path.GetExtension(path); } } }
using System; using IO = System.IO; namespace dokas.EncodingConverter.Logic { internal sealed class FileData { public string Path { get; private set; } public string Name { get; private set; } public string Extension { get; private set; } public FileData(string path) { if (path == null) { throw new ArgumentNullException("path"); } Path = path; Name = IO.Path.GetFileName(path); Extension = IO.Path.GetExtension(path); } public override bool Equals(object obj) { var otherFileData = obj as FileData; return otherFileData != null && Path.Equals(otherFileData.Path); } public override int GetHashCode() { return Path.GetHashCode(); } } }
Make available to change the rule when editing A/B page setting.
@model Kooboo.CMS.Sites.ABTest.ABPageSetting @using Kooboo.CMS.Sites.ABTest; @{ ViewBag.Title = "Edit A/B page setting"; Layout = "~/Views/Shared/Blank.cshtml"; } @section Panel{ <ul class="panel"> <li> <a data-ajaxform=""> @Html.IconImage("save") @("Save".Localize())</a> </li> <li> <a href="@ViewContext.RequestContext.GetRequestValue("return")"> @Html.IconImage("cancel") @("Back".Localize())</a> </li> </ul> } <div class="block common-form"> <h1 class="title">@ViewBag.Title</h1> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <table> <tbody> @Html.DisplayFor(o => o.RuleName) @Html.HiddenFor(o => o.RuleName) @Html.DisplayFor(o => o.MainPage) @Html.EditorFor(o => o.Items) @Html.EditorFor(o => o.ABTestGoalPage, new { HtmlAttributes = new { @class = "medium" } }) </tbody> </table> } </div>
@model Kooboo.CMS.Sites.ABTest.ABPageSetting @using Kooboo.CMS.Sites.ABTest; @{ ViewBag.Title = "Edit A/B page setting"; Layout = "~/Views/Shared/Blank.cshtml"; } @section Panel{ <ul class="panel"> <li> <a data-ajaxform=""> @Html.IconImage("save") @("Save".Localize())</a> </li> <li> <a href="@ViewContext.RequestContext.GetRequestValue("return")"> @Html.IconImage("cancel") @("Back".Localize())</a> </li> </ul> } <div class="block common-form"> <h1 class="title">@ViewBag.Title</h1> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <table> <tbody> @Html.EditorFor(o => o.RuleName) @Html.DisplayFor(o => o.MainPage) @Html.EditorFor(o => o.Items) @Html.EditorFor(o => o.ABTestGoalPage, new { HtmlAttributes = new { @class = "medium" } }) </tbody> </table> } </div>