Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Apply velocity based on rotational value
using UnityEngine; using System.Collections; public class Player : MonoBehaviour { // Movement speed, can be set in the editor public float speed = 1.0f; // Player (camera) rotation private Vector3 playerRotation = new Vector3 (35, 0, 0); // Player (camera) height private float playerHeight = 5.0f; void Start () { // Setup the player camera Camera camera = gameObject.AddComponent<Camera> (); } void Update () { float horizontalMovement = Input.GetAxis ("Horizontal"); float verticalMovement = Input.GetAxis ("Vertical"); float rotationMovement = 0.0f; // Handle camera rotation if (Input.GetKey (KeyCode.Q)) { rotationMovement = -1.0f; } else if (Input.GetKey (KeyCode.E)) { rotationMovement = 1.0f; } playerRotation.y += rotationMovement * (speed / 2); // Handle movement on the terrain Vector3 movement = new Vector3 (horizontalMovement, 0.0f, verticalMovement); GetComponent<Rigidbody>().velocity = movement * speed; // Keep position with a variable height transform.position = new Vector3 (transform.position.x, playerHeight, transform.position.z); // Set player rotation transform.rotation = Quaternion.Euler (playerRotation); } }
using UnityEngine; using System.Collections; public class Player : MonoBehaviour { // Movement speed, can be set in the editor public float speed = 1.0f; // Player (camera) rotation private Vector3 playerRotation = new Vector3 (35, 0, 0); // Player (camera) height private float playerHeight = 5.0f; void Start () { // Setup the player camera Camera camera = gameObject.AddComponent<Camera> (); // This is probably stupid to do gameObject.tag = "MainCamera"; } void Update () { float horizontalMovement = Input.GetAxis ("Horizontal"); float verticalMovement = Input.GetAxis ("Vertical"); float rotationMovement = 0.0f; // Handle camera rotation if (Input.GetKey (KeyCode.Q)) { rotationMovement = -1.0f; } else if (Input.GetKey (KeyCode.E)) { rotationMovement = 1.0f; } playerRotation.y += rotationMovement * (speed / 2); // Calculate movement velocity Vector3 velocityVertical = transform.forward * speed * verticalMovement; Vector3 velocityHorizontal = transform.right * speed * horizontalMovement; Vector3 calculatedVelocity = velocityHorizontal + velocityVertical; calculatedVelocity.y = 0.0f; // Apply calculated velocity GetComponent<Rigidbody>().velocity = calculatedVelocity; // Keep position with a variable height transform.position = new Vector3 (transform.position.x, playerHeight, transform.position.z); // Set player rotation transform.rotation = Quaternion.Euler (playerRotation); } }
Update test to check that breadcrumbs are returned in correct order when MaximumBreadcrumbs is exceeded
using System.Linq; using Xunit; namespace Bugsnag.Tests { public class BreadcrumbsTests { [Fact] public void RestrictsMaxNumberOfBreadcrumbs() { var breadcrumbs = new Breadcrumbs(new Configuration { MaximumBreadcrumbs = 25 }); for (int i = 0; i < 30; i++) { breadcrumbs.Leave($"{i}"); } Assert.Equal(25, breadcrumbs.Retrieve().Count()); } [Fact] public void WhenRetrievingBreadcrumbsCorrectNumberIsReturned() { var breadcrumbs = new Breadcrumbs(new Configuration { MaximumBreadcrumbs = 25 }); for (int i = 0; i < 10; i++) { breadcrumbs.Leave($"{i}"); } Assert.Equal(10, breadcrumbs.Retrieve().Count()); } [Fact] public void CorrectBreadcrumbsAreReturned() { var breadcrumbs = new Breadcrumbs(new Configuration { MaximumBreadcrumbs = 5 }); for (int i = 0; i < 10; i++) { breadcrumbs.Leave($"{i}"); } var breadcrumbNames = breadcrumbs.Retrieve().Select(b => b.Name); Assert.Equal(new string[] { "5", "6", "7", "8", "9" }, breadcrumbNames); } } }
using System.Linq; using Xunit; namespace Bugsnag.Tests { public class BreadcrumbsTests { [Fact] public void RestrictsMaxNumberOfBreadcrumbs() { var breadcrumbs = new Breadcrumbs(new Configuration { MaximumBreadcrumbs = 25 }); for (int i = 0; i < 30; i++) { breadcrumbs.Leave($"{i}"); } Assert.Equal(25, breadcrumbs.Retrieve().Count()); } [Fact] public void WhenRetrievingBreadcrumbsCorrectNumberIsReturned() { var breadcrumbs = new Breadcrumbs(new Configuration { MaximumBreadcrumbs = 25 }); for (int i = 0; i < 10; i++) { breadcrumbs.Leave($"{i}"); } Assert.Equal(10, breadcrumbs.Retrieve().Count()); } [Fact] public void CorrectBreadcrumbsAreReturned() { var breadcrumbs = new Breadcrumbs(new Configuration { MaximumBreadcrumbs = 5 }); for (int i = 0; i < 6; i++) { breadcrumbs.Leave($"{i}"); } var breadcrumbNames = breadcrumbs.Retrieve().Select(b => b.Name); Assert.Equal(new string[] { "1", "2", "3", "4", "5" }, breadcrumbNames); } } }
Use SampleOverrideLongestPlaying for audio samples.
using ManagedBass; using System; using System.Diagnostics; using System.Resources; namespace BrewLib.Audio { public class AudioSample { private const int MaxSimultaneousPlayBacks = 8; private string path; public string Path => path; private int sample; public readonly AudioManager Manager; internal AudioSample(AudioManager audioManager, string path, ResourceManager resourceManager) { Manager = audioManager; this.path = path; sample = Bass.SampleLoad(path, 0, 0, MaxSimultaneousPlayBacks, BassFlags.Default); if (sample == 0) { Trace.WriteLine($"Failed to load audio sample ({path}): {Bass.LastError}"); return; } } public void Play(float volume = 1) { if (sample == 0) return; var channel = new AudioChannel(Manager, Bass.SampleGetChannel(sample), true) { Volume = volume, }; Manager.RegisterChannel(channel); channel.Playing = true; } #region IDisposable Support private bool disposedValue = false; protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { } if (sample != 0) { Bass.SampleFree(sample); sample = 0; } disposedValue = true; } } ~AudioSample() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } }
using ManagedBass; using System; using System.Diagnostics; using System.Resources; namespace BrewLib.Audio { public class AudioSample { private const int MaxSimultaneousPlayBacks = 8; private string path; public string Path => path; private int sample; public readonly AudioManager Manager; internal AudioSample(AudioManager audioManager, string path, ResourceManager resourceManager) { Manager = audioManager; this.path = path; sample = Bass.SampleLoad(path, 0, 0, MaxSimultaneousPlayBacks, BassFlags.SampleOverrideLongestPlaying); if (sample == 0) { Trace.WriteLine($"Failed to load audio sample ({path}): {Bass.LastError}"); return; } } public void Play(float volume = 1) { if (sample == 0) return; var channel = new AudioChannel(Manager, Bass.SampleGetChannel(sample), true) { Volume = volume, }; Manager.RegisterChannel(channel); channel.Playing = true; } #region IDisposable Support private bool disposedValue = false; protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { } if (sample != 0) { Bass.SampleFree(sample); sample = 0; } disposedValue = true; } } ~AudioSample() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } }
Change header size in HTML generation.
using System.Text; namespace SnippetsToMarkdown.Commands { class WriteHeaderHtmlCommand : ICommand { private string directory; public WriteHeaderHtmlCommand(string directory) { this.directory = directory; } public void WriteToOutput(StringBuilder output) { output.AppendLine("<h3>" + directory.Substring(directory.LastIndexOf('\\') + 1) + "</h3>"); output.AppendLine("<br />"); output.AppendLine("<table>"); output.AppendLine("<thead>"); output.AppendLine("<tr>"); output.AppendLine("<td>Shortcut</td>"); output.AppendLine("<td>Name</td>"); output.AppendLine("</tr>"); output.AppendLine("</thead>"); output.AppendLine("<tbody>"); } } }
using System.Text; namespace SnippetsToMarkdown.Commands { class WriteHeaderHtmlCommand : ICommand { private string directory; public WriteHeaderHtmlCommand(string directory) { this.directory = directory; } public void WriteToOutput(StringBuilder output) { output.AppendLine("<h4>" + directory.Substring(directory.LastIndexOf('\\') + 1) + "</h4>"); output.AppendLine("<br />"); output.AppendLine("<table>"); output.AppendLine("<thead>"); output.AppendLine("<tr>"); output.AppendLine("<td>Shortcut</td>"); output.AppendLine("<td>Name</td>"); output.AppendLine("</tr>"); output.AppendLine("</thead>"); output.AppendLine("<tbody>"); } } }
Make JSNLogLogger available to the outside world, so it can actually be used in ASP.NET 5 apps
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Extensions.Logging; using JSNLog.Infrastructure; namespace JSNLog { internal class JSNlogLogger : IJSNLogLogger { private ILoggerFactory _loggerFactory; public JSNlogLogger(ILoggerFactory loggerFactory) { _loggerFactory = loggerFactory; } public void Log(FinalLogData finalLogData) { ILogger logger = _loggerFactory.CreateLogger(finalLogData.FinalLogger); Object message = LogMessageHelpers.DeserializeIfPossible(finalLogData.FinalMessage); switch (finalLogData.FinalLevel) { case Level.TRACE: logger.LogDebug("{logMessage}", message); break; case Level.DEBUG: logger.LogVerbose("{logMessage}", message); break; case Level.INFO: logger.LogInformation("{logMessage}", message); break; case Level.WARN: logger.LogWarning("{logMessage}", message); break; case Level.ERROR: logger.LogError("{logMessage}", message); break; case Level.FATAL: logger.LogCritical("{logMessage}", message); break; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Extensions.Logging; using JSNLog.Infrastructure; namespace JSNLog { public class JSNlogLogger : IJSNLogLogger { private ILoggerFactory _loggerFactory; public JSNlogLogger(ILoggerFactory loggerFactory) { _loggerFactory = loggerFactory; } public void Log(FinalLogData finalLogData) { ILogger logger = _loggerFactory.CreateLogger(finalLogData.FinalLogger); Object message = LogMessageHelpers.DeserializeIfPossible(finalLogData.FinalMessage); switch (finalLogData.FinalLevel) { case Level.TRACE: logger.LogDebug("{logMessage}", message); break; case Level.DEBUG: logger.LogVerbose("{logMessage}", message); break; case Level.INFO: logger.LogInformation("{logMessage}", message); break; case Level.WARN: logger.LogWarning("{logMessage}", message); break; case Level.ERROR: logger.LogError("{logMessage}", message); break; case Level.FATAL: logger.LogCritical("{logMessage}", message); break; } } } }
Fix up distance -> positional length comments.
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE namespace osu.Game.Modes.Objects.Types { /// <summary> /// A HitObject that has a distance. /// </summary> public interface IHasDistance : IHasEndTime { /// <summary> /// The distance of the HitObject. /// </summary> double Distance { get; } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE namespace osu.Game.Modes.Objects.Types { /// <summary> /// A HitObject that has a positional length. /// </summary> public interface IHasDistance : IHasEndTime { /// <summary> /// The positional length of the HitObject. /// </summary> double Distance { get; } } }
Document and suppress an FxCop warning
 namespace Nvelope { public enum Month { January = 1, February = 2, March = 3, April = 4, May = 5, June = 6, July = 7, August = 8, September = 9, October = 10, November = 11, December = 12 } }
//----------------------------------------------------------------------- // <copyright file="Month.cs" company="TWU"> // MIT Licenced // </copyright> //----------------------------------------------------------------------- namespace Nvelope { using System.Diagnostics.CodeAnalysis; /// <summary> /// Represents a month of the year /// </summary> [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "There's no such thing as a 'default' or 'none' month.")] public enum Month { /* These doc comments are stupid, but it keeps FxCop from getting made * and it by looking at Microsoft's docs it seems to be in line with * their practices */ /// <summary> /// Indicates January /// </summary> January = 1, /// <summary> /// Indicates February /// </summary> February = 2, /// <summary> /// Indicates January /// </summary> March = 3, /// <summary> /// Indicates April /// </summary> April = 4, /// <summary> /// Indicates January /// </summary> May = 5, /// <summary> /// Indicates June /// </summary> June = 6, /// <summary> /// Indicates July /// </summary> July = 7, /// <summary> /// Indicates August /// </summary> August = 8, /// <summary> /// Indicates September /// </summary> September = 9, /// <summary> /// Indicates October /// </summary> October = 10, /// <summary> /// Indicates November /// </summary> November = 11, /// <summary> /// Indicates December /// </summary> December = 12 } }
Add XML description for Authentication Scheme
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.Devices.Client { public enum AuthenticationScheme { // Shared Access Signature SAS = 0, // X509 Certificate X509 = 1 } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.Devices.Client { /// <summary> /// Specifies the Authentication Scheme used by Device Client /// </summary> public enum S { // Shared Access Signature SAS = 0, // X509 Certificate X509 = 1 } }
Add playerID and revisit the moving.
using UnityEngine; using System.Collections; public class Player : MonoBehaviour { public float baseFireCooldown; public float baseRotationSpeed; public God god; // public Weapon weapon; public Vector2 direction; // Maybe this should be private? public Vector2 targetDirection; // This too. // Temporary public GameObject tempProjectile; private float cooldownTimeStamp; // Use this for initialization void Start () { } public void Move(float horizontal, float vertical) { targetDirection = new Vector2 (horizontal, vertical); } public void Fire () { // Don't fire when the cooldown is still active. if (this.cooldownTimeStamp >= Time.time) { return; } // Fire the weapon. // TODO Moveable arrowMoveable = Instantiate(tempProjectile).GetComponent<Moveable> (); arrowMoveable.direction = this.direction; // Set the cooldown. this.cooldownTimeStamp = Time.time + this.baseFireCooldown; } // Update is called once per frame void Update () { float angle = Vector2.Angle (direction, targetDirection); this.transform.Rotate (targetDirection.x, angle * baseRotationSpeed * Time.deltaTime); this.direction = new Vector2 (this.transform.TransformDirection.x, this.transform.TransformDirection.y); } }
using UnityEngine; using System.Collections; public class Player : MonoBehaviour { public int playerID; public float baseFireCooldown; public float baseRotationSpeed; public God god; // public Weapon weapon; public Vector2 direction; // Maybe this should be private? public Vector2 targetDirection; // This too. // Temporary public GameObject tempProjectile; private float cooldownTimeStamp; // Use this for initialization void Start () { } public void Move(float horizontal, float vertical) { targetDirection = new Vector2 (horizontal, vertical); } public void Fire () { // Don't fire when the cooldown is still active. if (this.cooldownTimeStamp >= Time.time) { return; } // Fire the weapon. // TODO Moveable arrowMoveable = Instantiate(tempProjectile).GetComponent<Moveable> (); arrowMoveable.direction = this.direction; // Set the cooldown. this.cooldownTimeStamp = Time.time + this.baseFireCooldown; } // Update is called once per frame void Update () { float angle = Vector2.Angle (direction, targetDirection); // this.transform.Rotate (targetDirection.x, angle * baseRotationSpeed * Time.deltaTime); this.direction = new Vector2 (this.transform.TransformDirection.x , this.transform.TransformDirection.y); } }
Allow double click to open on junctions when lacking a destination
using System.Diagnostics; using System.Windows.Controls; using System.Windows.Input; using Junctionizer.Model; namespace Junctionizer.UI.Styles { public partial class DataGridStyles { private void DataGridRow_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) { if (e.ChangedButton != MouseButton.Left) return; var dataGridRow = sender as DataGridRow; if (dataGridRow?.Item is GameFolder folder) { OpenInFileExplorer(folder); } else if (dataGridRow?.Item is GameFolderPair pair) { if (pair.SourceEntry?.IsJunction == false) OpenInFileExplorer(pair.SourceEntry); if (pair.DestinationEntry?.IsJunction == false) OpenInFileExplorer(pair.DestinationEntry); } } private static void OpenInFileExplorer(GameFolder folder) { var path = folder.DirectoryInfo.FullName; ErrorHandling.ThrowIfDirectoryNotFound(path); Process.Start(path); } } }
using System.Diagnostics; using System.Windows.Controls; using System.Windows.Input; using Junctionizer.Model; namespace Junctionizer.UI.Styles { public partial class DataGridStyles { private void DataGridRow_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) { if (e.ChangedButton != MouseButton.Left) return; var dataGridRow = sender as DataGridRow; if (dataGridRow?.Item is GameFolder folder) { OpenInFileExplorer(folder); } else if (dataGridRow?.Item is GameFolderPair pair) { if (pair.DestinationEntry == null || pair.SourceEntry?.IsJunction == false) OpenInFileExplorer(pair.SourceEntry); if (pair.DestinationEntry != null) OpenInFileExplorer(pair.DestinationEntry); } } private static void OpenInFileExplorer(GameFolder folder) { var path = folder.DirectoryInfo.FullName; ErrorHandling.ThrowIfDirectoryNotFound(path); Process.Start(path); } } }
Change caption of Tool Window
//------------------------------------------------------------------------------ // <copyright file="StackAnalysisToolWindow.cs" company="Microsoft"> // Copyright (c) Microsoft. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace StackUsageAnalyzer { using System; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Shell; /// <summary> /// This class implements the tool window exposed by this package and hosts a user control. /// </summary> /// <remarks> /// In Visual Studio tool windows are composed of a frame (implemented by the shell) and a pane, /// usually implemented by the package implementer. /// <para> /// This class derives from the ToolWindowPane class provided from the MPF in order to use its /// implementation of the IVsUIElementPane interface. /// </para> /// </remarks> [Guid("ffbd67c0-1100-4fa5-8c20-cc10264c540b")] public class StackAnalysisToolWindow : ToolWindowPane { /// <summary> /// Initializes a new instance of the <see cref="StackAnalysisToolWindow"/> class. /// </summary> public StackAnalysisToolWindow() : base(null) { this.Caption = "StackAnalysisToolWindow"; // This is the user control hosted by the tool window; Note that, even if this class implements IDisposable, // we are not calling Dispose on this object. This is because ToolWindowPane calls Dispose on // the object returned by the Content property. this.Content = new StackAnalysisToolWindowControl(); } } }
//------------------------------------------------------------------------------ // <copyright file="StackAnalysisToolWindow.cs" company="Microsoft"> // Copyright (c) Microsoft. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace StackUsageAnalyzer { using System; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Shell; /// <summary> /// This class implements the tool window exposed by this package and hosts a user control. /// </summary> /// <remarks> /// In Visual Studio tool windows are composed of a frame (implemented by the shell) and a pane, /// usually implemented by the package implementer. /// <para> /// This class derives from the ToolWindowPane class provided from the MPF in order to use its /// implementation of the IVsUIElementPane interface. /// </para> /// </remarks> [Guid("ffbd67c0-1100-4fa5-8c20-cc10264c540b")] public class StackAnalysisToolWindow : ToolWindowPane { /// <summary> /// Initializes a new instance of the <see cref="StackAnalysisToolWindow"/> class. /// </summary> public StackAnalysisToolWindow() : base(null) { this.Caption = "Function Stack Analysis"; // This is the user control hosted by the tool window; Note that, even if this class implements IDisposable, // we are not calling Dispose on this object. This is because ToolWindowPane calls Dispose on // the object returned by the Content property. this.Content = new StackAnalysisToolWindowControl(); } } }
Fix using for Release build
using NLog; namespace Wox.Infrastructure.Logger { public class Log { private static NLog.Logger logger = LogManager.GetCurrentClassLogger(); public static void Error(System.Exception e) { #if DEBUG throw e; #else while (e.InnerException != null) { logger.Error(e.Message); logger.Error(e.StackTrace); e = e.InnerException; } #endif } public static void Debug(string msg) { System.Diagnostics.Debug.WriteLine($"DEBUG: {msg}"); logger.Debug(msg); } public static void Info(string msg) { System.Diagnostics.Debug.WriteLine($"INFO: {msg}"); logger.Info(msg); } public static void Warn(string msg) { System.Diagnostics.Debug.WriteLine($"WARN: {msg}"); logger.Warn(msg); } public static void Fatal(System.Exception e) { #if DEBUG throw e; #else logger.Fatal(ExceptionFormatter.FormatExcpetion(e)); #endif } } }
using NLog; using Wox.Infrastructure.Exception; namespace Wox.Infrastructure.Logger { public class Log { private static NLog.Logger logger = LogManager.GetCurrentClassLogger(); public static void Error(System.Exception e) { #if DEBUG throw e; #else while (e.InnerException != null) { logger.Error(e.Message); logger.Error(e.StackTrace); e = e.InnerException; } #endif } public static void Debug(string msg) { System.Diagnostics.Debug.WriteLine($"DEBUG: {msg}"); logger.Debug(msg); } public static void Info(string msg) { System.Diagnostics.Debug.WriteLine($"INFO: {msg}"); logger.Info(msg); } public static void Warn(string msg) { System.Diagnostics.Debug.WriteLine($"WARN: {msg}"); logger.Warn(msg); } public static void Fatal(System.Exception e) { #if DEBUG throw e; #else logger.Fatal(ExceptionFormatter.FormatExcpetion(e)); #endif } } }
Change the location of where the Enums are generated to be at the same level as the types.
// Copyright (c) Alex Ghiondea. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; namespace SmugMugCodeGen { public class Options { public string OutputDir { get; private set; } public string OutputDirEnums { get; private set; } public string[] InputFiles { get; private set; } public Options(string[] args) { OutputDir = args[0]; OutputDirEnums = Path.Combine(OutputDir, "Enums"); // Copy the input files from the args array. InputFiles = new string[args.Length - 1]; Array.Copy(args, 1, InputFiles, 0, args.Length - 1); } } }
// Copyright (c) Alex Ghiondea. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; namespace SmugMugCodeGen { public class Options { public string OutputDir { get; private set; } public string OutputDirEnums { get; private set; } public string[] InputFiles { get; private set; } public Options(string[] args) { OutputDir = args[0]; OutputDirEnums = Path.Combine(OutputDir, @"\..\Enums"); // Copy the input files from the args array. InputFiles = new string[args.Length - 1]; Array.Copy(args, 1, InputFiles, 0, args.Length - 1); } } }
Remove stray integration test call.
using System; using System.Collections; using UnityEngine; using System.Threading; using UnityEngine.Networking; namespace GLTF { class GLTFComponent : MonoBehaviour { public string Url; public Shader Shader; public bool Multithreaded = true; IEnumerator Start() { var loader = new GLTFLoader(Url, Shader, gameObject.transform); loader.Multithreaded = Multithreaded; yield return loader.Load(); IntegrationTest.Pass(); } } }
using System; using System.Collections; using UnityEngine; using System.Threading; using UnityEngine.Networking; namespace GLTF { class GLTFComponent : MonoBehaviour { public string Url; public Shader Shader; public bool Multithreaded = true; IEnumerator Start() { var loader = new GLTFLoader(Url, Shader, gameObject.transform); loader.Multithreaded = Multithreaded; yield return loader.Load(); } } }
Return IServiceCollection from AddSession extension methods
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Session; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Extension methods for adding session services to the DI container. /// </summary> public static class SessionServiceCollectionExtensions { /// <summary> /// Adds services required for application session state. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> to add the services to.</param> public static void AddSession(this IServiceCollection services) { if (services == null) { throw new ArgumentNullException(nameof(services)); } services.AddTransient<ISessionStore, DistributedSessionStore>(); } /// <summary> /// Adds services required for application session state. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> to add the services to.</param> /// <param name="configure">The session options to configure the middleware with.</param> public static void AddSession(this IServiceCollection services, Action<SessionOptions> configure) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (configure == null) { throw new ArgumentNullException(nameof(configure)); } services.Configure(configure); services.AddSession(); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Session; namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Extension methods for adding session services to the DI container. /// </summary> public static class SessionServiceCollectionExtensions { /// <summary> /// Adds services required for application session state. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> to add the services to.</param> /// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns> public static IServiceCollection AddSession(this IServiceCollection services) { if (services == null) { throw new ArgumentNullException(nameof(services)); } services.AddTransient<ISessionStore, DistributedSessionStore>(); return services; } /// <summary> /// Adds services required for application session state. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> to add the services to.</param> /// <param name="configure">The session options to configure the middleware with.</param> /// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns> public static IServiceCollection AddSession(this IServiceCollection services, Action<SessionOptions> configure) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (configure == null) { throw new ArgumentNullException(nameof(configure)); } services.Configure(configure); services.AddSession(); return services; } } }
Add missing "announce" channel type
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Online.Chat { public enum ChannelType { Public, Private, Multiplayer, Spectator, Temporary, PM, Group, System, } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Online.Chat { public enum ChannelType { Public, Private, Multiplayer, Spectator, Temporary, PM, Group, System, Announce, } }
Add test of scheduler usage
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Threading; using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osuTK; namespace osu.Framework.Tests.Visual.Drawables { public class TestSceneSynchronizationContext : FrameworkTestScene { private AsyncPerformingBox box; [Test] public void TestAsyncPerformingBox() { AddStep("add box", () => Child = box = new AsyncPerformingBox()); AddAssert("not spun", () => box.Rotation == 0); AddStep("trigger", () => box.Trigger()); AddUntilStep("has spun", () => box.Rotation == 180); } public class AsyncPerformingBox : Box { private readonly SemaphoreSlim waiter = new SemaphoreSlim(0); public AsyncPerformingBox() { Size = new Vector2(100); Anchor = Anchor.Centre; Origin = Anchor.Centre; } protected override async void LoadComplete() { base.LoadComplete(); await waiter.WaitAsync().ConfigureAwait(true); this.RotateTo(180, 500); } public void Trigger() { waiter.Release(); } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Threading; using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osuTK; namespace osu.Framework.Tests.Visual.Drawables { public class TestSceneSynchronizationContext : FrameworkTestScene { private AsyncPerformingBox box; [Test] public void TestAsyncPerformingBox() { AddStep("add box", () => Child = box = new AsyncPerformingBox()); AddAssert("not spun", () => box.Rotation == 0); AddStep("trigger", () => box.Trigger()); AddUntilStep("has spun", () => box.Rotation == 180); } [Test] public void TestUsingLocalScheduler() { AddStep("add box", () => Child = box = new AsyncPerformingBox()); AddAssert("scheduler null", () => box.Scheduler == null); AddStep("trigger", () => box.Trigger()); AddUntilStep("scheduler non-null", () => box.Scheduler != null); } public class AsyncPerformingBox : Box { private readonly SemaphoreSlim waiter = new SemaphoreSlim(0); public AsyncPerformingBox() { Size = new Vector2(100); Anchor = Anchor.Centre; Origin = Anchor.Centre; } protected override async void LoadComplete() { base.LoadComplete(); await waiter.WaitAsync().ConfigureAwait(true); this.RotateTo(180, 500); } public void Trigger() { waiter.Release(); } } } }
Add EnumerateArray() extension for tables
using System; namespace Eluant { public static class LuaValueExtensions { public static bool IsNil(this LuaValue self) { return self == null || self == LuaNil.Instance; } } }
using System; using System.Collections.Generic; namespace Eluant { public static class LuaValueExtensions { public static bool IsNil(this LuaValue self) { return self == null || self == LuaNil.Instance; } public static IEnumerable<LuaValue> EnumerateArray(this LuaTable self) { if (self == null) { throw new ArgumentNullException("self"); } return CreateEnumerateArrayEnumerable(self); } private static IEnumerable<LuaValue> CreateEnumerateArrayEnumerable(LuaTable self) { // By convention, the 'n' field refers to the array length, if present. using (var n = self["n"]) { var num = n as LuaNumber; if (num != null) { var length = (int)num.Value; for (int i = 1; i <= length; ++i) { yield return self[i]; } yield break; } } // If no 'n' then stop at the first nil element. for (int i = 1; ; ++i) { var value = self[i]; if (value.IsNil()) { yield break; } yield return value; } } } }
Fix NullException ocurring in GetFeaturesInView() when BoundingBox is null
using Mapsui.Fetcher; using Mapsui.Geometries; using Mapsui.Providers; using System.Collections.Generic; using System.Threading.Tasks; using Mapsui.Styles; namespace Mapsui.Layers { public class MemoryLayer : BaseLayer { public IProvider DataSource { get; set; } public override IEnumerable<IFeature> GetFeaturesInView(BoundingBox box, double resolution) { var biggerBox = box.Grow(SymbolStyle.DefaultWidth * 2 * resolution, SymbolStyle.DefaultHeight * 2 * resolution); return DataSource.GetFeaturesInView(biggerBox, resolution); } public override BoundingBox Envelope => DataSource?.GetExtents(); public override void AbortFetch() { // do nothing. This is not an async layer } public override void ViewChanged(bool majorChange, BoundingBox extent, double resolution) { //The MemoryLayer always has it's data ready so can fire a DataChanged event immediately so that listeners can act on it. Task.Run(() => OnDataChanged(new DataChangedEventArgs())); } public override void ClearCache() { // do nothing. This is not an async layer } } }
using Mapsui.Fetcher; using Mapsui.Geometries; using Mapsui.Providers; using System.Collections.Generic; using System.Threading.Tasks; using Mapsui.Styles; namespace Mapsui.Layers { public class MemoryLayer : BaseLayer { public IProvider DataSource { get; set; } public override IEnumerable<IFeature> GetFeaturesInView(BoundingBox box, double resolution) { // Safeguard in case BoundingBox is null, most likely due to no features in layer if (box == null) { return new List<IFeature>(); } var biggerBox = box.Grow(SymbolStyle.DefaultWidth * 2 * resolution, SymbolStyle.DefaultHeight * 2 * resolution); return DataSource.GetFeaturesInView(biggerBox, resolution); } public override BoundingBox Envelope => DataSource?.GetExtents(); public override void AbortFetch() { // do nothing. This is not an async layer } public override void ViewChanged(bool majorChange, BoundingBox extent, double resolution) { //The MemoryLayer always has it's data ready so can fire a DataChanged event immediately so that listeners can act on it. Task.Run(() => OnDataChanged(new DataChangedEventArgs())); } public override void ClearCache() { // do nothing. This is not an async layer } } }
Allow cactbot to be restarted
using Advanced_Combat_Tracker; using CefSharp; using CefSharp.Wpf; using System; using System.Windows.Forms; namespace Cactbot { public class ACTPlugin : IActPluginV1 { SettingsTab settingsTab = new SettingsTab(); BrowserWindow browserWindow; #region IActPluginV1 Members public void InitPlugin(TabPage pluginScreenSpace, Label pluginStatusText) { settingsTab.Initialize(pluginStatusText); browserWindow = new BrowserWindow(); browserWindow.ShowInTaskbar = false; browserWindow.BrowserControl.CreationHandlers += OnBrowserCreated; browserWindow.Show(); pluginScreenSpace.Controls.Add(settingsTab); } public void DeInitPlugin() { browserWindow.Hide(); settingsTab.Shutdown(); // FIXME: This needs to be called from the right thread, so it can't happen automatically. // However, calling it here means the plugin can never be reinitialized, oops. Cef.Shutdown(); } #endregion private void OnBrowserCreated(object sender, IWpfWebBrowser browser) { browser.RegisterJsObject("act", new BrowserBindings()); // FIXME: Make it possible to create more than one window. // Tie loading html to the browser window creation and bindings to the // browser creation. browser.Load(settingsTab.HTMLFile()); browser.ShowDevTools(); } } }
using Advanced_Combat_Tracker; using CefSharp; using CefSharp.Wpf; using System; using System.Windows.Forms; namespace Cactbot { public class ACTPlugin : IActPluginV1 { SettingsTab settingsTab = new SettingsTab(); BrowserWindow browserWindow; #region IActPluginV1 Members public void InitPlugin(TabPage pluginScreenSpace, Label pluginStatusText) { settingsTab.Initialize(pluginStatusText); browserWindow = new BrowserWindow(); browserWindow.ShowInTaskbar = false; browserWindow.BrowserControl.CreationHandlers += OnBrowserCreated; browserWindow.Show(); pluginScreenSpace.Controls.Add(settingsTab); Application.ApplicationExit += OnACTShutdown; } public void DeInitPlugin() { browserWindow.Hide(); settingsTab.Shutdown(); } #endregion private void OnBrowserCreated(object sender, IWpfWebBrowser browser) { browser.RegisterJsObject("act", new BrowserBindings()); // FIXME: Make it possible to create more than one window. // Tie loading html to the browser window creation and bindings to the // browser creation. browser.Load(settingsTab.HTMLFile()); browser.ShowDevTools(); } private void OnACTShutdown(object sender, EventArgs args) { // Cef has to be manually shutdown on this thread, but can only be // shutdown once. Cef.Shutdown(); } } }
Use new API to build durable Exchange
using System; using System.Threading.Tasks; using Carrot.Configuration; using Carrot.Extensions; using RabbitMQ.Client; using RabbitMQ.Client.Events; namespace Carrot.Messages { public abstract class ConsumedMessageBase { protected readonly BasicDeliverEventArgs Args; protected ConsumedMessageBase(BasicDeliverEventArgs args) { Args = args; } internal abstract Object Content { get; } internal abstract Task<AggregateConsumingResult> ConsumeAsync(SubscriptionConfiguration configuration); internal ConsumedMessage<TMessage> As<TMessage>() where TMessage : class { var content = Content as TMessage; if (content == null) throw new InvalidCastException(String.Format("cannot cast '{0}' to '{1}'", Content.GetType(), typeof(TMessage))); return new ConsumedMessage<TMessage>(content, HeaderCollection.Parse(Args)); } internal abstract Boolean Match(Type type); internal void Acknowledge(IModel model) { model.BasicAck(Args.DeliveryTag, false); } internal void Requeue(IModel model) { model.BasicNack(Args.DeliveryTag, false, true); } internal void ForwardTo(IModel model, Func<String, String> exchangeNameBuilder) { var exchange = Exchange.DurableDirect(exchangeNameBuilder(Args.Exchange)); exchange.Declare(model); var properties = Args.BasicProperties.Copy(); properties.Persistent = true; model.BasicPublish(exchange.Name, String.Empty, properties, Args.Body); } } }
using System; using System.Threading.Tasks; using Carrot.Configuration; using Carrot.Extensions; using RabbitMQ.Client; using RabbitMQ.Client.Events; namespace Carrot.Messages { public abstract class ConsumedMessageBase { protected readonly BasicDeliverEventArgs Args; protected ConsumedMessageBase(BasicDeliverEventArgs args) { Args = args; } internal abstract Object Content { get; } internal abstract Task<AggregateConsumingResult> ConsumeAsync(SubscriptionConfiguration configuration); internal ConsumedMessage<TMessage> As<TMessage>() where TMessage : class { var content = Content as TMessage; if (content == null) throw new InvalidCastException(String.Format("cannot cast '{0}' to '{1}'", Content.GetType(), typeof(TMessage))); return new ConsumedMessage<TMessage>(content, HeaderCollection.Parse(Args)); } internal abstract Boolean Match(Type type); internal void Acknowledge(IModel model) { model.BasicAck(Args.DeliveryTag, false); } internal void Requeue(IModel model) { model.BasicNack(Args.DeliveryTag, false, true); } internal void ForwardTo(IModel model, Func<String, String> exchangeNameBuilder) { var exchange = Exchange.Direct(exchangeNameBuilder(Args.Exchange)).Durable(); exchange.Declare(model); var properties = Args.BasicProperties.Copy(); properties.Persistent = true; model.BasicPublish(exchange.Name, String.Empty, properties, Args.Body); } } }
Add mLogger to Unity Window menu
using UnityEngine; using UnityEditor; using System; using System.Collections; namespace mLogger { public class LoggerWindow : EditorWindow { private Logger loggerInstance; public Logger LoggerInstance { get { if (loggerInstance == null) { loggerInstance = FindObjectOfType<Logger>(); if (loggerInstance == null) { GameObject loggerGO = new GameObject(); loggerGO.AddComponent<Logger>(); loggerInstance = loggerGO.GetComponent<Logger>(); } } return loggerInstance; } } [MenuItem("Debug/Logger")] public static void Init() { LoggerWindow window = (LoggerWindow)EditorWindow.GetWindow(typeof(LoggerWindow)); window.title = "Logger"; window.minSize = new Vector2(100f, 60f); } private void OnGUI() { EditorGUILayout.BeginHorizontal(); // Draw Start/Stop button. LoggerInstance.LoggingEnabled = InspectorControls.DrawStartStopButton( LoggerInstance.LoggingEnabled, LoggerInstance.EnableOnPlay, null, () => LoggerInstance.LogWriter.Add("[PAUSE]", true), () => LoggerInstance.LogWriter.WriteAll( LoggerInstance.FilePath, false)); // Draw -> button. if (GUILayout.Button("->", GUILayout.Width(30))) { EditorGUIUtility.PingObject(LoggerInstance); Selection.activeGameObject = LoggerInstance.gameObject; } EditorGUILayout.EndHorizontal(); Repaint(); } } }
using UnityEngine; using UnityEditor; using System; using System.Collections; namespace mLogger { public class LoggerWindow : EditorWindow { private Logger loggerInstance; public Logger LoggerInstance { get { if (loggerInstance == null) { loggerInstance = FindObjectOfType<Logger>(); if (loggerInstance == null) { GameObject loggerGO = new GameObject(); loggerGO.AddComponent<Logger>(); loggerInstance = loggerGO.GetComponent<Logger>(); } } return loggerInstance; } } [MenuItem("Window/mLogger")] public static void Init() { LoggerWindow window = (LoggerWindow)EditorWindow.GetWindow(typeof(LoggerWindow)); window.title = "Logger"; window.minSize = new Vector2(100f, 60f); } private void OnGUI() { EditorGUILayout.BeginHorizontal(); // Draw Start/Stop button. LoggerInstance.LoggingEnabled = InspectorControls.DrawStartStopButton( LoggerInstance.LoggingEnabled, LoggerInstance.EnableOnPlay, null, () => LoggerInstance.LogWriter.Add("[PAUSE]", true), () => LoggerInstance.LogWriter.WriteAll( LoggerInstance.FilePath, false)); // Draw -> button. if (GUILayout.Button("->", GUILayout.Width(30))) { EditorGUIUtility.PingObject(LoggerInstance); Selection.activeGameObject = LoggerInstance.gameObject; } EditorGUILayout.EndHorizontal(); Repaint(); } } }
Remove Main()'s unused args parameter
using System; namespace Yeamul.Test { class Program { static void Main(string[] args) { Node nn = Node.Null; Console.WriteLine(nn); Node nbt = true; Console.WriteLine(nbt); Node nbf = false; Console.WriteLine(nbf); Node n16 = short.MinValue; Console.WriteLine(n16); Node n32 = int.MinValue; Console.WriteLine(n32); Node n64 = long.MinValue; Console.WriteLine(n64); Node nu16 = ushort.MaxValue; Console.WriteLine(nu16); Node nu32 = uint.MaxValue; Console.WriteLine(nu32); Node nu64 = ulong.MaxValue; Console.WriteLine(nu64); Node nf = 1.2f; Console.WriteLine(nf); Node nd = Math.PI; Console.WriteLine(nd); Node nm = 1.2345678901234567890m; Console.WriteLine(nm); Node ng = Guid.NewGuid(); Console.WriteLine(ng); Node ns = "derp"; Console.WriteLine(ns); Console.ReadKey(); } } }
using System; namespace Yeamul.Test { class Program { static void Main() { Node nn = Node.Null; Console.WriteLine(nn); Node nbt = true; Console.WriteLine(nbt); Node nbf = false; Console.WriteLine(nbf); Node n16 = short.MinValue; Console.WriteLine(n16); Node n32 = int.MinValue; Console.WriteLine(n32); Node n64 = long.MinValue; Console.WriteLine(n64); Node nu16 = ushort.MaxValue; Console.WriteLine(nu16); Node nu32 = uint.MaxValue; Console.WriteLine(nu32); Node nu64 = ulong.MaxValue; Console.WriteLine(nu64); Node nf = 1.2f; Console.WriteLine(nf); Node nd = Math.PI; Console.WriteLine(nd); Node nm = 1.2345678901234567890m; Console.WriteLine(nm); Node ng = Guid.NewGuid(); Console.WriteLine(ng); Node ns = "derp"; Console.WriteLine(ns); Console.ReadKey(); } } }
Add test for autor properties
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace LivrariaTest { [TestClass] public class AutorTest { [TestMethod] public void TestMethod1() { Assert.AreEqual(true, true); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Livraria; namespace LivrariaTest { [TestClass] public class AutorTest { [TestMethod] public void TestProperties() { Autor autor = new Autor(); autor.CodAutor = 999; autor.Nome = "George R. R. Martin"; autor.Cpf = "012.345.678.90"; autor.DtNascimento = new DateTime(1948, 9, 20); Assert.AreEqual(autor.CodAutor, 999); Assert.AreEqual(autor.Nome, "George R. R. Martin"); Assert.AreEqual(autor.Cpf, "012.345.678.90"); Assert.AreEqual<DateTime>(autor.DtNascimento, new DateTime(1948, 9, 20)); } } }
Use graying rather than alpha
// 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.Framework.Graphics.UserInterface; using osu.Framework.Input.Events; namespace osu.Game.Screens.Multi.Components { public abstract class DisableableTabControl<T> : TabControl<T> { public readonly BindableBool ReadOnly = new BindableBool(); protected override void AddTabItem(TabItem<T> tab, bool addToDropdown = true) { if (tab is DisableableTabItem<T> disableable) disableable.ReadOnly.BindTo(ReadOnly); base.AddTabItem(tab, addToDropdown); } protected abstract class DisableableTabItem<T> : TabItem<T> { public readonly BindableBool ReadOnly = new BindableBool(); protected DisableableTabItem(T value) : base(value) { ReadOnly.BindValueChanged(updateReadOnly); } private void updateReadOnly(bool readOnly) { Alpha = readOnly ? 0.2f : 1; } protected override bool OnClick(ClickEvent e) { if (ReadOnly) return true; return base.OnClick(e); } } } }
// 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.Framework.Graphics.UserInterface; using osu.Framework.Input.Events; using osuTK.Graphics; namespace osu.Game.Screens.Multi.Components { public abstract class DisableableTabControl<T> : TabControl<T> { public readonly BindableBool ReadOnly = new BindableBool(); protected override void AddTabItem(TabItem<T> tab, bool addToDropdown = true) { if (tab is DisableableTabItem<T> disableable) disableable.ReadOnly.BindTo(ReadOnly); base.AddTabItem(tab, addToDropdown); } protected abstract class DisableableTabItem<T> : TabItem<T> { public readonly BindableBool ReadOnly = new BindableBool(); protected DisableableTabItem(T value) : base(value) { ReadOnly.BindValueChanged(updateReadOnly); } private void updateReadOnly(bool readOnly) { Colour = readOnly ? Color4.Gray : Color4.White; } protected override bool OnClick(ClickEvent e) { if (ReadOnly) return true; return base.OnClick(e); } } } }
Use OpenTK triangle sample in OpenTkApp project
using System; namespace OpenTkApp { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
using System; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTK.Input; namespace OpenTkApp { class Game : GameWindow { public Game() : base(800, 600, GraphicsMode.Default, "OpenTK Quick Start Sample") { VSync = VSyncMode.On; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); GL.ClearColor(0.1f, 0.2f, 0.5f, 0.0f); GL.Enable(EnableCap.DepthTest); } protected override void OnResize(EventArgs e) { base.OnResize(e); GL.Viewport(ClientRectangle.X, ClientRectangle.Y, ClientRectangle.Width, ClientRectangle.Height); Matrix4 projection = Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, Width / (float)Height, 1.0f, 64.0f); GL.MatrixMode(MatrixMode.Projection); GL.LoadMatrix(ref projection); } protected override void OnUpdateFrame(FrameEventArgs e) { base.OnUpdateFrame(e); if (Keyboard[Key.Escape]) Exit(); } protected override void OnRenderFrame(FrameEventArgs e) { base.OnRenderFrame(e); GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); Matrix4 modelview = Matrix4.LookAt(Vector3.Zero, Vector3.UnitZ, Vector3.UnitY); GL.MatrixMode(MatrixMode.Modelview); GL.LoadMatrix(ref modelview); GL.Begin(BeginMode.Triangles); GL.Color3(1.0f, 1.0f, 0.0f); GL.Vertex3(-1.0f, -1.0f, 4.0f); GL.Color3(1.0f, 0.0f, 0.0f); GL.Vertex3(1.0f, -1.0f, 4.0f); GL.Color3(0.2f, 0.9f, 1.0f); GL.Vertex3(0.0f, 1.0f, 4.0f); GL.End(); SwapBuffers(); } } class Program { [STAThread] static void Main(string[] args) { using (Game game = new Game()) { game.Run(30.0); } } } }
Mark WinApiNet assembly as not CLS-compliant
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="WinAPI.NET"> // Copyright (c) Marek Dzikiewicz, All Rights Reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; 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("WinApiNet")] [assembly: AssemblyDescription("")] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("01efe7d3-2f81-420a-9ba7-290c1d5554e4")] // Assembly is CLS-compliant [assembly: CLSCompliant(true)]
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="WinAPI.NET"> // Copyright (c) Marek Dzikiewicz, All Rights Reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; 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("WinApiNet")] [assembly: AssemblyDescription("")] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("01efe7d3-2f81-420a-9ba7-290c1d5554e4")] // Assembly is not CLS-compliant [assembly: CLSCompliant(false)]
Set property store before creating the root collection to make the property store available for some internal file hiding logic
// <copyright file="DotNetFileSystem.cs" company="Fubar Development Junker"> // Copyright (c) Fubar Development Junker. All rights reserved. // </copyright> using System; using System.IO; using System.Threading; using System.Threading.Tasks; using FubarDev.WebDavServer.Props.Store; using Microsoft.VisualStudio.Threading; namespace FubarDev.WebDavServer.FileSystem.DotNet { public class DotNetFileSystem : ILocalFileSystem { private readonly PathTraversalEngine _pathTraversalEngine; public DotNetFileSystem(DotNetFileSystemOptions options, string rootFolder, PathTraversalEngine pathTraversalEngine, IPropertyStoreFactory propertyStoreFactory = null) { RootDirectoryPath = rootFolder; _pathTraversalEngine = pathTraversalEngine; var rootDir = new DotNetDirectory(this, null, new DirectoryInfo(rootFolder), new Uri(string.Empty, UriKind.Relative)); Root = new AsyncLazy<ICollection>(() => Task.FromResult<ICollection>(rootDir)); Options = options; PropertyStore = propertyStoreFactory?.Create(this); } public string RootDirectoryPath { get; } public AsyncLazy<ICollection> Root { get; } public DotNetFileSystemOptions Options { get; } public IPropertyStore PropertyStore { get; } public Task<SelectionResult> SelectAsync(string path, CancellationToken ct) { return _pathTraversalEngine.TraverseAsync(this, path, ct); } } }
// <copyright file="DotNetFileSystem.cs" company="Fubar Development Junker"> // Copyright (c) Fubar Development Junker. All rights reserved. // </copyright> using System; using System.IO; using System.Threading; using System.Threading.Tasks; using FubarDev.WebDavServer.Props.Store; using Microsoft.VisualStudio.Threading; namespace FubarDev.WebDavServer.FileSystem.DotNet { public class DotNetFileSystem : ILocalFileSystem { private readonly PathTraversalEngine _pathTraversalEngine; public DotNetFileSystem(DotNetFileSystemOptions options, string rootFolder, PathTraversalEngine pathTraversalEngine, IPropertyStoreFactory propertyStoreFactory = null) { RootDirectoryPath = rootFolder; _pathTraversalEngine = pathTraversalEngine; Options = options; PropertyStore = propertyStoreFactory?.Create(this); var rootDir = new DotNetDirectory(this, null, new DirectoryInfo(rootFolder), new Uri(string.Empty, UriKind.Relative)); Root = new AsyncLazy<ICollection>(() => Task.FromResult<ICollection>(rootDir)); } public string RootDirectoryPath { get; } public AsyncLazy<ICollection> Root { get; } public DotNetFileSystemOptions Options { get; } public IPropertyStore PropertyStore { get; } public Task<SelectionResult> SelectAsync(string path, CancellationToken ct) { return _pathTraversalEngine.TraverseAsync(this, path, ct); } } }
Make Compose a non-extension method
using System; namespace Sharper.C.Data { using static UnitModule; public static class FunctionModule { public static Func<A, B> Fun<A, B>(Func<A, B> f) => f; public static Func<A, Unit> Fun<A>(Action<A> f) => ToFunc(f); public static Action<A> Act<A>(Action<A> f) => f; public static A Id<A>(A a) => a; public static Func<B, A> Const<A, B>(A a) => b => a; public static Func<B, A, C> Flip<A, B, C>(Func<A, B, C> f) => (b, a) => f(a, b); public static Func<A, C> Compose<A, B, C>(this Func<B, C> f, Func<A, B> g) => a => f(g(a)); public static Func<A, C> Then<A, B, C>(this Func<A, B> f, Func<B, C> g) => a => g(f(a)); public static Func<A, Func<B, C>> Curry<A, B, C>(Func<A, B, C> f) => a => b => f(a, b); public static Func<A, B, C> Uncurry<A, B, C>(Func<A, Func<B, C>> f) => (a, b) => f(a)(b); } }
using System; namespace Sharper.C.Data { using static UnitModule; public static class FunctionModule { public static Func<A, B> Fun<A, B>(Func<A, B> f) => f; public static Func<A, Unit> Fun<A>(Action<A> f) => ToFunc(f); public static Action<A> Act<A>(Action<A> f) => f; public static A Id<A>(A a) => a; public static Func<B, A> Const<A, B>(A a) => b => a; public static Func<B, A, C> Flip<A, B, C>(Func<A, B, C> f) => (b, a) => f(a, b); public static Func<A, C> Compose<A, B, C>(Func<B, C> f, Func<A, B> g) => a => f(g(a)); public static Func<A, C> Then<A, B, C>(this Func<A, B> f, Func<B, C> g) => a => g(f(a)); public static Func<A, Func<B, C>> Curry<A, B, C>(Func<A, B, C> f) => a => b => f(a, b); public static Func<A, B, C> Uncurry<A, B, C>(Func<A, Func<B, C>> f) => (a, b) => f(a)(b); } }
Fix travis/mono by remove SUO
using Autofac; using SceneJect.Autofac; using SceneJect.Common; using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace SceneJect.Autofac { public class AutofacServiceAdapter : ContainerServiceProvider, IResolver, IServiceRegister { private readonly AutofacRegisterationStrat registerationStrat = new AutofacRegisterationStrat(new ContainerBuilder()); public override IServiceRegister Registry { get { return registerationStrat; } } private IResolver resolver = null; public override IResolver Resolver { get { return GenerateResolver(); } } private readonly object syncObj = new object(); private IResolver GenerateResolver() { if(resolver == null) { //double check locking lock(syncObj) if (resolver == null) resolver = new AutofacResolverStrat(registerationStrat.Build()); } return resolver; } } }
using Autofac; using SceneJect.Common; using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace SceneJect.Autofac { public class AutofacServiceAdapter : ContainerServiceProvider, IResolver, IServiceRegister { private readonly AutofacRegisterationStrat registerationStrat = new AutofacRegisterationStrat(new ContainerBuilder()); public override IServiceRegister Registry { get { return registerationStrat; } } private IResolver resolver = null; public override IResolver Resolver { get { return GenerateResolver(); } } private readonly object syncObj = new object(); private IResolver GenerateResolver() { if(resolver == null) { //double check locking lock(syncObj) if (resolver == null) resolver = new AutofacResolverStrat(registerationStrat.Build()); } return resolver; } } }
Correct in order not to use "Wait" method for synchronized method
using System.IO; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.CSharp.Scripting; namespace UserInputMacro { static class ScriptExecuter { public static async Task ExecuteAsync( string scriptPath ) { using( var hook = new UserInputHook() ) { HookSetting( hook ); var script = CSharpScript.Create( File.ReadAllText( scriptPath ), ScriptOptions.Default, typeof( MacroScript ) ); await script.RunAsync( new MacroScript() ); } } private static void LoggingMouseMacro( MouseHookStruct mouseHookStr, int mouseEvent ) { if( CommonUtil.CheckMode( ModeKind.CreateLog ) ) { Logger.WriteMouseEvent( mouseHookStr, ( MouseHookEvent ) mouseEvent ); } } private static void LoggingKeyMacro( KeyHookStruct keyHookStr, int keyEvent ) { if( CommonUtil.CheckMode( ModeKind.CreateLog ) ) { Logger.WriteKeyEventAsync( keyHookStr, ( KeyHookEvent ) keyEvent ).Wait(); } } private static void HookSetting( UserInputHook hook ) { hook.MouseHook = LoggingMouseMacro; hook.KeyHook = LoggingKeyMacro; hook.HookErrorProc = CommonUtil.HandleException; hook.RegisterKeyHook(); hook.RegisterMouseHook(); } } }
using System.IO; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.CSharp.Scripting; namespace UserInputMacro { static class ScriptExecuter { public static async Task ExecuteAsync( string scriptPath ) { using( var hook = new UserInputHook() ) { HookSetting( hook ); var script = CSharpScript.Create( File.ReadAllText( scriptPath ), ScriptOptions.Default, typeof( MacroScript ) ); await script.RunAsync( new MacroScript() ); } } private static void LoggingMouseMacro( MouseHookStruct mouseHookStr, int mouseEvent ) { if( CommonUtil.CheckMode( ModeKind.CreateLog ) ) { Logger.WriteMouseEvent( mouseHookStr, ( MouseHookEvent ) mouseEvent ); } } private static void LoggingKeyMacro( KeyHookStruct keyHookStr, int keyEvent ) { if( CommonUtil.CheckMode( ModeKind.CreateLog ) ) { Logger.WriteKeyEvent( keyHookStr, ( KeyHookEvent ) keyEvent ); } } private static void HookSetting( UserInputHook hook ) { hook.MouseHook = LoggingMouseMacro; hook.KeyHook = LoggingKeyMacro; hook.HookErrorProc = CommonUtil.HandleException; hook.RegisterKeyHook(); hook.RegisterMouseHook(); } } }
Validate data in the ctors
namespace ElectronicCash { public struct ActorName { private readonly string _firstName; private readonly string _middleName; private readonly string _lastName; private readonly string _title; private readonly string _entityName; public ActorName(string firstName, string middleName, string lastName, string title) { _firstName = firstName; _middleName = middleName; _lastName = lastName; _title = title; _entityName = null; } public ActorName(string entityName) { _firstName = null; _middleName = null; _lastName = null; _title = null; _entityName = entityName; } public string FirstName => _firstName; public string MiddleName => _middleName; public string LastName => _lastName; public string Title => _title; public string EntityName => _entityName; } }
using System; namespace ElectronicCash { public struct ActorName { private readonly string _firstName; private readonly string _middleName; private readonly string _lastName; private readonly string _title; private readonly string _entityName; public ActorName(string firstName, string middleName, string lastName, string title) { if (string.IsNullOrEmpty(firstName)) { throw new ArgumentException("First name must not be empty"); } if (string.IsNullOrEmpty(middleName)) { throw new ArgumentException("Middle name must not be empty"); } if (string.IsNullOrEmpty(lastName)) { throw new ArgumentException("Last name must not be empty"); } _firstName = firstName; _middleName = middleName; _lastName = lastName; _title = title; _entityName = null; } public ActorName(string entityName) { if (string.IsNullOrEmpty(entityName)) { throw new ArgumentException("Entity name must be provided"); } _firstName = null; _middleName = null; _lastName = null; _title = null; _entityName = entityName; } public string FirstName => _firstName; public string MiddleName => _middleName; public string LastName => _lastName; public string Title => _title; public string EntityName => _entityName; } }
Improve time service interface documentation
// Copyright (c) MarinAtanasov. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the project root for license information. // using System; namespace AppBrix.Time { /// <summary> /// Service which operates with <see cref="DateTime"/>. /// </summary> public interface ITimeService { /// <summary> /// Gets the current time. /// This should be used instead of DateTime.Now or DateTime.UtcNow. /// </summary> /// <returns></returns> DateTime GetTime(); /// <summary> /// Converts the specified time to the configured application time kind. /// </summary> /// <param name="time">The specified time.</param> /// <returns>The converted time.</returns> DateTime ToAppTime(DateTime time); /// <summary> /// Converts a given <see cref="DateTime"/> to a predefined <see cref="string"/> representation. /// </summary> /// <param name="time">The time.</param> /// <returns>The string representation of the time.</returns> string ToString(DateTime time); /// <summary> /// Converts a given <see cref="string"/> to a <see cref="DateTime"/> in a system time kind. /// </summary> /// <param name="time"></param> /// <returns></returns> DateTime ToDateTime(string time); } }
// Copyright (c) MarinAtanasov. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the project root for license information. // using System; namespace AppBrix.Time { /// <summary> /// Service which operates with <see cref="DateTime"/>. /// </summary> public interface ITimeService { /// <summary> /// Gets the current time. /// This should be used instead of <see cref="DateTime.Now"/> or <see cref="DateTime.UtcNow"/>. /// </summary> /// <returns>The current date and time.</returns> DateTime GetTime(); /// <summary> /// Converts the specified time to the configured application <see cref="DateTimeKind"/>. /// </summary> /// <param name="time">The specified time.</param> /// <returns>The converted time.</returns> DateTime ToAppTime(DateTime time); /// <summary> /// Converts a given <see cref="DateTime"/> to a predefined <see cref="string"/> representation. /// </summary> /// <param name="time">The time.</param> /// <returns>The string representation of the time.</returns> string ToString(DateTime time); /// <summary> /// Converts a given <see cref="string"/> to a <see cref="DateTime"/> in the configured <see cref="DateTimeKind"/>. /// </summary> /// <param name="time">The date and time in string representation.</param> /// <returns>The date and time.</returns> DateTime ToDateTime(string time); } }
Improve how the link is made and page is cached
using ToSic.Razor.Blade; // todo: change to use Get public class Links : Custom.Hybrid.Code12 { // Returns a safe url to a post details page public dynamic LinkToDetailsPage(dynamic post) { var detailsPageTabId = Text.Has(Settings.DetailsPage) ? int.Parse((AsEntity(App.Settings).GetBestValue("DetailsPage")).Split(':')[1]) : CmsContext.Page.Id; return Link.To(pageId: detailsPageTabId, parameters: "details=" + post.UrlKey); } }
using ToSic.Razor.Blade; public class Links : Custom.Hybrid.Code12 { /// <Summary> /// Returns a safe url to a post details page /// </Summary> public dynamic LinkToDetailsPage(dynamic post) { return Link.To(pageId: DetailsPageId, parameters: "details=" + post.UrlKey); } /// <Summary> /// Get / cache the page which will show the details of a post /// </Summary> private int DetailsPageId { get { if (_detailsPageId != 0) return _detailsPageId; if (Text.Has(Settings.DetailsPage)) _detailsPageId = int.Parse((App.Settings.Get("DetailsPage", convertLinks: false)).Split(':')[1]); else _detailsPageId = CmsContext.Page.Id; return _detailsPageId; } } private int _detailsPageId; }
Use the correct call to FunctionNameHelper
#load "LogHelper.csx" #load "FunctionNameHelper.csx" using System.Configuration; public static class AppSettingsHelper { public static string GetAppSetting(string SettingName, bool LogValue = true ) { string SettingValue = ""; string methodName = this.GetType().FullName; try { SettingValue = ConfigurationManager.AppSettings[SettingName].ToString(); if ((!String.IsNullOrEmpty(SettingValue)) && LogValue) { LogHelper.Info($"{FunctionnameHelper} {GetFunctionName()} {methodName} Retreived AppSetting {SettingName} with a value of {SettingValue}"); } else if((!String.IsNullOrEmpty(SettingValue)) && !LogValue) { LogHelper.Info($"{FunctionnameHelper} {methodName} Retreived AppSetting {SettingName} but logging value was turned off"); } else if(!String.IsNullOrEmpty(SettingValue)) { LogHelper.Info($"{FunctionnameHelper} {methodName} AppSetting {SettingName} was null or empty"); } } catch (ConfigurationErrorsException ex) { LogHelper.Error($"{FunctionnameHelper} {methodName} Unable to find AppSetting {SettingName} with exception of {ex.Message}"); } catch (System.Exception ex) { LogHelper.Error($"{FunctionnameHelper} {methodName} Looking for AppSetting {SettingName} caused an exception of {ex.Message}"); } return SettingValue; } }
#load "LogHelper.csx" #load "FunctionNameHelper.csx" using System.Configuration; public static class AppSettingsHelper { public static string GetAppSetting(string SettingName, bool LogValue = true ) { string SettingValue = ""; string methodName = this.GetType().FullName; try { SettingValue = ConfigurationManager.AppSettings[SettingName].ToString(); if ((!String.IsNullOrEmpty(SettingValue)) && LogValue) { LogHelper.Info($"{FunctionnameHelper.GetFunctionName()} {GetFunctionName()} {methodName} Retreived AppSetting {SettingName} with a value of {SettingValue}"); } else if((!String.IsNullOrEmpty(SettingValue)) && !LogValue) { LogHelper.Info($"{FunctionnameHelper.GetFunctionName()} {methodName} Retreived AppSetting {SettingName} but logging value was turned off"); } else if(!String.IsNullOrEmpty(SettingValue)) { LogHelper.Info($"{FunctionnameHelper.GetFunctionName()} {methodName} AppSetting {SettingName} was null or empty"); } } catch (ConfigurationErrorsException ex) { LogHelper.Error($"{FunctionnameHelper.GetFunctionName()} {methodName} Unable to find AppSetting {SettingName} with exception of {ex.Message}"); } catch (System.Exception ex) { LogHelper.Error($"{FunctionnameHelper.GetFunctionName()} {methodName} Looking for AppSetting {SettingName} caused an exception of {ex.Message}"); } return SettingValue; } }
Change aliasing of Modded Showdown Import
namespace PKHeX.WinForms { partial class Main { public System.Windows.Forms.ToolStripMenuItem EnableAutoLegality(System.ComponentModel.ComponentResourceManager resources) { this.Menu_ShowdownImportPKMModded = new System.Windows.Forms.ToolStripMenuItem(); this.Menu_ShowdownImportPKMModded.Image = ((System.Drawing.Image)(resources.GetObject("Menu_ShowdownImportPKM.Image"))); this.Menu_ShowdownImportPKMModded.Name = "Menu_ShowdownImportPKMModded"; this.Menu_ShowdownImportPKMModded.Size = new System.Drawing.Size(231, 22); this.Menu_ShowdownImportPKMModded.Text = "Modded Showdown Import"; this.Menu_ShowdownImportPKMModded.Click += new System.EventHandler(this.ClickShowdownImportPKMModded); return this.Menu_ShowdownImportPKMModded; } private System.Windows.Forms.ToolStripMenuItem Menu_ShowdownImportPKMModded; } }
namespace PKHeX.WinForms { partial class Main { public System.Windows.Forms.ToolStripMenuItem EnableAutoLegality(System.ComponentModel.ComponentResourceManager resources) { this.Menu_ShowdownImportPKMModded = new System.Windows.Forms.ToolStripMenuItem(); this.Menu_ShowdownImportPKMModded.Image = ((System.Drawing.Image)(resources.GetObject("Menu_ShowdownImportPKM.Image"))); this.Menu_ShowdownImportPKMModded.Name = "Menu_ShowdownImportPKMModded"; this.Menu_ShowdownImportPKMModded.Size = new System.Drawing.Size(231, 22); this.Menu_ShowdownImportPKMModded.Text = "Import with Auto-Legality Mod"; this.Menu_ShowdownImportPKMModded.Click += new System.EventHandler(this.ClickShowdownImportPKMModded); return this.Menu_ShowdownImportPKMModded; } private System.Windows.Forms.ToolStripMenuItem Menu_ShowdownImportPKMModded; } }
Fix S3 create bucket test
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using FluentAssertions; using NuGet.Test.Helpers; using Sleet.Test.Common; namespace Sleet.AmazonS3.Tests { public class AmazonS3FileSystemTests { [EnvVarExistsFact(AmazonS3TestContext.EnvAccessKeyId)] public async Task GivenAS3AccountVerifyBucketOperations() { using (var testContext = new AmazonS3TestContext()) { testContext.CreateBucketOnInit = false; await testContext.InitAsync(); // Verify at the start (await testContext.FileSystem.HasBucket(testContext.Logger, CancellationToken.None)).Should().BeFalse(); (await testContext.FileSystem.Validate(testContext.Logger, CancellationToken.None)).Should().BeFalse(); // Create await testContext.FileSystem.CreateBucket(testContext.Logger, CancellationToken.None); (await testContext.FileSystem.HasBucket(testContext.Logger, CancellationToken.None)).Should().BeTrue(); (await testContext.FileSystem.Validate(testContext.Logger, CancellationToken.None)).Should().BeTrue(); // Delete await testContext.FileSystem.DeleteBucket(testContext.Logger, CancellationToken.None); (await testContext.FileSystem.HasBucket(testContext.Logger, CancellationToken.None)).Should().BeFalse(); (await testContext.FileSystem.Validate(testContext.Logger, CancellationToken.None)).Should().BeFalse(); await testContext.CleanupAsync(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using FluentAssertions; using NuGet.Test.Helpers; using Sleet.Test.Common; namespace Sleet.AmazonS3.Tests { public class AmazonS3FileSystemTests { [EnvVarExistsFact(AmazonS3TestContext.EnvAccessKeyId)] public async Task GivenAS3AccountVerifyBucketOperations() { using (var testContext = new AmazonS3TestContext()) { testContext.CreateBucketOnInit = false; await testContext.InitAsync(); // Verify at the start (await testContext.FileSystem.HasBucket(testContext.Logger, CancellationToken.None)).Should().BeFalse(); (await testContext.FileSystem.Validate(testContext.Logger, CancellationToken.None)).Should().BeFalse(); // Create await testContext.FileSystem.CreateBucket(testContext.Logger, CancellationToken.None); (await testContext.FileSystem.HasBucket(testContext.Logger, CancellationToken.None)).Should().BeTrue(); (await testContext.FileSystem.Validate(testContext.Logger, CancellationToken.None)).Should().BeTrue(); await testContext.CleanupAsync(); } } } }
Trim end of post on Save. Incase someone hits enter loads and then blows the size of the page. This will stop that.
using NGM.Forum.Models; namespace NGM.Forum.ViewModels { public class PostBodyEditorViewModel { public PostPart PostPart { get; set; } public string Text { get { return PostPart.Record.Text; } set { PostPart.Record.Text = value; } } public string Format { get { return PostPart.Record.Format; } set { PostPart.Record.Format = value; } } public string EditorFlavor { get; set; } } }
using NGM.Forum.Models; namespace NGM.Forum.ViewModels { public class PostBodyEditorViewModel { public PostPart PostPart { get; set; } public string Text { get { return PostPart.Record.Text; } set { PostPart.Record.Text = string.IsNullOrWhiteSpace(value) ? value : value.TrimEnd(); } } public string Format { get { return PostPart.Record.Format; } set { PostPart.Record.Format = value; } } public string EditorFlavor { get; set; } } }
Fix if httpContext is null we cannot wrap it
using System; using System.Web; namespace Umbraco.Web { internal class AspNetHttpContextAccessor : IHttpContextAccessor { public HttpContextBase HttpContext { get { return new HttpContextWrapper(System.Web.HttpContext.Current); } set { throw new NotSupportedException(); } } } }
using System; using System.Web; namespace Umbraco.Web { internal class AspNetHttpContextAccessor : IHttpContextAccessor { public HttpContextBase HttpContext { get { var httpContext = System.Web.HttpContext.Current; return httpContext is null ? null : new HttpContextWrapper(httpContext); } set { throw new NotSupportedException(); } } } }
Add message inside this class to convey exception
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Web; namespace ADWS.Models { [DataContract] public class UserInfoResponse { [DataMember] public string Title { set; get; } [DataMember] public string DisplayName { set; get; } [DataMember] public string FirstName { set; get; } [DataMember] public string LastName { set; get; } [DataMember] public string SamAccountName { set; get; } [DataMember] public string Upn { set; get; } [DataMember] public string EmailAddress { set; get; } [DataMember] public string EmployeeId { set; get; } [DataMember] public string Department { set; get; } [DataMember] public string BusinessPhone { get; set; } [DataMember] public string Telephone { get; set; } [DataMember] public string SipAccount { set; get; } [DataMember] public string PrimaryHomeServerDn { get; set; } [DataMember] public string PoolName { set; get; } [DataMember] public string PhysicalDeliveryOfficeName { set; get; } [DataMember] public string OtherTelphone { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Web; namespace ADWS.Models { [DataContract] public class UserInfoResponse { [DataMember] public string Title { set; get; } [DataMember] public string DisplayName { set; get; } [DataMember] public string FirstName { set; get; } [DataMember] public string LastName { set; get; } [DataMember] public string SamAccountName { set; get; } [DataMember] public string Upn { set; get; } [DataMember] public string EmailAddress { set; get; } [DataMember] public string EmployeeId { set; get; } [DataMember] public string Department { set; get; } [DataMember] public string BusinessPhone { get; set; } [DataMember] public string Telephone { get; set; } [DataMember] public string SipAccount { set; get; } [DataMember] public string PrimaryHomeServerDn { get; set; } [DataMember] public string PoolName { set; get; } [DataMember] public string PhysicalDeliveryOfficeName { set; get; } [DataMember] public string OtherTelphone { get; set; } [DataMember] public string Message { get; set; } } }
Add log for audit api
using System; using System.Threading.Tasks; using MediatR; using NLog; using SFA.DAS.EmployerUsers.Application.Commands.DeleteUser; using SFA.DAS.EmployerUsers.Application.Queries.GetUsersWithExpiredRegistrations; namespace SFA.DAS.EmployerUsers.RegistrationTidyUpJob.RegistrationManagement { public class RegistrationManager { private readonly IMediator _mediator; private readonly ILogger _logger; public RegistrationManager(IMediator mediator, ILogger logger) { _mediator = mediator; _logger = logger; } public async Task RemoveExpiredRegistrations() { _logger.Info("Starting deletion of expired registrations"); try { var users = await _mediator.SendAsync(new GetUsersWithExpiredRegistrationsQuery()); _logger.Info($"Found {users.Length} users with expired registrations"); foreach (var user in users) { _logger.Info($"Deleting user with email '{user.Email}' (id: '{user.Id}')"); await _mediator.SendAsync(new DeleteUserCommand { User = user }); } } catch (Exception ex) { _logger.Error(ex); throw; } _logger.Info("Finished deletion of expired registrations"); } } }
using System; using System.Threading.Tasks; using MediatR; using Microsoft.Azure; using NLog; using SFA.DAS.EmployerUsers.Application.Commands.DeleteUser; using SFA.DAS.EmployerUsers.Application.Queries.GetUsersWithExpiredRegistrations; namespace SFA.DAS.EmployerUsers.RegistrationTidyUpJob.RegistrationManagement { public class RegistrationManager { private readonly IMediator _mediator; private readonly ILogger _logger; public RegistrationManager(IMediator mediator, ILogger logger) { _mediator = mediator; _logger = logger; } public async Task RemoveExpiredRegistrations() { _logger.Info("Starting deletion of expired registrations"); _logger.Info($"AuditApiBaseUrl: {CloudConfigurationManager.GetSetting("AuditApiBaseUrl")}"); try { var users = await _mediator.SendAsync(new GetUsersWithExpiredRegistrationsQuery()); _logger.Info($"Found {users.Length} users with expired registrations"); foreach (var user in users) { _logger.Info($"Deleting user with email '{user.Email}' (id: '{user.Id}')"); await _mediator.SendAsync(new DeleteUserCommand { User = user }); } } catch (Exception ex) { _logger.Error(ex); throw; } _logger.Info("Finished deletion of expired registrations"); } } }
Move https redirection above basic auth
using System; using System.IO; using hutel.Filters; using hutel.Middleware; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace server { public class Startup { private const string _envUseBasicAuth = "HUTEL_USE_BASIC_AUTH"; // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services .AddMvc() .AddJsonOptions(opt => { opt.SerializerSettings.DateParseHandling = DateParseHandling.None; }); services.AddScoped<ValidateModelStateAttribute>(); services.AddMemoryCache(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(LogLevel.Trace); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } if (Environment.GetEnvironmentVariable(_envUseBasicAuth) == "1") { app.UseBasicAuthMiddleware(); } app.UseRedirectToHttpsMiddleware(); app.UseMvc(); app.UseStaticFiles(); } } }
using System; using System.IO; using hutel.Filters; using hutel.Middleware; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace server { public class Startup { private const string _envUseBasicAuth = "HUTEL_USE_BASIC_AUTH"; // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services .AddMvc() .AddJsonOptions(opt => { opt.SerializerSettings.DateParseHandling = DateParseHandling.None; }); services.AddScoped<ValidateModelStateAttribute>(); services.AddMemoryCache(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(LogLevel.Trace); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRedirectToHttpsMiddleware(); if (Environment.GetEnvironmentVariable(_envUseBasicAuth) == "1") { app.UseBasicAuthMiddleware(); } app.UseMvc(); app.UseStaticFiles(); } } }
Fix formatting exception when script compilation fails with certain error messages
using System; namespace Casper { public class CasperException : Exception { public const int EXIT_CODE_COMPILATION_ERROR = 1; public const int EXIT_CODE_MISSING_TASK = 2; public const int EXIT_CODE_CONFIGURATION_ERROR = 3; public const int EXIT_CODE_TASK_FAILED = 4; public const int EXIT_CODE_UNHANDLED_EXCEPTION = 255; private readonly int exitCode; public CasperException(int exitCode, string message, params object[] args) : base(string.Format(message, args)) { this.exitCode = exitCode; } public CasperException(int exitCode, Exception innerException) : base(innerException.Message, innerException) { this.exitCode = exitCode; } public int ExitCode { get { return exitCode; } } } }
using System; namespace Casper { public class CasperException : Exception { public const int EXIT_CODE_COMPILATION_ERROR = 1; public const int EXIT_CODE_MISSING_TASK = 2; public const int EXIT_CODE_CONFIGURATION_ERROR = 3; public const int EXIT_CODE_TASK_FAILED = 4; public const int EXIT_CODE_UNHANDLED_EXCEPTION = 255; private readonly int exitCode; public CasperException(int exitCode, string message) : base(message) { this.exitCode = exitCode; } public CasperException(int exitCode, string message, params object[] args) : this(exitCode, string.Format(message, args)) { } public CasperException(int exitCode, Exception innerException) : base(innerException.Message, innerException) { this.exitCode = exitCode; } public int ExitCode { get { return exitCode; } } } }
Make the client request the RavenDB server version. If we don't do this the client doesn't appear to raise an exception in the case of a dead server so the health check will still return healthy.
using Raven.Abstractions.Data; using System; namespace Dotnet.Microservice.Health.Checks { public class RavenDbHealthCheck { public static HealthResponse CheckHealth(string connectionString) { try { ConnectionStringParser<RavenConnectionStringOptions> parser = ConnectionStringParser<RavenConnectionStringOptions>.FromConnectionString(connectionString); parser.Parse(); var store = new Raven.Client.Document.DocumentStore { Url = parser.ConnectionStringOptions.Url, DefaultDatabase = parser.ConnectionStringOptions.DefaultDatabase }; store.Initialize(); return HealthResponse.Healthy(new { server = store.Url, database = store.DefaultDatabase }); } catch (Exception ex) { return HealthResponse.Unhealthy(ex); } } } }
using Raven.Abstractions.Data; using System; namespace Dotnet.Microservice.Health.Checks { public class RavenDbHealthCheck { public static HealthResponse CheckHealth(string connectionString) { try { ConnectionStringParser<RavenConnectionStringOptions> parser = ConnectionStringParser<RavenConnectionStringOptions>.FromConnectionString(connectionString); parser.Parse(); var store = new Raven.Client.Document.DocumentStore { Url = parser.ConnectionStringOptions.Url, DefaultDatabase = parser.ConnectionStringOptions.DefaultDatabase }; store.Initialize(); // Client doesn't seem to throw an exception until we try to do something so let's just do something simple and get the build number of the server. var build = store.DatabaseCommands.GlobalAdmin.GetBuildNumber(); // Dispose the store object store.Dispose(); return HealthResponse.Healthy(new { server = store.Url, database = store.DefaultDatabase, serverBuild = build.BuildVersion }); } catch (Exception ex) { return HealthResponse.Unhealthy(ex); } } } }
Switch to new backup email recipient
using FluentEmail.Core; using FluentScheduler; using System; namespace BatteryCommander.Web.Jobs { public class SqliteBackupJob : IJob { private const String Recipient = "mattgwagner+backup@gmail.com"; // TODO Make this configurable private readonly IFluentEmail emailSvc; public SqliteBackupJob(IFluentEmail emailSvc) { this.emailSvc = emailSvc; } public virtual void Execute() { emailSvc .To(Recipient) .Subject("Nightly Db Backup") .Body("Please find the nightly database backup attached.") .Attach(new FluentEmail.Core.Models.Attachment { ContentType = "application/octet-stream", Filename = "Data.db", Data = System.IO.File.OpenRead("Data.db") }) .Send(); } } }
using FluentEmail.Core; using FluentScheduler; using System; namespace BatteryCommander.Web.Jobs { public class SqliteBackupJob : IJob { private const String Recipient = "Backups@RedLeg.app"; private readonly IFluentEmail emailSvc; public SqliteBackupJob(IFluentEmail emailSvc) { this.emailSvc = emailSvc; } public virtual void Execute() { emailSvc .To(Recipient) .Subject("Nightly Db Backup") .Body("Please find the nightly database backup attached.") .Attach(new FluentEmail.Core.Models.Attachment { ContentType = "application/octet-stream", Filename = "Data.db", Data = System.IO.File.OpenRead("Data.db") }) .Send(); } } }
Fix up how we generate debugging info for var simple.
using System; using LinqToTTreeInterfacesLib; using LINQToTTreeLib.Utils; namespace LINQToTTreeLib.Variables { /// <summary> /// A simple variable (like int, etc.). /// </summary> public class VarSimple : IVariable { public string VariableName { get; private set; } public string RawValue { get; private set; } public Type Type { get; private set; } public VarSimple(System.Type type) { if (type == null) throw new ArgumentNullException("Must have a good type!"); Type = type; VariableName = type.CreateUniqueVariableName(); RawValue = VariableName; Declare = false; } public IValue InitialValue { get; set; } /// <summary> /// Get/Set if this variable needs to be declared. /// </summary> public bool Declare { get; set; } /// <summary> /// TO help with debugging... /// </summary> /// <returns></returns> public override string ToString() { return VariableName + " = (" + Type.Name + ") " + RawValue; } public void RenameRawValue(string oldname, string newname) { if (InitialValue != null) InitialValue.RenameRawValue(oldname, newname); if (RawValue == oldname) { RawValue = newname; VariableName = newname; } } } }
using System; using LinqToTTreeInterfacesLib; using LINQToTTreeLib.Utils; namespace LINQToTTreeLib.Variables { /// <summary> /// A simple variable (like int, etc.). /// </summary> public class VarSimple : IVariable { public string VariableName { get; private set; } public string RawValue { get; private set; } public Type Type { get; private set; } public VarSimple(System.Type type) { if (type == null) throw new ArgumentNullException("Must have a good type!"); Type = type; VariableName = type.CreateUniqueVariableName(); RawValue = VariableName; Declare = false; } public IValue InitialValue { get; set; } /// <summary> /// Get/Set if this variable needs to be declared. /// </summary> public bool Declare { get; set; } /// <summary> /// TO help with debugging... /// </summary> /// <returns></returns> public override string ToString() { var s = string.Format("{0} {1}", Type.Name, VariableName); if (InitialValue != null) s = string.Format("{0} = {1}", s, InitialValue.RawValue); return s; } public void RenameRawValue(string oldname, string newname) { if (InitialValue != null) InitialValue.RenameRawValue(oldname, newname); if (RawValue == oldname) { RawValue = newname; VariableName = newname; } } } }
Add editor button to update build path
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; [CustomEditor(typeof(MicrogameCollection))] public class MicrogameCollectionEditor : Editor { public override void OnInspectorGUI() { MicrogameCollection collection = (MicrogameCollection)target; if (GUILayout.Button("Update Microgames")) { collection.updateMicrogames(); EditorUtility.SetDirty(collection); } DrawDefaultInspector(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; [CustomEditor(typeof(MicrogameCollection))] public class MicrogameCollectionEditor : Editor { public override void OnInspectorGUI() { MicrogameCollection collection = (MicrogameCollection)target; if (GUILayout.Button("Update Microgames")) { collection.updateMicrogames(); EditorUtility.SetDirty(collection); } if (GUILayout.Button("Update Build Path")) { collection.updateBuildPath(); EditorUtility.SetDirty(collection); } DrawDefaultInspector(); } }
Add square extension method to floats
using System; namespace DynamixelServo.Quadruped { static class MathExtensions { public static double RadToDegree(this double angle) { return angle * (180.0 / Math.PI); } public static float RadToDegree(this float angle) { return angle * (180f / (float)Math.PI); } public static double DegreeToRad(this double angle) { return Math.PI * angle / 180.0; } public static float DegreeToRad(this float angle) { return (float)Math.PI * angle / 180f; } public static double ToPower(this double number, double powerOf) { return Math.Pow(number, powerOf); } } }
using System; namespace DynamixelServo.Quadruped { static class MathExtensions { public static double RadToDegree(this double angle) { return angle * (180.0 / Math.PI); } public static float RadToDegree(this float angle) { return angle * (180f / (float)Math.PI); } public static double DegreeToRad(this double angle) { return Math.PI * angle / 180.0; } public static float DegreeToRad(this float angle) { return (float)Math.PI * angle / 180f; } public static double ToPower(this double number, double powerOf) { return Math.Pow(number, powerOf); } public static float Square(this float number) { return number * number; } } }
Order organization members by name.
@inherits Umbraco.Web.Mvc.UmbracoTemplatePage @{ Layout = "_Layout.cshtml"; } @{ Html.RenderPartial("PageHeading"); } <div class="row"> <div class="small-12 large-12 columns"> @{ var members = Umbraco.TypedContentAtXPath("//OrganizationMember") .Where(m => m.GetPropertyValue<string>("Position") != "Coach"); } <ul class="small-block-grid-2 medium-block-grid-4 large-block-grid-4"> @foreach (var item in members) { <li> <div class="panel-box"> <div class="row"> <div class="large-12 columns"> @if (item.HasValue("ProfilePhoto")) { <div class="img-container ratio-2-3"> <img src="@item.GetPropertyValue("ProfilePhoto")" /> </div> } <h5 class="text-center"> @item.GetPropertyValue("FirstName") @item.GetPropertyValue("LastName") </h5> @if (item.HasValue("HomeTown")) { <p class="text-center">@item.GetPropertyValue("HomeTown")</p> } </div> </div> </div> </li> } </ul> </div> </div>
@inherits Umbraco.Web.Mvc.UmbracoTemplatePage @{ Layout = "_Layout.cshtml"; } @{ Html.RenderPartial("PageHeading"); } <div class="row"> <div class="small-12 large-12 columns"> @{ var members = Umbraco.TypedContentAtXPath("//OrganizationMember") .Where(m => m.GetPropertyValue<string>("Position") != "Coach") .OrderBy(m => m.GetPropertyValue("LastName")) .ThenBy(m => m.GetPropertyValue("FirstName")); } <ul class="small-block-grid-2 medium-block-grid-4 large-block-grid-4"> @foreach (var item in members) { <li> <div class="panel-box"> <div class="row"> <div class="large-12 columns"> @if (item.HasValue("ProfilePhoto")) { <div class="img-container ratio-2-3"> <img src="@item.GetPropertyValue("ProfilePhoto")" /> </div> } <h5 class="text-center"> @item.GetPropertyValue("FirstName") @item.GetPropertyValue("LastName") </h5> @if (item.HasValue("HomeTown")) { <p class="text-center">@item.GetPropertyValue("HomeTown")</p> } </div> </div> </div> </li> } </ul> </div> </div>
Fix running on < iOS 6.0
using System; using MonoTouch.Foundation; using MonoTouch.UIKit; using Eto.Platform.iOS.Forms; using Eto.Forms; namespace Eto.Platform.iOS { [MonoTouch.Foundation.Register("EtoAppDelegate")] public class EtoAppDelegate : UIApplicationDelegate { public EtoAppDelegate () { } public override bool WillFinishLaunching (UIApplication application, NSDictionary launchOptions) { ApplicationHandler.Instance.Initialize(this); return true; } } }
using System; using MonoTouch.Foundation; using MonoTouch.UIKit; using Eto.Platform.iOS.Forms; using Eto.Forms; namespace Eto.Platform.iOS { [MonoTouch.Foundation.Register("EtoAppDelegate")] public class EtoAppDelegate : UIApplicationDelegate { public EtoAppDelegate () { } public override bool FinishedLaunching (UIApplication application, NSDictionary launcOptions) { ApplicationHandler.Instance.Initialize(this); return true; } } }
Add custom display option props based on sliders
using Newtonsoft.Json; namespace SurveyMonkey.Containers { [JsonConverter(typeof(TolerantJsonConverter))] public class QuestionDisplayOptionsCustomOptions { } }
using Newtonsoft.Json; using System.Collections.Generic; namespace SurveyMonkey.Containers { [JsonConverter(typeof(TolerantJsonConverter))] public class QuestionDisplayOptionsCustomOptions { public List<string> OptionSet { get; set; } public int StartingPosition { get; set; } public int StepSize { get; set; } } }
Convert all dates to UTC time
using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; namespace Presentation.Web { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); // Turns off self reference looping when serializing models in API controlllers GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // Support polymorphism in web api JSON output GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto; // Set JSON serialization in WEB API to use camelCase (javascript) instead of PascalCase (C#) GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); //Format datetime correctly. From: http://stackoverflow.com/questions/20143739/date-format-in-mvc-4-api-controller var dateTimeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }; GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings .Converters.Add(dateTimeConverter); } } }
using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Presentation.Web { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); // Turns off self reference looping when serializing models in API controlllers GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // Support polymorphism in web api JSON output GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto; // Set JSON serialization in WEB API to use camelCase (javascript) instead of PascalCase (C#) GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // Convert all dates to UTC GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc; } } }
Change ASN int array to IList
namespace BmpListener.Bgp { public class ASPathSegment { public ASPathSegment(Type type, int[] asns) { SegmentType = Type; ASNs = asns; } public enum Type { AS_SET = 1, AS_SEQUENCE, AS_CONFED_SEQUENCE, AS_CONFED_SET } public Type SegmentType { get; set; } public int[] ASNs { get; set; } } }
using System.Collections.Generic; namespace BmpListener.Bgp { public class ASPathSegment { public ASPathSegment(Type type, IList<int> asns) { SegmentType = type; ASNs = asns; } public enum Type { AS_SET = 1, AS_SEQUENCE, AS_CONFED_SEQUENCE, AS_CONFED_SET } public Type SegmentType { get; set; } public IList<int> ASNs { get; set; } } }
Bump assembly info for 1.2.2 release
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("SurveyMonkeyApi")] [assembly: AssemblyDescription("Library for accessing v2 of the Survey Monkey Api")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SurveyMonkeyApi")] [assembly: AssemblyCopyright("Copyright © Ben Emmett")] [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("da9e0373-83cd-4deb-87a5-62b313be61ec")] // 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.2.1.0")] [assembly: AssemblyFileVersion("1.2.1.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("SurveyMonkeyApi")] [assembly: AssemblyDescription("Library for accessing v2 of the Survey Monkey Api")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SurveyMonkeyApi")] [assembly: AssemblyCopyright("Copyright © Ben Emmett")] [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("da9e0373-83cd-4deb-87a5-62b313be61ec")] // 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.2.2.0")] [assembly: AssemblyFileVersion("1.2.2.0")]
Use inspector for child classes
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEditor; namespace Microsoft.MixedReality.Toolkit.Input.Editor { [CustomEditor(typeof(MixedRealityControllerVisualizer))] public class MixedRealityControllerVisualizerInspector : ControllerPoseSynchronizerInspector { } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEditor; namespace Microsoft.MixedReality.Toolkit.Input.Editor { [CustomEditor(typeof(MixedRealityControllerVisualizer), true)] public class MixedRealityControllerVisualizerInspector : ControllerPoseSynchronizerInspector { } }
Update bundle config to match exampe in wiki page
using System.Diagnostics.CodeAnalysis; using System.Web.Optimization; namespace T4MVCHostMvcApp.App_Start { public static class BundleConfig { // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725 [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0")] public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new StyleBundle(Links.Bundles.Content.Styles).Include( Links.Bundles.Content.Assets.Site_css )); } } } namespace Links { public static partial class Bundles { public static partial class Content { public const string Styles = "~/content/styles"; } } }
using System.Diagnostics.CodeAnalysis; using System.Web.Optimization; namespace T4MVCHostMvcApp.App_Start { public static class BundleConfig { // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725 [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0")] public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle(Links.Bundles.Scripts.jquery).Include("~/scripts/jquery-{version}.js")); bundles.Add(new StyleBundle(Links.Bundles.Styles.bootstrap).Include("~/styles/bootstrap*.css")); bundles.Add(new StyleBundle(Links.Bundles.Styles.common).Include(Links.Bundles.Content.Assets.Site_css)); } } } namespace Links { public static partial class Bundles { public static partial class Scripts { public static readonly string jquery = "~/scripts/jquery"; public static readonly string jqueryui = "~/scripts/jqueryui"; } public static partial class Styles { public static readonly string bootstrap = "~/styles/boostrap"; public static readonly string theme = "~/styles/theme"; public static readonly string common = "~/styles/common"; } } }
Use character class as transition key
using System.Collections.Generic; namespace slang.Lexing.Trees.Nodes { public class Transitions : Dictionary<char,Node> { } }
using System.Collections.Generic; namespace slang.Lexing.Trees.Nodes { public class Transitions : Dictionary<Character,Transition> { } }
Add a way to get the vendors from the Site entity.
// Copyright (c) Alex Ghiondea. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using SmugMug.v2.Authentication; using System.Threading.Tasks; namespace SmugMug.v2.Types { public class SiteEntity : SmugMugEntity { public SiteEntity(OAuthToken token) { _oauthToken = token; } public async Task<UserEntity> GetAuthenticatedUserAsync() { // !authuser string requestUri = string.Format("{0}!authuser", SmugMug.v2.Constants.Addresses.SmugMugApi); return await RetrieveEntityAsync<UserEntity>(requestUri); } public async Task<UserEntity[]> SearchForUser(string query) { // api/v2/user!search?q= string requestUri = string.Format("{0}/user!search?q={1}", SmugMug.v2.Constants.Addresses.SmugMugApi, query); return await RetrieveEntityArrayAsync<UserEntity>(requestUri); } } }
// Copyright (c) Alex Ghiondea. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using SmugMug.v2.Authentication; using System.Threading.Tasks; namespace SmugMug.v2.Types { public class SiteEntity : SmugMugEntity { public SiteEntity(OAuthToken token) { _oauthToken = token; } public async Task<UserEntity> GetAuthenticatedUserAsync() { // !authuser string requestUri = string.Format("{0}!authuser", SmugMug.v2.Constants.Addresses.SmugMugApi); return await RetrieveEntityAsync<UserEntity>(requestUri); } public async Task<CatalogVendorEntity[]> GetVendors() { // /catalog!vendors string requestUri = string.Format("{0}/catalog!vendors", SmugMug.v2.Constants.Addresses.SmugMugApi); return await RetrieveEntityArrayAsync<CatalogVendorEntity>(requestUri); } public async Task<UserEntity[]> SearchForUser(string query) { // api/v2/user!search?q= string requestUri = string.Format("{0}/user!search?q={1}", SmugMug.v2.Constants.Addresses.SmugMugApi, query); return await RetrieveEntityArrayAsync<UserEntity>(requestUri); } } }
Fix InMemory context for unit tests
using System.ComponentModel.Composition; using Microsoft.EntityFrameworkCore; using Waf.BookLibrary.Library.Applications.Data; using Waf.BookLibrary.Library.Applications.Services; using Waf.BookLibrary.Library.Domain; namespace Test.BookLibrary.Library.Applications.Services { [Export, Export(typeof(IDBContextService))] public class MockDBContextService : IDBContextService { public DbContext GetBookLibraryContext(out string dataSourcePath) { dataSourcePath = @"C:\Test.db"; var options = new DbContextOptionsBuilder<BookLibraryContext>().UseInMemoryDatabase(databaseName: "TestDatabase").Options; var context = new BookLibraryContext(options, modelBuilder => { modelBuilder.Entity<Book>().Ignore(x => x.Errors).Ignore(x => x.HasErrors); modelBuilder.Entity<Person>().Ignore(x => x.Errors).Ignore(x => x.HasErrors); }); return context; } } }
using System.ComponentModel.Composition; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage; using Waf.BookLibrary.Library.Applications.Data; using Waf.BookLibrary.Library.Applications.Services; using Waf.BookLibrary.Library.Domain; namespace Test.BookLibrary.Library.Applications.Services { [Export, Export(typeof(IDBContextService))] public class MockDBContextService : IDBContextService { public DbContext GetBookLibraryContext(out string dataSourcePath) { dataSourcePath = @"C:\Test.db"; var options = new DbContextOptionsBuilder<BookLibraryContext>().UseInMemoryDatabase(databaseName: "TestDatabase", databaseRoot: new InMemoryDatabaseRoot()).Options; var context = new BookLibraryContext(options, modelBuilder => { modelBuilder.Entity<Book>().Ignore(x => x.Errors).Ignore(x => x.HasErrors); modelBuilder.Entity<Person>().Ignore(x => x.Errors).Ignore(x => x.HasErrors); }); return context; } } }
Refactor the menu's max height to be a property
// 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.Graphics; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays.Settings { public class SettingsEnumDropdown<T> : SettingsDropdown<T> where T : struct, Enum { protected override OsuDropdown<T> CreateDropdown() => new DropdownControl(); protected new class DropdownControl : OsuEnumDropdown<T> { public DropdownControl() { Margin = new MarginPadding { Top = 5 }; RelativeSizeAxes = Axes.X; } protected override DropdownMenu CreateMenu() => base.CreateMenu().With(m => m.MaxHeight = 200); } } }
// 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.Graphics; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays.Settings { public class SettingsEnumDropdown<T> : SettingsDropdown<T> where T : struct, Enum { protected override OsuDropdown<T> CreateDropdown() => new DropdownControl(); protected new class DropdownControl : OsuEnumDropdown<T> { protected virtual int MenuMaxHeight => 200; public DropdownControl() { Margin = new MarginPadding { Top = 5 }; RelativeSizeAxes = Axes.X; } protected override DropdownMenu CreateMenu() => base.CreateMenu().With(m => m.MaxHeight = MenuMaxHeight); } } }
Write test to ensure characters are normalized.
using System; using FluentAssertions; using Xunit; namespace Grobid.PdfToXml.Test { public class TokenBlockFactoryTest { [Fact] public void TestA() { var stub = new TextRenderInfoStub(); var testSubject = new TokenBlockFactory(100, 100); Action test = () => testSubject.Create(stub); test.ShouldThrow<NullReferenceException>("I am still implementing the code."); } } }
using System; using FluentAssertions; using iTextSharp.text.pdf.parser; using Xunit; namespace Grobid.PdfToXml.Test { public class TokenBlockFactoryTest { [Fact] public void FactoryShouldNormalizeUnicodeStrings() { var stub = new TextRenderInfoStub { AscentLine = new LineSegment(new Vector(0, 0, 0), new Vector(1, 1, 1)), Baseline = new LineSegment(new Vector(0, 0, 0), new Vector(1, 1, 1)), DescentLine = new LineSegment(new Vector(0, 0, 0), new Vector(1, 1, 1)), PostscriptFontName = "CHUFSU+NimbusRomNo9L-Medi", Text = "abcd\u0065\u0301fgh", }; var testSubject = new TokenBlockFactory(100, 100); var tokenBlock = testSubject.Create(stub); stub.Text.ToCharArray().Should().HaveCount(9); tokenBlock.Text.ToCharArray().Should().HaveCount(8); } } }
Simplify Login() action - no explicit return necessary
// Copyright(c) 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. using System.Web; using System.Web.Mvc; using Microsoft.Owin.Security; namespace GoogleCloudSamples.Controllers { // [START login] public class SessionController : Controller { public ActionResult Login() { // Redirect to the Google OAuth 2.0 user consent screen HttpContext.GetOwinContext().Authentication.Challenge( new AuthenticationProperties { RedirectUri = "/" }, "Google" ); return new HttpUnauthorizedResult(); } // ... // [END login] // [START logout] public ActionResult Logout() { Request.GetOwinContext().Authentication.SignOut(); return Redirect("/"); } // [END logout] } }
// Copyright(c) 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. using System.Web; using System.Web.Mvc; using Microsoft.Owin.Security; namespace GoogleCloudSamples.Controllers { // [START login] public class SessionController : Controller { public void Login() { // Redirect to the Google OAuth 2.0 user consent screen HttpContext.GetOwinContext().Authentication.Challenge( new AuthenticationProperties { RedirectUri = "/" }, "Google" ); } // ... // [END login] // [START logout] public ActionResult Logout() { Request.GetOwinContext().Authentication.SignOut(); return Redirect("/"); } // [END logout] } }
Update Custom field to the correct POCO representation
using System.Collections.Generic; using commercetools.Common; using commercetools.CustomFields; using Newtonsoft.Json; namespace commercetools.Carts { /// <summary> /// API representation for creating a new CustomLineItem. /// </summary> /// <see href="http://dev.commercetools.com/http-api-projects-carts.html#customlineitemdraft"/> public class CustomLineItemDraft { #region Properties [JsonProperty(PropertyName = "name")] public LocalizedString Name { get; set; } [JsonProperty(PropertyName = "quantity")] public int? Quantity { get; set; } [JsonProperty(PropertyName = "money")] public Money Money { get; set; } [JsonProperty(PropertyName = "slug")] public string Slug { get; set; } [JsonProperty(PropertyName = "taxCategory")] public Reference TaxCategory { get; set; } [JsonProperty(PropertyName = "custom")] public List<CustomFieldsDraft> Custom { get; set; } #endregion #region Constructors /// <summary> /// Constructor. /// </summary> public CustomLineItemDraft(LocalizedString name) { this.Name = name; } #endregion } }
using System.Collections.Generic; using commercetools.Common; using commercetools.CustomFields; using Newtonsoft.Json; namespace commercetools.Carts { /// <summary> /// API representation for creating a new CustomLineItem. /// </summary> /// <see href="http://dev.commercetools.com/http-api-projects-carts.html#customlineitemdraft"/> public class CustomLineItemDraft { #region Properties [JsonProperty(PropertyName = "name")] public LocalizedString Name { get; set; } [JsonProperty(PropertyName = "quantity")] public int? Quantity { get; set; } [JsonProperty(PropertyName = "money")] public Money Money { get; set; } [JsonProperty(PropertyName = "slug")] public string Slug { get; set; } [JsonProperty(PropertyName = "taxCategory")] public Reference TaxCategory { get; set; } [JsonProperty(PropertyName = "custom")] public CustomFieldsDraft Custom { get; set; } #endregion #region Constructors /// <summary> /// Constructor. /// </summary> public CustomLineItemDraft(LocalizedString name) { this.Name = name; } #endregion } }
Remove unnecessary argument exception documentation on user info
namespace Cronofy { using System; /// <summary> /// Interface for a Cronofy client base that manages the /// access token and any shared client methods. /// </summary> public interface ICronofyUserInfoClient { /// <summary> /// Gets the user info belonging to the account. /// </summary> /// <returns>The account's user info.</returns> /// <exception cref="ArgumentException"> /// Thrown if <paramref name="request"/> is null. /// </exception> /// <exception cref="CronofyException"> /// Thrown if an error is encountered whilst making the request. /// </exception> UserInfo GetUserInfo(); } }
namespace Cronofy { using System; /// <summary> /// Interface for a Cronofy client base that manages the /// access token and any shared client methods. /// </summary> public interface ICronofyUserInfoClient { /// <summary> /// Gets the user info belonging to the account. /// </summary> /// <returns>The account's user info.</returns> /// <exception cref="CronofyException"> /// Thrown if an error is encountered whilst making the request. /// </exception> UserInfo GetUserInfo(); } }
Improve when there is no carrier
namespace MyParcelApi.Net.Models { public enum Carrier { PostNl = 1, BPost = 2 } }
namespace MyParcelApi.Net.Models { public enum Carrier { None = 0, PostNl = 1, BPost = 2 } }
Check for shots going out of bounds and kill them
using UnityEngine; using System.Collections; public class ShotControl : MonoBehaviour { public float speed = 0.2f; private bool inBlock; private int life = 3; void Start () { } void Update () { // Old position Vector3 position = transform.position; // Move transform.Translate(Vector3.up * speed); // Check for collision Collider2D collider = Physics2D.OverlapCircle(transform.position, 0.1f); if (collider) { if (collider.name == "ArenaBlock") { if (!inBlock) { // Reduce life if (--life == 0) { Destroy(gameObject); return; } // Find vector to block center (normalized for stretched blocks) Vector3 v = collider.transform.position - position; v.x /= collider.transform.localScale.x; v.y /= collider.transform.localScale.y; Vector3 forward = transform.up; if (Mathf.Abs(v.x) < Mathf.Abs(v.y)) { forward.y = -forward.y; // bounce vertically } else { forward.x = -forward.x; // bounce horizontally } transform.up = forward; } inBlock = true; } } else { inBlock = false; } } }
using UnityEngine; using System.Collections; public class ShotControl : MonoBehaviour { public float speed = 0.2f; private bool inBlock; private int life = 3; void Start () { } void Update () { // Old position Vector3 position = transform.position; // Move transform.Translate(Vector3.up * speed); // Check for out of bounds if (100f <= Mathf.Abs(transform.position.magnitude)) { Destroy(gameObject); return; } // Check for collision Collider2D collider = Physics2D.OverlapCircle(transform.position, 0.15f); if (collider) { if (collider.name == "ArenaBlock") { if (!inBlock) { // Reduce life if (--life == 0) { Destroy(gameObject); return; } // Find vector to block center (normalized for stretched blocks) Vector3 v = collider.transform.position - position; v.x /= collider.transform.localScale.x; v.y /= collider.transform.localScale.y; Vector3 forward = transform.up; if (Mathf.Abs(v.x) < Mathf.Abs(v.y)) { forward.y = -forward.y; // bounce vertically } else { forward.x = -forward.x; // bounce horizontally } transform.up = forward; } inBlock = true; } } else { inBlock = false; } } }
Add more style extension methods
using WootzJs.Mvc.Views; using WootzJs.Mvc.Views.Css; namespace WootzJs.Mvc { public static class StyleExtensions { public static T WithBold<T>(this T control) where T : Control { control.Style.Font.Weight = new CssFontWeight(CssFontWeightType.Bold); return control; } } }
using WootzJs.Mvc.Views; using WootzJs.Mvc.Views.Css; namespace WootzJs.Mvc { public static class StyleExtensions { public static T WithBold<T>(this T control) where T : Control { control.Style.Font.Weight = new CssFontWeight(CssFontWeightType.Bold); return control; } public static T WithPadding<T>(this T control, CssPadding padding) where T : Control { control.Style.Padding = padding; return control; } } }
Handle URL's with or without a / suffix
using System.Net; using System.Web.Script.Serialization; namespace MultiMiner.MobileMiner.Api { public class ApiContext { static public void SubmitMiningStatistics(string url, MiningStatistics miningStatistics) { string fullUrl = url + "/api/MiningStatisticsInput"; using (WebClient client = new WebClient()) { JavaScriptSerializer serializer = new JavaScriptSerializer(); string jsonData = serializer.Serialize(miningStatistics); client.Headers[HttpRequestHeader.ContentType] = "application/json"; client.UploadString(fullUrl, jsonData); } } } }
using System.Net; using System.Web.Script.Serialization; namespace MultiMiner.MobileMiner.Api { public class ApiContext { static public void SubmitMiningStatistics(string url, MiningStatistics miningStatistics) { if (!url.EndsWith("/")) url = url + "/"; string fullUrl = url + "api/MiningStatisticsInput"; using (WebClient client = new WebClient()) { JavaScriptSerializer serializer = new JavaScriptSerializer(); string jsonData = serializer.Serialize(miningStatistics); client.Headers[HttpRequestHeader.ContentType] = "application/json"; client.UploadString(fullUrl, jsonData); } } } }
Disable dupfinder because of Hg.Net
#load nuget:https://www.myget.org/F/cake-contrib/api/v2?package=Cake.Recipe&prerelease Environment.SetVariableNames(); BuildParameters.SetParameters(context: Context, buildSystem: BuildSystem, sourceDirectoryPath: "./src", title: "Cake.Hg", repositoryOwner: "cake-contrib", repositoryName: "Cake.Hg", appVeyorAccountName: "cakecontrib", solutionFilePath: "./src/Cake.Hg.sln", shouldRunCodecov: false, wyamSourceFiles: "../../src/**/{!bin,!obj,!packages,!*Tests,}/**/*.cs"); BuildParameters.PrintParameters(Context); ToolSettings.SetToolSettings(context: Context, dupFinderExcludePattern: new string[] { BuildParameters.RootDirectoryPath + "/src/Cake.HgTests/**/*.cs", BuildParameters.RootDirectoryPath + "/src/Cake.Hg/**/*.AssemblyInfo.cs" }); Build.Run();
#load nuget:https://www.myget.org/F/cake-contrib/api/v2?package=Cake.Recipe&prerelease Environment.SetVariableNames(); BuildParameters.SetParameters(context: Context, buildSystem: BuildSystem, sourceDirectoryPath: "./src", title: "Cake.Hg", repositoryOwner: "cake-contrib", repositoryName: "Cake.Hg", appVeyorAccountName: "cakecontrib", solutionFilePath: "./src/Cake.Hg.sln", shouldRunCodecov: false, shouldRunDupFinder: false, wyamSourceFiles: "../../src/**/{!bin,!obj,!packages,!*Tests,}/**/*.cs"); BuildParameters.PrintParameters(Context); ToolSettings.SetToolSettings(context: Context, dupFinderExcludePattern: new string[] { BuildParameters.RootDirectoryPath + "/src/Cake.HgTests/**/*.cs", BuildParameters.RootDirectoryPath + "/src/Cake.Hg/**/*.AssemblyInfo.cs" }); Build.Run();
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Autofac.Extras.DomainServices")] [assembly: AssemblyDescription("Autofac Integration for RIA Services")] [assembly: ComVisible(false)]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Autofac.Extras.DomainServices")] [assembly: ComVisible(false)]
Use a const for excess length
// 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.Linq; using osu.Framework.Audio.Track; using osu.Game.Rulesets.Objects.Types; namespace osu.Game.Beatmaps { public partial class WorkingBeatmap { /// <summary> /// A type of <see cref="TrackVirtual"/> which provides a valid length based on the <see cref="HitObject"/>s of an <see cref="IBeatmap"/>. /// </summary> protected class VirtualBeatmapTrack : TrackVirtual { private readonly IBeatmap beatmap; public VirtualBeatmapTrack(IBeatmap beatmap) { this.beatmap = beatmap; updateVirtualLength(); } protected override void UpdateState() { updateVirtualLength(); base.UpdateState(); } private void updateVirtualLength() { var lastObject = beatmap.HitObjects.LastOrDefault(); switch (lastObject) { case null: Length = 1000; break; case IHasEndTime endTime: Length = endTime.EndTime + 1000; break; default: Length = lastObject.StartTime + 1000; break; } } } } }
// 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.Linq; using osu.Framework.Audio.Track; using osu.Game.Rulesets.Objects.Types; namespace osu.Game.Beatmaps { public partial class WorkingBeatmap { /// <summary> /// A type of <see cref="TrackVirtual"/> which provides a valid length based on the <see cref="HitObject"/>s of an <see cref="IBeatmap"/>. /// </summary> protected class VirtualBeatmapTrack : TrackVirtual { private const double excess_length = 1000; private readonly IBeatmap beatmap; public VirtualBeatmapTrack(IBeatmap beatmap) { this.beatmap = beatmap; updateVirtualLength(); } protected override void UpdateState() { updateVirtualLength(); base.UpdateState(); } private void updateVirtualLength() { var lastObject = beatmap.HitObjects.LastOrDefault(); switch (lastObject) { case null: Length = excess_length; break; case IHasEndTime endTime: Length = endTime.EndTime + excess_length; break; default: Length = lastObject.StartTime + excess_length; break; } } } } }
Remove printing of invocation in case of non-zero exit code.
// Copyright Matthias Koch 2017. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using JetBrains.Annotations; using Nuke.Core.Utilities; namespace Nuke.Core.Tooling { [PublicAPI] [DebuggerStepThrough] [DebuggerNonUserCode] public static class ProcessExtensions { [AssertionMethod] public static void AssertWaitForExit ([AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [CanBeNull] this IProcess process) { ControlFlow.Assert(process != null && process.WaitForExit(), "process != null && process.WaitForExit()"); } [AssertionMethod] public static void AssertZeroExitCode ([AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [CanBeNull] this IProcess process) { process.AssertWaitForExit(); ControlFlow.Assert(process.ExitCode == 0, new[] { $"Process '{Path.GetFileName(process.StartInfo.FileName)}' exited with code {process.ExitCode}. Please verify the invocation:", $"> {process.StartInfo.FileName.DoubleQuoteIfNeeded()} {process.StartInfo.Arguments}" }.Join(EnvironmentInfo.NewLine)); } public static IEnumerable<Output> EnsureOnlyStd (this IEnumerable<Output> output) { foreach (var o in output) { ControlFlow.Assert(o.Type == OutputType.Std, "o.Type == OutputType.Std"); yield return o; } } } }
// Copyright Matthias Koch 2017. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using JetBrains.Annotations; using Nuke.Core.Utilities; namespace Nuke.Core.Tooling { [PublicAPI] [DebuggerStepThrough] [DebuggerNonUserCode] public static class ProcessExtensions { [AssertionMethod] public static void AssertWaitForExit ([AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [CanBeNull] this IProcess process) { ControlFlow.Assert(process != null && process.WaitForExit(), "process != null && process.WaitForExit()"); } [AssertionMethod] public static void AssertZeroExitCode ([AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [CanBeNull] this IProcess process) { process.AssertWaitForExit(); ControlFlow.Assert(process.ExitCode == 0, $"Process '{Path.GetFileName(process.StartInfo.FileName)}' exited with code {process.ExitCode}. Please verify the invocation."); } public static IEnumerable<Output> EnsureOnlyStd (this IEnumerable<Output> output) { foreach (var o in output) { ControlFlow.Assert(o.Type == OutputType.Std, "o.Type == OutputType.Std"); yield return o; } } } }
Create directory for error screenshot if it does not exist
using System; using System.Drawing.Imaging; using System.IO; using Tellurium.MvcPages.Utils; namespace Tellurium.MvcPages.BrowserCamera.Storage { public class FileSystemScreenshotStorage : IScreenshotStorage { private readonly string screenshotDirectoryPath; public FileSystemScreenshotStorage(string screenshotDirectoryPath) { this.screenshotDirectoryPath = screenshotDirectoryPath; } public virtual void Persist(byte[] image, string screenshotName) { var screenshotPath = GetScreenshotPath(screenshotName); image.ToBitmap().Save(screenshotPath, ImageFormat.Jpeg); } protected string GetScreenshotPath(string screenshotName) { if (string.IsNullOrWhiteSpace(screenshotDirectoryPath)) { throw new ApplicationException("Screenshot directory path not defined"); } if (string.IsNullOrWhiteSpace(screenshotName)) { throw new ArgumentException("Screenshot name cannot be empty", nameof(screenshotName)); } var fileName = $"{screenshotName}.jpg"; return Path.Combine(screenshotDirectoryPath, fileName); } } }
using System; using System.Drawing.Imaging; using System.IO; using Tellurium.MvcPages.Utils; namespace Tellurium.MvcPages.BrowserCamera.Storage { public class FileSystemScreenshotStorage : IScreenshotStorage { private readonly string screenshotDirectoryPath; public FileSystemScreenshotStorage(string screenshotDirectoryPath) { this.screenshotDirectoryPath = screenshotDirectoryPath; } public virtual void Persist(byte[] image, string screenshotName) { var screenshotPath = GetScreenshotPath(screenshotName); image.ToBitmap().Save(screenshotPath, ImageFormat.Jpeg); } protected string GetScreenshotPath(string screenshotName) { if (string.IsNullOrWhiteSpace(screenshotDirectoryPath)) { throw new ApplicationException("Screenshot directory path not defined"); } if (string.IsNullOrWhiteSpace(screenshotName)) { throw new ArgumentException("Screenshot name cannot be empty", nameof(screenshotName)); } if (Directory.Exists(screenshotDirectoryPath) == false) { Directory.CreateDirectory(screenshotDirectoryPath); } var fileName = $"{screenshotName}.jpg"; return Path.Combine(screenshotDirectoryPath, fileName); } } }
Use different percentage in the unit test.
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET. // Licensed under the Apache License, Version 2.0. using ImageMagick; using Xunit; using Xunit.Sdk; namespace Magick.NET.Tests { public partial class ResourceLimitsTests { [Collection(nameof(RunTestsSeparately))] public class TheMaxMemoryRequest { [Fact] public void ShouldHaveTheCorrectValue() { if (ResourceLimits.MaxMemoryRequest < 100000000U) throw new XunitException("Invalid memory limit: " + ResourceLimits.MaxMemoryRequest); } [Fact] public void ShouldReturnTheCorrectValueWhenChanged() { var oldMemory = ResourceLimits.MaxMemoryRequest; var newMemory = (ulong)(ResourceLimits.MaxMemoryRequest * 0.9); ResourceLimits.MaxMemoryRequest = newMemory; Assert.Equal(newMemory, ResourceLimits.MaxMemoryRequest); ResourceLimits.MaxMemoryRequest = oldMemory; } } } }
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET. // Licensed under the Apache License, Version 2.0. using ImageMagick; using Xunit; using Xunit.Sdk; namespace Magick.NET.Tests { public partial class ResourceLimitsTests { [Collection(nameof(RunTestsSeparately))] public class TheMaxMemoryRequest { [Fact] public void ShouldHaveTheCorrectValue() { if (ResourceLimits.MaxMemoryRequest < 100000000U) throw new XunitException("Invalid memory limit: " + ResourceLimits.MaxMemoryRequest); } [Fact] public void ShouldReturnTheCorrectValueWhenChanged() { var oldMemory = ResourceLimits.MaxMemoryRequest; var newMemory = (ulong)(ResourceLimits.MaxMemoryRequest * 0.8); ResourceLimits.MaxMemoryRequest = newMemory; Assert.Equal(newMemory, ResourceLimits.MaxMemoryRequest); ResourceLimits.MaxMemoryRequest = oldMemory; } } } }
Add process index to state as primary key. Use process name as property
using System.Collections.Generic; namespace AttachToolbar { internal static class State { public static string ProcessName = ""; public static List<string> ProcessList = new List<string>(); public static EngineType EngineType = EngineType.Native; public static bool IsAttached = false; public static void Clear() { ProcessList.Clear(); EngineType = EngineType.Native; IsAttached = false; ProcessName = ""; } } }
using System.Collections.Generic; namespace AttachToolbar { internal static class State { public static int ProcessIndex = -1; public static List<string> ProcessList = new List<string>(); public static EngineType EngineType = EngineType.Native; public static bool IsAttached = false; public static string ProcessName { get { string processName = ProcessIndex >= 0 ? ProcessList[ProcessIndex] : ""; return processName; } set { ProcessIndex = ProcessList.IndexOf(value); } } public static void Clear() { ProcessList.Clear(); EngineType = EngineType.Native; IsAttached = false; ProcessIndex = -1; } } }
Fix system memory check for Linux (20210323)
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bloom.Utils { class MemoryUtils { /// <summary> /// A crude way of measuring when we might be short enough of memory to need a full reload. /// </summary> /// <returns></returns> public static bool SystemIsShortOfMemory() { // A rather arbitrary limit of 750M...a bit more than Bloom typically uses for a large book // before memory leaks start to mount up. return GetPrivateBytes() > 750000000; } /// <summary> /// Significance: This counter indicates the current number of bytes allocated to this process that cannot be shared with /// other processes. This counter has been useful for identifying memory leaks. /// </summary> /// <remarks>We've had other versions of this method which, confusingly, returned results in KB. This one actually answers bytes.</remarks> /// <returns></returns> public static long GetPrivateBytes() { using (var perfCounter = new PerformanceCounter("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName)) { return perfCounter.RawValue; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bloom.Utils { class MemoryUtils { /// <summary> /// A crude way of measuring when we might be short enough of memory to need a full reload. /// </summary> /// <returns></returns> public static bool SystemIsShortOfMemory() { // A rather arbitrary limit of 750M...a bit more than Bloom typically uses for a large book // before memory leaks start to mount up. A larger value is wanted for 64-bit processes // since they can start out above the 750M level. var triggerLevel = Environment.Is64BitProcess ? 2000000000L : 750000000; return GetPrivateBytes() > triggerLevel; } /// <summary> /// Significance: This value indicates the current number of bytes allocated to this process that cannot be shared with /// other processes. This value has been useful for identifying memory leaks. /// </summary> /// <remarks>We've had other versions of this method which, confusingly, returned results in KB. This one actually answers bytes.</remarks> public static long GetPrivateBytes() { // Using a PerformanceCounter does not work on Linux and gains nothing on Windows. // After using the PerformanceCounter once on Windows, it always returns the same // value as getting it directly from the Process property. using (var process = Process.GetCurrentProcess()) { return process.PrivateMemorySize64; } } } }
Add new line for file logging
using System; using System.Diagnostics; using System.IO; namespace PackageRunner { /// <summary> /// </summary> internal class FileLogging { private readonly string _file; private static readonly object _lock = new object(); public FileLogging(string file) { _file = file; } public void AddLine(string text) { lock (_lock) { File.AppendAllText(_file, DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + " " + text); Debug.WriteLine(text); } } /// <summary> /// </summary> public void AddLine(string format, params object[] args) { var text = string.Format(format, args); this.AddLine(text); } } }
using System; using System.Diagnostics; using System.IO; namespace PackageRunner { /// <summary> /// </summary> internal class FileLogging { private readonly string _file; private static readonly object _lock = new object(); public FileLogging(string file) { _file = file; } public void AddLine(string text) { lock (_lock) { File.AppendAllText(_file, DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + " " + text + Environment.NewLine); Debug.WriteLine(text); } } /// <summary> /// </summary> public void AddLine(string format, params object[] args) { var text = string.Format(format, args); this.AddLine(text); } } }
Add Debug writer for diagnostic purpose
using System; using System.Threading; using Topshelf; namespace Tellurium.VisualAssertion.Dashboard { public class Program { public static void Main(string[] args) { #if DEBUG using (var server = new WebServer()) { server.Run(consoleMode:true); Console.ReadKey(); } #else InstallDashboardService(); #endif } private static void InstallDashboardService() { HostFactory.Run(hostConfiguration => { hostConfiguration.Service<WebServer>(wsc => { wsc.ConstructUsing(() => new WebServer()); wsc.WhenStarted(server => { server.Run(); }); wsc.WhenStopped(ws => ws.Dispose()); }); hostConfiguration.RunAsLocalSystem(); hostConfiguration.SetDescription("This is Tellurium Dashboard"); hostConfiguration.SetDisplayName("Tellurium Dashboard"); hostConfiguration.SetServiceName("TelluriumDashboard"); hostConfiguration.StartAutomatically(); }); } } }
using System; using System.Diagnostics; using System.IO; using System.Threading; using Topshelf; namespace Tellurium.VisualAssertion.Dashboard { public class Program { public static void Main(string[] args) { #if DEBUG using (var server = new WebServer()) { Console.SetOut(new DebugWriter()); server.Run(consoleMode:true); Console.ReadKey(); } #else InstallDashboardService(); #endif } private static void InstallDashboardService() { HostFactory.Run(hostConfiguration => { hostConfiguration.Service<WebServer>(wsc => { wsc.ConstructUsing(() => new WebServer()); wsc.WhenStarted(server => { server.Run(); }); wsc.WhenStopped(ws => ws.Dispose()); }); hostConfiguration.RunAsLocalSystem(); hostConfiguration.SetDescription("This is Tellurium Dashboard"); hostConfiguration.SetDisplayName("Tellurium Dashboard"); hostConfiguration.SetServiceName("TelluriumDashboard"); hostConfiguration.StartAutomatically(); }); } } public class DebugWriter : StringWriter { public override void WriteLine(string value) { Debug.WriteLine(value); base.WriteLine(value); } } }
Fix - RuntimeUniqueIdProdiver is static
#if FAT namespace Theraot.Threading { public static partial class ThreadingHelper { private static readonly RuntimeUniqueIdProdiver _threadIdProvider = new RuntimeUniqueIdProdiver(); // Leaked until AppDomain unload private static readonly NoTrackingThreadLocal<RuntimeUniqueIdProdiver.UniqueId> _threadRuntimeUniqueId = new NoTrackingThreadLocal<RuntimeUniqueIdProdiver.UniqueId>(_threadIdProvider.GetNextId); public static bool HasThreadUniqueId { get { return _threadRuntimeUniqueId.IsValueCreated; } } public static RuntimeUniqueIdProdiver.UniqueId ThreadUniqueId { get { return _threadRuntimeUniqueId.Value; } } } } #endif
#if FAT namespace Theraot.Threading { public static partial class ThreadingHelper { // Leaked until AppDomain unload private static readonly NoTrackingThreadLocal<RuntimeUniqueIdProdiver.UniqueId> _threadRuntimeUniqueId = new NoTrackingThreadLocal<RuntimeUniqueIdProdiver.UniqueId>(RuntimeUniqueIdProdiver.GetNextId); public static bool HasThreadUniqueId { get { return _threadRuntimeUniqueId.IsValueCreated; } } public static RuntimeUniqueIdProdiver.UniqueId ThreadUniqueId { get { return _threadRuntimeUniqueId.Value; } } } } #endif
Fix namespace and add inheritance
using IdentityServer3.Core.Services; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using IdentityServer3.Core.Models; using IdentityServer3.Contrib.RedisStores.Models; using StackExchange.Redis; using IdentityServer3.Contrib.RedisStores.Converters; namespace IdentityServer3.Contrib.RedisStores.Stores { /// <summary> /// /// </summary> public class RefreshTokenStore : RedisTransientStore<RefreshToken, RefreshTokenModel> { /// <summary> /// /// </summary> /// <param name="redis"></param> /// <param name="options"></param> public RefreshTokenStore(IDatabase redis, RedisOptions options) : base(redis, options, new RefreshTokenConverter()) { } /// <summary> /// /// </summary> /// <param name="redis"></param> public RefreshTokenStore(IDatabase redis) : base(redis, new RefreshTokenConverter()) { } internal override string CollectionName => "refreshTokens"; internal override int GetTokenLifetime(RefreshToken token) { return token.LifeTime; } } }
using IdentityServer3.Core.Services; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using IdentityServer3.Core.Models; using IdentityServer3.Contrib.RedisStores.Models; using StackExchange.Redis; using IdentityServer3.Contrib.RedisStores.Converters; namespace IdentityServer3.Contrib.RedisStores { /// <summary> /// /// </summary> public class RefreshTokenStore : RedisTransientStore<RefreshToken, RefreshTokenModel>, IRefreshTokenStore { /// <summary> /// /// </summary> /// <param name="redis"></param> /// <param name="options"></param> public RefreshTokenStore(IDatabase redis, RedisOptions options) : base(redis, options, new RefreshTokenConverter()) { } /// <summary> /// /// </summary> /// <param name="redis"></param> public RefreshTokenStore(IDatabase redis) : base(redis, new RefreshTokenConverter()) { } internal override string CollectionName => "refreshTokens"; internal override int GetTokenLifetime(RefreshToken token) { return token.LifeTime; } } }
Fix handling of CONNECTION_PLAYER when sending response to GameServer
using AutomaticTypeMapper; using EOLib.Logger; using EOLib.Net; using EOLib.Net.Communication; using EOLib.Net.Handlers; using EOLib.Net.PacketProcessing; namespace EOLib.PacketHandlers { /// <summary> /// Handles incoming CONNECTION_PLAYER packets which are used for updating sequence numbers in the EO protocol /// </summary> [AutoMappedType] public class ConnectionPlayerHandler : DefaultAsyncPacketHandler { private readonly IPacketProcessActions _packetProcessActions; private readonly IPacketSendService _packetSendService; private readonly ILoggerProvider _loggerProvider; public override PacketFamily Family => PacketFamily.Connection; public override PacketAction Action => PacketAction.Player; public override bool CanHandle => true; public ConnectionPlayerHandler(IPacketProcessActions packetProcessActions, IPacketSendService packetSendService, ILoggerProvider loggerProvider) { _packetProcessActions = packetProcessActions; _packetSendService = packetSendService; _loggerProvider = loggerProvider; } public override bool HandlePacket(IPacket packet) { var seq1 = packet.ReadShort(); var seq2 = packet.ReadChar(); _packetProcessActions.SetUpdatedBaseSequenceNumber(seq1, seq2); var response = new PacketBuilder(PacketFamily.Connection, PacketAction.Ping).Build(); try { _packetSendService.SendPacket(response); } catch (NoDataSentException) { return false; } return true; } } }
using AutomaticTypeMapper; using EOLib.Logger; using EOLib.Net; using EOLib.Net.Communication; using EOLib.Net.Handlers; using EOLib.Net.PacketProcessing; namespace EOLib.PacketHandlers { /// <summary> /// Handles incoming CONNECTION_PLAYER packets which are used for updating sequence numbers in the EO protocol /// </summary> [AutoMappedType] public class ConnectionPlayerHandler : DefaultAsyncPacketHandler { private readonly IPacketProcessActions _packetProcessActions; private readonly IPacketSendService _packetSendService; private readonly ILoggerProvider _loggerProvider; public override PacketFamily Family => PacketFamily.Connection; public override PacketAction Action => PacketAction.Player; public override bool CanHandle => true; public ConnectionPlayerHandler(IPacketProcessActions packetProcessActions, IPacketSendService packetSendService, ILoggerProvider loggerProvider) { _packetProcessActions = packetProcessActions; _packetSendService = packetSendService; _loggerProvider = loggerProvider; } public override bool HandlePacket(IPacket packet) { var seq1 = packet.ReadShort(); var seq2 = packet.ReadChar(); _packetProcessActions.SetUpdatedBaseSequenceNumber(seq1, seq2); var response = new PacketBuilder(PacketFamily.Connection, PacketAction.Ping) .AddString("k") .Build(); try { _packetSendService.SendPacket(response); } catch (NoDataSentException) { return false; } return true; } } }
Fix issue where Dapper was trying to insert Read into the post table where that column doesnt exist
using System; namespace gdRead.Data.Models { public class Post { public int Id { get; set; } public int FeedId { get; set; } public string Name { get; set; } public string Url { get; set; } public string Summary { get; set; } public string Content { get; set; } public DateTime PublishDate { get; set; } public bool Read { get; set; } public DateTime DateFetched { get;set; } public Post() { DateFetched = DateTime.Now; } } }
using System; using DapperExtensions.Mapper; namespace gdRead.Data.Models { public class Post { public int Id { get; set; } public int FeedId { get; set; } public string Name { get; set; } public string Url { get; set; } public string Summary { get; set; } public string Content { get; set; } public DateTime PublishDate { get; set; } public bool Read { get; set; } public DateTime DateFetched { get;set; } public Post() { DateFetched = DateTime.Now; } } public class PostMapper : ClassMapper<Post> { public PostMapper() { Table("Post"); Map(m => m.Read).Ignore(); AutoMap(); } } }
Replace string[] field by IEnumerable<string> property
using System; using System.Collections.Generic; using System.Linq; using Avalonia.Controls; using WalletWasabi.Gui.ViewModels; namespace WalletWasabi.Gui.ManagedDialogs { internal class ManagedFileChooserFilterViewModel : ViewModelBase { private readonly string[] Extensions; public string Name { get; } public ManagedFileChooserFilterViewModel(FileDialogFilter filter) { Name = filter.Name; if (filter.Extensions.Contains("*")) { return; } Extensions = filter.Extensions?.Select(e => "." + e.ToLowerInvariant()).ToArray(); } public ManagedFileChooserFilterViewModel() { Name = "All files"; } public bool Match(string filename) { if (Extensions is null) { return true; } foreach (var ext in Extensions) { if (filename.EndsWith(ext, StringComparison.InvariantCultureIgnoreCase)) { return true; } } return false; } public override string ToString() => Name; } }
using System; using System.Collections.Generic; using System.Linq; using Avalonia.Controls; using WalletWasabi.Gui.ViewModels; namespace WalletWasabi.Gui.ManagedDialogs { internal class ManagedFileChooserFilterViewModel : ViewModelBase { private IEnumerable<string> Extensions { get; } public string Name { get; } public ManagedFileChooserFilterViewModel(FileDialogFilter filter) { Name = filter.Name; if (filter.Extensions.Contains("*")) { return; } Extensions = filter.Extensions?.Select(e => "." + e.ToLowerInvariant()); } public ManagedFileChooserFilterViewModel() { Name = "All files"; } public bool Match(string filename) { if (Extensions is null) { return true; } foreach (var ext in Extensions) { if (filename.EndsWith(ext, StringComparison.InvariantCultureIgnoreCase)) { return true; } } return false; } public override string ToString() => Name; } }
Use GitVersion for test app
// Copyright (c) 2015 Eberhard Beilharz // This software is licensed under the MIT license (http://opensource.org/licenses/MIT) using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("BuildDependencyTestApp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("(c) 2014-2016 Eberhard Beilharz")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
// Copyright (c) 2015 Eberhard Beilharz // This software is licensed under the MIT license (http://opensource.org/licenses/MIT) using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("BuildDependencyTestApp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("(c) 2014-2017 Eberhard Beilharz")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")]
Fix issue when adding type to ExtensionsProvider
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace DotVVM.Framework.Compilation.Binding { public class DefaultExtensionsProvider : IExtensionsProvider { private readonly List<Type> typesLookup; public DefaultExtensionsProvider() { typesLookup = new List<Type>(); AddTypeForExtensionsLookup(typeof(Enumerable)); } protected void AddTypeForExtensionsLookup(Type type) { typesLookup.Add(typeof(Enumerable)); } public virtual IEnumerable<MethodInfo> GetExtensionMethods() { foreach (var registeredType in typesLookup) foreach (var method in registeredType.GetMethods(BindingFlags.Public | BindingFlags.Static)) yield return method; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace DotVVM.Framework.Compilation.Binding { public class DefaultExtensionsProvider : IExtensionsProvider { private readonly List<Type> typesLookup; public DefaultExtensionsProvider() { typesLookup = new List<Type>(); AddTypeForExtensionsLookup(typeof(Enumerable)); } protected void AddTypeForExtensionsLookup(Type type) { typesLookup.Add(type); } public virtual IEnumerable<MethodInfo> GetExtensionMethods() { foreach (var registeredType in typesLookup) foreach (var method in registeredType.GetMethods(BindingFlags.Public | BindingFlags.Static)) yield return method; } } }
Stop exception when no argument sare suppplied to minigzip
// project created on 11.11.2001 at 15:19 using System; using System.IO; using ICSharpCode.SharpZipLib.GZip; class MainClass { public static void Main(string[] args) { if (args[0] == "-d") { // decompress Stream s = new GZipInputStream(File.OpenRead(args[1])); FileStream fs = File.Create(Path.GetFileNameWithoutExtension(args[1])); int size = 2048; byte[] writeData = new byte[2048]; while (true) { size = s.Read(writeData, 0, size); if (size > 0) { fs.Write(writeData, 0, size); } else { break; } } s.Close(); } else { // compress Stream s = new GZipOutputStream(File.Create(args[0] + ".gz")); FileStream fs = File.OpenRead(args[0]); byte[] writeData = new byte[fs.Length]; fs.Read(writeData, 0, (int)fs.Length); s.Write(writeData, 0, writeData.Length); s.Close(); } } }
// project created on 11.11.2001 at 15:19 using System; using System.IO; using ICSharpCode.SharpZipLib.GZip; class MainClass { public static void Main(string[] args) { if ( args.Length > 0 ) { if ( args[0] == "-d" ) { // decompress Stream s = new GZipInputStream(File.OpenRead(args[1])); FileStream fs = File.Create(Path.GetFileNameWithoutExtension(args[1])); int size = 2048; byte[] writeData = new byte[2048]; while (true) { size = s.Read(writeData, 0, size); if (size > 0) { fs.Write(writeData, 0, size); } else { break; } } s.Close(); } else { // compress Stream s = new GZipOutputStream(File.Create(args[0] + ".gz")); FileStream fs = File.OpenRead(args[0]); byte[] writeData = new byte[fs.Length]; fs.Read(writeData, 0, (int)fs.Length); s.Write(writeData, 0, writeData.Length); s.Close(); } } } }
Remove assembly load debug lines.
using System; using System.IO; using System.Reflection; // ReSharper disable once CheckNamespace internal static class Program { private static int Main(string[] args) { // Mono's XBuild uses assembly redirects to make sure it uses .NET 4.5 target binaries. // We emulate it using our own assembly redirector. AppDomain.CurrentDomain.AssemblyLoad += (sender, e) => { var assemblyName = e.LoadedAssembly.GetName(); Console.WriteLine("Assembly load: {0}", assemblyName); }; var mainAsm = Assembly.Load("citizenmp_server_updater"); mainAsm.GetType("Costura.AssemblyLoader") .GetMethod("Attach") .Invoke(null, null); return (int) mainAsm.GetType("CitizenMP.Server.Installer.Program") .GetMethod("Main", BindingFlags.NonPublic | BindingFlags.Static) .Invoke(null, new object[] {args}); } }
using System; using System.IO; using System.Reflection; // ReSharper disable once CheckNamespace internal static class Program { private static int Main(string[] args) { var mainAsm = Assembly.Load("citizenmp_server_updater"); mainAsm.GetType("Costura.AssemblyLoader") .GetMethod("Attach") .Invoke(null, null); return (int) mainAsm.GetType("CitizenMP.Server.Installer.Program") .GetMethod("Main", BindingFlags.NonPublic | BindingFlags.Static) .Invoke(null, new object[] {args}); } }
Test if a failed test will fail the build
using Microsoft.VisualStudio.TestTools.UnitTesting; using SaurusConsole.OthelloAI; namespace SaurusConsoleTests { [TestClass] public class MoveTests { [TestMethod] public void NotationConstuctorTest() { Move e4move = new Move("E4"); Assert.AreEqual("E4", e4move.ToString()); Move a1move = new Move("A1"); Assert.AreEqual("A1", a1move.ToString()); Move a8move = new Move("A8"); Assert.AreEqual("A8", a8move.ToString()); Move h1move = new Move("H1"); Assert.AreEqual("H1", h1move.ToString()); Move h8move = new Move("H8"); Assert.AreEqual("H8", h8move.ToString()); } [TestMethod] public void ToStringTest() { ulong h1Mask = 1; Move h1Move = new Move(h1Mask); Assert.AreEqual("H1", h1Move.ToString()); ulong e4Mask = 0x8000000; Move e4Move = new Move(e4Mask); Assert.AreEqual("E4", e4Move.ToString()); } [TestMethod] public void GetBitMaskTest() { ulong mask = 0b1000000000000; Move move = new Move(mask); Assert.AreEqual(mask, move.GetBitMask()); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using SaurusConsole.OthelloAI; namespace SaurusConsoleTests { [TestClass] public class MoveTests { [TestMethod] public void NotationConstuctorTest() { Move e4move = new Move("E4"); Assert.AreEqual("E4", e4move.ToString()); Move a1move = new Move("A1"); Assert.AreEqual("A1", a1move.ToString()); Move a8move = new Move("A8"); Assert.AreEqual("A8", a8move.ToString()); Move h1move = new Move("H1"); Assert.AreEqual("H1", h1move.ToString()); Move h8move = new Move("H8"); Assert.AreEqual("H8", h8move.ToString()); Assert.Fail(); } [TestMethod] public void ToStringTest() { ulong h1Mask = 1; Move h1Move = new Move(h1Mask); Assert.AreEqual("H1", h1Move.ToString()); ulong e4Mask = 0x8000000; Move e4Move = new Move(e4Mask); Assert.AreEqual("E4", e4Move.ToString()); } [TestMethod] public void GetBitMaskTest() { ulong mask = 0b1000000000000; Move move = new Move(mask); Assert.AreEqual(mask, move.GetBitMask()); } } }
Set interval to 10 minutes
using System.Diagnostics; using System.IO; using Hangfire; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Server.HttpSys; using SupportManager.Contracts; using Topshelf; namespace SupportManager.Web { public class Program { private static string[] args; public static void Main() { HostFactory.Run(cfg => { cfg.AddCommandLineDefinition("aspnetcoreargs", v => args = v.Split(' ')); cfg.SetServiceName("SupportManager.Web"); cfg.SetDisplayName("SupportManager.Web"); cfg.SetDescription("SupportManager Web Interface"); cfg.Service<IWebHost>(svc => { svc.ConstructUsing(CreateWebHost); svc.WhenStarted(webHost => { webHost.Start(); RecurringJob.AddOrUpdate<IForwarder>(f => f.ReadAllTeamStatus(null), Cron.Minutely); }); svc.WhenStopped(webHost => webHost.Dispose()); }); cfg.RunAsLocalSystem(); cfg.StartAutomatically(); }); } private static IWebHost CreateWebHost() { var builder = WebHost.CreateDefaultBuilder(args).UseStartup<Startup>(); if (!Debugger.IsAttached) { builder.UseHttpSys(options => { options.Authentication.Schemes = AuthenticationSchemes.NTLM | AuthenticationSchemes.Negotiate; options.Authentication.AllowAnonymous = true; }); builder.UseContentRoot(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)); } return builder.Build(); } } }
using System.Diagnostics; using System.IO; using Hangfire; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Server.HttpSys; using SupportManager.Contracts; using Topshelf; namespace SupportManager.Web { public class Program { private static string[] args; public static void Main() { HostFactory.Run(cfg => { cfg.AddCommandLineDefinition("aspnetcoreargs", v => args = v.Split(' ')); cfg.SetServiceName("SupportManager.Web"); cfg.SetDisplayName("SupportManager.Web"); cfg.SetDescription("SupportManager Web Interface"); cfg.Service<IWebHost>(svc => { svc.ConstructUsing(CreateWebHost); svc.WhenStarted(webHost => { webHost.Start(); RecurringJob.AddOrUpdate<IForwarder>(f => f.ReadAllTeamStatus(null), Cron.MinuteInterval(10)); }); svc.WhenStopped(webHost => webHost.Dispose()); }); cfg.RunAsLocalSystem(); cfg.StartAutomatically(); }); } private static IWebHost CreateWebHost() { var builder = WebHost.CreateDefaultBuilder(args).UseStartup<Startup>(); if (!Debugger.IsAttached) { builder.UseHttpSys(options => { options.Authentication.Schemes = AuthenticationSchemes.NTLM | AuthenticationSchemes.Negotiate; options.Authentication.AllowAnonymous = true; }); builder.UseContentRoot(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)); } return builder.Build(); } } }
Make identity-test API easier to consume
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Linq; namespace Nether.Web.Features.Identity { [Route("identity-test")] [Authorize] public class IdentityTestController : ControllerBase { [HttpGet] public IActionResult Get() { return new JsonResult(from c in User.Claims select new { c.Type, c.Value }); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Linq; namespace Nether.Web.Features.Identity { [Route("identity-test")] [Authorize] public class IdentityTestController : ControllerBase { [HttpGet] public IActionResult Get() { // Convert claim type, value pairs into a dictionary for easier consumption as JSON // Need to group as there can be multiple claims of the same type (e.g. 'scope') var result = User.Claims .GroupBy(c => c.Type) .ToDictionary( keySelector: g => g.Key, elementSelector: g => g.Count() == 1 ? (object)g.First().Value : g.Select(t => t.Value).ToArray() ); return new JsonResult(result); } } }
Fix Alpaca error message deserialization
/* * The official C# API client for alpaca brokerage * Sourced from: https://github.com/alpacahq/alpaca-trade-api-csharp/tree/v3.0.2 */ using System; using Newtonsoft.Json; namespace QuantConnect.Brokerages.Alpaca.Markets { internal sealed class JsonError { [JsonProperty(PropertyName = "code", Required = Required.Always)] public Int32 Code { get; set; } [JsonProperty(PropertyName = "message", Required = Required.Always)] public String Message { get; set; } } }
/* * The official C# API client for alpaca brokerage * Sourced from: https://github.com/alpacahq/alpaca-trade-api-csharp/tree/v3.0.2 */ using System; using Newtonsoft.Json; namespace QuantConnect.Brokerages.Alpaca.Markets { internal sealed class JsonError { [JsonProperty(PropertyName = "code", Required = Required.Default)] public Int32 Code { get; set; } [JsonProperty(PropertyName = "message", Required = Required.Always)] public String Message { get; set; } } }
Change user id type to int
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System; using osu.Game.Users; namespace osu.Game.Online.RealtimeMultiplayer { [Serializable] public class MultiplayerRoomUser : IEquatable<MultiplayerRoomUser> { public readonly long UserID; public MultiplayerUserState State { get; set; } = MultiplayerUserState.Idle; public User? User { get; set; } public MultiplayerRoomUser(in int userId) { UserID = userId; } public bool Equals(MultiplayerRoomUser other) { if (ReferenceEquals(this, other)) return true; return UserID == other.UserID; } public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((MultiplayerRoomUser)obj); } public override int GetHashCode() => UserID.GetHashCode(); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System; using osu.Game.Users; namespace osu.Game.Online.RealtimeMultiplayer { [Serializable] public class MultiplayerRoomUser : IEquatable<MultiplayerRoomUser> { public readonly int UserID; public MultiplayerUserState State { get; set; } = MultiplayerUserState.Idle; public User? User { get; set; } public MultiplayerRoomUser(in int userId) { UserID = userId; } public bool Equals(MultiplayerRoomUser other) { if (ReferenceEquals(this, other)) return true; return UserID == other.UserID; } public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((MultiplayerRoomUser)obj); } public override int GetHashCode() => UserID.GetHashCode(); } }
Remove locking code and make it possible to have a dummy history, by calling the parameterless constructor.
using System; using System.Collections.Generic; namespace IvionSoft { public class History<T> { public int Length { get; private set; } HashSet<T> hashes; Queue<T> queue; object _locker = new object(); public History(int length) : this(length, null) {} public History(int length, IEqualityComparer<T> comparer) { if (length < 1) throw new ArgumentException("Must be 1 or larger", "length"); Length = length; queue = new Queue<T>(length + 1); if (comparer != null) hashes = new HashSet<T>(comparer); else hashes = new HashSet<T>(); } public bool Contains(T item) { return hashes.Contains(item); } public bool Add(T item) { bool added; lock (_locker) { added = hashes.Add(item); if (added) { queue.Enqueue(item); if (queue.Count > Length) { T toRemove = queue.Dequeue(); hashes.Remove(toRemove); } } } return added; } } }
using System; using System.Collections.Generic; namespace IvionSoft { public class History<T> { public int Length { get; private set; } HashSet<T> hashes; Queue<T> queue; public History() { Length = 0; } public History(int length) : this(length, null) {} public History(int length, IEqualityComparer<T> comparer) { if (length < 1) throw new ArgumentException("Cannot be less than or equal to 0.", "length"); Length = length; queue = new Queue<T>(length + 1); if (comparer != null) hashes = new HashSet<T>(comparer); else hashes = new HashSet<T>(); } public bool Contains(T item) { if (Length > 0) return hashes.Contains(item); else return false; } public bool Add(T item) { if (Length == 0) return false; bool added; added = hashes.Add(item); if (added) { queue.Enqueue(item); if (queue.Count > Length) { T toRemove = queue.Dequeue(); hashes.Remove(toRemove); } } return added; } } }
Add helpers for saving in Library and Library/Caches
using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace Stampsy.ImageSource { public class FileDestination : IDestination<FileRequest> { public string Folder { get; private set; } public FileDestination (string folder) { Folder = folder; } public FileRequest CreateRequest (IDescription description) { var url = description.Url; var filename = ComputeHash (url) + description.Extension; return new FileRequest (description) { Filename = Path.Combine (Folder, filename) }; } static string ComputeHash (Uri url) { string hash; using (var sha1 = new SHA1CryptoServiceProvider ()) { var bytes = Encoding.ASCII.GetBytes (url.ToString ()); hash = BitConverter.ToString (sha1.ComputeHash (bytes)); } return hash.Replace ("-", string.Empty).ToLower (); } } }
using System; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; namespace Stampsy.ImageSource { public class FileDestination : IDestination<FileRequest> { public static FileDestination InLibrary (params string [] folders) { var folder = Path.Combine (new [] { "..", "Library" }.Concat (folders).ToArray ()); Directory.CreateDirectory (folder); return new FileDestination (folder); } public static FileDestination InLibraryCaches (params string [] folders) { return InLibrary (new [] { "Caches" }.Concat (folders).ToArray ()); } public string Folder { get; private set; } public FileDestination (string folder) { Folder = folder; } public FileRequest CreateRequest (IDescription description) { var url = description.Url; var filename = ComputeHash (url) + description.Extension; return new FileRequest (description) { Filename = Path.Combine (Folder, filename) }; } static string ComputeHash (Uri url) { string hash; using (var sha1 = new SHA1CryptoServiceProvider ()) { var bytes = Encoding.ASCII.GetBytes (url.ToString ()); hash = BitConverter.ToString (sha1.ComputeHash (bytes)); } return hash.Replace ("-", string.Empty).ToLower (); } } }
Update to use new User
using System; using System.Collections.Generic; namespace Simple.Domain.Model { public class Organization { public Guid Id { get; set; } public string Name { get; set; } public string CatchPhrase { get; set; } public string BSPhrase { get; set; } // Ref public DomainUser Owner { get; set; } // List Ref public List<Address> Addresses { get; set; } public List<DomainUser> Employees { get; set; } } }
using System; using System.Collections.Generic; using Simple.Domain.Entities; namespace Simple.Domain.Model { public class Organization { public Guid Id { get; set; } public string Name { get; set; } public string CatchPhrase { get; set; } public string BSPhrase { get; set; } // Ref public User Owner { get; set; } // List Ref public List<Address> Addresses { get; set; } public List<User> Employees { get; set; } } }
Add some helpers and stuff
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ElectronicCash { /// <summary> /// The customer /// </summary> public class Alice : BaseActor { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ElectronicCash { /// <summary> /// The customer /// </summary> public class Alice : BaseActor { public List<MoneyOrder> MoneyOrders { get; private set; } public string PersonalData { get; private set; } public byte[] PersonalDataBytes { get; private set; } public Alice(string _name, Guid _actorGuid, string _personalData) { Name = _name; ActorGuid = _actorGuid; Money = 1000; PersonalData = _personalData; PersonalDataBytes = GetBytes(_personalData); } /// <summary> /// Called every time the customer wants to pay for something /// </summary> public void CreateMoneyOrders() { MoneyOrders = new List<MoneyOrder>(); } #region private methods /// <summary> /// stackoverflow.com/questions/472906/converting-a-string-to-byte-array-without-using-an-encoding-byte-by-byte /// </summary> /// <param name="str"></param> /// <returns></returns> private static byte[] GetBytes(string str) { byte[] bytes = new byte[str.Length * sizeof(char)]; System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); return bytes; } /// <summary> /// stackoverflow.com/questions/472906/converting-a-string-to-byte-array-without-using-an-encoding-byte-by-byte /// </summary> /// <param name="bytes"></param> /// <returns></returns> private static string GetString(byte[] bytes) { char[] chars = new char[bytes.Length / sizeof(char)]; System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length); return new string(chars); } #endregion } }
Revert "Use a PrivateAdditionalLibrary for czmq.lib instead of a public one"
// Copyright 2015 Palm Stone Games, Inc. All Rights Reserved. using System.IO; namespace UnrealBuildTool.Rules { public class ue4czmq : ModuleRules { public ue4czmq(TargetInfo Target) { // Include paths //PublicIncludePaths.AddRange(new string[] {}); //PrivateIncludePaths.AddRange(new string[] {}); // Dependencies PublicDependencyModuleNames.AddRange(new string[] { "Core", "Engine", }); //PrivateDependencyModuleNames.AddRange(new string[] {}); // Dynamically loaded modules //DynamicallyLoadedModuleNames.AddRange(new string[] {}); // Definitions Definitions.Add("WITH_UE4CZMQ=1"); LoadLib(Target); } public void LoadLib(TargetInfo Target) { string ModulePath = Path.GetDirectoryName(RulesCompiler.GetModuleFilename(this.GetType().Name)); // CZMQ string czmqPath = Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/", Target.Platform.ToString(), "czmq")); PrivateAdditionalLibraries.Add(Path.Combine(czmqPath, "Libraries", "czmq.lib")); PrivateIncludePaths.Add(Path.Combine(czmqPath, "Includes")); // LIBZMQ string libzmqPath = Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/", Target.Platform.ToString(), "libzmq")); PrivateIncludePaths.Add(Path.Combine(libzmqPath, "Includes")); } } }
// Copyright 2015 Palm Stone Games, Inc. All Rights Reserved. using System.IO; namespace UnrealBuildTool.Rules { public class ue4czmq : ModuleRules { public ue4czmq(TargetInfo Target) { // Include paths //PublicIncludePaths.AddRange(new string[] {}); //PrivateIncludePaths.AddRange(new string[] {}); // Dependencies PublicDependencyModuleNames.AddRange(new string[] { "Core", "Engine", }); //PrivateDependencyModuleNames.AddRange(new string[] {}); // Dynamically loaded modules //DynamicallyLoadedModuleNames.AddRange(new string[] {}); // Definitions Definitions.Add("WITH_UE4CZMQ=1"); LoadLib(Target); } public void LoadLib(TargetInfo Target) { string ModulePath = Path.GetDirectoryName(RulesCompiler.GetModuleFilename(this.GetType().Name)); // CZMQ string czmqPath = Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/", Target.Platform.ToString(), "czmq")); PublicAdditionalLibraries.Add(Path.Combine(czmqPath, "Libraries", "czmq.lib")); PrivateIncludePaths.Add(Path.Combine(czmqPath, "Includes")); // LIBZMQ string libzmqPath = Path.GetFullPath(Path.Combine(ModulePath, "../../ThirdParty/", Target.Platform.ToString(), "libzmq")); PrivateIncludePaths.Add(Path.Combine(libzmqPath, "Includes")); } } }
Make soldier a dropdown list
@model APFT @using (Html.BeginForm("Edit", "APFT", FormMethod.Post, new { @class = "form-horizontal" role = "form" })) { @Html.AntiForgeryToken() @Html.HiddenFor(model => model.Id) @Html.ValidationSummary() <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Soldier) @Html.EditorFor(model => model.SoldierId) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Date) @Html.EditorFor(model => model.Date) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.PushUps) @Html.EditorFor(model => model.PushUps) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.SitUps) @Html.EditorFor(model => model.SitUps) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Run) @Html.EditorFor(model => model.Run) </div> <button type="submit">Save</button> }
@model APFT @using (Html.BeginForm("Edit", "APFT", FormMethod.Post, new { @class = "form-horizontal" role = "form" })) { @Html.AntiForgeryToken() @Html.HiddenFor(model => model.Id) @Html.ValidationSummary() <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Soldier) @Html.DropDownListFor(model => model.SoldierId, (IEnumerable<SelectListItem>)ViewBag.Soldiers, "-- Select a Soldier --") </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Date) @Html.EditorFor(model => model.Date) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.PushUps) @Html.EditorFor(model => model.PushUps) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.SitUps) @Html.EditorFor(model => model.SitUps) </div> <div class="form-group form-group-lg"> @Html.DisplayNameFor(model => model.Run) @Html.EditorFor(model => model.Run) </div> <button type="submit">Save</button> }
Update unit test error for new const
#region copyright // -------------------------------------------------------------------------------------------------------------------- // <copyright file="SimpleTests.cs" company="Stephen Reindl"> // Copyright (c) Stephen Reindl. All rights reserved. // Licensed under the MIT license. See LICENSE.md file in the project root for full license information. // </copyright> // <summary> // Part of oberon0 - Oberon0Compiler.Tests/SimpleTests.cs // </summary> // -------------------------------------------------------------------------------------------------------------------- #endregion namespace Oberon0.Compiler.Tests { using NUnit.Framework; using Oberon0.Compiler.Definitions; using Oberon0.TestSupport; [TestFixture] public class SimpleTests { [Test] public void EmptyApplication() { Module m = Oberon0Compiler.CompileString("MODULE Test; END Test."); Assert.AreEqual("Test", m.Name); Assert.AreEqual(2, m.Block.Declarations.Count); } [Test] public void EmptyApplication2() { Module m = TestHelper.CompileString( @"MODULE Test; BEGIN END Test."); Assert.AreEqual(0, m.Block.Statements.Count); } [Test] public void ModuleMissingDot() { TestHelper.CompileString( @"MODULE Test; END Test", "missing '.' at '<EOF>'"); } [Test] public void ModuleMissingId() { TestHelper.CompileString( @"MODULE ; BEGIN END Test.", "missing ID at ';'", "The name of the module does not match the end node"); } } }
#region copyright // -------------------------------------------------------------------------------------------------------------------- // <copyright file="SimpleTests.cs" company="Stephen Reindl"> // Copyright (c) Stephen Reindl. All rights reserved. // Licensed under the MIT license. See LICENSE.md file in the project root for full license information. // </copyright> // <summary> // Part of oberon0 - Oberon0Compiler.Tests/SimpleTests.cs // </summary> // -------------------------------------------------------------------------------------------------------------------- #endregion namespace Oberon0.Compiler.Tests { using NUnit.Framework; using Oberon0.Compiler.Definitions; using Oberon0.TestSupport; [TestFixture] public class SimpleTests { [Test] public void EmptyApplication() { Module m = Oberon0Compiler.CompileString("MODULE Test; END Test."); Assert.AreEqual("Test", m.Name); Assert.AreEqual(3, m.Block.Declarations.Count); } [Test] public void EmptyApplication2() { Module m = TestHelper.CompileString( @"MODULE Test; BEGIN END Test."); Assert.AreEqual(0, m.Block.Statements.Count); } [Test] public void ModuleMissingDot() { TestHelper.CompileString( @"MODULE Test; END Test", "missing '.' at '<EOF>'"); } [Test] public void ModuleMissingId() { TestHelper.CompileString( @"MODULE ; BEGIN END Test.", "missing ID at ';'", "The name of the module does not match the end node"); } } }
Disable warning "Type is not CLS-compliant"
namespace MvvmFx.CaliburnMicro { using System; /// <summary> /// Used to manage logging. /// </summary> public static class LogManager { private static readonly Logging.ILog NullLogInstance = new Logging.NullLogger(); /// <summary> /// Creates an <see cref="Logging.ILog"/> for the provided type. /// </summary> public static Func<Type, Logging.ILog> GetLog = type => NullLogInstance; } }
namespace MvvmFx.CaliburnMicro { using System; /// <summary> /// Used to manage logging. /// </summary> public static class LogManager { private static readonly Logging.ILog NullLogInstance = new Logging.NullLogger(); #pragma warning disable CS3003 // Type is not CLS-compliant /// <summary> /// Creates an <see cref="Logging.ILog"/> for the provided type. /// </summary> public static Func<Type, Logging.ILog> GetLog = type => NullLogInstance; #pragma warning restore CS3003 // Type is not CLS-compliant } }