Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Fix bug in http handler constraints
using System.Web; using System.Web.Routing; namespace ConsolR.Hosting { public static class HttpHandlerExtensions { public static void MapHttpHandler<THandler>(this RouteCollection routes, string url) where THandler : IHttpHandler, new() { routes.MapHttpHandler<THandler>(null, url, null, null); } public static void MapHttpHandler<THandler>(this RouteCollection routes, string name, string url, object defaults, object constraints) where THandler : IHttpHandler, new() { var route = new Route(url, new HttpHandlerRouteHandler<THandler>()); route.Defaults = new RouteValueDictionary(defaults); route.Constraints = new RouteValueDictionary(constraints); routes.Add(name, route); } private class HttpHandlerRouteHandler<THandler> : IRouteHandler where THandler : IHttpHandler, new() { public IHttpHandler GetHttpHandler(RequestContext requestContext) { return new THandler(); } } } }
using System.Web; using System.Web.Routing; namespace ConsolR.Hosting { public static class HttpHandlerExtensions { public static void MapHttpHandler<THandler>(this RouteCollection routes, string url) where THandler : IHttpHandler, new() { routes.MapHttpHandler<THandler>(null, url, null, null); } public static void MapHttpHandler<THandler>(this RouteCollection routes, string name, string url, object defaults, object constraints) where THandler : IHttpHandler, new() { var route = new Route(url, new HttpHandlerRouteHandler<THandler>()); route.Defaults = new RouteValueDictionary(defaults); route.Constraints = new RouteValueDictionary(); route.Constraints.Add(name, constraints); routes.Add(name, route); } private class HttpHandlerRouteHandler<THandler> : IRouteHandler where THandler : IHttpHandler, new() { public IHttpHandler GetHttpHandler(RequestContext requestContext) { return new THandler(); } } } }
Replace default constructor with failed property on PageProvider
using System.Collections.Generic; namespace RazorLight.Templating { public class PageLookupResult { public PageLookupResult() { this.Success = false; } public PageLookupResult(PageLookupItem item, IReadOnlyList<PageLookupItem> viewStartEntries) { this.ViewEntry = item; this.ViewStartEntries = viewStartEntries; this.Success = true; } public bool Success { get; } public PageLookupItem ViewEntry { get; } public IReadOnlyList<PageLookupItem> ViewStartEntries { get; } } }
using System.Collections.Generic; namespace RazorLight.Templating { public class PageLookupResult { public static PageLookupResult Failed => new PageLookupResult(); private PageLookupResult() { this.Success = false; } public PageLookupResult(PageLookupItem item, IReadOnlyList<PageLookupItem> viewStartEntries) { this.ViewEntry = item; this.ViewStartEntries = viewStartEntries; this.Success = true; } public bool Success { get; } public PageLookupItem ViewEntry { get; } public IReadOnlyList<PageLookupItem> ViewStartEntries { get; } } }
Add XML doc comments on Id and NodeId
using System; namespace Microsoft.Build.Logging.StructuredLogger { public class TimedNode : NamedNode { public int Id { get; set; } public int NodeId { get; set; } /// <summary> /// Unique index of the node in the build tree, can be used as a /// "URL" to node /// </summary> public int Index { get; set; } public DateTime StartTime { get; set; } public DateTime EndTime { get; set; } public TimeSpan Duration { get { if (EndTime >= StartTime) { return EndTime - StartTime; } return TimeSpan.Zero; } } public string DurationText => TextUtilities.DisplayDuration(Duration); public override string TypeName => nameof(TimedNode); public string GetTimeAndDurationText(bool fullPrecision = false) { var duration = DurationText; if (string.IsNullOrEmpty(duration)) { duration = "0"; } return $@"Start: {TextUtilities.Display(StartTime, displayDate: true, fullPrecision)} End: {TextUtilities.Display(EndTime, displayDate: true, fullPrecision)} Duration: {duration}"; } public override string ToolTip => GetTimeAndDurationText(); } }
using System; namespace Microsoft.Build.Logging.StructuredLogger { public class TimedNode : NamedNode { /// <summary> /// The Id of a Project, ProjectEvaluation, Target and Task. /// Corresponds to ProjectStartedEventsArgs.ProjectId, TargetStartedEventArgs.TargetId, etc. /// </summary> public int Id { get; set; } /// <summary> /// Corresponds to BuildEventArgs.BuildEventContext.NodeId, /// which is the id of the MSBuild.exe node process that built the current project or /// executed the given target or task. /// </summary> public int NodeId { get; set; } /// <summary> /// Unique index of the node in the build tree, can be used as a /// "URL" to node /// </summary> public int Index { get; set; } public DateTime StartTime { get; set; } public DateTime EndTime { get; set; } public TimeSpan Duration { get { if (EndTime >= StartTime) { return EndTime - StartTime; } return TimeSpan.Zero; } } public string DurationText => TextUtilities.DisplayDuration(Duration); public override string TypeName => nameof(TimedNode); public string GetTimeAndDurationText(bool fullPrecision = false) { var duration = DurationText; if (string.IsNullOrEmpty(duration)) { duration = "0"; } return $@"Start: {TextUtilities.Display(StartTime, displayDate: true, fullPrecision)} End: {TextUtilities.Display(EndTime, displayDate: true, fullPrecision)} Duration: {duration}"; } public override string ToolTip => GetTimeAndDurationText(); } }
Add setting to toggle performance logging
// 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.Configuration; using osu.Framework.Graphics; namespace osu.Game.Overlays.Settings.Sections.Debug { public class GeneralSettings : SettingsSubsection { protected override string Header => "General"; [BackgroundDependencyLoader] private void load(FrameworkDebugConfigManager config, FrameworkConfigManager frameworkConfig) { Children = new Drawable[] { new SettingsCheckbox { LabelText = "Bypass caching", Bindable = config.GetBindable<bool>(DebugSetting.BypassCaching) }, new SettingsCheckbox { LabelText = "Debug logs", Bindable = frameworkConfig.GetBindable<bool>(FrameworkSetting.ShowLogOverlay) } }; } } }
// 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.Configuration; using osu.Framework.Graphics; namespace osu.Game.Overlays.Settings.Sections.Debug { public class GeneralSettings : SettingsSubsection { protected override string Header => "General"; [BackgroundDependencyLoader] private void load(FrameworkDebugConfigManager config, FrameworkConfigManager frameworkConfig) { Children = new Drawable[] { new SettingsCheckbox { LabelText = "Show log overlay", Bindable = frameworkConfig.GetBindable<bool>(FrameworkSetting.ShowLogOverlay) }, new SettingsCheckbox { LabelText = "Performance logging", Bindable = frameworkConfig.GetBindable<bool>(FrameworkSetting.PerformanceLogging) }, new SettingsCheckbox { LabelText = "Bypass caching (slow)", Bindable = config.GetBindable<bool>(DebugSetting.BypassCaching) }, }; } } }
Use StringEnum converter in API model
#pragma warning disable CS1591 using System; using Newtonsoft.Json; namespace Discord.API { internal class Embed { [JsonProperty("title")] public string Title { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("url")] public string Url { get; set; } [JsonProperty("color")] public uint? Color { get; set; } [JsonProperty("type")] public EmbedType Type { get; set; } [JsonProperty("timestamp")] public DateTimeOffset? Timestamp { get; set; } [JsonProperty("author")] public Optional<EmbedAuthor> Author { get; set; } [JsonProperty("footer")] public Optional<EmbedFooter> Footer { get; set; } [JsonProperty("video")] public Optional<EmbedVideo> Video { get; set; } [JsonProperty("thumbnail")] public Optional<EmbedThumbnail> Thumbnail { get; set; } [JsonProperty("image")] public Optional<EmbedImage> Image { get; set; } [JsonProperty("provider")] public Optional<EmbedProvider> Provider { get; set; } [JsonProperty("fields")] public Optional<EmbedField[]> Fields { get; set; } } }
#pragma warning disable CS1591 using System; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Discord.API { internal class Embed { [JsonProperty("title")] public string Title { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("url")] public string Url { get; set; } [JsonProperty("color")] public uint? Color { get; set; } [JsonProperty("type"), JsonConverter(typeof(StringEnumConverter))] public EmbedType Type { get; set; } [JsonProperty("timestamp")] public DateTimeOffset? Timestamp { get; set; } [JsonProperty("author")] public Optional<EmbedAuthor> Author { get; set; } [JsonProperty("footer")] public Optional<EmbedFooter> Footer { get; set; } [JsonProperty("video")] public Optional<EmbedVideo> Video { get; set; } [JsonProperty("thumbnail")] public Optional<EmbedThumbnail> Thumbnail { get; set; } [JsonProperty("image")] public Optional<EmbedImage> Image { get; set; } [JsonProperty("provider")] public Optional<EmbedProvider> Provider { get; set; } [JsonProperty("fields")] public Optional<EmbedField[]> Fields { get; set; } } }
Add NotFound and ErrorHandling middlewares
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.Framework.DependencyInjection; using Microsoft.AspNet.FileProviders; using Microsoft.Dnx.Runtime; using MakingSense.AspNet.Documentation; namespace MakingSense.AspNet.HypermediaApi.Seed { public class Startup { // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { } public void Configure(IApplicationBuilder app, IApplicationEnvironment appEnv) { app.UseStaticFiles(); UseDocumentation(app, appEnv); app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); } private static void UseDocumentation(IApplicationBuilder app, IApplicationEnvironment appEnv) { var documentationFilesProvider = new PhysicalFileProvider(appEnv.ApplicationBasePath); app.UseDocumentation(new DocumentationOptions() { DefaultFileName = "index", RequestPath = "/docs", NotFoundHtmlFile = documentationFilesProvider.GetFileInfo("DocumentationTemplates\\NotFound.html"), LayoutFile = documentationFilesProvider.GetFileInfo("DocumentationTemplates\\Layout.html") }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.Framework.DependencyInjection; using Microsoft.AspNet.FileProviders; using Microsoft.Dnx.Runtime; using MakingSense.AspNet.Documentation; using MakingSense.AspNet.HypermediaApi.Formatters; using MakingSense.AspNet.HypermediaApi.ValidationFilters; namespace MakingSense.AspNet.HypermediaApi.Seed { public class Startup { // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { options.OutputFormatters.Clear(); options.OutputFormatters.Add(new HypermediaApiJsonOutputFormatter()); options.InputFormatters.Clear(); options.InputFormatters.Add(new HypermediaApiJsonInputFormatter()); options.Filters.Add(new PayloadValidationFilter()); options.Filters.Add(new RequiredPayloadFilter()); }); } public void Configure(IApplicationBuilder app, IApplicationEnvironment appEnv) { app.UseApiErrorHandler(); app.UseMvc(); app.UseStaticFiles(); UseDocumentation(app, appEnv); app.UseNotFoundHandler(); } private static void UseDocumentation(IApplicationBuilder app, IApplicationEnvironment appEnv) { var documentationFilesProvider = new PhysicalFileProvider(appEnv.ApplicationBasePath); app.UseDocumentation(new DocumentationOptions() { DefaultFileName = "index", RequestPath = "/docs", NotFoundHtmlFile = documentationFilesProvider.GetFileInfo("DocumentationTemplates\\NotFound.html"), LayoutFile = documentationFilesProvider.GetFileInfo("DocumentationTemplates\\Layout.html") }); } } }
Make info messages look better
using CupCake.Core.Log; using CupCake.Messages.Receive; using CupCake.Players; namespace CupCake.Server.Muffins { public class LogMuffin : CupCakeMuffin { protected override void Enable() { this.Events.Bind<SayPlayerEvent>(this.OnSay); this.Events.Bind<WriteReceiveEvent>(this.OnWrite); this.Events.Bind<InfoReceiveEvent>(this.OnInfo); this.Events.Bind<UpgradeReceiveEvent>(this.OnUpgrade); } private void OnUpgrade(object sender, UpgradeReceiveEvent e) { this.Logger.Log(LogPriority.Message, "The game has been updated."); } private void OnInfo(object sender, InfoReceiveEvent e) { this.Logger.LogPlatform.Log(e.Title, LogPriority.Message, e.Text); } private void OnWrite(object sender, WriteReceiveEvent e) { this.Logger.LogPlatform.Log(e.Title, LogPriority.Message, e.Text); } private void OnSay(object sender, SayPlayerEvent e) { this.Logger.LogPlatform.Log(e.Player.Username, LogPriority.Message, e.Player.Say); } } }
using CupCake.Core.Log; using CupCake.Messages.Receive; using CupCake.Players; namespace CupCake.Server.Muffins { public class LogMuffin : CupCakeMuffin { protected override void Enable() { this.Events.Bind<SayPlayerEvent>(this.OnSay); this.Events.Bind<WriteReceiveEvent>(this.OnWrite); this.Events.Bind<InfoReceiveEvent>(this.OnInfo); this.Events.Bind<UpgradeReceiveEvent>(this.OnUpgrade); } private void OnUpgrade(object sender, UpgradeReceiveEvent e) { this.Logger.Log(LogPriority.Message, "The game has been updated."); } private void OnInfo(object sender, InfoReceiveEvent e) { this.Logger.Log(LogPriority.Message, e.Title); this.Logger.Log(LogPriority.Message, e.Text); } private void OnWrite(object sender, WriteReceiveEvent e) { this.Logger.LogPlatform.Log(e.Title, LogPriority.Message, e.Text); } private void OnSay(object sender, SayPlayerEvent e) { this.Logger.LogPlatform.Log(e.Player.Username, LogPriority.Message, e.Player.Say); } } }
Reset list of main and side rooms on every selection
using UnityEngine; using System.Collections.Generic; using System; [RequireComponent(typeof(RoomGenerator))] public class MainRoomSelector : MonoBehaviour { public float aboveMeanWidthFactor = 1.25f; public float aboveMeanLengthFactor = 1.25f; [HideInInspector] public List<Room> mainRooms; [HideInInspector] public List<Room> sideRooms; Room[] _rooms; public void Run() { var generator = this.GetComponent<RoomGenerator> (); _rooms = generator.generatedRooms; float meanWidth = 0f; float meanLength = 0f; foreach (var room in _rooms) { meanWidth += room.width; meanLength += room.length; } meanWidth /= _rooms.Length; meanLength /= _rooms.Length; foreach (var room in _rooms) { if (room.width >= meanWidth * aboveMeanWidthFactor && room.length >= meanLength * aboveMeanLengthFactor) { mainRooms.Add (room); room.isMainRoom = true; } else { sideRooms.Add (room); room.isMainRoom = false; } } } }
using UnityEngine; using System.Collections.Generic; using System; [RequireComponent(typeof(RoomGenerator))] public class MainRoomSelector : MonoBehaviour { public float aboveMeanWidthFactor = 1.25f; public float aboveMeanLengthFactor = 1.25f; [HideInInspector] public List<Room> mainRooms; [HideInInspector] public List<Room> sideRooms; Room[] _rooms; public void Run() { mainRooms = new List<Room>(); sideRooms = new List<Room>(); var generator = this.GetComponent<RoomGenerator> (); _rooms = generator.generatedRooms; float meanWidth = 0f; float meanLength = 0f; foreach (var room in _rooms) { meanWidth += room.width; meanLength += room.length; } meanWidth /= _rooms.Length; meanLength /= _rooms.Length; foreach (var room in _rooms) { if (room.width >= meanWidth * aboveMeanWidthFactor && room.length >= meanLength * aboveMeanLengthFactor) { mainRooms.Add (room); room.isMainRoom = true; } else { sideRooms.Add (room); room.isMainRoom = false; } } } }
Fix for Order Lines in Order Refund
using System.Collections.Generic; namespace Mollie.Api.Models.Order { public class OrderRefundRequest { /// <summary> /// An array of objects containing the order line details you want to create a refund for. If you send /// an empty array, the entire order will be refunded. /// </summary> public IEnumerable<OrderLineRequest> Lines { get; set; } /// <summary> /// The description of the refund you are creating. This will be shown to the consumer on their card or /// bank statement when possible. Max. 140 characters. /// </summary> public string Description { get; set; } } }
using System.Collections.Generic; namespace Mollie.Api.Models.Order { public class OrderRefundRequest { /// <summary> /// An array of objects containing the order line details you want to create a refund for. If you send /// an empty array, the entire order will be refunded. /// </summary> public IEnumerable<OrderLineDetails> Lines { get; set; } /// <summary> /// The description of the refund you are creating. This will be shown to the consumer on their card or /// bank statement when possible. Max. 140 characters. /// </summary> public string Description { get; set; } } }
Save authorization information, when app is suspended.
namespace TraktApiSharp.Example.UWP { using Services.SettingsServices; using System.Threading.Tasks; using Template10.Controls; using Windows.ApplicationModel.Activation; using Windows.UI.Xaml; using Windows.UI.Xaml.Data; [Bindable] sealed partial class App : Template10.Common.BootStrapper { public App() { InitializeComponent(); SplashFactory = (e) => new Views.Splash(e); var settings = SettingsService.Instance; RequestedTheme = settings.AppTheme; CacheMaxDuration = settings.CacheMaxDuration; ShowShellBackButton = settings.UseShellBackButton; } public override async Task OnInitializeAsync(IActivatedEventArgs args) { if (Window.Current.Content as ModalDialog == null) { // create a new frame var nav = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include); // create modal root Window.Current.Content = new ModalDialog { DisableBackButtonWhenModal = true, Content = new Views.Shell(nav), ModalContent = new Views.Busy(), }; } await Task.CompletedTask; } public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args) { NavigationService.Navigate(typeof(Views.MainPage)); await Task.CompletedTask; } } }
namespace TraktApiSharp.Example.UWP { using Services.SettingsServices; using Services.TraktService; using System.Threading.Tasks; using Template10.Controls; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.UI.Xaml; using Windows.UI.Xaml.Data; [Bindable] sealed partial class App : Template10.Common.BootStrapper { public App() { InitializeComponent(); SplashFactory = (e) => new Views.Splash(e); var settings = SettingsService.Instance; RequestedTheme = settings.AppTheme; CacheMaxDuration = settings.CacheMaxDuration; ShowShellBackButton = settings.UseShellBackButton; } public override async Task OnInitializeAsync(IActivatedEventArgs args) { if (Window.Current.Content as ModalDialog == null) { // create a new frame var nav = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include); // create modal root Window.Current.Content = new ModalDialog { DisableBackButtonWhenModal = true, Content = new Views.Shell(nav), ModalContent = new Views.Busy(), }; } await Task.CompletedTask; } public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args) { NavigationService.Navigate(typeof(Views.MainPage)); await Task.CompletedTask; } public override async Task OnSuspendingAsync(object s, SuspendingEventArgs e, bool prelaunchActivated) { var authorization = TraktServiceProvider.Instance.Client.Authorization; SettingsService.Instance.TraktClientAuthorization = authorization; await Task.CompletedTask; } } }
Add xml comment to TransitionType
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System.Collections.Specialized; namespace CefSharp { public interface IRequest { string Url { get; set; } string Method { get; } string Body { get; } NameValueCollection Headers { get; set; } TransitionType TransitionType { get; } } }
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System.Collections.Specialized; namespace CefSharp { public interface IRequest { string Url { get; set; } string Method { get; } string Body { get; } NameValueCollection Headers { get; set; } /// <summary> /// Get the transition type for this request. /// Applies to requests that represent a main frame or sub-frame navigation. /// </summary> TransitionType TransitionType { get; } } }
Fix home page next show time
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using live.asp.net.Data; using live.asp.net.Services; using live.asp.net.ViewModels; using Microsoft.AspNet.Authorization; using Microsoft.AspNet.Mvc; using Microsoft.Data.Entity; namespace live.asp.net.Controllers { public class HomeController : Controller { private readonly AppDbContext _db; private readonly IShowsService _showsService; public HomeController(IShowsService showsService, AppDbContext dbContext) { _showsService = showsService; _db = dbContext; } [Route("/")] public async Task<IActionResult> Index(bool? disableCache, bool? useDesignData) { var liveShowDetails = await _db.LiveShowDetails.FirstOrDefaultAsync(); var showList = await _showsService.GetRecordedShowsAsync(User, disableCache ?? false, useDesignData ?? false); return View(new HomeViewModel { AdminMessage = liveShowDetails?.AdminMessage, NextShowDate = liveShowDetails?.NextShowDate, LiveShowEmbedUrl = liveShowDetails?.LiveShowEmbedUrl, PreviousShows = showList.Shows, MoreShowsUrl = showList.MoreShowsUrl }); } [HttpGet("error")] public IActionResult Error() { return View(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using live.asp.net.Data; using live.asp.net.Services; using live.asp.net.ViewModels; using Microsoft.AspNet.Authorization; using Microsoft.AspNet.Mvc; using Microsoft.Data.Entity; namespace live.asp.net.Controllers { public class HomeController : Controller { private readonly AppDbContext _db; private readonly IShowsService _showsService; public HomeController(IShowsService showsService, AppDbContext dbContext) { _showsService = showsService; _db = dbContext; } [Route("/")] public async Task<IActionResult> Index(bool? disableCache, bool? useDesignData) { var liveShowDetails = await _db.LiveShowDetails.FirstOrDefaultAsync(); var showList = await _showsService.GetRecordedShowsAsync(User, disableCache ?? false, useDesignData ?? false); DateTimeOffset? nextShowDateOffset = null; if (liveShowDetails != null) { nextShowDateOffset= TimeZoneInfo.ConvertTimeBySystemTimeZoneId(liveShowDetails.NextShowDate.Value, "Pacific Standard Time"); } return View(new HomeViewModel { AdminMessage = liveShowDetails?.AdminMessage, NextShowDate = nextShowDateOffset, LiveShowEmbedUrl = liveShowDetails?.LiveShowEmbedUrl, PreviousShows = showList.Shows, MoreShowsUrl = showList.MoreShowsUrl }); } [HttpGet("error")] public IActionResult Error() { return View(); } } }
Split MemberOutputTests to separate asserts
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace T4TS.Tests { [TestClass] public class MemberOutputAppenderTests { [TestMethod] public void MemberOutputAppenderRespectsCompatibilityVersion() { var sb = new StringBuilder(); var member = new TypeScriptInterfaceMember { Name = "Foo", //FullName = "Foo", Type = new BoolType() }; var settings = new Settings(); var appender = new MemberOutputAppender(sb, 0, settings); settings.CompatibilityVersion = new Version(0, 8, 3); appender.AppendOutput(member); Assert.IsTrue(sb.ToString().Contains("bool")); Assert.IsFalse(sb.ToString().Contains("boolean")); sb.Clear(); settings.CompatibilityVersion = new Version(0, 9, 0); appender.AppendOutput(member); Assert.IsTrue(sb.ToString().Contains("boolean")); sb.Clear(); settings.CompatibilityVersion = null; appender.AppendOutput(member); Assert.IsTrue(sb.ToString().Contains("boolean")); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace T4TS.Tests { [TestClass] public class MemberOutputAppenderTests { [TestMethod] public void TypescriptVersion083YieldsBool() { var sb = new StringBuilder(); var member = new TypeScriptInterfaceMember { Name = "Foo", Type = new BoolType() }; var appender = new MemberOutputAppender(sb, 0, new Settings { CompatibilityVersion = new Version(0, 8, 3) }); appender.AppendOutput(member); Assert.AreEqual("Foo: bool;", sb.ToString().Trim()); } [TestMethod] public void TypescriptVersion090YieldsBoolean() { var sb = new StringBuilder(); var member = new TypeScriptInterfaceMember { Name = "Foo", Type = new BoolType() }; var appender = new MemberOutputAppender(sb, 0, new Settings { CompatibilityVersion = new Version(0, 9, 0) }); appender.AppendOutput(member); Assert.AreEqual("Foo: boolean;", sb.ToString().Trim()); } [TestMethod] public void DefaultTypescriptVersionYieldsBoolean() { var sb = new StringBuilder(); var member = new TypeScriptInterfaceMember { Name = "Foo", Type = new BoolType() }; var appender = new MemberOutputAppender(sb, 0, new Settings { CompatibilityVersion = null }); appender.AppendOutput(member); Assert.AreEqual("Foo: boolean;", sb.ToString().Trim()); } } }
Fix default database is not set properly the first time
using System; using System.Collections.Generic; using CupCake.Protocol; namespace CupCake.Client.Settings { public class Settings { public Settings() : this(false) { } public Settings(bool isNew) { this.Accounts = new List<Account>(); this.Profiles = new List<Profile>(); this.RecentWorlds = new List<RecentWorld>(); this.Databases = new List<Database>(); if (isNew) { this.Profiles.Add(new Profile { Id = SettingsManager.DefaultId, Name = SettingsManager.DefaultString, Folder = SettingsManager.ProfilesPath }); this.Databases.Add(new Database { Id = SettingsManager.DefaultId, Name = SettingsManager.DefaultString, Type = DatabaseType.SQLite, ConnectionString = String.Format(Database.SQLiteFormat, SettingsManager.DefaultDatabasePath) }); } } public List<Account> Accounts { get; set; } public List<Profile> Profiles { get; set; } public List<RecentWorld> RecentWorlds { get; set; } public List<Database> Databases { get; set; } public int LastProfileId { get; set; } public int LastAccountId { get; set; } public int LastRecentWorldId { get; set; } public int LastDatabaseId { get; set; } public string LastAttachAddress { get; set; } public string LastAttachPin { get; set; } } }
using System; using System.Collections.Generic; using CupCake.Protocol; namespace CupCake.Client.Settings { public class Settings { public Settings() : this(false) { } public Settings(bool isNew) { this.Accounts = new List<Account>(); this.Profiles = new List<Profile>(); this.RecentWorlds = new List<RecentWorld>(); this.Databases = new List<Database>(); if (isNew) { this.Profiles.Add(new Profile { Id = SettingsManager.DefaultId, Name = SettingsManager.DefaultString, Folder = SettingsManager.ProfilesPath, Database = SettingsManager.DefaultId }); this.Databases.Add(new Database { Id = SettingsManager.DefaultId, Name = SettingsManager.DefaultString, Type = DatabaseType.SQLite, ConnectionString = String.Format(Database.SQLiteFormat, SettingsManager.DefaultDatabasePath) }); } } public List<Account> Accounts { get; set; } public List<Profile> Profiles { get; set; } public List<RecentWorld> RecentWorlds { get; set; } public List<Database> Databases { get; set; } public int LastProfileId { get; set; } public int LastAccountId { get; set; } public int LastRecentWorldId { get; set; } public int LastDatabaseId { get; set; } public string LastAttachAddress { get; set; } public string LastAttachPin { get; set; } } }
Change version number to 1.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("DNSAgent")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DNSAgent")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8424ad23-98aa-4697-a9e7-cb6d5b450c6c")] // 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.1.*")] [assembly: AssemblyFileVersion("1.0.0.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("DNSAgent")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DNSAgent")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8424ad23-98aa-4697-a9e7-cb6d5b450c6c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyFileVersion("1.0.0.0")]
Change hover colour for news title
// 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.Platform; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Online.API.Requests.Responses; namespace osu.Game.Overlays.Dashboard.Home.News { public class NewsTitleLink : OsuHoverContainer { private readonly APINewsPost post; public NewsTitleLink(APINewsPost post) { this.post = post; RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; } [BackgroundDependencyLoader] private void load(GameHost host) { Child = new TextFlowContainer(t => { t.Font = OsuFont.GetFont(weight: FontWeight.Bold); }) { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Text = post.Title }; TooltipText = "view in browser"; Action = () => host.OpenUrlExternally("https://osu.ppy.sh/home/news/" + post.Slug); } } }
// 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.Platform; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Online.API.Requests.Responses; namespace osu.Game.Overlays.Dashboard.Home.News { public class NewsTitleLink : OsuHoverContainer { private readonly APINewsPost post; public NewsTitleLink(APINewsPost post) { this.post = post; RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; } [BackgroundDependencyLoader] private void load(GameHost host, OverlayColourProvider colourProvider) { Child = new TextFlowContainer(t => { t.Font = OsuFont.GetFont(weight: FontWeight.Bold); }) { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Text = post.Title }; HoverColour = colourProvider.Light1; TooltipText = "view in browser"; Action = () => host.OpenUrlExternally("https://osu.ppy.sh/home/news/" + post.Slug); } } }
Add api point to controller.
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CK.Glouton.Lucene; using Microsoft.AspNetCore.Mvc; namespace CK.Glouton.Web.Controllers { [Route("api/stats")] public class StatisticsController : Controller { LuceneStatistics luceneStatistics; public StatisticsController() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CK.Glouton.Lucene; using CK.Glouton.Model.Lucene; using Microsoft.AspNetCore.Mvc; namespace CK.Glouton.Web.Controllers { [Route("api/stats")] public class StatisticsController : Controller { private readonly ILuceneStatisticsService _luceneStatistics; public StatisticsController(ILuceneStatisticsService luceneStatistics) { _luceneStatistics = luceneStatistics; } [HttpGet("logperappname")] public Dictionary<string, int> LogPerAppName() { return _luceneStatistics.GetLogByAppName(); } [HttpGet("exceptionperappname")] public Dictionary<string, int> ExceptionPerAppName() { return _luceneStatistics.GetExceptionByAppName(); } [HttpGet("Log")] public int AllLogCount() => _luceneStatistics.AllLogCount(); [HttpGet("AppName")] public int AppNameCount() => _luceneStatistics.AppNameCount; [HttpGet("Exception")] public int AllException() => _luceneStatistics.AllExceptionCount; [HttpGet("AppNames")] public IEnumerable<string> AppNames() => _luceneStatistics.GetAppNames; } }
Remove invalid test as the directory should not be deleted since multiple artifacts / dependencies maybe be unzipping into a folder or a child folder.
using NSubstitute; using Ploeh.AutoFixture.Xunit; using TeamCityApi.Domain; using TeamCityConsole.Tests.Helpers; using TeamCityConsole.Utils; using Xunit.Extensions; namespace TeamCityConsole.Tests.Utils { public class FileDownloaderTests { [Theory] [AutoNSubstituteData] public void Should_unzip_when_double_star_used([Frozen]IFileSystem fileSystem, FileDownloader downloader) { var file = new File() { Name = "web.zip!**", ContentHref = ""}; string tempFile = @"c:\temp\abc.tmp"; fileSystem.CreateTempFile().Returns(tempFile); downloader.Download(@"c:\temp", file).Wait(); fileSystem.Received().ExtractToDirectory(tempFile, @"c:\temp"); } [Theory] [AutoNSubstituteData] public void Should_delete_target_directory_when_unziping([Frozen]IFileSystem fileSystem, FileDownloader downloader) { var file = new File() { Name = "web.zip!**", ContentHref = "" }; var destPath = @"c:\temp"; fileSystem.DirectoryExists(destPath).Returns(true); downloader.Download(destPath, file).Wait(); fileSystem.Received().DeleteDirectory(destPath, true); } } }
using NSubstitute; using Ploeh.AutoFixture.Xunit; using TeamCityApi.Domain; using TeamCityConsole.Tests.Helpers; using TeamCityConsole.Utils; using Xunit.Extensions; namespace TeamCityConsole.Tests.Utils { public class FileDownloaderTests { [Theory] [AutoNSubstituteData] public void Should_unzip_when_double_star_used([Frozen]IFileSystem fileSystem, FileDownloader downloader) { var file = new File() { Name = "web.zip!**", ContentHref = ""}; string tempFile = @"c:\temp\abc.tmp"; fileSystem.CreateTempFile().Returns(tempFile); downloader.Download(@"c:\temp", file).Wait(); fileSystem.Received().ExtractToDirectory(tempFile, @"c:\temp"); } } }
Change "Search" widget "Base URL" default value
using System.ComponentModel; using DesktopWidgets.Classes; namespace DesktopWidgets.Widgets.Search { public class Settings : WidgetSettingsBase { public Settings() { Width = 150; } [Category("General")] [DisplayName("Base URL")] public string BaseUrl { get; set; } [Category("General")] [DisplayName("URL Suffix")] public string URLSuffix { get; set; } } }
using System.ComponentModel; using DesktopWidgets.Classes; namespace DesktopWidgets.Widgets.Search { public class Settings : WidgetSettingsBase { public Settings() { Width = 150; } [Category("General")] [DisplayName("URL Prefix")] public string BaseUrl { get; set; } = "http://"; [Category("General")] [DisplayName("URL Suffix")] public string URLSuffix { get; set; } } }
Allow the CommandRuntime to be set for a cmdlet.
// Copyright (C) Pash Contributors. License: GPL/BSD. See https://github.com/Pash-Project/Pash/ using System.Management.Automation.Host; using System.Xml.Schema; using Pash.Implementation; namespace System.Management.Automation.Internal { public abstract class InternalCommand { internal CommandInfo CommandInfo { get; set; } internal PSHost PSHostInternal { get; private set; } internal PSObject CurrentPipelineObject { get; set; } internal SessionState State { get; private set; } internal ICommandRuntime CommandRuntime { get; set; } private ExecutionContext _executionContext; internal ExecutionContext ExecutionContext { get { return _executionContext; } set { _executionContext = value; State = new SessionState(_executionContext.SessionState.SessionStateGlobal); PSHostInternal = _executionContext.LocalHost; } } internal bool IsStopping { get { return ((PipelineCommandRuntime)CommandRuntime).IsStopping; } } internal InternalCommand() { } internal virtual void DoBeginProcessing() { } internal virtual void DoEndProcessing() { } internal virtual void DoProcessRecord() { } internal virtual void DoStopProcessing() { } internal void ThrowIfStopping() { } } }
// Copyright (C) Pash Contributors. License: GPL/BSD. See https://github.com/Pash-Project/Pash/ using System.Management.Automation.Host; using System.Xml.Schema; using Pash.Implementation; namespace System.Management.Automation.Internal { public abstract class InternalCommand { internal CommandInfo CommandInfo { get; set; } internal PSHost PSHostInternal { get; private set; } internal PSObject CurrentPipelineObject { get; set; } internal SessionState State { get; private set; } public ICommandRuntime CommandRuntime { get; set; } private ExecutionContext _executionContext; internal ExecutionContext ExecutionContext { get { return _executionContext; } set { _executionContext = value; State = new SessionState(_executionContext.SessionState.SessionStateGlobal); PSHostInternal = _executionContext.LocalHost; } } internal bool IsStopping { get { return ((PipelineCommandRuntime)CommandRuntime).IsStopping; } } internal InternalCommand() { } internal virtual void DoBeginProcessing() { } internal virtual void DoEndProcessing() { } internal virtual void DoProcessRecord() { } internal virtual void DoStopProcessing() { } internal void ThrowIfStopping() { } } }
Add default path action provider for Mac
using System; using System.Collections.Generic; using RepoZ.Api.IO; namespace RepoZ.Api.Mac { public class MacPathActionProvider : IPathActionProvider { public IEnumerable<PathAction> GetFor(string path) { yield return createPathAction("Open", "nil"); } private PathAction createPathAction(string name, string command) { return new PathAction() { Name = name, Action = (sender, args) => sender = null }; } private PathAction createDefaultPathAction(string name, string command) { var action = createPathAction(name, command); action.IsDefault = true; return action; } } }
using System.Diagnostics; using System.Collections.Generic; using RepoZ.Api.IO; namespace RepoZ.Api.Mac { public class MacPathActionProvider : IPathActionProvider { public IEnumerable<PathAction> GetFor(string path) { yield return createDefaultPathAction("Open in Finder", path); } private PathAction createPathAction(string name, string command) { return new PathAction() { Name = name, Action = (sender, args) => startProcess(command) }; } private PathAction createDefaultPathAction(string name, string command) { var action = createPathAction(name, command); action.IsDefault = true; return action; } private void startProcess(string command) { Process.Start(command); } } }
Fix the failing test case.
namespace Nancy.AttributeRouting { using System; using System.Reflection; /// <summary> /// The View attribute indicates the view path to render from request. /// </summary> /// <example> /// The following code will render <c>View/index.html</c> with routing instance. /// <code> /// View('View/index.html') /// </code> /// </example> [AttributeUsage(AttributeTargets.Method)] public class ViewAttribute : Attribute { private readonly string path; /// <summary> /// Initializes a new instance of the <see cref="ViewAttribute"/> class. /// </summary> /// <param name="path">The view path for rendering.</param> public ViewAttribute(string path) { this.path = path.Trim('/'); } internal static string GetPath(MethodBase method) { var attr = method.GetCustomAttribute<ViewAttribute>(false); if (attr == null) { return string.Empty; } string prefix = ViewPrefixAttribute.GetPrefix(method.DeclaringType); string path = string.Format("{0}/{1}", prefix, attr.path); return path; } } }
namespace Nancy.AttributeRouting { using System; using System.Reflection; /// <summary> /// The View attribute indicates the view path to render from request. /// </summary> /// <example> /// The following code will render <c>View/index.html</c> with routing instance. /// <code> /// View('View/index.html') /// </code> /// </example> [AttributeUsage(AttributeTargets.Method)] public class ViewAttribute : Attribute { private readonly string path; /// <summary> /// Initializes a new instance of the <see cref="ViewAttribute"/> class. /// </summary> /// <param name="path">The view path for rendering.</param> public ViewAttribute(string path) { this.path = path.Trim('/'); } internal static string GetPath(MethodBase method) { var attr = method.GetCustomAttribute<ViewAttribute>(false); if (attr == null) { return string.Empty; } string prefix = ViewPrefixAttribute.GetPrefix(method.DeclaringType); string path = string.Format("{0}/{1}", prefix, attr.path).Trim('/'); return path; } } }
Add right click by a short cut key comination
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using WindowsInput; namespace TargetClicker { /// <summary> /// MainWindow.xaml の相互作用ロジック /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void clickButtonClick(object sender, RoutedEventArgs e) { var sim = new InputSimulator(); sim.Mouse.MoveMouseTo(0, 0); sim.Mouse.RightButtonClick(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using WindowsInput; using NHotkey; using NHotkey.Wpf; namespace TargetClicker { /// <summary> /// MainWindow.xaml の相互作用ロジック /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); HotkeyManager.Current.AddOrReplace("clickTarget", Key.D1 , ModifierKeys.Control | ModifierKeys.Alt, clickTarget); } private void clickButtonClick(object sender, RoutedEventArgs e) { var sim = new InputSimulator(); sim.Mouse.MoveMouseTo(0, 0); sim.Mouse.RightButtonClick(); } private void clickTarget(object sender, HotkeyEventArgs e) { var sim = new InputSimulator(); sim.Mouse.MoveMouseTo(0, 0); sim.Mouse.RightButtonClick(); } } }
Fix test launcher to not use Drivers directory.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using AgateLib; namespace Tests { class Launcher { [STAThread] public static void Main(string[] args) { AgateFileProvider.Assemblies.AddPath("../Drivers"); AgateFileProvider.Images.AddPath("Data"); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmLauncher()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using AgateLib; namespace Tests { class Launcher { [STAThread] public static void Main(string[] args) { AgateFileProvider.Images.AddPath("Data"); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmLauncher()); } } }
Implement utlity for requesting JSON as string
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace Schedutalk.Logic { class HttpRequestor { public async Task<string> getHttpRequestAsString(Func<string, HttpRequestMessage> requestTask, string input) { HttpClient httpClient = new HttpClient(); HttpRequestMessage request = requestTask(input); var response = httpClient.SendAsync(request); var result = await response.Result.Content.ReadAsStringAsync(); return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace Schedutalk.Logic { class HttpRequestor { public async Task<string> getHttpRequestAsString(Func<string, HttpRequestMessage> requestTask, string input) { HttpClient httpClient = new HttpClient(); HttpRequestMessage request = requestTask(input); var response = httpClient.SendAsync(request); var result = await response.Result.Content.ReadAsStringAsync(); return result; } public string getJSONAsString(Func<string, HttpRequestMessage> requestTask, string placeName) { Task<string> task = getHttpRequestAsString(requestTask, "E2"); task.Wait(); //Format string string replacement = task.Result; if (0 == replacement[0].CompareTo('[')) replacement = replacement.Substring(1); if (0 == replacement[replacement.Length - 1].CompareTo(']')) replacement = replacement.Remove(replacement.Length - 1); return replacement; } } }
Fix XML docs containing an ampersand
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Net.Http { /// <summary> /// Defines default values for http handler properties which is meant to be re-used across WinHttp & UnixHttp Handlers /// </summary> internal static class HttpHandlerDefaults { public const int DefaultMaxAutomaticRedirections = 50; public const DecompressionMethods DefaultAutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; public const bool DefaultAutomaticRedirection = true; public const bool DefaultUseCookies = true; public const bool DefaultPreAuthenticate = false; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Net.Http { /// <summary> /// Defines default values for http handler properties which is meant to be re-used across WinHttp and UnixHttp Handlers /// </summary> internal static class HttpHandlerDefaults { public const int DefaultMaxAutomaticRedirections = 50; public const DecompressionMethods DefaultAutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; public const bool DefaultAutomaticRedirection = true; public const bool DefaultUseCookies = true; public const bool DefaultPreAuthenticate = false; } }
Remove configfile prefix from settings file and let tablename drive naming.
//****************************************************************************************************** // Setting.cs - Gbtc // // Copyright © 2021, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this // file except in compliance with the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 06/09/2021 - Billy Ernest // Generated original version of source code. // //****************************************************************************************************** using GSF.Data.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SystemCenter.Model { [ConfigFileTableNamePrefix, TableName("SystemCenter.Setting"), UseEscapedName, AllowSearch] [PostRoles("Administrator")] [DeleteRoles("Administrator")] [PatchRoles("Administrator")] public class Setting: openXDA.Model.Setting {} }
//****************************************************************************************************** // Setting.cs - Gbtc // // Copyright © 2021, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this // file except in compliance with the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 06/09/2021 - Billy Ernest // Generated original version of source code. // //****************************************************************************************************** using GSF.Data.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SystemCenter.Model { [TableName("SystemCenter.Setting"), UseEscapedName, AllowSearch] [PostRoles("Administrator")] [DeleteRoles("Administrator")] [PatchRoles("Administrator")] public class Setting: openXDA.Model.Setting {} }
Fix mania scroll direction not being read from database
// 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.Configuration; using osu.Game.Rulesets.Mania.Configuration; using osu.Game.Rulesets.UI.Scrolling; namespace osu.Game.Rulesets.Mania.UI { public class ManiaScrollingInfo : IScrollingInfo { private readonly Bindable<ManiaScrollingDirection> configDirection = new Bindable<ManiaScrollingDirection>(); public readonly Bindable<ScrollingDirection> Direction = new Bindable<ScrollingDirection>(); IBindable<ScrollingDirection> IScrollingInfo.Direction => Direction; public ManiaScrollingInfo(ManiaConfigManager config) { config.BindWith(ManiaSetting.ScrollDirection, configDirection); configDirection.BindValueChanged(v => Direction.Value = (ScrollingDirection)v); } } }
// 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.Configuration; using osu.Game.Rulesets.Mania.Configuration; using osu.Game.Rulesets.UI.Scrolling; namespace osu.Game.Rulesets.Mania.UI { public class ManiaScrollingInfo : IScrollingInfo { private readonly Bindable<ManiaScrollingDirection> configDirection = new Bindable<ManiaScrollingDirection>(); public readonly Bindable<ScrollingDirection> Direction = new Bindable<ScrollingDirection>(); IBindable<ScrollingDirection> IScrollingInfo.Direction => Direction; public ManiaScrollingInfo(ManiaConfigManager config) { config.BindWith(ManiaSetting.ScrollDirection, configDirection); configDirection.BindValueChanged(v => Direction.Value = (ScrollingDirection)v, true); } } }
Add the [200 .. 300] bpm speed bonus
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Game.Rulesets.Osu.Difficulty.Preprocessing; namespace osu.Game.Rulesets.Osu.Difficulty.Skills { /// <summary> /// Represents the skill required to press keys with regards to keeping up with the speed at which objects need to be hit. /// </summary> public class Speed : Skill { protected override double SkillMultiplier => 1400; protected override double StrainDecayBase => 0.3; protected override double StrainValueOf(OsuDifficultyHitObject current) { double distance = Math.Min(SINGLE_SPACING_THRESHOLD, current.TravelDistance + current.JumpDistance); return (0.95 + Math.Pow(distance / SINGLE_SPACING_THRESHOLD, 4)) / current.StrainTime; } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Game.Rulesets.Osu.Difficulty.Preprocessing; namespace osu.Game.Rulesets.Osu.Difficulty.Skills { /// <summary> /// Represents the skill required to press keys with regards to keeping up with the speed at which objects need to be hit. /// </summary> public class Speed : Skill { protected override double SkillMultiplier => 1400; protected override double StrainDecayBase => 0.3; private const double min_speed_bonus = 75; // ~200BPM private const double max_speed_bonus = 45; // ~330BPM private const double speed_balancing_factor = 40; protected override double StrainValueOf(OsuDifficultyHitObject current) { double distance = Math.Min(SINGLE_SPACING_THRESHOLD, current.TravelDistance + current.JumpDistance); double deltaTime = Math.Max(max_speed_bonus, current.DeltaTime); double speedBonus = 1.0; if (deltaTime < min_speed_bonus) speedBonus = 1 + Math.Pow((min_speed_bonus - deltaTime) / speed_balancing_factor, 2); return speedBonus * (0.95 + Math.Pow(distance / SINGLE_SPACING_THRESHOLD, 4)) / current.StrainTime; } } }
Fix landing on the ground not working occasionally
using System; using UnityEngine; using System.Collections; public class GroundCheck : MonoBehaviour { public bool IsOnGround { get; private set; } public void OnTriggerEnter(Collider other) { var geometry = other.gameObject.GetComponent<LevelGeometry>(); if (geometry != null) { IsOnGround = true; } } public void OnTriggerExit(Collider other) { var geometry = other.gameObject.GetComponent<LevelGeometry>(); if (geometry != null) { IsOnGround = false; } } }
using System; using UnityEngine; using System.Collections; public class GroundCheck : MonoBehaviour { public bool IsOnGround { get; private set; } public void OnTriggerStay(Collider other) { var geometry = other.gameObject.GetComponent<LevelGeometry>(); if (geometry != null) { IsOnGround = true; } } public void OnTriggerExit(Collider other) { var geometry = other.gameObject.GetComponent<LevelGeometry>(); if (geometry != null) { IsOnGround = false; } } }
Return null IPC response for archive imports
// 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.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using osu.Framework.Platform; using osu.Game.Database; namespace osu.Game.IPC { public class ArchiveImportIPCChannel : IpcChannel<ArchiveImportMessage> { private readonly ICanAcceptFiles importer; public ArchiveImportIPCChannel(IIpcHost host, ICanAcceptFiles importer = null) : base(host) { this.importer = importer; MessageReceived += msg => { Debug.Assert(importer != null); ImportAsync(msg.Path).ContinueWith(t => { if (t.Exception != null) throw t.Exception; }, TaskContinuationOptions.OnlyOnFaulted); }; } public async Task ImportAsync(string path) { if (importer == null) { // we want to contact a remote osu! to handle the import. await SendMessageAsync(new ArchiveImportMessage { Path = path }).ConfigureAwait(false); return; } if (importer.HandledExtensions.Contains(Path.GetExtension(path)?.ToLowerInvariant())) await importer.Import(path).ConfigureAwait(false); } } public class ArchiveImportMessage { public string Path; } }
// 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.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using osu.Framework.Platform; using osu.Game.Database; namespace osu.Game.IPC { public class ArchiveImportIPCChannel : IpcChannel<ArchiveImportMessage> { private readonly ICanAcceptFiles importer; public ArchiveImportIPCChannel(IIpcHost host, ICanAcceptFiles importer = null) : base(host) { this.importer = importer; MessageReceived += msg => { Debug.Assert(importer != null); ImportAsync(msg.Path).ContinueWith(t => { if (t.Exception != null) throw t.Exception; }, TaskContinuationOptions.OnlyOnFaulted); return null; }; } public async Task ImportAsync(string path) { if (importer == null) { // we want to contact a remote osu! to handle the import. await SendMessageAsync(new ArchiveImportMessage { Path = path }).ConfigureAwait(false); return; } if (importer.HandledExtensions.Contains(Path.GetExtension(path)?.ToLowerInvariant())) await importer.Import(path).ConfigureAwait(false); } } public class ArchiveImportMessage { public string Path; } }
Fix one more test regression
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using osu.Framework.Allocation; using osu.Game.Rulesets; using osu.Game.Screens.Edit; using osu.Game.Tests.Beatmaps; namespace osu.Game.Tests.Visual { public abstract class EditorTestCase : ScreenTestCase { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(Editor), typeof(EditorScreen) }; private readonly Ruleset ruleset; protected EditorTestCase(Ruleset ruleset) { this.ruleset = ruleset; } [BackgroundDependencyLoader] private void load() { Beatmap.Value = new TestWorkingBeatmap(ruleset.RulesetInfo, Clock); LoadComponentAsync(new Editor(), LoadScreen); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using osu.Framework.Allocation; using osu.Game.Rulesets; using osu.Game.Screens.Edit; using osu.Game.Tests.Beatmaps; namespace osu.Game.Tests.Visual { public abstract class EditorTestCase : ScreenTestCase { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(Editor), typeof(EditorScreen) }; private readonly Ruleset ruleset; protected EditorTestCase(Ruleset ruleset) { this.ruleset = ruleset; } [BackgroundDependencyLoader] private void load() { Beatmap.Value = new TestWorkingBeatmap(ruleset.RulesetInfo, null); LoadComponentAsync(new Editor(), LoadScreen); } } }
Change for to foreach in endpoints list
// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved. // The Apache v2. See License.txt in the project root for license information. using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Routing.Matching; namespace Wangkanai.Detection.Hosting { internal class ResponsivePageMatcherPolicy : MatcherPolicy, IEndpointComparerPolicy, IEndpointSelectorPolicy { public ResponsivePageMatcherPolicy() => Comparer = EndpointMetadataComparer<IResponsiveMetadata>.Default; public IComparer<Endpoint> Comparer { get; } public override int Order => 10000; public bool AppliesToEndpoints(IReadOnlyList<Endpoint> endpoints) { for (var i = 0; i < endpoints.Count; i++) if (endpoints[i].Metadata.GetMetadata<IResponsiveMetadata>() != null) return true; return false; } public Task ApplyAsync(HttpContext httpContext, CandidateSet candidates) { var device = httpContext.GetDevice(); for (var i = 0; i < candidates.Count; i++) { var endpoint = candidates[i].Endpoint; var metadata = endpoint.Metadata.GetMetadata<IResponsiveMetadata>(); if (metadata?.Device != null && device != metadata.Device) { // This endpoint is not a match for the selected device. candidates.SetValidity(i, false); } } return Task.CompletedTask; } } }
// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved. // The Apache v2. See License.txt in the project root for license information. using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Routing.Matching; namespace Wangkanai.Detection.Hosting { internal class ResponsivePageMatcherPolicy : MatcherPolicy, IEndpointComparerPolicy, IEndpointSelectorPolicy { public ResponsivePageMatcherPolicy() => Comparer = EndpointMetadataComparer<IResponsiveMetadata>.Default; public IComparer<Endpoint> Comparer { get; } public override int Order => 10000; public bool AppliesToEndpoints(IReadOnlyList<Endpoint> endpoints) { foreach (var endpoint in endpoints) if (endpoint?.Metadata.GetMetadata<IResponsiveMetadata>() != null) return true; return false; } public Task ApplyAsync(HttpContext httpContext, CandidateSet candidates) { var device = httpContext.GetDevice(); for (var i = 0; i < candidates.Count; i++) { var endpoint = candidates[i].Endpoint; var metadata = endpoint.Metadata.GetMetadata<IResponsiveMetadata>(); if (metadata?.Device != null && device != metadata.Device) { // This endpoint is not a match for the selected device. candidates.SetValidity(i, false); } } return Task.CompletedTask; } } }
Fix typo in exception message
using System; namespace StateMechanic { /// <summary> /// Exception thrown when a transition could not be created from a state on an event, because the state and event do not belong to the same state machine /// </summary> public class InvalidEventTransitionException : Exception { /// <summary> /// Gets the state from which the transition could not be created /// </summary> public IState From { get; private set; } /// <summary> /// Gets the event on which the transition could not be created /// </summary> public IEvent Event { get; private set; } internal InvalidEventTransitionException(IState from, IEvent @event) : base(String.Format("Unable to create from state {0} on event {1}, as state {0} does not belong to the same state machine as event {1}, or to a child state machine of event {1}", from.Name, @event.Name)) { this.From = from; this.Event = @event; } } }
using System; namespace StateMechanic { /// <summary> /// Exception thrown when a transition could not be created from a state on an event, because the state and event do not belong to the same state machine /// </summary> public class InvalidEventTransitionException : Exception { /// <summary> /// Gets the state from which the transition could not be created /// </summary> public IState From { get; private set; } /// <summary> /// Gets the event on which the transition could not be created /// </summary> public IEvent Event { get; private set; } internal InvalidEventTransitionException(IState from, IEvent @event) : base(String.Format("Unable to create transition from state {0} on event {1}, as state {0} does not belong to the same state machine as event {1}, or to a child state machine of event {1}", from.Name, @event.Name)) { this.From = from; this.Event = @event; } } }
Fix continuing historic time entries.
using System; using System.Linq; using Android.App; using Android.OS; using Android.Views; using Android.Widget; using Toggl.Joey.UI.Adapters; namespace Toggl.Joey.UI.Fragments { public class LogTimeEntriesListFragment : ListFragment { public override void OnViewCreated (View view, Bundle savedInstanceState) { base.OnViewCreated (view, savedInstanceState); ListAdapter = new LogTimeEntriesAdapter (); } public override void OnListItemClick (ListView l, View v, int position, long id) { var adapter = l.Adapter as LogTimeEntriesAdapter; if (adapter == null) return; var model = adapter.GetModel (position); if (model == null) return; model.Continue (); } } }
using System; using System.Linq; using Android.App; using Android.OS; using Android.Views; using Android.Widget; using Toggl.Joey.UI.Adapters; namespace Toggl.Joey.UI.Fragments { public class LogTimeEntriesListFragment : ListFragment { public override void OnViewCreated (View view, Bundle savedInstanceState) { base.OnViewCreated (view, savedInstanceState); ListAdapter = new LogTimeEntriesAdapter (); } public override void OnListItemClick (ListView l, View v, int position, long id) { var adapter = l.Adapter as LogTimeEntriesAdapter; if (adapter == null) return; var model = adapter.GetModel (position); if (model == null) return; model.IsPersisted = true; model.Continue (); } } }
Disable DebugIL2CPU to test all kernels
using System; using System.Collections.Generic; using Cosmos.Build.Common; using Cosmos.TestRunner.Core; namespace Cosmos.TestRunner.Full { public class DefaultEngineConfiguration : IEngineConfiguration { public virtual int AllowedSecondsInKernel => 6000; public virtual IEnumerable<RunTargetEnum> RunTargets { get { yield return RunTargetEnum.Bochs; //yield return RunTargetEnum.VMware; //yield return RunTargetEnum.HyperV; //yield return RunTargetEnum.Qemu; } } public virtual bool RunWithGDB => true; public virtual bool StartBochsDebugGUI => true; public virtual bool DebugIL2CPU => true; public virtual string KernelPkg => String.Empty; public virtual TraceAssemblies TraceAssembliesLevel => TraceAssemblies.User; public virtual bool EnableStackCorruptionChecks => true; public virtual StackCorruptionDetectionLevel StackCorruptionDetectionLevel => StackCorruptionDetectionLevel.MethodFooters; public virtual DebugMode DebugMode => DebugMode.Source; public virtual IEnumerable<string> KernelAssembliesToRun { get { foreach (var xKernelType in TestKernelSets.GetKernelTypesToRun()) { yield return xKernelType.Assembly.Location; } } } } }
using System; using System.Collections.Generic; using Cosmos.Build.Common; using Cosmos.TestRunner.Core; namespace Cosmos.TestRunner.Full { public class DefaultEngineConfiguration : IEngineConfiguration { public virtual int AllowedSecondsInKernel => 6000; public virtual IEnumerable<RunTargetEnum> RunTargets { get { yield return RunTargetEnum.Bochs; //yield return RunTargetEnum.VMware; //yield return RunTargetEnum.HyperV; //yield return RunTargetEnum.Qemu; } } public virtual bool RunWithGDB => true; public virtual bool StartBochsDebugGUI => true; public virtual bool DebugIL2CPU => false; public virtual string KernelPkg => String.Empty; public virtual TraceAssemblies TraceAssembliesLevel => TraceAssemblies.User; public virtual bool EnableStackCorruptionChecks => true; public virtual StackCorruptionDetectionLevel StackCorruptionDetectionLevel => StackCorruptionDetectionLevel.MethodFooters; public virtual DebugMode DebugMode => DebugMode.Source; public virtual IEnumerable<string> KernelAssembliesToRun { get { foreach (var xKernelType in TestKernelSets.GetKernelTypesToRun()) { yield return xKernelType.Assembly.Location; } } } } }
Add the ability to create a readonly deploy key
using System; using System.Diagnostics; using System.Globalization; namespace Octokit { /// <summary> /// Describes a new deployment key to create. /// </summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public class NewDeployKey { public string Title { get; set; } public string Key { get; set; } internal string DebuggerDisplay { get { return String.Format(CultureInfo.InvariantCulture, "Key: {0}, Title: {1}", Key, Title); } } } }
using System; using System.Diagnostics; using System.Globalization; namespace Octokit { /// <summary> /// Describes a new deployment key to create. /// </summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public class NewDeployKey { public string Title { get; set; } public string Key { get; set; } /// <summary> /// Gets or sets a value indicating whether the key will only be able to read repository contents. Otherwise, /// the key will be able to read and write. /// </summary> /// <value> /// <c>true</c> if [read only]; otherwise, <c>false</c>. /// </value> public bool ReadOnly { get; set; } internal string DebuggerDisplay { get { return String.Format(CultureInfo.InvariantCulture, "Key: {0}, Title: {1}", Key, Title); } } } }
Update filter to support PWSH
using System.Linq; using System.ServiceModel.Syndication; namespace Firehose.Web.Extensions { public static class SyndicationItemExtensions { public static bool ApplyDefaultFilter(this SyndicationItem item) { if (item == null) return false; var hasPowerShellCategory = false; var hasPowerShellKeywords = false; if (item.Categories.Count > 0) { hasPowerShellCategory = item.Categories.Any(category => category.Name.ToLowerInvariant().Contains("powershell")); } if (item.ElementExtensions.Count > 0) { var element = item.ElementExtensions.FirstOrDefault(e => e.OuterName == "keywords"); if (element != null) { var keywords = element.GetObject<string>(); hasPowerShellKeywords = keywords.ToLowerInvariant().Contains("powershell"); } } var hasPowerShellTitle = item.Title?.Text.ToLowerInvariant().Contains("powershell") ?? false; return hasPowerShellTitle || hasPowerShellCategory || hasPowerShellKeywords; } public static string ToHtml(this SyndicationContent content) { var textSyndicationContent = content as TextSyndicationContent; if (textSyndicationContent != null) { return textSyndicationContent.Text; } return content.ToString(); } } }
using System.Linq; using System.ServiceModel.Syndication; namespace Firehose.Web.Extensions { public static class SyndicationItemExtensions { public static bool ApplyDefaultFilter(this SyndicationItem item) { if (item == null) return false; var hasPowerShellCategory = false; var hasPowerShellKeywords = false; var hasPWSHCategory = false; var hasPWSHKeywords = false; if (item.Categories.Count > 0) { hasPowerShellCategory = item.Categories.Any(category => category.Name.ToLowerInvariant().Contains("powershell")); hasPWSHCategory = item.Categories.Any(category => category.Name.ToLowerInvariant().Contains("pwsh")); } if (item.ElementExtensions.Count > 0) { var element = item.ElementExtensions.FirstOrDefault(e => e.OuterName == "keywords"); if (element != null) { var keywords = element.GetObject<string>(); hasPowerShellKeywords = keywords.ToLowerInvariant().Contains("powershell"); hasPWSHKeywords = keywords.ToLowerInvariant().Contains("pwsh"); } } var hasPowerShellTitle = item.Title?.Text.ToLowerInvariant().Contains("powershell") ?? false; var hasPWSHTitle = item.Title?.Text.ToLowerInvariant().Contains("pwsh") ?? false; return hasPowerShellTitle || hasPowerShellCategory || hasPowerShellKeywords || hasPWSHTitle || hasPWSHCategory || hasPWSHKeywords; } public static string ToHtml(this SyndicationContent content) { var textSyndicationContent = content as TextSyndicationContent; if (textSyndicationContent != null) { return textSyndicationContent.Text; } return content.ToString(); } } }
Fix an issue with the default URI
using SkiResort.XamarinApp.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace SkiResort.XamarinApp { public static class Config { public const string API_URL = "__SERVERURI__/api"; public const double USER_DEFAULT_POSITION_LATITUDE = 40.7201013; public const double USER_DEFAULT_POSITION_LONGITUDE = -74.0101931; public static Color BAR_COLOR_BLACK = Color.FromHex("#141414"); } }
using SkiResort.XamarinApp.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace SkiResort.XamarinApp { public static class Config { public const string API_URL = "__SERVERURI__"; public const double USER_DEFAULT_POSITION_LATITUDE = 40.7201013; public const double USER_DEFAULT_POSITION_LONGITUDE = -74.0101931; public static Color BAR_COLOR_BLACK = Color.FromHex("#141414"); } }
Add Is any key function
using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Networking; public static class UnityUtils { public static bool IsAnyKeyUp(KeyCode[] keys) { foreach (KeyCode key in keys) { if (Input.GetKeyUp(key)) return true; } return false; } public static bool IsAnyKeyDown(KeyCode[] keys) { foreach (KeyCode key in keys) { if (Input.GetKeyDown(key)) return true; } return false; } public static bool IsHeadless() { return SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null; } public static bool TryGetByNetId<T>(NetworkInstanceId targetNetId, out T output) where T : Component { output = null; GameObject foundObject = ClientScene.FindLocalObject(targetNetId); if (foundObject == null) return false; output = foundObject.GetComponent<T>(); if (output == null) return false; return true; } }
using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Networking; public static class UnityUtils { public static bool IsAnyKeyUp(KeyCode[] keys) { foreach (KeyCode key in keys) { if (Input.GetKeyUp(key)) return true; } return false; } public static bool IsAnyKeyDown(KeyCode[] keys) { foreach (KeyCode key in keys) { if (Input.GetKeyDown(key)) return true; } return false; } public static bool IsAnyKey(KeyCode[] keys) { foreach (KeyCode key in keys) { if (Input.GetKey(key)) return true; } return false; } public static bool IsHeadless() { return SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null; } public static bool TryGetByNetId<T>(NetworkInstanceId targetNetId, out T output) where T : Component { output = null; GameObject foundObject = ClientScene.FindLocalObject(targetNetId); if (foundObject == null) return false; output = foundObject.GetComponent<T>(); if (output == null) return false; return true; } }
Add Travis to contact page.
@{ ViewBag.Title = "Contact"; } <h2>@ViewBag.Title.</h2> <h3>@ViewBag.Message</h3> <address> One Microsoft Way<br /> Redmond, WA 98052-6399<br /> <abbr title="Phone">P:</abbr> 425.555.0100 </address> <address> <strong>Support:</strong> <a href="mailto:Support@example.com">Support@wechangedthis.com</a><br /> <strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a> <strong>Batman:</strong> <a href="mailto:Batman@batman.com">Batman@batman.com</a> <strong>Peter Parker</strong> <a href="mailto:spiderman@spiderman.com">Spiderman@spiderman.com</a> </address>
@{ ViewBag.Title = "Contact"; } <h2>@ViewBag.Title.</h2> <h3>@ViewBag.Message</h3> <address> One Microsoft Way<br /> Redmond, WA 98052-6399<br /> <abbr title="Phone">P:</abbr> 425.555.0100 </address> <address> <strong>Support:</strong> <a href="mailto:Support@example.com">Support@wechangedthis.com</a><br /> <strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a> <strong>Batman:</strong> <a href="mailto:Batman@batman.com">Batman@batman.com</a> <strong>Peter Parker</strong> <a href="mailto:spiderman@spiderman.com">Spiderman@spiderman.com</a> <strong>Travis Elkins</strong> </address>
Fix the TODO item in Ushelve so it can support multiple TFS remotes
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using CommandLine.OptParse; using Sep.Git.Tfs.Core; using Sep.Git.Tfs.Core.TfsInterop; using StructureMap; namespace Sep.Git.Tfs.Commands { [Pluggable("unshelve")] [Description("unshelve [options] (-l | shelveset-name destination-branch)")] [RequiresValidGitRepository] public class Unshelve : GitTfsCommand { private readonly Globals _globals; public Unshelve(Globals globals) { _globals = globals; } [OptDef(OptValType.ValueReq)] [ShortOptionName('u')] [LongOptionName("user")] [UseNameAsLongOption(false)] [Description("Shelveset owner (default is the current user; 'all' means all users)")] public string Owner { get; set; } public IEnumerable<IOptionResults> ExtraOptions { get { return this.MakeNestedOptionResults(); } } public int Run(IList<string> args) { // TODO -- let the remote be specified on the command line. var remote = _globals.Repository.ReadAllTfsRemotes().First(); return remote.Tfs.Unshelve(this, remote, args); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Text.RegularExpressions; using CommandLine.OptParse; using Sep.Git.Tfs.Core; using StructureMap; namespace Sep.Git.Tfs.Commands { [Pluggable("unshelve")] [Description("unshelve [options] (-l | shelveset-name destination-branch)")] [RequiresValidGitRepository] public class Unshelve : GitTfsCommand { private readonly Globals _globals; public Unshelve(Globals globals) { _globals = globals; } [OptDef(OptValType.ValueReq)] [ShortOptionName('u')] [LongOptionName("user")] [UseNameAsLongOption(false)] [Description("Shelveset owner (default is the current user; 'all' means all users)")] public string Owner { get; set; } public IEnumerable<IOptionResults> ExtraOptions { get { return this.MakeNestedOptionResults(); } } public int Run(IList<string> args) { var remote = _globals.Repository.ReadTfsRemote(_globals.RemoteId); return remote.Tfs.Unshelve(this, remote, args); } } }
Fix field name and accessibility
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using osu.Game.Beatmaps; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Edit.Checks.Components; using osu.Game.Rulesets.Osu.Edit.Checks; namespace osu.Game.Rulesets.Osu.Edit { public class OsuChecker : Checker { public readonly List<Check> beatmapChecks = new List<Check> { new CheckOffscreenObjects() }; public override IEnumerable<Issue> Run(IBeatmap beatmap) { // Also run mode-invariant checks. foreach (var issue in base.Run(beatmap)) yield return issue; foreach (var issue in beatmapChecks.SelectMany(check => check.Run(beatmap))) yield return issue; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using osu.Game.Beatmaps; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Edit.Checks.Components; using osu.Game.Rulesets.Osu.Edit.Checks; namespace osu.Game.Rulesets.Osu.Edit { public class OsuChecker : Checker { private readonly List<Check> checks = new List<Check> { new CheckOffscreenObjects() }; public override IEnumerable<Issue> Run(IBeatmap beatmap) { // Also run mode-invariant checks. foreach (var issue in base.Run(beatmap)) yield return issue; foreach (var issue in checks.SelectMany(check => check.Run(beatmap))) yield return issue; } } }
Fix source dir path (doesn't like "./")
#load nuget:https://www.myget.org/F/cake-contrib/api/v2?package=Cake.Recipe&prerelease Environment.SetVariableNames(); BuildParameters.SetParameters(context: Context, buildSystem: BuildSystem, sourceDirectoryPath: "./", title: "Cake.FileHelpers", repositoryOwner: "cake-contrib", repositoryName: "Cake.FileHelpers", appVeyorAccountName: "cakecontrib", shouldRunDupFinder: false, shouldRunInspectCode: false); BuildParameters.PrintParameters(Context); ToolSettings.SetToolSettings(context: Context, dupFinderExcludePattern: new string[] { BuildParameters.RootDirectoryPath + "/Cake.FileHelpers.Tests/*.cs" }, testCoverageFilter: "+[*]* -[xunit.*]* -[Cake.Core]* -[Cake.Testing]* -[*.Tests]* -[FakeItEasy]*", testCoverageExcludeByAttribute: "*.ExcludeFromCodeCoverage*", testCoverageExcludeByFile: "*/*Designer.cs;*/*.g.cs;*/*.g.i.cs"); Build.RunDotNetCore();
#load nuget:https://www.myget.org/F/cake-contrib/api/v2?package=Cake.Recipe&prerelease Environment.SetVariableNames(); BuildParameters.SetParameters(context: Context, buildSystem: BuildSystem, sourceDirectoryPath: Context.Environment.WorkingDirectory, title: "Cake.FileHelpers", repositoryOwner: "cake-contrib", repositoryName: "Cake.FileHelpers", appVeyorAccountName: "cakecontrib", shouldRunDupFinder: false, shouldRunInspectCode: false); BuildParameters.PrintParameters(Context); ToolSettings.SetToolSettings(context: Context, dupFinderExcludePattern: new string[] { BuildParameters.RootDirectoryPath + "/Cake.FileHelpers.Tests/*.cs" }, testCoverageFilter: "+[*]* -[xunit.*]* -[Cake.Core]* -[Cake.Testing]* -[*.Tests]* -[FakeItEasy]*", testCoverageExcludeByAttribute: "*.ExcludeFromCodeCoverage*", testCoverageExcludeByFile: "*/*Designer.cs;*/*.g.cs;*/*.g.i.cs"); Build.RunDotNetCore();
Fix bug with reassigning the variable.
using System; namespace xFunc.Library.Maths.Expressions { public class AssignMathExpression : IMathExpression { private VariableMathExpression variable; private IMathExpression value; public AssignMathExpression() : this(null, null) { } public AssignMathExpression(VariableMathExpression variable, IMathExpression value) { this.variable = variable; this.value = value; } public double Calculate(MathParameterCollection parameters) { if (parameters == null) throw new ArgumentNullException("parameters"); parameters.Add(variable.Variable, value.Calculate(parameters)); return double.NaN; } public IMathExpression Derivative() { throw new NotSupportedException(); } public IMathExpression Derivative(VariableMathExpression variable) { throw new NotSupportedException(); } public VariableMathExpression Variable { get { return variable; } set { variable = value; } } public IMathExpression Value { get { return this.value; } set { this.value = value; } } public IMathExpression Parent { get { return null; } set { } } } }
using System; namespace xFunc.Library.Maths.Expressions { public class AssignMathExpression : IMathExpression { private VariableMathExpression variable; private IMathExpression value; public AssignMathExpression() : this(null, null) { } public AssignMathExpression(VariableMathExpression variable, IMathExpression value) { this.variable = variable; this.value = value; } public double Calculate(MathParameterCollection parameters) { if (parameters == null) throw new ArgumentNullException("parameters"); parameters[variable.Variable] = value.Calculate(parameters); return double.NaN; } public IMathExpression Derivative() { throw new NotSupportedException(); } public IMathExpression Derivative(VariableMathExpression variable) { throw new NotSupportedException(); } public VariableMathExpression Variable { get { return variable; } set { variable = value; } } public IMathExpression Value { get { return this.value; } set { this.value = value; } } public IMathExpression Parent { get { return null; } set { } } } }
Add other mocking libs in dependency contraints
using System.Linq; using NUnit.Framework; namespace Ploeh.AutoFixture.NUnit3.UnitTest { [TestFixture] public class DependencyConstraints { [TestCase("Moq")] [TestCase("Rhino.Mocks")] public void AutoFixtureNUnit3DoesNotReference(string assemblyName) { // Fixture setup // Exercise system var references = typeof(AutoDataAttribute).Assembly.GetReferencedAssemblies(); // Verify outcome Assert.False(references.Any(an => an.Name == assemblyName)); // Teardown } [TestCase("Moq")] [TestCase("Rhino.Mocks")] public void AutoFixtureNUnit3UnitTestsDoNotReference(string assemblyName) { // Fixture setup // Exercise system var references = this.GetType().Assembly.GetReferencedAssemblies(); // Verify outcome Assert.False(references.Any(an => an.Name == assemblyName)); // Teardown } } }
using System.Linq; using NUnit.Framework; namespace Ploeh.AutoFixture.NUnit3.UnitTest { [TestFixture] public class DependencyConstraints { [TestCase("FakeItEasy")] [TestCase("Foq")] [TestCase("FsCheck")] [TestCase("Moq")] [TestCase("NSubstitute")] [TestCase("Rhino.Mocks")] [TestCase("Unquote")] [TestCase("xunit")] [TestCase("xunit.extensions")] public void AutoFixtureNUnit3DoesNotReference(string assemblyName) { // Fixture setup // Exercise system var references = typeof(AutoDataAttribute).Assembly.GetReferencedAssemblies(); // Verify outcome Assert.False(references.Any(an => an.Name == assemblyName)); // Teardown } [TestCase("FakeItEasy")] [TestCase("Foq")] [TestCase("FsCheck")] [TestCase("Moq")] [TestCase("NSubstitute")] [TestCase("Rhino.Mocks")] [TestCase("Unquote")] [TestCase("xunit")] [TestCase("xunit.extensions")] public void AutoFixtureNUnit3UnitTestsDoNotReference(string assemblyName) { // Fixture setup // Exercise system var references = this.GetType().Assembly.GetReferencedAssemblies(); // Verify outcome Assert.False(references.Any(an => an.Name == assemblyName)); // Teardown } } }
Stop mouse cursor disappearing when input is restored with Esc button
using System; using UnityEngine; public static class InputInterceptor { static InputInterceptor() { Type abstractControlsType = ReflectionHelper.FindType("AbstractControls"); _inputSystems = Resources.FindObjectsOfTypeAll(abstractControlsType); } public static void EnableInput() { foreach (UnityEngine.Object inputSystem in _inputSystems) { try { ((MonoBehaviour)inputSystem).gameObject.SetActive(true); } catch (Exception ex) { Debug.LogException(ex); } } } public static void DisableInput() { foreach (UnityEngine.Object inputSystem in _inputSystems) { try { ((MonoBehaviour)inputSystem).gameObject.SetActive(false); } catch (Exception ex) { Debug.LogException(ex); } } } private static UnityEngine.Object[] _inputSystems = null; }
using System; using UnityEngine; public static class InputInterceptor { static InputInterceptor() { Type abstractControlsType = ReflectionHelper.FindType("AbstractControls"); _inputSystems = Resources.FindObjectsOfTypeAll(abstractControlsType); } public static void EnableInput() { foreach (UnityEngine.Object inputSystem in _inputSystems) { try { ((MonoBehaviour)inputSystem).gameObject.SetActive(true); Cursor.visible = true; } catch (Exception ex) { Debug.LogException(ex); } } } public static void DisableInput() { foreach (UnityEngine.Object inputSystem in _inputSystems) { try { ((MonoBehaviour)inputSystem).gameObject.SetActive(false); } catch (Exception ex) { Debug.LogException(ex); } } } private static UnityEngine.Object[] _inputSystems = null; }
Add method for rounding decimals.
using System; using System.ComponentModel; using System.Reflection; namespace CertiPay.Payroll.Common { public static class ExtensionMethods { /// <summary> /// Returns the display name from the description attribute on the enumeration, if available. /// Otherwise returns the ToString() value. /// </summary> public static string DisplayName(this Enum val) { FieldInfo fi = val.GetType().GetField(val.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attributes != null && attributes.Length > 0) { return attributes[0].Description; } return val.ToString(); } } }
using System; using System.ComponentModel; using System.Reflection; namespace CertiPay.Payroll.Common { public static class ExtensionMethods { /// <summary> /// Round the decimal to the given number of decimal places using the given method of rounding. /// By default, this is 2 decimal places to the nearest even for middle values /// i.e. 1.455 -> 1.46 /// </summary> public static Decimal Round(this Decimal val, int decimals = 2, MidpointRounding rounding = MidpointRounding.ToEven) { return Math.Round(val, decimals, rounding); } /// <summary> /// Returns the display name from the description attribute on the enumeration, if available. /// Otherwise returns the ToString() value. /// </summary> public static string DisplayName(this Enum val) { FieldInfo fi = val.GetType().GetField(val.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attributes != null && attributes.Length > 0) { return attributes[0].Description; } return val.ToString(); } } }
Hide HUD in a better way
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics.Sprites; using osu.Game.Graphics; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.UI; using osu.Game.Screens.Play; namespace osu.Game.Rulesets.Mods { public abstract class ModCinema<T> : ModCinema, IApplicableToDrawableRuleset<T> where T : HitObject { public virtual void ApplyToDrawableRuleset(DrawableRuleset<T> drawableRuleset) { drawableRuleset.SetReplayScore(CreateReplayScore(drawableRuleset.Beatmap)); drawableRuleset.Playfield.AlwaysPresent = true; drawableRuleset.Playfield.Hide(); } } public class ModCinema : ModAutoplay, IApplicableToHUD, IApplicableToPlayer { public override string Name => "Cinema"; public override string Acronym => "CN"; public override IconUsage Icon => OsuIcon.ModCinema; public override string Description => "Watch the video without visual distractions."; public void ApplyToHUD(HUDOverlay overlay) { overlay.AlwaysPresent = true; overlay.Hide(); } public void ApplyToPlayer(Player player) { player.Background.EnableUserDim.Value = false; player.DimmableVideo.IgnoreUserSettings.Value = true; player.DimmableStoryboard.IgnoreUserSettings.Value = true; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics.Sprites; using osu.Game.Graphics; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.UI; using osu.Game.Screens.Play; namespace osu.Game.Rulesets.Mods { public abstract class ModCinema<T> : ModCinema, IApplicableToDrawableRuleset<T> where T : HitObject { public virtual void ApplyToDrawableRuleset(DrawableRuleset<T> drawableRuleset) { drawableRuleset.SetReplayScore(CreateReplayScore(drawableRuleset.Beatmap)); drawableRuleset.Playfield.AlwaysPresent = true; drawableRuleset.Playfield.Hide(); } } public class ModCinema : ModAutoplay, IApplicableToHUD, IApplicableToPlayer { public override string Name => "Cinema"; public override string Acronym => "CN"; public override IconUsage Icon => OsuIcon.ModCinema; public override string Description => "Watch the video without visual distractions."; public void ApplyToHUD(HUDOverlay overlay) { overlay.ShowHud.Value = false; overlay.ShowHud.Disabled = true; } public void ApplyToPlayer(Player player) { player.Background.EnableUserDim.Value = false; player.DimmableVideo.IgnoreUserSettings.Value = true; player.DimmableStoryboard.IgnoreUserSettings.Value = true; } } }
Change field name to "_logDir"
using System; using System.Diagnostics; using System.IO; using System.Threading; using Serilog; using Serilog.Core; namespace Titan.Logging { public class LogCreator { public static DirectoryInfo LogDirectory = new DirectoryInfo(Environment.CurrentDirectory + Path.DirectorySeparatorChar + "logs"); public static Logger Create(string name) { return new LoggerConfiguration() .WriteTo.LiterateConsole(outputTemplate: "{Timestamp:HH:mm:ss} [{Thread}] {Level:u} {Name} - {Message}{NewLine}{Exception}") .WriteTo.Async(a => a.RollingFile(Path.Combine(LogDirectory.ToString(), name + "-{Date}.log"), outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u}] {Name} @ {ThreadId} - {Message}{NewLine}{Exception}")) .MinimumLevel.Debug() // TODO: Change this to "INFO" on release. .Enrich.WithProperty("Name", name) .Enrich.WithProperty("Thread", Thread.CurrentThread.Name) .Enrich.FromLogContext() .Enrich.WithThreadId() .CreateLogger(); } public static Logger Create() { var reflectedType = new StackTrace().GetFrame(1).GetMethod().ReflectedType; return Create(reflectedType != null ? reflectedType.Name : "Titan (unknown Parent)"); } } }
using System; using System.Diagnostics; using System.IO; using System.Threading; using Serilog; using Serilog.Core; namespace Titan.Logging { public class LogCreator { private static DirectoryInfo _logDir = new DirectoryInfo(Environment.CurrentDirectory + Path.DirectorySeparatorChar + "logs"); public static Logger Create(string name) { return new LoggerConfiguration() .WriteTo.LiterateConsole(outputTemplate: "{Timestamp:HH:mm:ss} [{Thread}] {Level:u} {Name} - {Message}{NewLine}{Exception}") .WriteTo.Async(a => a.RollingFile(Path.Combine(_logDir.ToString(), name + "-{Date}.log"), outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u}] {Name} @ {ThreadId} - {Message}{NewLine}{Exception}")) .MinimumLevel.Debug() // TODO: Change this to "INFO" on release. .Enrich.WithProperty("Name", name) .Enrich.WithProperty("Thread", Thread.CurrentThread.Name) .Enrich.FromLogContext() .Enrich.WithThreadId() .CreateLogger(); } public static Logger Create() { var reflectedType = new StackTrace().GetFrame(1).GetMethod().ReflectedType; return Create(reflectedType != null ? reflectedType.Name : "Titan (unknown Parent)"); } } }
Allow using F11 to toggle fullscreen
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using osu.Framework.Input.Bindings; namespace osu.Framework.Input { internal class FrameworkActionContainer : KeyBindingContainer<FrameworkAction> { public override IEnumerable<KeyBinding> DefaultKeyBindings => new[] { new KeyBinding(new[] { InputKey.Control, InputKey.F1 }, FrameworkAction.ToggleDrawVisualiser), new KeyBinding(new[] { InputKey.Control, InputKey.F2 }, FrameworkAction.ToggleGlobalStatistics), new KeyBinding(new[] { InputKey.Control, InputKey.F11 }, FrameworkAction.CycleFrameStatistics), new KeyBinding(new[] { InputKey.Control, InputKey.F10 }, FrameworkAction.ToggleLogOverlay), new KeyBinding(new[] { InputKey.Alt, InputKey.Enter }, FrameworkAction.ToggleFullscreen), }; protected override bool Prioritised => true; } public enum FrameworkAction { CycleFrameStatistics, ToggleDrawVisualiser, ToggleGlobalStatistics, ToggleLogOverlay, ToggleFullscreen } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using osu.Framework.Input.Bindings; namespace osu.Framework.Input { internal class FrameworkActionContainer : KeyBindingContainer<FrameworkAction> { public override IEnumerable<KeyBinding> DefaultKeyBindings => new[] { new KeyBinding(new[] { InputKey.Control, InputKey.F1 }, FrameworkAction.ToggleDrawVisualiser), new KeyBinding(new[] { InputKey.Control, InputKey.F2 }, FrameworkAction.ToggleGlobalStatistics), new KeyBinding(new[] { InputKey.Control, InputKey.F11 }, FrameworkAction.CycleFrameStatistics), new KeyBinding(new[] { InputKey.Control, InputKey.F10 }, FrameworkAction.ToggleLogOverlay), new KeyBinding(new[] { InputKey.Alt, InputKey.Enter }, FrameworkAction.ToggleFullscreen), new KeyBinding(new[] { InputKey.F11 }, FrameworkAction.ToggleFullscreen) }; protected override bool Prioritised => true; } public enum FrameworkAction { CycleFrameStatistics, ToggleDrawVisualiser, ToggleGlobalStatistics, ToggleLogOverlay, ToggleFullscreen } }
Update IUrlModifier to work on any thread by not using HttpContext.Current in the Modify method.
using System; using System.Web; using Cassette; namespace Precompiled { /// <summary> /// An example implementation of Cassette.IUrlModifier. /// /// </summary> public class CdnUrlModifier : IUrlModifier { public string Modify(string url) { // The url passed to modify will be a relative path. // For example: "_cassette/scriptbundle/scripts/app_abc123" // We can return a modified URL. For example, prefixing something like "http://mycdn.com/myapp/" var prefix = GetCdnUrlPrefix(); return prefix + url; } static string GetCdnUrlPrefix() { // We don't have a CDN for this sample. // So just build an absolute URL instead. var host = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority); var prefix = host + HttpRuntime.AppDomainAppVirtualPath.TrimEnd('/') + "/"; return prefix; } } }
using System; using System.Web; using Cassette; namespace Precompiled { /// <summary> /// An example implementation of Cassette.IUrlModifier. /// </summary> public class CdnUrlModifier : IUrlModifier { readonly string prefix; public CdnUrlModifier(HttpContextBase httpContext) { // We don't have a CDN for this sample. // So just build an absolute URL instead. var host = httpContext.Request.Url.GetLeftPart(UriPartial.Authority); prefix = host + httpContext.Request.ApplicationPath.TrimEnd('/') + "/"; } public string Modify(string url) { // The url passed to modify will be a relative path. // For example: "_cassette/scriptbundle/scripts/app_abc123" // We can return a modified URL. For example, prefixing something like "http://mycdn.com/myapp/" return prefix + url; } } }
Refactor in pagination view to use tag helpers
@model Microsoft.eShopOnContainers.WebMVC.ViewModels.Pagination.PaginationInfo <div class="esh-pager"> <div class="container"> <article class="esh-pager-wrapper row"> <nav> <a class="esh-pager-item esh-pager-item--navigable @Model.Previous" id="Previous" href="@Url.Action("Index","Catalog", new { page = Model.ActualPage -1 })" aria-label="Previous"> Previous </a> <span class="esh-pager-item"> Showing @Html.DisplayFor(modelItem => modelItem.ItemsPerPage) of @Html.DisplayFor(modelItem => modelItem.TotalItems) products - Page @(Model.ActualPage + 1) - @Html.DisplayFor(x => x.TotalPages) </span> <a class="esh-pager-item esh-pager-item--navigable @Model.Next" id="Next" href="@Url.Action("Index","Catalog", new { page = Model.ActualPage + 1 })" aria-label="Next"> Next </a> </nav> </article> </div> </div>
@model Microsoft.eShopOnContainers.WebMVC.ViewModels.Pagination.PaginationInfo <div class="esh-pager"> <div class="container"> <article class="esh-pager-wrapper row"> <nav> <a class="esh-pager-item esh-pager-item--navigable @Model.Previous" id="Previous" asp-controller="Catalog" asp-action="Index" asp-route-page="@(Model.ActualPage -1)" aria-label="Previous"> Previous </a> <span class="esh-pager-item"> Showing @Model.ItemsPerPage of @Model.TotalItems products - Page @(Model.ActualPage + 1) - @Model.TotalPages </span> <a class="esh-pager-item esh-pager-item--navigable @Model.Next" id="Next" asp-controller="Catalog" asp-action="Index" asp-route-page="@(Model.ActualPage + 1)" aria-label="Next"> Next </a> </nav> </article> </div> </div>
Fix poorly named test file.
using System.Collections.Generic; using System.IO; using System.Linq; using Duplicati.Library.Main; using NUnit.Framework; namespace Duplicati.UnitTest { [TestFixture] public class RepairHandlerTests : BasicSetupHelper { public override void SetUp() { base.SetUp(); File.WriteAllBytes(Path.Combine(this.DATAFOLDER, "emptyFile"), new byte[] {0}); } [Test] [Category("RepairHandler")] [TestCase("true")] [TestCase("false")] public void RepairMissingIndexFiles(string noEncryption) { Dictionary<string, string> options = new Dictionary<string, string>(this.TestOptions) {["no-encryption"] = noEncryption}; using (Controller c = new Controller("file://" + this.TARGETFOLDER, options, null)) { c.Backup(new[] {this.DATAFOLDER}); } string[] dindexFiles = Directory.EnumerateFiles(this.TARGETFOLDER, "*dindex*").ToArray(); Assert.Greater(dindexFiles.Length, 0); foreach (string f in dindexFiles) { File.Delete(f); } using (Controller c = new Controller("file://" + this.TARGETFOLDER, options, null)) { c.Repair(); } foreach (string file in dindexFiles) { Assert.IsTrue(File.Exists(Path.Combine(this.TARGETFOLDER, file))); } } } }
using System.Collections.Generic; using System.IO; using System.Linq; using Duplicati.Library.Main; using NUnit.Framework; namespace Duplicati.UnitTest { [TestFixture] public class RepairHandlerTests : BasicSetupHelper { public override void SetUp() { base.SetUp(); File.WriteAllBytes(Path.Combine(this.DATAFOLDER, "file"), new byte[] {0}); } [Test] [Category("RepairHandler")] [TestCase("true")] [TestCase("false")] public void RepairMissingIndexFiles(string noEncryption) { Dictionary<string, string> options = new Dictionary<string, string>(this.TestOptions) {["no-encryption"] = noEncryption}; using (Controller c = new Controller("file://" + this.TARGETFOLDER, options, null)) { c.Backup(new[] {this.DATAFOLDER}); } string[] dindexFiles = Directory.EnumerateFiles(this.TARGETFOLDER, "*dindex*").ToArray(); Assert.Greater(dindexFiles.Length, 0); foreach (string f in dindexFiles) { File.Delete(f); } using (Controller c = new Controller("file://" + this.TARGETFOLDER, options, null)) { c.Repair(); } foreach (string file in dindexFiles) { Assert.IsTrue(File.Exists(Path.Combine(this.TARGETFOLDER, file))); } } } }
Use CreateChild to override child creation
// 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 Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using System; using System.Collections.Generic; namespace Core2D.Avalonia.Presenters { public class CachedContentPresenter : ContentPresenter { private static IDictionary<Type, Func<Control>> _factory = new Dictionary<Type, Func<Control>>(); private readonly IDictionary<Type, Control> _cache = new Dictionary<Type, Control>(); public static void Register(Type type, Func<Control> create) => _factory[type] = create; public CachedContentPresenter() { this.GetObservable(DataContextProperty).Subscribe((value) => SetContent(value)); } public Control GetControl(Type type) { Control control; _cache.TryGetValue(type, out control); if (control == null) { Func<Control> createInstance; _factory.TryGetValue(type, out createInstance); control = createInstance?.Invoke(); if (control != null) { _cache[type] = control; } else { throw new Exception($"Can not find factory method for type: {type}"); } } return control; } public void SetContent(object value) { Control control = null; if (value != null) { control = GetControl(value.GetType()); } this.Content = control; } } }
// 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 Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using System; using System.Collections.Generic; namespace Core2D.Avalonia.Presenters { public class CachedContentPresenter : ContentPresenter { private static IDictionary<Type, Func<Control>> _factory = new Dictionary<Type, Func<Control>>(); private readonly IDictionary<Type, Control> _cache = new Dictionary<Type, Control>(); public static void Register(Type type, Func<Control> create) => _factory[type] = create; public CachedContentPresenter() { this.GetObservable(DataContextProperty).Subscribe((value) => Content = value); } protected override IControl CreateChild() { var content = Content; if (content != null) { Type type = content.GetType(); Control control; _cache.TryGetValue(type, out control); if (control == null) { Func<Control> createInstance; _factory.TryGetValue(type, out createInstance); control = createInstance?.Invoke(); if (control != null) { _cache[type] = control; } else { throw new Exception($"Can not find factory method for type: {type}"); } } return control; } return base.CreateChild(); } } }
Add todo about shifting where messages are to be resolved
using System; using System.Collections.Generic; using Microsoft.Framework.DependencyInjection; using System.Threading.Tasks; namespace Glimpse.Web { public class MasterRequestRuntime { private readonly IDiscoverableCollection<IRequestRuntime> _requestRuntimes; private readonly IDiscoverableCollection<IRequestHandler> _requestHandlers; public MasterRequestRuntime(IServiceProvider serviceProvider) { _requestRuntimes = serviceProvider.GetService<IDiscoverableCollection<IRequestRuntime>>(); _requestRuntimes.Discover(); _requestHandlers = serviceProvider.GetService<IDiscoverableCollection<IRequestHandler>>(); _requestHandlers.Discover(); } public async Task Begin(IHttpContext context) { foreach (var requestRuntime in _requestRuntimes) { await requestRuntime.Begin(context); } } public bool TryGetHandle(IHttpContext context, out IRequestHandler handeler) { foreach (var requestHandler in _requestHandlers) { if (requestHandler.WillHandle(context)) { handeler = requestHandler; return true; } } handeler = null; return false; } public async Task End(IHttpContext context) { foreach (var requestRuntime in _requestRuntimes) { await requestRuntime.End(context); } } } }
using System; using System.Collections.Generic; using Microsoft.Framework.DependencyInjection; using System.Threading.Tasks; namespace Glimpse.Web { public class MasterRequestRuntime { private readonly IDiscoverableCollection<IRequestRuntime> _requestRuntimes; private readonly IDiscoverableCollection<IRequestHandler> _requestHandlers; public MasterRequestRuntime(IServiceProvider serviceProvider) { // TODO: Switch these over to being injected and doing the serviceProvider resolve in the middleware _requestRuntimes = serviceProvider.GetService<IDiscoverableCollection<IRequestRuntime>>(); _requestRuntimes.Discover(); _requestHandlers = serviceProvider.GetService<IDiscoverableCollection<IRequestHandler>>(); _requestHandlers.Discover(); } public async Task Begin(IHttpContext context) { foreach (var requestRuntime in _requestRuntimes) { await requestRuntime.Begin(context); } } public bool TryGetHandle(IHttpContext context, out IRequestHandler handeler) { foreach (var requestHandler in _requestHandlers) { if (requestHandler.WillHandle(context)) { handeler = requestHandler; return true; } } handeler = null; return false; } public async Task End(IHttpContext context) { foreach (var requestRuntime in _requestRuntimes) { await requestRuntime.End(context); } } } }
Change version number to auto-increment
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SimpleZipCode")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SimpleZipCode")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f5a869d6-0f69-4c26-bee2-917e3da08061")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.2")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SimpleZipCode")] [assembly: AssemblyDescription("")] [assembly: AssemblyProduct("SimpleZipCode")] [assembly: AssemblyCopyright("Copyright © 2017")] // 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("f5a869d6-0f69-4c26-bee2-917e3da08061")] // 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.*")]
Remove explicit parameters from the reservation query string
using System; using System.Threading.Tasks; using SFA.DAS.Reservations.Api.Types.Configuration; namespace SFA.DAS.Reservations.Api.Types { public class ReservationHelper : IReservationHelper { private readonly ReservationsClientApiConfiguration _config; public ReservationHelper(ReservationsClientApiConfiguration config) { _config = config; } public Task<ReservationValidationResult> ValidateReservation(ValidationReservationMessage request, Func<string, object, Task<ReservationValidationResult>> call) { var effectiveApiBaseUrl = _config.EffectiveApiBaseUrl.TrimEnd(new[] {'/'}); var url = $"{effectiveApiBaseUrl}/api/reservations/validate/{request.ReservationId}?courseCode={request.CourseCode}&startDate={request.StartDate}"; var data = new { StartDate = request.StartDate.ToString("yyyy-MM-dd"), request.CourseCode }; return call(url, data); } } }
using System; using System.Threading.Tasks; using SFA.DAS.Reservations.Api.Types.Configuration; namespace SFA.DAS.Reservations.Api.Types { public class ReservationHelper : IReservationHelper { private readonly ReservationsClientApiConfiguration _config; public ReservationHelper(ReservationsClientApiConfiguration config) { _config = config; } public Task<ReservationValidationResult> ValidateReservation(ValidationReservationMessage request, Func<string, object, Task<ReservationValidationResult>> call) { var effectiveApiBaseUrl = _config.EffectiveApiBaseUrl.TrimEnd(new[] {'/'}); var url = $"{effectiveApiBaseUrl}/api/reservations/validate/{request.ReservationId}"; var data = new { StartDate = request.StartDate.ToString("yyyy-MM-dd"), request.CourseCode }; return call(url, data); } } }
Change Assembly Version to 2.3.0.0
// // Copyright (c) Microsoft. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Reflection; using System.Resources; [assembly: AssemblyTitle("Windows Azure Compute Management Library")] [assembly: AssemblyDescription("Provides management functionality for Windows Azure Virtual Machines and Hosted Services.")] [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.2.1.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Windows Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")]
// // Copyright (c) Microsoft. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Reflection; using System.Resources; [assembly: AssemblyTitle("Windows Azure Compute Management Library")] [assembly: AssemblyDescription("Provides management functionality for Windows Azure Virtual Machines and Hosted Services.")] [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.3.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Windows Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")]
Fix inability to join a multiplayer room which has no password
// 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.Net.Http; using osu.Framework.IO.Network; using osu.Game.Online.API; namespace osu.Game.Online.Rooms { public class JoinRoomRequest : APIRequest { public readonly Room Room; public readonly string Password; public JoinRoomRequest(Room room, string password) { Room = room; Password = password; } protected override WebRequest CreateWebRequest() { var req = base.CreateWebRequest(); req.Method = HttpMethod.Put; req.AddParameter(@"password", Password, RequestParameterType.Query); return req; } protected override string Target => $@"rooms/{Room.RoomID.Value}/users/{User.Id}"; } }
// 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.Net.Http; using osu.Framework.IO.Network; using osu.Game.Online.API; namespace osu.Game.Online.Rooms { public class JoinRoomRequest : APIRequest { public readonly Room Room; public readonly string Password; public JoinRoomRequest(Room room, string password) { Room = room; Password = password; } protected override WebRequest CreateWebRequest() { var req = base.CreateWebRequest(); req.Method = HttpMethod.Put; if (!string.IsNullOrEmpty(Password)) req.AddParameter(@"password", Password, RequestParameterType.Query); return req; } protected override string Target => $@"rooms/{Room.RoomID.Value}/users/{User.Id}"; } }
Load customers from the database.
using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using Vidly.Models; namespace Vidly.Controllers { public class CustomersController : Controller { public ActionResult Index() { var customers = GetCustomers(); return View(customers); } //[Route("Customers/Details/{id}")] public ActionResult Details(int id) { var customer = GetCustomers().SingleOrDefault(c => c.Id == id); if (customer == null) return HttpNotFound(); return View(customer); } private IEnumerable<Customer> GetCustomers() { return new List<Customer> { new Customer() {Id = 1, Name = "John Smith"}, new Customer() {Id = 2, Name = "Mary Williams"} }; } } }
using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using Vidly.Models; namespace Vidly.Controllers { public class CustomersController : Controller { private ApplicationDbContext _context; public CustomersController() { _context = new ApplicationDbContext(); } protected override void Dispose(bool disposing) { _context.Dispose(); } public ActionResult Index() { var customers = _context.Customers.ToList(); return View(customers); } public ActionResult Details(int id) { var customer = _context.Customers.SingleOrDefault(c => c.Id == id); if (customer == null) return HttpNotFound(); return View(customer); } } }
Update Readme for FastSerialization to fix a typo
// Copyright (c) Microsoft Corporation. All rights reserved. // Welcome to the Utilities code base. This _README.cs file is your table of contents. // // You will notice that the code is littered with code: qualifiers. If you install the 'hyperAddin' for // Visual Studio, these qualifiers turn into hyperlinks that allow easy cross references. The hyperAddin is // available on http://www.codeplex.com/hyperAddin // // ------------------------------------------------------------------------------------- // Overview of files // // * file:GrowableArray.cs - holds a VERY LEAN implentation of a variable sized array (it is // striped down, fast version of List<T>. There is never a reason to implement this logic by hand. // // * file:StreamUtilities.cs holds code:StreamUtilities which knows how to copy a stream. // // * file:FastSerialization.cs - holds defintions for code:FastSerialization.Serializer and // code:FastSerialization.Deserializer which are general purpose, very fast and efficient ways of dumping // an object graph to a stream (typically a file). It is used as a very convinient, versionable, // efficient and extensible file format. // // * file:StreamReaderWriter.cs - holds concreate subclasses of // code:FastSerialization.IStreamReader and code:FastSerialization.IStreamWriter, which allow you to // write files a byte, chareter, int, or string at a time efficiently.
// Copyright (c) Microsoft Corporation. All rights reserved. // Welcome to the Utilities code base. This _README.cs file is your table of contents. // // You will notice that the code is littered with code: qualifiers. If you install the 'hyperAddin' for // Visual Studio, these qualifiers turn into hyperlinks that allow easy cross references. The hyperAddin is // available on http://www.codeplex.com/hyperAddin // // ------------------------------------------------------------------------------------- // Overview of files // // * file:GrowableArray.cs - holds a VERY LEAN implentation of a variable sized array (it is // striped down, fast version of List<T>. There is never a reason to implement this logic by hand. // // * file:StreamUtilities.cs holds code:StreamUtilities which knows how to copy a stream. // // * file:FastSerialization.cs - holds defintions for code:FastSerialization.Serializer and // code:FastSerialization.Deserializer which are general purpose, very fast and efficient ways of dumping // an object graph to a stream (typically a file). It is used as a very convenient, versionable, // efficient and extensible file format. // // * file:StreamReaderWriter.cs - holds concreate subclasses of // code:FastSerialization.IStreamReader and code:FastSerialization.IStreamWriter, which allow you to // write files a byte, chareter, int, or string at a time efficiently.
Remove unlimited timing points in difficulty calculation
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using osu.Game.Beatmaps.ControlPoints; namespace osu.Game.Beatmaps.Formats { /// <summary> /// A <see cref="LegacyBeatmapDecoder"/> built for difficulty calculation of legacy <see cref="Beatmap"/>s /// <remarks> /// To use this, the decoder must be registered by the application through <see cref="LegacyDifficultyCalculatorBeatmapDecoder.Register"/>. /// Doing so will override any existing <see cref="Beatmap"/> decoders. /// </remarks> /// </summary> public class LegacyDifficultyCalculatorBeatmapDecoder : LegacyBeatmapDecoder { public LegacyDifficultyCalculatorBeatmapDecoder(int version = LATEST_VERSION) : base(version) { ApplyOffsets = false; } public new static void Register() { AddDecoder<Beatmap>(@"osu file format v", m => new LegacyDifficultyCalculatorBeatmapDecoder(int.Parse(m.Split('v').Last()))); SetFallbackDecoder<Beatmap>(() => new LegacyDifficultyCalculatorBeatmapDecoder()); } protected override TimingControlPoint CreateTimingControlPoint() => new LegacyDifficultyCalculatorTimingControlPoint(); private class LegacyDifficultyCalculatorTimingControlPoint : TimingControlPoint { public LegacyDifficultyCalculatorTimingControlPoint() { BeatLengthBindable.MinValue = double.MinValue; BeatLengthBindable.MaxValue = double.MaxValue; } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using osu.Game.Beatmaps.ControlPoints; namespace osu.Game.Beatmaps.Formats { /// <summary> /// A <see cref="LegacyBeatmapDecoder"/> built for difficulty calculation of legacy <see cref="Beatmap"/>s /// <remarks> /// To use this, the decoder must be registered by the application through <see cref="LegacyDifficultyCalculatorBeatmapDecoder.Register"/>. /// Doing so will override any existing <see cref="Beatmap"/> decoders. /// </remarks> /// </summary> public class LegacyDifficultyCalculatorBeatmapDecoder : LegacyBeatmapDecoder { public LegacyDifficultyCalculatorBeatmapDecoder(int version = LATEST_VERSION) : base(version) { ApplyOffsets = false; } public new static void Register() { AddDecoder<Beatmap>(@"osu file format v", m => new LegacyDifficultyCalculatorBeatmapDecoder(int.Parse(m.Split('v').Last()))); SetFallbackDecoder<Beatmap>(() => new LegacyDifficultyCalculatorBeatmapDecoder()); } } }
Add placeholder support for OnUpdate
using System; using System.Collections.Generic; using System.Linq; using Duality; using PythonScripting.Resources; using IronPython.Hosting; using Microsoft.Scripting.Hosting; using IronPython.Compiler; namespace PythonScripting { public class ScriptExecutor : Component, ICmpInitializable { public ContentRef<PythonScript> Script { get; set; } public void OnInit(InitContext context) { if (context == InitContext.Activate) { } } public void OnShutdown(ShutdownContext context) { if (context == ShutdownContext.Deactivate) { GameObj.DisposeLater(); } } } }
using System; using System.Collections.Generic; using System.Linq; using Duality; using PythonScripting.Resources; using IronPython.Hosting; using IronPython.Runtime; using IronPython.Compiler; using Microsoft.Scripting; using Microsoft.Scripting.Hosting; namespace PythonScripting { public class ScriptExecutor : Component, ICmpInitializable, ICmpUpdatable { public ContentRef<PythonScript> Script { get; set; } public void OnInit(InitContext context) { if (context == InitContext.Activate) { } } public void OnUpdate() { } public void OnShutdown(ShutdownContext context) { if (context == ShutdownContext.Deactivate) { GameObj.DisposeLater(); } } } }
Change movement, player folow mouse
using UnityEngine; using System.Collections; public class PlayerMovement : MonoBehaviour { public float speed = 6f; Vector3 movement; Rigidbody rb; float cameraRayLength = 100; int floorMask; void Awake() { floorMask = LayerMask.GetMask ("Floor"); rb = GetComponent<Rigidbody> (); } void FixedUpdate() { float moveHorizontal = Input.GetAxisRaw ("Horizontal"); float moveVertical = Input.GetAxisRaw ("Vertical"); Move (moveHorizontal, moveVertical); Turning (); } void Move(float horizontal, float vertical) { movement.Set (horizontal, 0f, vertical); movement = movement * speed * Time.deltaTime; rb.MovePosition (transform.position + movement); } void Turning() { Ray cameraRay = Camera.main.ScreenPointToRay (Input.mousePosition); RaycastHit floorHit; if (Physics.Raycast (cameraRay, out floorHit, cameraRayLength, floorMask)) { Vector3 playerToMouse = floorHit.point - transform.position; playerToMouse.y = 0f; Quaternion newRotation = Quaternion.LookRotation (playerToMouse); rb.MoveRotation (newRotation); } } }
using UnityEngine; using System.Collections; public class PlayerMovement : MonoBehaviour { public float speed = 6f; public float jumpSpeed = 8.0F; public float gravity = 20.0F; private Vector3 moveDirection = Vector3.zero; private CharacterController cc; private float cameraRayLength = 100; private int floorMask; void Awake() { floorMask = LayerMask.GetMask ("Floor"); cc = GetComponent<CharacterController> (); } void FixedUpdate() { float moveHorizontal = Input.GetAxisRaw ("Horizontal"); float moveVertical = Input.GetAxisRaw ("Vertical"); Move (moveHorizontal, moveVertical); Turning (); } void Move(float horizontal, float vertical) { if (cc.isGrounded) { moveDirection = new Vector3(horizontal, 0, vertical); moveDirection = transform.TransformDirection(moveDirection); moveDirection *= speed; if (Input.GetButton ("Jump")) { moveDirection.y = jumpSpeed; } } moveDirection.y -= gravity * Time.deltaTime; cc.Move(moveDirection * Time.deltaTime); } void Turning() { Ray cameraRay = Camera.main.ScreenPointToRay (Input.mousePosition); RaycastHit floorHit; if (Physics.Raycast (cameraRay, out floorHit, cameraRayLength, floorMask)) { Vector3 playerToMouse = floorHit.point - transform.position; playerToMouse.y = 0f; Quaternion newRotation = Quaternion.LookRotation (playerToMouse); transform.rotation = newRotation; } } }
Fix bad casing for readme tests
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using LegoSharp; using System.Linq; using System.Reflection; using System.IO.MemoryMappedFiles; namespace LegoSharpTest { [TestClass] public class ReadmeTests { [TestMethod] public async Task PickABrickExample() { LegoGraphClient graphClient = new LegoGraphClient(); await graphClient.authenticateAsync(); PickABrickQuery query = new PickABrickQuery(); query.addFilter(new BrickColorFilter() .addValue(BrickColor.Black) ); query.query = "wheel"; PickABrickQueryResult result = await graphClient.pickABrick(query); foreach (Brick brick in result.elements) { // do something with each brick } } [TestMethod] public async Task ProductSearchExample() { LegoGraphClient graphClient = new LegoGraphClient(); await graphClient.authenticateAsync(); ProductSearchQuery query = new ProductSearchQuery(); query.addFilter(new ProductCategoryFilter() .addValue(ProductCategory.Sets) ); query.query = "train"; await graphClient.productSearch(query); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using LegoSharp; using System.Linq; using System.Reflection; using System.IO.MemoryMappedFiles; namespace LegoSharpTest { [TestClass] public class ReadmeTests { [TestMethod] public async Task pickABrickExample() { LegoGraphClient graphClient = new LegoGraphClient(); await graphClient.authenticateAsync(); PickABrickQuery query = new PickABrickQuery(); query.addFilter(new BrickColorFilter() .addValue(BrickColor.Black) ); query.query = "wheel"; PickABrickQueryResult result = await graphClient.pickABrick(query); foreach (Brick brick in result.elements) { // do something with each brick } } [TestMethod] public async Task productSearchExample() { LegoGraphClient graphClient = new LegoGraphClient(); await graphClient.authenticateAsync(); ProductSearchQuery query = new ProductSearchQuery(); query.addFilter(new ProductCategoryFilter() .addValue(ProductCategory.Sets) ); query.query = "train"; await graphClient.productSearch(query); } } }
Fix Skeletron summoning message decoding.
using System; namespace Terraria_Server.Messages { public class SummonSkeletronMessage : IMessage { public Packet GetPacket() { return Packet.SUMMON_SKELETRON; } public void Process(int start, int length, int num, int whoAmI, byte[] readBuffer, byte bufferData) { byte action = readBuffer[num]; if (action == 1) { NPC.SpawnSkeletron(); } else if (action == 2) { NetMessage.SendData (51, -1, whoAmI, "", action, (float)readBuffer[num + 1], 0f, 0f, 0); } } } }
using System; namespace Terraria_Server.Messages { public class SummonSkeletronMessage : IMessage { public Packet GetPacket() { return Packet.SUMMON_SKELETRON; } public void Process(int start, int length, int num, int whoAmI, byte[] readBuffer, byte bufferData) { int player = readBuffer[num++]; //TODO: maybe check for forgery byte action = readBuffer[num]; if (action == 1) { NPC.SpawnSkeletron(); } else if (action == 2) { NetMessage.SendData (51, -1, whoAmI, "", player, action, 0f, 0f, 0); } } } }
Use a minimum fade length for clamping rather than zero
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Audio.Track; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Graphics.Containers; using osuTK.Graphics; namespace osu.Game.Rulesets.Osu.Skinning.Default { public class KiaiFlash : BeatSyncedContainer { private const double fade_length = 80; private const float flash_opacity = 0.25f; public KiaiFlash() { EarlyActivationMilliseconds = 80; Blending = BlendingParameters.Additive; Child = new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.White, Alpha = 0f, }; } protected override void OnNewBeat(int beatIndex, TimingControlPoint timingPoint, EffectControlPoint effectPoint, ChannelAmplitudes amplitudes) { if (!effectPoint.KiaiMode) return; Child .FadeTo(flash_opacity, EarlyActivationMilliseconds, Easing.OutQuint) .Then() .FadeOut(Math.Max(0, timingPoint.BeatLength - fade_length), Easing.OutSine); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Audio.Track; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Graphics.Containers; using osuTK.Graphics; namespace osu.Game.Rulesets.Osu.Skinning.Default { public class KiaiFlash : BeatSyncedContainer { private const double fade_length = 80; private const float flash_opacity = 0.25f; public KiaiFlash() { EarlyActivationMilliseconds = 80; Blending = BlendingParameters.Additive; Child = new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.White, Alpha = 0f, }; } protected override void OnNewBeat(int beatIndex, TimingControlPoint timingPoint, EffectControlPoint effectPoint, ChannelAmplitudes amplitudes) { if (!effectPoint.KiaiMode) return; Child .FadeTo(flash_opacity, EarlyActivationMilliseconds, Easing.OutQuint) .Then() .FadeOut(Math.Max(fade_length, timingPoint.BeatLength - fade_length), Easing.OutSine); } } }
Add action "Works If Muted", "Works If Foreground Is Fullscreen" options
using System; using System.ComponentModel; using System.Windows; using DesktopWidgets.Classes; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; namespace DesktopWidgets.Actions { public abstract class ActionBase { [PropertyOrder(0)] [DisplayName("Delay")] public TimeSpan Delay { get; set; } = TimeSpan.FromSeconds(0); [PropertyOrder(1)] [DisplayName("Show Errors")] public bool ShowErrors { get; set; } = false; public void Execute() { DelayedAction.RunAction((int) Delay.TotalMilliseconds, () => { try { ExecuteAction(); } catch (Exception ex) { if (ShowErrors) Popup.ShowAsync($"{GetType().Name} failed to execute.\n\n{ex.Message}", image: MessageBoxImage.Error); } }); } protected virtual void ExecuteAction() { } } }
using System; using System.ComponentModel; using System.Windows; using DesktopWidgets.Classes; using DesktopWidgets.Helpers; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; namespace DesktopWidgets.Actions { public abstract class ActionBase { [PropertyOrder(0)] [DisplayName("Delay")] public TimeSpan Delay { get; set; } = TimeSpan.FromSeconds(0); [PropertyOrder(1)] [DisplayName("Works If Foreground Is Fullscreen")] public bool WorksIfForegroundIsFullscreen { get; set; } [PropertyOrder(2)] [DisplayName("Works If Muted")] public bool WorksIfMuted { get; set; } [PropertyOrder(3)] [DisplayName("Show Errors")] public bool ShowErrors { get; set; } = false; public void Execute() { if (!WorksIfMuted && App.IsMuted || (!WorksIfForegroundIsFullscreen && FullScreenHelper.DoesAnyMonitorHaveFullscreenApp())) return; DelayedAction.RunAction((int) Delay.TotalMilliseconds, () => { try { ExecuteAction(); } catch (Exception ex) { if (ShowErrors) Popup.ShowAsync($"{GetType().Name} failed to execute.\n\n{ex.Message}", image: MessageBoxImage.Error); } }); } protected virtual void ExecuteAction() { } } }
Revert "Fixed compile error in shell view"
 using Xamarin.Forms; namespace AppShell.Mobile.Views { [ContentProperty("ShellContent")] public partial class ShellView : ContentView { public static readonly BindableProperty ShellContentProperty = BindableProperty.Create<ShellView, View>(d => d.ShellContent, null, propertyChanged: ShellContentPropertyChanged); public static readonly BindableProperty HasNavigationBarProperty = BindableProperty.Create<ShellView, bool>(x => x.HasNavigationBar, true, propertyChanged: OnHasNavigationBarChanged); public View ShellContent { get { return (View)GetValue(ShellContentProperty); } set { SetValue(ShellContentProperty, value); } } public bool HasNavigationBar { get { return (bool)GetValue(HasNavigationBarProperty); } set { SetValue(HasNavigationBarProperty, value); } } public static void ShellContentPropertyChanged(BindableObject d, View oldValue, View newValue) { ShellView shellView = d as ShellView; shellView.ShellContent = newValue; } private static void OnHasNavigationBarChanged(BindableObject d, bool oldValue, bool newValue) { ShellView shellView = d as ShellView; NavigationPage.SetHasNavigationBar(shellView, newValue); if (!newValue) shellView.Padding = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0); } public ShellView() { InitializeComponent(); SetBinding(HasNavigationBarProperty, new Binding("HasNavigationBar")); } } }
 using Xamarin.Forms; namespace AppShell.Mobile.Views { [ContentProperty("ShellContent")] public partial class ShellView : ContentView { public static readonly BindableProperty ShellContentProperty = BindableProperty.Create<ShellView, View>(d => d.ShellContent, null, propertyChanged: ShellContentPropertyChanged); public static readonly BindableProperty HasNavigationBarProperty = BindableProperty.Create<ShellView, bool>(x => x.HasNavigationBar, true, propertyChanged: OnHasNavigationBarChanged); public View ShellContent { get { return (View)GetValue(ShellContentProperty); } set { SetValue(ShellContentProperty, value); } } public bool HasNavigationBar { get { return (bool)GetValue(HasNavigationBarProperty); } set { SetValue(HasNavigationBarProperty, value); } } public static void ShellContentPropertyChanged(BindableObject d, View oldValue, View newValue) { ShellView shellView = d as ShellView; shellView.ShellContentView.Content = newValue; } private static void OnHasNavigationBarChanged(BindableObject d, bool oldValue, bool newValue) { ShellView shellView = d as ShellView; NavigationPage.SetHasNavigationBar(shellView, newValue); if (!newValue) shellView.Padding = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0); } public ShellView() { InitializeComponent(); SetBinding(HasNavigationBarProperty, new Binding("HasNavigationBar")); } } }
Copy deflate stream to temporary memory stream.
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; namespace Meowtrix.osuAMT.Training.DataGenerator { class OszArchive : Archive, IDisposable { public ZipArchive archive; private FileInfo fileinfo; public OszArchive(FileInfo file) { fileinfo = file; string name = file.Name; Name = name.EndsWith(".osz") ? name.Substring(0, name.Length - 4) : name; } public override string Name { get; } public void Dispose() => archive.Dispose(); private void EnsureArchiveOpened() { if (archive == null) archive = new ZipArchive(fileinfo.OpenRead(), ZipArchiveMode.Read, false); } public override Stream OpenFile(string filename) { EnsureArchiveOpened(); return archive.GetEntry(filename).Open(); } public override IEnumerable<Stream> OpenOsuFiles() { EnsureArchiveOpened(); return archive.Entries.Where(x => x.Name.EndsWith(".osu")).Select(e => e.Open()); } } }
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; namespace Meowtrix.osuAMT.Training.DataGenerator { class OszArchive : Archive, IDisposable { public ZipArchive archive; private FileInfo fileinfo; public OszArchive(FileInfo file) { fileinfo = file; string name = file.Name; Name = name.EndsWith(".osz") ? name.Substring(0, name.Length - 4) : name; } public override string Name { get; } public void Dispose() => archive.Dispose(); private void EnsureArchiveOpened() { if (archive == null) archive = new ZipArchive(fileinfo.OpenRead(), ZipArchiveMode.Read, false); } public override Stream OpenFile(string filename) { EnsureArchiveOpened(); var temp = new MemoryStream(); using (var deflate = archive.GetEntry(filename).Open()) { deflate.CopyTo(temp); temp.Seek(0, SeekOrigin.Begin); return temp; } } public override IEnumerable<Stream> OpenOsuFiles() { EnsureArchiveOpened(); return archive.Entries.Where(x => x.Name.EndsWith(".osu")).Select(e => e.Open()); } } }
Remove reference to settings section in routePath (so we can move the tree in theory)
using System.Net.Http.Formatting; using System.Web.Http.ModelBinding; using Umbraco.Core; using Umbraco.Web.Models.Trees; using Umbraco.Web.Mvc; using Umbraco.Web.Trees; using Umbraco.Web.WebApi.Filters; namespace uSync8.BackOffice.Controllers.Trees { [Tree(Constants.Applications.Settings, uSync.Trees.uSync, TreeGroup = uSync.Trees.Group, TreeTitle = uSync.Name, SortOrder = 35)] [PluginController(uSync.Name)] public class uSyncTreeController : TreeController { protected override TreeNode CreateRootNode(FormDataCollection queryStrings) { var root = base.CreateRootNode(queryStrings); root.RoutePath = $"{Constants.Applications.Settings}/{uSync.Trees.uSync}/dashboard"; root.Icon = "icon-infinity"; root.HasChildren = false; root.MenuUrl = null; return root; } protected override MenuItemCollection GetMenuForNode(string id, [ModelBinder(typeof(HttpQueryStringModelBinder))] FormDataCollection queryStrings) { return null; } protected override TreeNodeCollection GetTreeNodes(string id, [ModelBinder(typeof(HttpQueryStringModelBinder))] FormDataCollection queryStrings) { return new TreeNodeCollection(); } } }
using System.Net.Http.Formatting; using System.Web.Http.ModelBinding; using Umbraco.Core; using Umbraco.Web.Models.Trees; using Umbraco.Web.Mvc; using Umbraco.Web.Trees; using Umbraco.Web.WebApi.Filters; namespace uSync8.BackOffice.Controllers.Trees { [Tree(Constants.Applications.Settings, uSync.Trees.uSync, TreeGroup = uSync.Trees.Group, TreeTitle = uSync.Name, SortOrder = 35)] [PluginController(uSync.Name)] public class uSyncTreeController : TreeController { protected override TreeNode CreateRootNode(FormDataCollection queryStrings) { var root = base.CreateRootNode(queryStrings); root.RoutePath = $"{this.SectionAlias}/{uSync.Trees.uSync}/dashboard"; root.Icon = "icon-infinity"; root.HasChildren = false; root.MenuUrl = null; return root; } protected override MenuItemCollection GetMenuForNode(string id, [ModelBinder(typeof(HttpQueryStringModelBinder))] FormDataCollection queryStrings) { return null; } protected override TreeNodeCollection GetTreeNodes(string id, [ModelBinder(typeof(HttpQueryStringModelBinder))] FormDataCollection queryStrings) { return new TreeNodeCollection(); } } }
Add NamedValueDictionaryDatumConverterFactory to newtonsoft converter
using RethinkDb.DatumConverters; namespace RethinkDb.Newtonsoft.Configuration { public class NewtonSerializer : AggregateDatumConverterFactory { public NewtonSerializer() : base( PrimitiveDatumConverterFactory.Instance, TupleDatumConverterFactory.Instance, AnonymousTypeDatumConverterFactory.Instance, BoundEnumDatumConverterFactory.Instance, NullableDatumConverterFactory.Instance, NewtonsoftDatumConverterFactory.Instance ) { } } }
using RethinkDb.DatumConverters; namespace RethinkDb.Newtonsoft.Configuration { public class NewtonSerializer : AggregateDatumConverterFactory { public NewtonSerializer() : base( PrimitiveDatumConverterFactory.Instance, TupleDatumConverterFactory.Instance, AnonymousTypeDatumConverterFactory.Instance, BoundEnumDatumConverterFactory.Instance, NullableDatumConverterFactory.Instance, NamedValueDictionaryDatumConverterFactory.Instance, NewtonsoftDatumConverterFactory.Instance ) { } } }
Rename some variables for consistency
using System.Collections.Generic; using HarryPotterUnity.Cards.Generic; using HarryPotterUnity.Tween; using UnityEngine; namespace HarryPotterUnity.Utils { public static class GameManager { public const int PreviewLayer = 9; public const int CardLayer = 10; public const int ValidChoiceLayer = 11; public const int IgnoreRaycastLayer = 2; public const int DeckLayer = 12; public static byte NetworkIdCounter; public static readonly List<GenericCard> AllCards = new List<GenericCard>(); public static Camera PreviewCamera; public static readonly TweenQueue TweenQueue = new TweenQueue(); public static void DisableCards(List<GenericCard> cards) { cards.ForEach(card => card.Disable()); } public static void EnableCards(List<GenericCard> cards) { cards.ForEach(card => card.Enable()); } } }
using System.Collections.Generic; using HarryPotterUnity.Cards.Generic; using HarryPotterUnity.Tween; using UnityEngine; namespace HarryPotterUnity.Utils { public static class GameManager { public const int PREVIEW_LAYER = 9; public const int CARD_LAYER = 10; public const int VALID_CHOICE_LAYER = 11; public const int IGNORE_RAYCAST_LAYER = 2; public const int DECK_LAYER = 12; public static byte _networkIdCounter; public static readonly List<GenericCard> AllCards = new List<GenericCard>(); public static Camera _previewCamera; public static readonly TweenQueue TweenQueue = new TweenQueue(); public static void DisableCards(List<GenericCard> cards) { cards.ForEach(card => card.Disable()); } public static void EnableCards(List<GenericCard> cards) { cards.ForEach(card => card.Enable()); } } }
Make the namespace uniform accross the project
using System; namespace Table { public class Table { public int Width; public int Spacing; public Table(int width, int spacing) { Width = width; Spacing = spacing; } } }
using System; namespace Hangman { public class Table { public int Width; public int Spacing; public Table(int width, int spacing) { Width = width; Spacing = spacing; } } }
Use proper library/abi for qt on linux.
using System; using Mono.VisualC.Interop; using Mono.VisualC.Interop.ABI; namespace Qt { // Will be internal; public for testing public static class Libs { public static CppLibrary QtCore = null; public static CppLibrary QtGui = null; static Libs () { string lib; CppAbi abi; if (Environment.OSVersion.Platform == PlatformID.Win32NT) { // for Windows... lib = "{0}d4.dll"; abi = new MsvcAbi (); } else { // for Mac... lib = "/Library/Frameworks/{0}.framework/Versions/Current/{0}"; abi = new ItaniumAbi (); } QtCore = new CppLibrary (string.Format(lib, "QtCore"), abi); QtGui = new CppLibrary (string.Format(lib, "QtGui"), abi); } } }
using System; using Mono.VisualC.Interop; using Mono.VisualC.Interop.ABI; namespace Qt { // Will be internal; public for testing public static class Libs { public static CppLibrary QtCore = null; public static CppLibrary QtGui = null; static Libs () { string lib; CppAbi abi; if (Environment.OSVersion.Platform == PlatformID.Unix) { lib = "{0}.so"; abi = new ItaniumAbi (); } else if (Environment.OSVersion.Platform == PlatformID.Win32NT) { // for Windows... lib = "{0}d4.dll"; abi = new MsvcAbi (); } else { // for Mac... lib = "/Library/Frameworks/{0}.framework/Versions/Current/{0}"; abi = new ItaniumAbi (); } QtCore = new CppLibrary (string.Format(lib, "QtCore"), abi); QtGui = new CppLibrary (string.Format(lib, "QtGui"), abi); } } }
Fix up some room display issues
@using RightpointLabs.ConferenceRoom.Domain @model IEnumerable<RightpointLabs.ConferenceRoom.Domain.Models.Entities.DeviceEntity> @{ var buildings = (Dictionary<string, string>)ViewBag.Buildings; var rooms = (Dictionary<string, string>)ViewBag.Rooms; } <p> @Html.ActionLink("Create New", "Create") </p> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.Id) </th> <th> @Html.DisplayNameFor(model => model.BuildingId) </th> <th> @Html.DisplayNameFor(model => model.ControlledRoomIds) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @buildings.TryGetValue(item.Id) </td> <td> @(null == item.BuildingId ? "" : buildings.TryGetValue(item.BuildingId)) </td> <td> @string.Join(", ", item.ControlledRoomIds.Select(_ => rooms.TryGetValue(_))) </td> <td> @Html.ActionLink("Edit", "Edit", new { id=item.Id }) | @Html.ActionLink("Details", "Details", new { id=item.Id }) | @Html.ActionLink("Delete", "Delete", new { id=item.Id }) </td> </tr> } </table>
@using RightpointLabs.ConferenceRoom.Domain @model IEnumerable<RightpointLabs.ConferenceRoom.Domain.Models.Entities.DeviceEntity> @{ var buildings = (Dictionary<string, string>)ViewBag.Buildings; var rooms = (Dictionary<string, string>)ViewBag.Rooms; } <p> @Html.ActionLink("Create New", "Create") </p> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.Id) </th> <th> @Html.DisplayNameFor(model => model.BuildingId) </th> <th> @Html.DisplayNameFor(model => model.ControlledRoomIds) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @item.Id </td> <td> @(null == item.BuildingId ? "" : buildings.TryGetValue(item.BuildingId)) </td> <td> @string.Join(", ", (item.ControlledRoomIds ?? new string[0]).Select(_ => rooms.TryGetValue(_))) </td> <td> @Html.ActionLink("Edit", "Edit", new { id=item.Id }) | @Html.ActionLink("Details", "Details", new { id=item.Id }) | @Html.ActionLink("Delete", "Delete", new { id=item.Id }) </td> </tr> } </table>
Return null immediately if file handle is not valid
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Media.Imaging; namespace CefSharp.Wpf.Rendering { public class InteropBitmapInfo : WpfBitmapInfo { private static readonly PixelFormat PixelFormat = PixelFormats.Bgra32; public InteropBitmap Bitmap { get; private set; } public InteropBitmapInfo() { BytesPerPixel = PixelFormat.BitsPerPixel / 8; } public override bool CreateNewBitmap { get { return Bitmap == null; } } public override void ClearBitmap() { Bitmap = null; } public override void Invalidate() { if (Bitmap != null) { Bitmap.Invalidate(); } } public override BitmapSource CreateBitmap() { var stride = Width * BytesPerPixel; if (FileMappingHandle == IntPtr.Zero) { ClearBitmap(); } else { Bitmap = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(FileMappingHandle, Width, Height, PixelFormat, stride, 0); } return Bitmap; } } }
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Media.Imaging; namespace CefSharp.Wpf.Rendering { public class InteropBitmapInfo : WpfBitmapInfo { private static readonly PixelFormat PixelFormat = PixelFormats.Bgra32; public InteropBitmap Bitmap { get; private set; } public InteropBitmapInfo() { BytesPerPixel = PixelFormat.BitsPerPixel / 8; } public override bool CreateNewBitmap { get { return Bitmap == null; } } public override void ClearBitmap() { Bitmap = null; } public override void Invalidate() { if (Bitmap != null) { Bitmap.Invalidate(); } } public override BitmapSource CreateBitmap() { var stride = Width * BytesPerPixel; // Unable to create bitmap without valid File Handle (Most likely control is being disposed) if (FileMappingHandle == IntPtr.Zero) { return null; } else { Bitmap = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(FileMappingHandle, Width, Height, PixelFormat, stride, 0); } return Bitmap; } } }
Use the lock in the factory class.
using System; using System.Reflection; namespace AdoNetProfiler { /// <summary> /// The factory to create the object of <see cref="IProfiler"/>. /// </summary> public class AdoNetProfilerFactory { // ConstructorInfo is faster than Func<IProfiler> when invoking. private static ConstructorInfo _constructor; /// <summary> /// Initialize the setting for profiling of database accessing with ADO.NET. /// </summary> /// <param name="profilerType">The type to implement <see cref="IProfiler"/>.</param> public static void Initialize(Type profilerType) { if (profilerType == null) throw new ArgumentNullException(nameof(profilerType)); if (profilerType != typeof(IProfiler)) throw new ArgumentException($"The type must be {typeof(IProfiler).FullName}.", nameof(profilerType)); var constructor = profilerType.GetConstructor(Type.EmptyTypes); if (constructor == null) throw new InvalidOperationException("There is no default constructor. The profiler must have it."); _constructor = constructor; } public static IProfiler GetProfiler() { return (IProfiler)_constructor.Invoke(null); } } }
using System; using System.Reflection; using System.Threading; namespace AdoNetProfiler { /// <summary> /// The factory to create the object of <see cref="IProfiler"/>. /// </summary> public class AdoNetProfilerFactory { // ConstructorInfo is faster than Func<IProfiler> when invoking. private static ConstructorInfo _constructor; private static bool _initialized = false; private static readonly ReaderWriterLockSlim _readerWriterLockSlim = new ReaderWriterLockSlim(); /// <summary> /// Initialize the setting for profiling of database accessing with ADO.NET. /// </summary> /// <param name="profilerType">The type to implement <see cref="IProfiler"/>.</param> public static void Initialize(Type profilerType) { if (profilerType == null) throw new ArgumentNullException(nameof(profilerType)); if (profilerType != typeof(IProfiler)) throw new ArgumentException($"The type must be {typeof(IProfiler).FullName}.", nameof(profilerType)); _readerWriterLockSlim.ExecuteWithReadLock(() => { if (_initialized) throw new InvalidOperationException("This factory class has already initialized."); var constructor = profilerType.GetConstructor(Type.EmptyTypes); if (constructor == null) throw new InvalidOperationException("There is no default constructor. The profiler must have it."); _constructor = constructor; _initialized = true; }); } public static IProfiler GetProfiler() { return _readerWriterLockSlim.ExecuteWithWriteLock(() => { if (!_initialized) throw new InvalidOperationException("This factory class has not initialized yet."); return (IProfiler)_constructor.Invoke(null); }); } } }
Move class into correct namespace.
using System; using System.Web; using System.Web.Routing; namespace Cassette { public class ModuleRequestHandler<T> : IHttpHandler where T : Module { public ModuleRequestHandler(IModuleContainer<T> moduleContainer, RequestContext requestContext) { this.moduleContainer = moduleContainer; this.requestContext = requestContext; } readonly IModuleContainer<T> moduleContainer; readonly RequestContext requestContext; public bool IsReusable { get { return true; } } public void ProcessRequest(HttpContext _) { var path = requestContext.RouteData.GetRequiredString("path"); var index = path.LastIndexOf('_'); if (index >= 0) { path = path.Substring(0, index); } var module = moduleContainer.FindModuleByPath(path); var response = requestContext.HttpContext.Response; if (module == null) { response.StatusCode = 404; } else { response.Cache.SetCacheability(HttpCacheability.Public); response.Cache.SetMaxAge(TimeSpan.FromDays(365)); response.ContentType = module.ContentType; using (var assetStream = module.Assets[0].OpenStream()) { assetStream.CopyTo(response.OutputStream); } } } } }
using System; using System.Web; using System.Web.Routing; namespace Cassette.Web { public class ModuleRequestHandler<T> : IHttpHandler where T : Module { public ModuleRequestHandler(IModuleContainer<T> moduleContainer, RequestContext requestContext) { this.moduleContainer = moduleContainer; this.requestContext = requestContext; } readonly IModuleContainer<T> moduleContainer; readonly RequestContext requestContext; public bool IsReusable { get { return true; } } public void ProcessRequest(HttpContext _) { var path = requestContext.RouteData.GetRequiredString("path"); var index = path.LastIndexOf('_'); if (index >= 0) { path = path.Substring(0, index); } var module = moduleContainer.FindModuleByPath(path); var response = requestContext.HttpContext.Response; if (module == null) { response.StatusCode = 404; } else { response.Cache.SetCacheability(HttpCacheability.Public); response.Cache.SetMaxAge(TimeSpan.FromDays(365)); response.ContentType = module.ContentType; using (var assetStream = module.Assets[0].OpenStream()) { assetStream.CopyTo(response.OutputStream); } } } } }
Load Tcl in a cross-platform way
// The code is new, but the idea is from http://wiki.tcl.tk/9563 using System; using System.Runtime.InteropServices; namespace Irule { public class TclInterp : IDisposable { [DllImport("libtcl.dylib")] protected static extern IntPtr Tcl_CreateInterp(); [DllImport("libtcl.dylib")] protected static extern int Tcl_Init(IntPtr interp); [DllImport("libtcl.dylib")] protected static extern int Tcl_Eval(IntPtr interp, string script); [DllImport("libtcl.dylib")] protected static extern IntPtr Tcl_GetStringResult(IntPtr interp); [DllImport("libtcl.dylib")] protected static extern void Tcl_DeleteInterp(IntPtr interp); [DllImport("libtcl.dylib")] protected static extern void Tcl_Finalize(); private IntPtr interp; private bool disposed; public TclInterp() { interp = Tcl_CreateInterp(); Tcl_Init(interp); disposed = false; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing && interp != IntPtr.Zero) { Tcl_DeleteInterp(interp); Tcl_Finalize(); } interp = IntPtr.Zero; disposed = true; } } public string Eval(string text) { if (disposed) { throw new ObjectDisposedException("Attempt to use disposed Tcl interpreter"); } Tcl_Eval(interp, text); var result = Tcl_GetStringResult(interp); return Marshal.PtrToStringAnsi(result); } } }
// The code is new, but the idea is from http://wiki.tcl.tk/9563 using System; using System.Runtime.InteropServices; namespace Irule { public class TclInterp : IDisposable { [DllImport("tcl8.4")] protected static extern IntPtr Tcl_CreateInterp(); [DllImport("tcl8.4")] protected static extern int Tcl_Init(IntPtr interp); [DllImport("tcl8.4")] protected static extern int Tcl_Eval(IntPtr interp, string script); [DllImport("tcl8.4")] protected static extern IntPtr Tcl_GetStringResult(IntPtr interp); [DllImport("tcl8.4")] protected static extern void Tcl_DeleteInterp(IntPtr interp); [DllImport("tcl8.4")] protected static extern void Tcl_Finalize(); private IntPtr interp; private bool disposed; public TclInterp() { interp = Tcl_CreateInterp(); Tcl_Init(interp); disposed = false; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing && interp != IntPtr.Zero) { Tcl_DeleteInterp(interp); Tcl_Finalize(); } interp = IntPtr.Zero; disposed = true; } } public string Eval(string text) { if (disposed) { throw new ObjectDisposedException("Attempt to use disposed Tcl interpreter"); } Tcl_Eval(interp, text); var result = Tcl_GetStringResult(interp); return Marshal.PtrToStringAnsi(result); } } }
Move scale operation to base constructor.
using System; using Engine.cgimin.material.simpletexture; using Engine.cgimin.object3d; using Engine.cgimin.texture; using OpenTK; namespace Mugo { class PizzaModel : ClonedObject<PizzaModelInternal>, ITunnelSegementElementModel { private static readonly SimpleTextureMaterial material = new SimpleTextureMaterial(); public float Radius => radius; public new Matrix4 Transformation { get { return base.Transformation; } set { base.Transformation = value; } } public void Draw () { material.Draw(this, internalObject.TextureId); } } internal class PizzaModelInternal : ObjLoaderObject3D { private const String objFilePath = "data/objects/Pizza.model"; private const String texturePath = "data/textures/Pizza.png"; public PizzaModelInternal () : base (objFilePath) { TextureId = TextureManager.LoadTexture (texturePath); Transformation *= Matrix4.CreateScale (0.2f); Transformation *= Matrix4.CreateRotationY (MathHelper.DegreesToRadians (90)); Transformation *= Matrix4.CreateRotationX (MathHelper.DegreesToRadians (90)); Transformation *= Matrix4.CreateTranslation (0f, 1.5f, -TunnelSegmentConfig.Depth / 2f); DefaultTransformation = Transformation; } public int TextureId { get; private set; } public Matrix4 DefaultTransformation { get; } } }
using System; using Engine.cgimin.material.simpletexture; using Engine.cgimin.object3d; using Engine.cgimin.texture; using OpenTK; namespace Mugo { class PizzaModel : ClonedObject<PizzaModelInternal>, ITunnelSegementElementModel { private static readonly SimpleTextureMaterial material = new SimpleTextureMaterial(); public float Radius => radius; public new Matrix4 Transformation { get { return base.Transformation; } set { base.Transformation = value; } } public void Draw () { material.Draw(this, internalObject.TextureId); } } internal class PizzaModelInternal : ObjLoaderObject3D { private const String objFilePath = "data/objects/Pizza.model"; private const String texturePath = "data/textures/Pizza.png"; public PizzaModelInternal () : base (objFilePath, 0.2f) { TextureId = TextureManager.LoadTexture (texturePath); Transformation *= Matrix4.CreateRotationY (MathHelper.DegreesToRadians (90)); Transformation *= Matrix4.CreateRotationX (MathHelper.DegreesToRadians (90)); Transformation *= Matrix4.CreateTranslation (0f, 1.5f, -TunnelSegmentConfig.Depth / 2f); DefaultTransformation = Transformation; } public int TextureId { get; private set; } public Matrix4 DefaultTransformation { get; } } }
Update to Problem 9. Sum of n Numbers
/*Problem 9. Sum of n Numbers Write a program that enters a number n and after that enters more n numbers and calculates and prints their sum. Note: You may need to use a for-loop. Examples: numbers sum 3 90 20 60 10 5 6.5 2 -1 -0.5 4 2 1 1 1 */ using System; class SumOfNNumbers { static void Main() { Console.Title = "Sum of n Numbers"; //Changing the title of the console. Console.Write("Please, enter an integer n: "); int n = int.Parse(Console.ReadLine()); double sum = 0; for (int i = 1; i <= n; i++) { sum += double.Parse(Console.ReadLine()); } Console.WriteLine("\nsum = " + sum); Console.ReadKey(); // Keeping the console opened. } }
/*Problem 9. Sum of n Numbers Write a program that enters a number n and after that enters more n numbers and calculates and prints their sum. Note: You may need to use a for-loop. Examples: numbers sum 3 90 20 60 10 5 6.5 2 -1 -0.5 4 2 1 1 1 */ using System; class SumOfNNumbers { static void Main() { Console.Title = "Sum of n Numbers"; //Changing the title of the console. Console.Write("Please, enter an integer n and n numbers after that.\nn: "); int n = int.Parse(Console.ReadLine()); double sum = 0; for (int i = 1; i <= n; i++) { Console.Write("number {0}: ", i); sum += double.Parse(Console.ReadLine()); } Console.WriteLine("\nsum = " + sum); Console.ReadKey(); // Keeping the console opened. } }
Remove obsolete unit test (null check - can no longer be null)
using System; using System.Linq; using AutoFixture.Xunit2; using Shouldly; using Xunit; namespace Lloyd.AzureMailGateway.Models.Tests { public class EMailBuilderTests { //[Fact] //public void BuilderShouldReturnNonNullEMailInstance() //{ // // Arrange // var builder = new EMailBuilder(); // // Act // var email = new EMailBuilder().Build(); // // Assert //} [Fact] public void BuildShouldThrowOnInvalidState() { // Arrange var builder = new EMailBuilder(); // Act / Assert Should.Throw<InvalidOperationException>(() => new EMailBuilder().Build()); } [Theory, AutoData] public void BuilderShouldSetToAndFromProperties(Address toAddress, Address fromAddress) { // Arrange var builder = new EMailBuilder(); // Act builder .To(toAddress.EMail, toAddress.Name) .From(fromAddress.EMail, fromAddress.Name); var email = builder.Build(); // Assert email.To.Addresses.First().EMail.ShouldBe(toAddress.EMail); email.To.Addresses.First().Name.ShouldBe(toAddress.Name); } } }
using System; using System.Linq; using AutoFixture.Xunit2; using Shouldly; using Xunit; namespace Lloyd.AzureMailGateway.Models.Tests { public class EMailBuilderTests { [Fact] public void BuildShouldThrowOnInvalidState() { // Arrange var builder = new EMailBuilder(); // Act / Assert Should.Throw<InvalidOperationException>(() => new EMailBuilder().Build()); } [Theory, AutoData] public void BuilderShouldSetToAndFromProperties(Address toAddress, Address fromAddress) { // Arrange var builder = new EMailBuilder(); // Act builder .To(toAddress.EMail, toAddress.Name) .From(fromAddress.EMail, fromAddress.Name); var email = builder.Build(); // Assert email.To.Addresses.First().EMail.ShouldBe(toAddress.EMail); email.To.Addresses.First().Name.ShouldBe(toAddress.Name); } } }
Stop umbrella on player loss
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RemiCover_UmbrellaBehaviour : MonoBehaviour { public float verticalPosition; // Use this for initialization void Start () { Cursor.visible = false; } // Update is called once per frame void Update() { Vector2 mousePosition = CameraHelper.getCursorPosition(); this.transform.position = new Vector2(mousePosition.x, verticalPosition); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RemiCover_UmbrellaBehaviour : MonoBehaviour { public float verticalPosition; // Use this for initialization void Start () { Cursor.visible = false; } // Update is called once per frame void Update() { if (!MicrogameController.instance.getVictory()) return; Vector2 mousePosition = CameraHelper.getCursorPosition(); this.transform.position = new Vector2(mousePosition.x, verticalPosition); } }
Add support for array-like object declarations
using System.Collections.Generic; using Mond.Compiler.Expressions; namespace Mond.Compiler.Parselets { class ObjectParselet : IPrefixParselet { public Expression Parse(Parser parser, Token token) { var values = new List<KeyValuePair<string, Expression>>(); while (!parser.Match(TokenType.RightBrace)) { var identifier = parser.Take(TokenType.Identifier); parser.Take(TokenType.Colon); var value = parser.ParseExpession(); values.Add(new KeyValuePair<string, Expression>(identifier.Contents, value)); if (!parser.Match(TokenType.Comma)) break; parser.Take(TokenType.Comma); } parser.Take(TokenType.RightBrace); return new ObjectExpression(token, values); } } }
using System.Collections.Generic; using Mond.Compiler.Expressions; namespace Mond.Compiler.Parselets { class ObjectParselet : IPrefixParselet { public Expression Parse(Parser parser, Token token) { var values = new List<KeyValuePair<string, Expression>>(); while (!parser.Match(TokenType.RightBrace)) { var identifier = parser.Take(TokenType.Identifier); Expression value; if (parser.Match(TokenType.Comma) || parser.Match(TokenType.RightBrace)) { value = new IdentifierExpression(identifier); } else { parser.Take(TokenType.Colon); value = parser.ParseExpession(); } values.Add(new KeyValuePair<string, Expression>(identifier.Contents, value)); if (!parser.Match(TokenType.Comma)) break; parser.Take(TokenType.Comma); } parser.Take(TokenType.RightBrace); return new ObjectExpression(token, values); } } }
Fix a crash if we receive a too long unicode string
using System; using System.IO; using System.Text; namespace YGOSharp.Network.Utils { public static class BinaryExtensions { public static void WriteUnicode(this BinaryWriter writer, string text, int len) { byte[] unicode = Encoding.Unicode.GetBytes(text); byte[] result = new byte[len * 2]; int max = len * 2 - 2; Array.Copy(unicode, result, unicode.Length > max ? max : unicode.Length); writer.Write(result); } public static string ReadUnicode(this BinaryReader reader, int len) { byte[] unicode = reader.ReadBytes(len * 2); string text = Encoding.Unicode.GetString(unicode); text = text.Substring(0, text.IndexOf('\0')); return text; } public static byte[] ReadToEnd(this BinaryReader reader) { return reader.ReadBytes((int)(reader.BaseStream.Length - reader.BaseStream.Position)); } } }
using System; using System.IO; using System.Text; namespace YGOSharp.Network.Utils { public static class BinaryExtensions { public static void WriteUnicode(this BinaryWriter writer, string text, int len) { byte[] unicode = Encoding.Unicode.GetBytes(text); byte[] result = new byte[len * 2]; int max = len * 2 - 2; Array.Copy(unicode, result, unicode.Length > max ? max : unicode.Length); writer.Write(result); } public static string ReadUnicode(this BinaryReader reader, int len) { byte[] unicode = reader.ReadBytes(len * 2); string text = Encoding.Unicode.GetString(unicode); int index = text.IndexOf('\0'); if (index > 0) text = text.Substring(0, index); return text; } public static byte[] ReadToEnd(this BinaryReader reader) { return reader.ReadBytes((int)(reader.BaseStream.Length - reader.BaseStream.Position)); } } }
Add missing final newline in file
using System; namespace osu.Game.Online.RealtimeMultiplayer { public class NotJoinedRoomException : Exception { public NotJoinedRoomException() : base("This user has not yet joined a multiplayer room.") { } } }
using System; namespace osu.Game.Online.RealtimeMultiplayer { public class NotJoinedRoomException : Exception { public NotJoinedRoomException() : base("This user has not yet joined a multiplayer room.") { } } }
Fix a bug where you could create an already existing playlist
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows.Forms; namespace MusicRandomizer { public partial class NewPlaylistForm : Form { public String name; public NewPlaylistForm() { InitializeComponent(); } private void btnSave_Click(object sender, EventArgs e) { name = txtName.Text; // Check to make sure the user actually entered a name if (name.Length == 0) { MessageBox.Show("Please enter in a name."); return; } // Check for invalid characters in the filename foreach (char c in Path.GetInvalidFileNameChars()) { if (name.Contains(c)) { MessageBox.Show("There are invalid characters in the playlist name."); return; } } // Check to make sure this name isn't already taken String[] playlists = Directory.GetFiles("playlists"); foreach (String playlist in playlists) { if (playlist.Equals(name)) { MessageBox.Show("This playlist already exists."); return; } } // Create the playlist using (FileStream writer = File.OpenWrite("playlists\\" + name + ".xml")) { MainForm.serializer.Serialize(writer, new List<MusicFile>()); } this.Close(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows.Forms; namespace MusicRandomizer { public partial class NewPlaylistForm : Form { public String name; public NewPlaylistForm() { InitializeComponent(); } private void btnSave_Click(object sender, EventArgs e) { name = txtName.Text; // Check to make sure the user actually entered a name if (name.Length == 0) { MessageBox.Show("Please enter in a name."); return; } // Check for invalid characters in the filename foreach (char c in Path.GetInvalidFileNameChars()) { if (name.Contains(c)) { MessageBox.Show("There are invalid characters in the playlist name."); return; } } // Check to make sure this name isn't already taken if (File.Exists("playlists\\" + name + ".xml")) { MessageBox.Show("That playlist already exists."); return; } // Create the playlist using (FileStream writer = File.OpenWrite("playlists\\" + name + ".xml")) { MainForm.serializer.Serialize(writer, new List<MusicFile>()); } this.Close(); } } }
Change "Slideshow" "Root Folder" option name
using System; using System.ComponentModel; using DesktopWidgets.WidgetBase.Settings; namespace DesktopWidgets.Widgets.PictureSlideshow { public class Settings : WidgetSettingsBase { public Settings() { Width = 384; Height = 216; } [Category("General")] [DisplayName("Root Folder")] public string RootPath { get; set; } [Category("General")] [DisplayName("Allowed File Extensions")] public string FileFilterExtension { get; set; } = ".jpg|.jpeg|.png|.bmp|.gif|.ico|.tiff|.wmp"; [Category("General")] [DisplayName("Maximum File Size (bytes)")] public double FileFilterSize { get; set; } = 1024000; [Category("General")] [DisplayName("Next Image Interval")] public TimeSpan ChangeInterval { get; set; } = TimeSpan.FromSeconds(15); [Category("General")] [DisplayName("Shuffle")] public bool Shuffle { get; set; } = true; [Category("General")] [DisplayName("Recursive")] public bool Recursive { get; set; } = false; [Category("General")] [DisplayName("Current Image Path")] public string ImageUrl { get; set; } [Category("General")] [DisplayName("Allow Dropping Images")] public bool AllowDropFiles { get; set; } = true; [Category("General")] [DisplayName("Freeze")] public bool Freeze { get; set; } } }
using System; using System.ComponentModel; using DesktopWidgets.WidgetBase.Settings; namespace DesktopWidgets.Widgets.PictureSlideshow { public class Settings : WidgetSettingsBase { public Settings() { Width = 384; Height = 216; } [Category("General")] [DisplayName("Image Folder Path")] public string RootPath { get; set; } [Category("General")] [DisplayName("Allowed File Extensions")] public string FileFilterExtension { get; set; } = ".jpg|.jpeg|.png|.bmp|.gif|.ico|.tiff|.wmp"; [Category("General")] [DisplayName("Maximum File Size (bytes)")] public double FileFilterSize { get; set; } = 1024000; [Category("General")] [DisplayName("Next Image Interval")] public TimeSpan ChangeInterval { get; set; } = TimeSpan.FromSeconds(15); [Category("General")] [DisplayName("Shuffle")] public bool Shuffle { get; set; } = true; [Category("General")] [DisplayName("Recursive")] public bool Recursive { get; set; } = false; [Category("General")] [DisplayName("Current Image Path")] public string ImageUrl { get; set; } [Category("General")] [DisplayName("Allow Dropping Images")] public bool AllowDropFiles { get; set; } = true; [Category("General")] [DisplayName("Freeze")] public bool Freeze { get; set; } } }
Fix rim flying hits changing colour
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; namespace osu.Game.Rulesets.Taiko.Objects.Drawables { /// <summary> /// A hit used specifically for drum rolls, where spawning flying hits is required. /// </summary> public class DrawableFlyingHit : DrawableHit { public DrawableFlyingHit(DrawableDrumRollTick drumRollTick) : base(new IgnoreHit { StartTime = drumRollTick.HitObject.StartTime + drumRollTick.Result.TimeOffset, IsStrong = drumRollTick.HitObject.IsStrong, Type = drumRollTick.JudgementType }) { HitObject.ApplyDefaults(new ControlPointInfo(), new BeatmapDifficulty()); } protected override void LoadComplete() { base.LoadComplete(); ApplyResult(r => r.Type = r.Judgement.MaxResult); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; namespace osu.Game.Rulesets.Taiko.Objects.Drawables { /// <summary> /// A hit used specifically for drum rolls, where spawning flying hits is required. /// </summary> public class DrawableFlyingHit : DrawableHit { public DrawableFlyingHit(DrawableDrumRollTick drumRollTick) : base(new IgnoreHit { StartTime = drumRollTick.HitObject.StartTime + drumRollTick.Result.TimeOffset, IsStrong = drumRollTick.HitObject.IsStrong, Type = drumRollTick.JudgementType }) { HitObject.ApplyDefaults(new ControlPointInfo(), new BeatmapDifficulty()); } protected override void LoadComplete() { base.LoadComplete(); ApplyResult(r => r.Type = r.Judgement.MaxResult); } protected override void LoadSamples() { // block base call - flying hits are not supposed to play samples // the base call could overwrite the type of this hit } } }
Update Mike's Working with Images sample.
using System; using System.Collections.Generic; using System.Linq; using MonoTouch.Foundation; using MonoTouch.UIKit; namespace Working_with_images { /// <summary> /// The UIApplicationDelegate for the application. This class is responsible for launching the /// User Interface of the application, as well as listening (and optionally responding) to /// application events from iOS. /// </summary> [Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; /// <summary> /// This method is invoked when the application has loaded and is ready to run. In this /// method you should instantiate the window, load the UI into it and then make the window /// visible. /// </summary> /// <remarks> /// You have 5 seconds to return from this method, or iOS will terminate your application. /// </remarks> public override bool FinishedLaunching (UIApplication app, NSDictionary options) { // create a new window instance based on the screen size window = new UIWindow (UIScreen.MainScreen.Bounds); // If you have defined a view, add it here: // window.AddSubview (navigationController.View); // make the window visible window.MakeKeyAndVisible (); return true; } } }
using System; using System.Collections.Generic; using System.Linq; using MonoTouch.Foundation; using MonoTouch.UIKit; namespace Working_with_images { /// <summary> /// The UIApplicationDelegate for the application. This class is responsible for launching the /// User Interface of the application, as well as listening (and optionally responding) to /// application events from iOS. /// </summary> [Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; // Added contoller. As of MonoTouch 5.0.2, applications are expected to // have a root view controller at the end of application launch UIViewController controller; UILabel label; /// <summary> /// This method is invoked when the application has loaded and is ready to run. In this /// method you should instantiate the window, load the UI into it and then make the window /// visible. /// </summary> /// <remarks> /// You have 5 seconds to return from this method, or iOS will terminate your application. /// </remarks> public override bool FinishedLaunching (UIApplication app, NSDictionary options) { // create a new window instance based on the screen size window = new UIWindow (UIScreen.MainScreen.Bounds); controller = new UIViewController (); controller.View.BackgroundColor = UIColor.White; label = new UILabel(); label.Frame = new System.Drawing.RectangleF(10 ,10, UIScreen.MainScreen.Bounds.Width, 50); label.Text = "Hello, Working with Images"; controller.View.AddSubview(label); window.RootViewController = controller; // make the window visible window.MakeKeyAndVisible (); return true; } } }
Change some some syntax conventions.
using UnityEngine; using System.Collections; public sealed class HUD : MonoBehaviour { private int frameCount = 0; private float dt = 0.0F; private float fps = 0.0F; private float updateRate = 4.0F; void Start () { } void Update () { frameCount++; dt += Time.deltaTime; if (dt > 1.0F / updateRate) { fps = frameCount / dt ; frameCount = 0; dt -= 1.0F / updateRate; } } void OnGUI () { GUI.Label(new Rect(10, 10, 150, 100), "Current FPS: " + ((int)fps).ToString()); GUI.Box(new Rect(Screen.width / 2, Screen.height / 2, 0, 0), "This is a crosshair"); } }
using UnityEngine; using System.Collections; public sealed class HUD : MonoBehaviour { private int FrameCount = 0; private float DeltaTime = 0.0F; private float FPS = 0.0F; private float UpdateRate = 5.0F; void Start () { } void Update () { FrameCount++; DeltaTime += Time.deltaTime; if (DeltaTime > 1.0F / UpdateRate) { FPS = FrameCount / DeltaTime ; FrameCount = 0; DeltaTime -= 1.0F / UpdateRate; } } void OnGUI () { GUI.Label(new Rect(10, 10, 150, 100), "Current FPS: " + ((int)FPS).ToString()); GUI.Box(new Rect(Screen.width / 2, Screen.height / 2, 0, 0), "This is a crosshair"); } }
Fix rounded buttons not allowing custom colour specifications
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Graphics.UserInterface; using osu.Game.Overlays; namespace osu.Game.Graphics.UserInterfaceV2 { public class RoundedButton : OsuButton, IFilterable { public override float Height { get => base.Height; set { base.Height = value; if (IsLoaded) updateCornerRadius(); } } [BackgroundDependencyLoader(true)] private void load([CanBeNull] OverlayColourProvider overlayColourProvider, OsuColour colours) { BackgroundColour = overlayColourProvider?.Highlight1 ?? colours.Blue3; } protected override void LoadComplete() { base.LoadComplete(); updateCornerRadius(); } private void updateCornerRadius() => Content.CornerRadius = DrawHeight / 2; public virtual IEnumerable<string> FilterTerms => new[] { Text.ToString() }; public bool MatchingFilter { set => this.FadeTo(value ? 1 : 0); } public bool FilteringActive { get; set; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Graphics.UserInterface; using osu.Game.Overlays; using osuTK.Graphics; namespace osu.Game.Graphics.UserInterfaceV2 { public class RoundedButton : OsuButton, IFilterable { public override float Height { get => base.Height; set { base.Height = value; if (IsLoaded) updateCornerRadius(); } } [BackgroundDependencyLoader(true)] private void load([CanBeNull] OverlayColourProvider overlayColourProvider, OsuColour colours) { if (BackgroundColour == Color4.White) BackgroundColour = overlayColourProvider?.Highlight1 ?? colours.Blue3; } protected override void LoadComplete() { base.LoadComplete(); updateCornerRadius(); } private void updateCornerRadius() => Content.CornerRadius = DrawHeight / 2; public virtual IEnumerable<string> FilterTerms => new[] { Text.ToString() }; public bool MatchingFilter { set => this.FadeTo(value ? 1 : 0); } public bool FilteringActive { get; set; } } }
Remove redundant websocket sample code.
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using System; using System.Net.WebSockets; using System.Threading; using System.Threading.Tasks; namespace SampleApp { public class Startup { public void Configure(IApplicationBuilder app) { app.Run(async context => { Console.WriteLine("{0} {1}{2}{3}", context.Request.Method, context.Request.PathBase, context.Request.Path, context.Request.QueryString); if (context.IsWebSocketRequest) { var webSocket = await context.AcceptWebSocketAsync(); await EchoAsync(webSocket); } else { context.Response.ContentLength = 11; context.Response.ContentType = "text/plain"; await context.Response.WriteAsync("Hello world"); } }); } public async Task EchoAsync(WebSocket webSocket) { var buffer = new ArraySegment<byte>(new byte[8192]); for (; ;) { var result = await webSocket.ReceiveAsync( buffer, CancellationToken.None); if (result.MessageType == WebSocketMessageType.Close) { return; } else if (result.MessageType == WebSocketMessageType.Text) { Console.WriteLine("{0}", System.Text.Encoding.UTF8.GetString(buffer.Array, 0, result.Count)); } await webSocket.SendAsync( new ArraySegment<byte>(buffer.Array, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None); } } } }
using System; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; namespace SampleApp { public class Startup { public void Configure(IApplicationBuilder app) { app.Run(async context => { Console.WriteLine("{0} {1}{2}{3}", context.Request.Method, context.Request.PathBase, context.Request.Path, context.Request.QueryString); context.Response.ContentLength = 11; context.Response.ContentType = "text/plain"; await context.Response.WriteAsync("Hello world"); }); } } }
Use switch instead of ifs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System.Collections.Generic; using osu.Framework.Event; using osu.Framework.Input.Handlers; using osu.Framework.Platform; using OpenTK; namespace osu.Framework.Input { public class UserInputManager : PassThroughInputManager { protected override IEnumerable<InputHandler> InputHandlers => Host.AvailableInputHandlers; protected override bool HandleHoverEvents => Host.Window?.CursorInWindow ?? true; public UserInputManager() { UseParentInput = false; } public override void HandleInputStateChange(InputStateChangeEvent inputStateChange) { if (inputStateChange is MousePositionChangeEvent mousePositionChange) { var mouse = mousePositionChange.InputState.Mouse; // confine cursor if (Host.Window != null && (Host.Window.CursorState & CursorState.Confined) > 0) mouse.Position = Vector2.Clamp(mouse.Position, Vector2.Zero, new Vector2(Host.Window.Width, Host.Window.Height)); } if (inputStateChange is MouseScrollChangeEvent) { if (Host.Window != null && !Host.Window.CursorInWindow) return; } base.HandleInputStateChange(inputStateChange); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System.Collections.Generic; using osu.Framework.Event; using osu.Framework.Input.Handlers; using osu.Framework.Platform; using OpenTK; namespace osu.Framework.Input { public class UserInputManager : PassThroughInputManager { protected override IEnumerable<InputHandler> InputHandlers => Host.AvailableInputHandlers; protected override bool HandleHoverEvents => Host.Window?.CursorInWindow ?? true; public UserInputManager() { UseParentInput = false; } public override void HandleInputStateChange(InputStateChangeEvent inputStateChange) { switch (inputStateChange) { case MousePositionChangeEvent mousePositionChange: var mouse = mousePositionChange.InputState.Mouse; // confine cursor if (Host.Window != null && (Host.Window.CursorState & CursorState.Confined) > 0) mouse.Position = Vector2.Clamp(mouse.Position, Vector2.Zero, new Vector2(Host.Window.Width, Host.Window.Height)); break; case MouseScrollChangeEvent _: if (Host.Window != null && !Host.Window.CursorInWindow) return; break; } base.HandleInputStateChange(inputStateChange); } } }
Fix crash when navigating back to ScheduleView
using System; using System.Linq; using Autofac; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace Zermelo.App.UWP.Schedule { public sealed partial class ScheduleView : Page { public ScheduleView() { this.InitializeComponent(); NavigationCacheMode = NavigationCacheMode.Enabled; } ScheduleViewModel _viewModel; public ScheduleViewModel ViewModel => _viewModel ?? (_viewModel = (ScheduleViewModel)DataContext); private void Page_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e) { CalendarView.SelectedDates.Add(ViewModel.Date); } private void ScheduleListView_ItemClick(object sender, ItemClickEventArgs e) { ViewModel.SelectedAppointment = e.ClickedItem as Appointment; Modal.IsModal = true; } private void CalendarView_SelectedDatesChanged(CalendarView sender, CalendarViewSelectedDatesChangedEventArgs args) { if (args.AddedDates.Count > 0) ViewModel.Date = args.AddedDates.FirstOrDefault(); else CalendarView.SelectedDates.Add(ViewModel.Date); } private void CalendarView_CalendarViewDayItemChanging(CalendarView sender, CalendarViewDayItemChangingEventArgs args) { var day = args.Item.Date.DayOfWeek; if (day == DayOfWeek.Saturday || day == DayOfWeek.Sunday) args.Item.IsBlackout = true; } } }
using System; using System.Linq; using Autofac; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace Zermelo.App.UWP.Schedule { public sealed partial class ScheduleView : Page { public ScheduleView() { this.InitializeComponent(); NavigationCacheMode = NavigationCacheMode.Enabled; } ScheduleViewModel _viewModel; public ScheduleViewModel ViewModel => _viewModel ?? (_viewModel = (ScheduleViewModel)DataContext); private void Page_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e) { if (CalendarView.SelectedDates.Count < 1) CalendarView.SelectedDates.Add(ViewModel.Date); } private void ScheduleListView_ItemClick(object sender, ItemClickEventArgs e) { ViewModel.SelectedAppointment = e.ClickedItem as Appointment; Modal.IsModal = true; } private void CalendarView_SelectedDatesChanged(CalendarView sender, CalendarViewSelectedDatesChangedEventArgs args) { if (args.AddedDates.Count > 0) ViewModel.Date = args.AddedDates.FirstOrDefault(); else CalendarView.SelectedDates.Add(ViewModel.Date); } private void CalendarView_CalendarViewDayItemChanging(CalendarView sender, CalendarViewDayItemChangingEventArgs args) { var day = args.Item.Date.DayOfWeek; if (day == DayOfWeek.Saturday || day == DayOfWeek.Sunday) args.Item.IsBlackout = true; } } }
Add encryption support to relying party model
/* * Copyright (c) Dominick Baier, Brock Allen. All rights reserved. * see license */ using System.Collections.Generic; namespace Thinktecture.IdentityServer.WsFed.Models { public class RelyingParty { public string Name { get; set; } public bool Enabled { get; set; } public string Realm { get; set; } public string ReplyUrl { get; set; } public string TokenType { get; set; } public int TokenLifeTime { get; set; } public Dictionary<string, string> ClaimMappings { get; set; } } }
/* * Copyright (c) Dominick Baier, Brock Allen. All rights reserved. * see license */ using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; namespace Thinktecture.IdentityServer.WsFed.Models { public class RelyingParty { public string Name { get; set; } public bool Enabled { get; set; } public string Realm { get; set; } public string ReplyUrl { get; set; } public string TokenType { get; set; } public int TokenLifeTime { get; set; } public X509Certificate2 EncryptingCertificate { get; set; } public Dictionary<string, string> ClaimMappings { get; set; } } }
Fix issue where Id was not set when loading all entity paths
namespace Umbraco.Core.Models.Entities { /// <summary> /// Represents the path of a tree entity. /// </summary> public class TreeEntityPath { /// <summary> /// Gets or sets the identifier of the entity. /// </summary> public int Id { get; set; } /// <summary> /// Gets or sets the path of the entity. /// </summary> public string Path { get; set; } } }
namespace Umbraco.Core.Models.Entities { /// <summary> /// Represents the path of a tree entity. /// </summary> public class TreeEntityPath { /// <summary> /// Gets or sets the identifier of the entity. /// </summary> public int Id { get; set; } /// <summary> /// Gets or sets the path of the entity. /// </summary> public string Path { get; set; } /// <summary> /// Proxy of the Id /// </summary> public int NodeId { get => Id; set => Id = value; } } }
Use 'char' instead of 'ushort' for unicode character
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. namespace PInvoke { using System.Runtime.InteropServices; /// <content> /// Contains the <see cref="CHAR_INFO_ENCODING"/> nested type. /// </content> public partial class Kernel32 { /// <summary> /// A union of the Unicode and Ascii encodings. /// </summary> [StructLayout(LayoutKind.Explicit)] public struct CHAR_INFO_ENCODING { /// <summary> /// Unicode character of a screen buffer character cell. /// </summary> [FieldOffset(0)] public ushort UnicodeChar; /// <summary> /// ANSI character of a screen buffer character cell. /// </summary> [FieldOffset(0)] public byte AsciiChar; } } }
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. namespace PInvoke { using System.Runtime.InteropServices; /// <content> /// Contains the <see cref="CHAR_INFO_ENCODING"/> nested type. /// </content> public partial class Kernel32 { /// <summary> /// A union of the Unicode and Ascii encodings. /// </summary> [StructLayout(LayoutKind.Explicit)] public struct CHAR_INFO_ENCODING { /// <summary> /// Unicode character of a screen buffer character cell. /// </summary> [FieldOffset(0)] public char UnicodeChar; /// <summary> /// ANSI character of a screen buffer character cell. /// </summary> [FieldOffset(0)] public byte AsciiChar; } } }