using System;
using System.Collections.Generic;
using System.Linq;
using AvsAnLib.Internals;
using WikipediaAvsAnTrieExtractor;
using Xunit;

namespace WikipediaAvsAnTrieExtractorTest {
    public class TriePrefixIncrementorTest {
        [Fact]
        public void BasicIncrementWorks() {
            var node = new Node();
            IncrementPrefixExtensions.IncrementPrefix(ref node, true, "test", 0);
            Assert.Equal(NodeSerializer.Serialize(node), @"(0:1)t(0:1)te(0:1)tes(0:1)test(0:1)test (0:1)" );
        }

        [Fact]
        public void IncrementWithSharedPrefixWorks() {
            var node = new Node();
            IncrementPrefixExtensions.IncrementPrefix(ref node, true, "test", 0);
            IncrementPrefixExtensions.IncrementPrefix(ref node, true, "taste", 0);
            Assert.Equal(NodeSerializer.Serialize(node), @"(0:2)t(0:2)ta(0:1)tas(0:1)tast(0:1)taste(0:1)taste (0:1)te(0:1)tes(0:1)test(0:1)test (0:1)");
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using AvsAnLib.Internals;
using WikipediaAvsAnTrieExtractor;
using Xunit;

namespace WikipediaAvsAnTrieExtractorTest {
    public class TriePrefixIncrementorTest {
        [Fact]
        public void BasicIncrementWorks() {
            var node = new Node();
            IncrementPrefixExtensions.IncrementPrefix(ref node, true, "test", 0);
            Assert.Equal(@"(0:1)t(0:1)te(0:1)tes(0:1)test(0:1)test (0:1)" , NodeSerializer.Serialize(node));
        }

        [Fact]
        public void IncrementWithSharedPrefixWorks() {
            var node = new Node();
            IncrementPrefixExtensions.IncrementPrefix(ref node, true, "test", 0);
            IncrementPrefixExtensions.IncrementPrefix(ref node, true, "taste", 0);
            Assert.Equal(@"(0:2)t(0:2)ta(0:1)tas(0:1)tast(0:1)taste(0:1)taste (0:1)te(0:1)tes(0:1)test(0:1)test (0:1)", NodeSerializer.Serialize(node));
        }
    }
}

Use correct order of equality assertion for better error message (xUnit analyzer)


// Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file

namespace EndlessClient.HUD
{
    public interface IHudButtonController
    {
        void ClickInventory();

        void ClickViewMapToggle();

        void ClickActiveSpells();

        void ClickPassiveSpells();

        void ClickChat();

        void ClickStats();

        void ClickOnlineList();

        void ClickParty();

        //void ClickMacro();

        void ClickSettings();

        void ClickHelp();

        //friend/ignore

        //E/Q
    }
}

// Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file

namespace EndlessClient.HUD
{
    public interface IHudButtonController
    {
        void ClickInventory();

        void ClickViewMapToggle();

        void ClickActiveSpells();

        void ClickPassiveSpells();

        void ClickChat();

        void ClickStats();

        void ClickOnlineList();

        void ClickParty();

        void ClickSettings();

        void ClickHelp();

        //friend/ignore

        //E/Q
    }
}

Remove unused ClickMacro controller method


namespace Grobid.NET
{
    public enum FontSizeStatus
    {
        HIGHERFONT,
        SAMEFONTSIZE,
        LOWFONT,
    }
}

namespace Grobid.NET
{
    public enum FontSizeStatus
    {
        HIGHERFONT,
        SAMEFONTSIZE,
        LOWERFONT,
    }
}

Fix misnamed LOWFONT enumeration to LOWERFONT


using DspAdpcm.Adpcm.Formats.Internal;
using DspAdpcm.Adpcm.Formats.Structures;

namespace DspAdpcm.Adpcm.Formats.Configuration
{
    /// <summary>
    /// Contains the options used to build the BRSTM file.
    /// </summary>
    public class BrstmConfiguration : B_stmConfiguration
    {
        /// <summary>
        /// The type of track description to be used when building the
        /// BRSTM header.
        /// Default is <see cref="BrstmTrackType.Short"/>
        /// </summary>
        public BrstmTrackType TrackType { get; set; } = BrstmTrackType.Short;

        /// <summary>
        /// The type of seek table to use when building the BRSTM
        /// ADPC chunk.
        /// Default is <see cref="BrstmSeekTableType.Standard"/>
        /// </summary>
        public BrstmSeekTableType SeekTableType { get; set; } = BrstmSeekTableType.Standard;
    }
}

using DspAdpcm.Adpcm.Formats.Internal;
using DspAdpcm.Adpcm.Formats.Structures;

namespace DspAdpcm.Adpcm.Formats.Configuration
{
    /// <summary>
    /// Contains the options used to build the BRSTM file.
    /// </summary>
    public class BrstmConfiguration : B_stmConfiguration
    {
        /// <summary>
        /// The type of track description to be used when building the
        /// BRSTM header.
        /// Default is <see cref="BrstmTrackType.Standard"/>
        /// </summary>
        public BrstmTrackType TrackType { get; set; } = BrstmTrackType.Standard;

        /// <summary>
        /// The type of seek table to use when building the BRSTM
        /// ADPC chunk.
        /// Default is <see cref="BrstmSeekTableType.Standard"/>
        /// </summary>
        public BrstmSeekTableType SeekTableType { get; set; } = BrstmSeekTableType.Standard;
    }
}

Make the default BrstmTrackType Standard


using MonoHaven.UI.Widgets;

namespace MonoHaven.UI.Remote
{
	public class ServerImage : ServerWidget
	{
		public static ServerWidget Create(ushort id, ServerWidget parent, object[] args)
		{
			var resName = (string)args[0];

			var widget = new Image(parent.Widget);
			widget.Drawable = App.Resources.GetImage(resName);
			widget.Resize(widget.Drawable.Size);
			return new ServerImage(id, parent, widget);
		}

		public ServerImage(ushort id, ServerWidget parent, Image widget)
			: base(id, parent, widget)
		{
		}
	}
}

using MonoHaven.UI.Widgets;

namespace MonoHaven.UI.Remote
{
	public class ServerImage : ServerWidget
	{
		public static ServerWidget Create(ushort id, ServerWidget parent, object[] args)
		{
			var resName = (string)args[0];

			var widget = new Image(parent.Widget);
			widget.Drawable = App.Resources.GetImage(resName);
			widget.Resize(widget.Drawable.Size);
			return new ServerImage(id, parent, widget);
		}

		private readonly Image widget;

		public ServerImage(ushort id, ServerWidget parent, Image widget)
			: base(id, parent, widget)
		{
			this.widget = widget;
		}

		public override void ReceiveMessage(string message, object[] args)
		{
			if (message == "ch")
				widget.Drawable = App.Resources.GetImage((string)args[0]);
			else
				base.ReceiveMessage(message, args);
		}
	}
}

Support server messages in the Image widget


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System;
using System.Collections.Generic;
using osu.Framework.Extensions.ListExtensions;

namespace osu.Framework.Graphics.Containers
{
    /// <summary>
    /// A basic implementation of <see cref="ITextPart"/>,
    /// which automatically handles returning correct <see cref="Drawables"/>
    /// and raising <see cref="DrawablePartsRecreated"/>.
    /// </summary>
    public abstract class TextPart : ITextPart
    {
        public IEnumerable<Drawable> Drawables => drawables.AsSlimReadOnly();
        private readonly List<Drawable> drawables = new List<Drawable>();

        public event Action<IEnumerable<Drawable>> DrawablePartsRecreated;

        public void RecreateDrawablesFor(TextFlowContainer textFlowContainer)
        {
            drawables.Clear();
            drawables.AddRange(CreateDrawablesFor(textFlowContainer));
            DrawablePartsRecreated?.Invoke(drawables);
        }

        /// <summary>
        /// Creates drawables representing the contents of this <see cref="TextPart"/>,
        /// to be appended to the <paramref name="textFlowContainer"/>.
        /// </summary>
        protected abstract IEnumerable<Drawable> CreateDrawablesFor(TextFlowContainer textFlowContainer);
    }
}

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System;
using System.Collections.Generic;

namespace osu.Framework.Graphics.Containers
{
    /// <summary>
    /// A basic implementation of <see cref="ITextPart"/>,
    /// which automatically handles returning correct <see cref="Drawables"/>
    /// and raising <see cref="DrawablePartsRecreated"/>.
    /// </summary>
    public abstract class TextPart : ITextPart
    {
        public IEnumerable<Drawable> Drawables { get; }
        public event Action<IEnumerable<Drawable>> DrawablePartsRecreated;

        private readonly List<Drawable> drawables = new List<Drawable>();

        protected TextPart()
        {
            Drawables = drawables.AsReadOnly();
        }

        public void RecreateDrawablesFor(TextFlowContainer textFlowContainer)
        {
            drawables.Clear();
            drawables.AddRange(CreateDrawablesFor(textFlowContainer));
            DrawablePartsRecreated?.Invoke(drawables);
        }

        /// <summary>
        /// Creates drawables representing the contents of this <see cref="TextPart"/>,
        /// to be appended to the <paramref name="textFlowContainer"/>.
        /// </summary>
        protected abstract IEnumerable<Drawable> CreateDrawablesFor(TextFlowContainer textFlowContainer);
    }
}

Reduce allocations while maintaining read-only-ness


using System;
using System.Collections.Generic;
using System.Threading;

namespace Toggl.Phoebe.Tests
{
    public class MainThreadSynchronizationContext : SynchronizationContext
    {
        private readonly Thread thread;
        private readonly object syncRoot = new Object ();
        private readonly Queue<Job> jobs = new Queue<Job> ();

        public MainThreadSynchronizationContext ()
        {
            thread = Thread.CurrentThread;
        }

        public bool Run ()
        {
            int count;
            Job job;

            lock (syncRoot) {
                count = jobs.Count;
                if (count < 1)
                    return false;
                job = jobs.Dequeue ();
            }

            try {
                job.Callback (job.State);
            } finally {
                if (job.OnProcessed != null) {
                    job.OnProcessed ();
                }
            }

            return count > 1;
        }

        public override void Post (SendOrPostCallback d, object state)
        {
            Post (d, state, null);
        }

        public override void Send (SendOrPostCallback d, object state)
        {
            if (thread == Thread.CurrentThread) {
                d (state);
            } else {
                // Schedule task and wait for it to complete
                var reset = new ManualResetEventSlim ();
                Post (d, state, reset.Set);
                reset.Wait ();
            }
        }

        private void Post (SendOrPostCallback d, object state, Action completionHandler)
        {
            lock (syncRoot) {
                jobs.Enqueue (new Job () {
                    Callback = d,
                    State = state,
                    OnProcessed = completionHandler,
                });
            }
        }

        struct Job
        {
            public SendOrPostCallback Callback;
            public object State;
            public Action OnProcessed;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Threading;

namespace Toggl.Phoebe.Tests
{
    public class MainThreadSynchronizationContext : SynchronizationContext
    {
        private readonly Thread thread;
        private readonly object syncRoot = new Object ();
        private readonly Queue<Job> jobs = new Queue<Job> ();

        public MainThreadSynchronizationContext ()
        {
            thread = Thread.CurrentThread;
        }

        public bool Run ()
        {
            Job job;

            lock (syncRoot) {
                if (jobs.Count < 1)
                    return false;
                job = jobs.Dequeue ();
            }

            try {
                job.Callback (job.State);
            } finally {
                if (job.OnProcessed != null) {
                    job.OnProcessed ();
                }
            }

            return true;
        }

        public override void Post (SendOrPostCallback d, object state)
        {
            Post (d, state, null);
        }

        public override void Send (SendOrPostCallback d, object state)
        {
            if (thread == Thread.CurrentThread) {
                d (state);
            } else {
                // Schedule task and wait for it to complete
                var reset = new ManualResetEventSlim ();
                Post (d, state, reset.Set);
                reset.Wait ();
            }
        }

        private void Post (SendOrPostCallback d, object state, Action completionHandler)
        {
            lock (syncRoot) {
                jobs.Enqueue (new Job () {
                    Callback = d,
                    State = state,
                    OnProcessed = completionHandler,
                });
            }
        }

        struct Job
        {
            public SendOrPostCallback Callback;
            public object State;
            public Action OnProcessed;
        }
    }
}

Fix sync context Run always returns true when it ran something.

This should fix a possible edgecase where some of the scheduled items
aren't being run due to being added at the very last minute.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

namespace Assets.Scripts
{
    public static class GameObjectUtilities
    {
        public static void SetEnabled(this GameObject obj, bool enabled)
        {
            // Disable rendering of this component
            obj.GetComponent<MeshRenderer>().enabled = enabled;

            // And of its children
            var subComponents = obj.GetComponentsInChildren<MeshRenderer>();

            foreach (var renderer in subComponents)
            {
                renderer.enabled = enabled;
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

namespace Assets.Scripts
{
    public static class GameObjectUtilities
    {
        public static void SetEnabled(this GameObject obj, bool enabled)
        {
            // Disable rendering of this component
            obj.GetComponent<Renderer>().enabled = enabled;

            // And of its children
            var subComponents = obj.GetComponentsInChildren<Renderer>();

            foreach (var renderer in subComponents)
            {
                renderer.enabled = enabled;
            }
        }
    }
}

Make GameObject.SetEnabled extension method more generic


using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;

namespace Modix.Modules
{
    [Name("Info"), Summary("General helper module")]
    public sealed class InfoModule : ModuleBase
    {
        private CommandService commandService;

        public InfoModule(CommandService cs)
        {
            commandService = cs;
        }

        [Command("help"), Summary("Prints a neat list of all commands.")]
        public async Task HelpAsync()
        {
            var eb = new EmbedBuilder();
            var userDm = await Context.User.GetOrCreateDMChannelAsync();

            foreach (var module in commandService.Modules)
            {
                eb = eb.WithTitle($"Module: {module.Name ?? ""}")
                       .WithDescription(module.Summary ?? "");

                foreach(var command in module.Commands)
                {
                    eb.AddField(new EmbedFieldBuilder().WithName($"Command: !{module.Name ?? ""} {command.Name ?? ""} {GetParams(command)}").WithValue(command.Summary ?? ""));
                }

                await userDm.SendMessageAsync(string.Empty, embed: eb.Build());
                eb = new EmbedBuilder();
            }
            await ReplyAsync($"Check your private messages, {Context.User.Mention}");
        }

        private string GetParams(CommandInfo info)
        {
            var sb = new StringBuilder();
            info.Parameters.ToList().ForEach(x =>
            {
                if (x.IsOptional)
                    sb.Append("[Optional(" + x.Name + ")]");
                else
                    sb.Append("[" + x.Name + "]");
            });
            return sb.ToString();
        }
    }
}

using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;

namespace Modix.Modules
{
    [Name("Info"), Summary("General helper module")]
    public sealed class InfoModule : ModuleBase
    {
        private CommandService commandService;

        public InfoModule(CommandService cs)
        {
            commandService = cs;
        }

        [Command("help"), Summary("Prints a neat list of all commands.")]
        public async Task HelpAsync()
        {
            var eb = new EmbedBuilder();
            var userDm = await Context.User.GetOrCreateDMChannelAsync();

            foreach (var module in commandService.Modules)
            {
                eb = eb.WithTitle($"Module: {module.Name ?? "Unknown"}")
                       .WithDescription(module.Summary ?? "Unknown");

                foreach(var command in module.Commands)
                {
                    eb.AddField(new EmbedFieldBuilder().WithName($"Command: !{module.Name ?? ""} {command.Name ?? ""} {GetParams(command)}").WithValue(command.Summary ?? "Unknown"));
                }

                await userDm.SendMessageAsync(string.Empty, embed: eb.Build());
                eb = new EmbedBuilder();
            }
            await ReplyAsync($"Check your private messages, {Context.User.Mention}");
        }

        private string GetParams(CommandInfo info)
        {
            var sb = new StringBuilder();
            info.Parameters.ToList().ForEach(x =>
            {
                if (x.IsOptional)
                    sb.Append("[Optional(" + x.Name + ")]");
                else
                    sb.Append("[" + x.Name + "]");
            });
            return sb.ToString();
        }
    }
}

Fix for help blowing up if a module or command lacks a summary


using System;
using System.Xml.Linq;

namespace Linq2Azure.SqlDatabases
{
    public class Database
    {
        internal Database(XElement xml, DatabaseServer databaseServer)
        {
            xml.HydrateObject(XmlNamespaces.WindowsAzure, this);
            DatabaseServer = databaseServer;
        }

        public DatabaseServer DatabaseServer { get; private set; }
        public string Name { get; private set; }
        public string Type { get; private set; }
        public string State { get; private set; }
        public Uri SelfLink { get; private set; }
        public Uri ParentLink { get; private set; }
        public int Id { get; private set; }
        public string Edition { get; private set; }
        public string CollationName { get; private set; }
        public DateTimeOffset CreationDate { get; private set; }
        public bool IsFederationRoot { get; private set; }
        public bool IsSystemObject { get; private set; }
        public decimal? SizeMB { get; private set; }
        public long MaxSizeBytes { get; private set; }
        public Guid ServiceObjectiveId { get; private set; }
        public Guid AssignedServiceObjectiveId { get; private set; }
        public int ServiceObjectiveAssignmentState { get; private set; }
        public string ServiceObjectiveAssignmentStateDescription { get; private set; }
        public int ServiceObjectiveAssignmentErrorCode { get; private set; }
        public string ServiceObjectiveAssignmentErrorDescription { get; private set; }
        public DateTimeOffset ServiceObjectiveAssignmentSuccessDate { get; private set; }
        public DateTimeOffset? RecoveryPeriodStartDate { get; private set; }
        public bool IsSuspended { get; private set; }
    }
}

using System;
using System.Xml.Linq;

namespace Linq2Azure.SqlDatabases
{
    public class Database
    {
        internal Database(XElement xml, DatabaseServer databaseServer)
        {
            xml.HydrateObject(XmlNamespaces.WindowsAzure, this);
            DatabaseServer = databaseServer;
        }

        public DatabaseServer DatabaseServer { get; private set; }
        public string Name { get; private set; }
        public string Type { get; private set; }
        public string State { get; private set; }
        public Uri SelfLink { get; private set; }
        public Uri ParentLink { get; private set; }
        public int Id { get; private set; }
        public string Edition { get; private set; }
        public string CollationName { get; private set; }
        public DateTimeOffset CreationDate { get; private set; }
        public bool IsFederationRoot { get; private set; }
        public bool IsSystemObject { get; private set; }
        public decimal? SizeMB { get; private set; }
        public long MaxSizeBytes { get; private set; }
        public Guid ServiceObjectiveId { get; private set; }
        public Guid AssignedServiceObjectiveId { get; private set; }
        public int? ServiceObjectiveAssignmentState { get; private set; }
        public string ServiceObjectiveAssignmentStateDescription { get; private set; }
        public int ServiceObjectiveAssignmentErrorCode { get; private set; }
        public string ServiceObjectiveAssignmentErrorDescription { get; private set; }
        public DateTimeOffset? ServiceObjectiveAssignmentSuccessDate { get; private set; }
        public DateTimeOffset? RecoveryPeriodStartDate { get; private set; }
        public bool IsSuspended { get; private set; }
    }
}

Allow properties to be nullable to support V12 databases


using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace BoardGamesApi.Controllers
{
    [ApiExplorerSettings(IgnoreApi = true)]
    public class TempController : Controller
    {
        private readonly IConfiguration _configuration;

        public TempController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        [AllowAnonymous]
        [Route("/get-token")]
        public IActionResult GenerateToken(string name = "mscommunity")
        {
            var jwt = JwtTokenGenerator
                .Generate(name, true, _configuration["Token:Issuer"], _configuration["Token:Key"]);

            return Ok(jwt);
        }
    }
}

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace BoardGamesApi.Controllers
{
    [ApiExplorerSettings(IgnoreApi = true)]
    public class TempController : Controller
    {
        private readonly IConfiguration _configuration;

        public TempController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        [AllowAnonymous]
        [Route("/get-token")]
        public IActionResult GenerateToken(string name = "mscommunity")
        {
            var jwt = JwtTokenGenerator
                .Generate(name, true, _configuration["Tokens:Issuer"], _configuration["Tokens:Key"]);

            return Ok(jwt);
        }
    }
}

Fix the issue with settings name

Fix the issue with settings name


@{
    ViewBag.Title = "Typing Classifier";
}

    This will be our awesome typing classifier

    Typing classifier goes here.

	@Html.ActionLink("Go to results", "Results", "Home");

@{
    ViewBag.Title = "Typing Classifier";
}
@section scripts
{

}

    This will be our awesome typing classifier

    Typing classifier goes here.

  <textarea></textarea>

	@Html.ActionLink("Go to results", "Results", "Home");

Add textarea, keyboard listener and timer.


using System;
using System.Linq;
using System.Web.Mvc;
using Hangfire.Highlighter.Jobs;
using Hangfire.Highlighter.Models;

namespace Hangfire.Highlighter.Controllers
{
    public class HomeController : Controller
    {
        private readonly HighlighterDbContext _db = new HighlighterDbContext();

        public ActionResult Index()
        {
            return View(_db.CodeSnippets.ToList());
        }

        public ActionResult Details(int id)
        {
            var snippet = _db.CodeSnippets.Find(id);
            return View(snippet);
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create([Bind(Include = "SourceCode")] CodeSnippet snippet)
        {
            if (ModelState.IsValid)
            {
                snippet.CreatedAt = DateTime.UtcNow;

                _db.CodeSnippets.Add(snippet);
                _db.SaveChanges();

                using (StackExchange.Profiling.MiniProfiler.StepStatic("Job enqueue"))
                {
                    // Enqueue a job
                    BackgroundJob.Enqueue<SnippetHighlighter>(x => x.HighlightAsync(snippet.Id));
                }

                return RedirectToAction("Details", new { id = snippet.Id });
            }

            return View(snippet);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

using System;
using System.Linq;
using System.Web.Mvc;
using Hangfire.Highlighter.Jobs;
using Hangfire.Highlighter.Models;

namespace Hangfire.Highlighter.Controllers
{
    public class HomeController : Controller
    {
        private readonly HighlighterDbContext _db = new HighlighterDbContext();

        public ActionResult Index()
        {
            return View(_db.CodeSnippets.OrderByDescending(x => x.Id).ToList());
        }

        public ActionResult Details(int id)
        {
            var snippet = _db.CodeSnippets.Find(id);
            return View(snippet);
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create([Bind(Include = "SourceCode")] CodeSnippet snippet)
        {
            if (ModelState.IsValid)
            {
                snippet.CreatedAt = DateTime.UtcNow;

                _db.CodeSnippets.Add(snippet);
                _db.SaveChanges();

                using (StackExchange.Profiling.MiniProfiler.StepStatic("Job enqueue"))
                {
                    // Enqueue a job
                    BackgroundJob.Enqueue<SnippetHighlighter>(x => x.HighlightAsync(snippet.Id));
                }

                return RedirectToAction("Details", new { id = snippet.Id });
            }

            return View(snippet);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

Sort snippets in descending order

Sort snippets in descending order


@using System.Threading.Tasks

Secure HTTP (HTTPS)

            Last updated

            This data measures whether GOV.UK support the HTTPS protocol (https://), and the strength of that support. HTTPS provides a secure connection across the internet between websites and their visitors, and is becoming the new baseline for public web services.

            Note that HTTPS generally does not affect whether a website is vulnerable to hacking.

            HTTPS and TLS data was last collected through a scan of the public internet on the .

            Domain
            Uses HTTPS
            SSL Labs Grade

Make pie chart div wider

Make pie chart div wider

Prevents clipping on narrow screens


using ProjectCDA.Model;
using ProjectCDA.Model.Constants;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace ProjectCDA.DAL
{
    public class DataService : IDataService
    {
        public IEnumerable<FacingPages> GetData()
        {
            ObservableCollection<FacingPages> gridData = new ObservableCollection<FacingPages>();

            FacingPages pages = new FacingPages();
            pages.ID = 0;
            pages.Type = FacingPagesTypes.DEFAULT;
            gridData.Add(pages);

            pages = new FacingPages();
            pages.ID = 1;
            pages.Type = FacingPagesTypes.NO_HEADER;
            gridData.Add(pages);

            pages = new FacingPages();
            pages.ID = 2;
            pages.Type = FacingPagesTypes.SINGLE_PAGE;
            gridData.Add(pages);

            for (int i = 3; i < 65; i++)
            {
                pages = new FacingPages();
                pages.ID = i;
                pages.Type = FacingPagesTypes.DEFAULT;
                gridData.Add(pages);
            }

            return gridData;
        }
    }
}

using ProjectCDA.Model;
using ProjectCDA.Model.Constants;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace ProjectCDA.DAL
{
    public class DataService : IDataService
    {
        public IEnumerable<FacingPages> GetData()
        {
            return GetMockData();
        }

        public IEnumerable<FacingPages> GetMockData()
        {
            ObservableCollection<FacingPages> gridData = new ObservableCollection<FacingPages>();

            FacingPages pages = new FacingPages();
            pages.ID = 0;
            pages.Type = FacingPagesTypes.DEFAULT;
            gridData.Add(pages);

            pages = new FacingPages();
            pages.ID = 1;
            pages.Type = FacingPagesTypes.NO_HEADER;
            gridData.Add(pages);

            pages = new FacingPages();
            pages.ID = 2;
            pages.Type = FacingPagesTypes.SINGLE_PAGE;
            gridData.Add(pages);

            for (int i = 3; i < 65; i++)
            {
                pages = new FacingPages();
                pages.ID = i;
                pages.Type = FacingPagesTypes.DEFAULT;
                gridData.Add(pages);
            }

            return gridData;
        }
    }
}

Move generating mock data to separate function.


using System;
using System.IO;

namespace Hangman {
  public class Hangman {
    public static void Main(string[] args) {
      var game = new Game("HANG THE MAN");

      while (true) {
        string titleText = File.ReadAllText("title.txt");

        Cell[] title = {
          new Cell(titleText, Cell.CentreAlign)
        };

        string shownWord = game.ShownWord();
        Cell[] word = {
          new Cell(shownWord, Cell.CentreAlign)
        };

        Cell[] stats = {
          new Cell("Incorrect letters:\n A B I U"),
          new Cell("Lives remaining:\n 11/15", Cell.RightAlign)
        };

        Cell[] status = {
          new Cell("Press any letter to guess!", Cell.CentreAlign)
        };

        Row[] rows = {
          new Row(title),
          new Row(word),
          new Row(stats),
          new Row(status)
        };

        var table = new Table(
          Math.Min(81, Console.WindowWidth),
          2,
          rows
        );

        var tableOutput = table.Draw();

        Console.WriteLine(tableOutput);

        char key = Console.ReadKey(true).KeyChar;
        bool wasCorrect = game.GuessLetter(key);
        Console.Clear();
      }
    }
  }
}

using System;
using System.IO;

namespace Hangman {
  public class Hangman {
    public static void Main(string[] args) {
      var game = new Game("HANG THE MAN");

      while (true) {
        string titleText = File.ReadAllText("title.txt");

        Cell[] title = {
          new Cell(titleText, Cell.CentreAlign)
        };

        string shownWord = game.ShownWord();
        Cell[] word = {
          new Cell(shownWord, Cell.CentreAlign)
        };

        Cell[] stats = {
          new Cell("Incorrect letters:\n A B I U"),
          new Cell("Lives remaining:\n 11/15", Cell.RightAlign)
        };

        Cell[] status = {
          new Cell("Press any letter to guess!", Cell.CentreAlign)
        };

        Row[] rows = {
          new Row(title),
          new Row(word),
          new Row(stats),
          new Row(status)
        };

        var table = new Table(
          Math.Min(81, Console.WindowWidth),
          2,
          rows
        );

        var tableOutput = table.Draw();

        Console.WriteLine(tableOutput);

        char key = Console.ReadKey(true).KeyChar;
        bool wasCorrect = game.GuessLetter(Char.ToUpper(key));
        Console.Clear();
      }
    }
  }
}

Make key entry case insensitive

Make key entry case insensitive


// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Microsoft.CodeAnalysis.InheritanceMargin;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Editor.InheritanceMargin
{
    internal static class InheritanceMarginHelpers
    {
        /// <summary>
        /// Decide which moniker should be shown.
        /// </summary>
        public static ImageMoniker GetMoniker(InheritanceRelationship inheritanceRelationship)
        {
            //  If there are multiple targets and we have the corresponding compound image, use it
            if (inheritanceRelationship.HasFlag(InheritanceRelationship.ImplementingOverriding))
            {
                return KnownMonikers.Implementing;
            }

            if (inheritanceRelationship.HasFlag(InheritanceRelationship.ImplementingOverridden))
            {
                return KnownMonikers.Implementing;
            }

            // Otherwise, show the image based on this preference
            if (inheritanceRelationship.HasFlag(InheritanceRelationship.Implemented))
            {
                return KnownMonikers.Implemented;
            }

            if (inheritanceRelationship.HasFlag(InheritanceRelationship.Implementing))
            {
                return KnownMonikers.Implementing;
            }

            if (inheritanceRelationship.HasFlag(InheritanceRelationship.Overridden))
            {
                return KnownMonikers.Overridden;
            }

            if (inheritanceRelationship.HasFlag(InheritanceRelationship.Overriding))
            {
                return KnownMonikers.Overriding;
            }

            // The relationship is None. Don't know what image should be shown, throws
            throw ExceptionUtilities.UnexpectedValue(inheritanceRelationship);
        }
    }
}

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Microsoft.CodeAnalysis.InheritanceMargin;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Editor.InheritanceMargin
{
    internal static class InheritanceMarginHelpers
    {
        /// <summary>
        /// Decide which moniker should be shown.
        /// </summary>
        public static ImageMoniker GetMoniker(InheritanceRelationship inheritanceRelationship)
        {
            //  If there are multiple targets and we have the corresponding compound image, use it
            if (inheritanceRelationship.HasFlag(InheritanceRelationship.ImplementingOverriding))
            {
                return KnownMonikers.ImplementingOverriding;
            }

            if (inheritanceRelationship.HasFlag(InheritanceRelationship.ImplementingOverridden))
            {
                return KnownMonikers.ImplementingOverridden;
            }

            // Otherwise, show the image based on this preference
            if (inheritanceRelationship.HasFlag(InheritanceRelationship.Implemented))
            {
                return KnownMonikers.Implemented;
            }

            if (inheritanceRelationship.HasFlag(InheritanceRelationship.Implementing))
            {
                return KnownMonikers.Implementing;
            }

            if (inheritanceRelationship.HasFlag(InheritanceRelationship.Overridden))
            {
                return KnownMonikers.Overridden;
            }

            if (inheritanceRelationship.HasFlag(InheritanceRelationship.Overriding))
            {
                return KnownMonikers.Overriding;
            }

            // The relationship is None. Don't know what image should be shown, throws
            throw ExceptionUtilities.UnexpectedValue(inheritanceRelationship);
        }
    }
}

Fix the temp enum change

Fix the temp enum change


using System;

namespace Avalonia.Media.Fonts
{
    public readonly struct FontKey : IEquatable<FontKey>
    {
        public readonly string FamilyName;
        public readonly FontStyle Style;
        public readonly FontWeight Weight;

        public FontKey(string familyName, FontWeight weight, FontStyle style)
        {
            FamilyName = familyName;
            Style = style;
            Weight = weight;
        }

        public override int GetHashCode()
        {
            var hash = FamilyName.GetHashCode();

            hash = hash * 31 + (int)Style;
            hash = hash * 31 + (int)Weight;

            return hash;
        }

        public override bool Equals(object other)
        {
            return other is FontKey key && Equals(key);
        }

        public bool Equals(FontKey other)
        {
            return FamilyName == other.FamilyName &&
                Style == other.Style &&
                   Weight == other.Weight;
        }
    }
}

using System;

namespace Avalonia.Media.Fonts
{
    public readonly struct FontKey : IEquatable<FontKey>
    {
        public FontKey(string familyName, FontWeight weight, FontStyle style)
        {
            FamilyName = familyName;
            Style = style;
            Weight = weight;
        }

        public string FamilyName { get; }
        public FontStyle Style { get; }
        public FontWeight Weight { get; }

        public override int GetHashCode()
        {
            var hash = FamilyName.GetHashCode();

            hash = hash * 31 + (int)Style;
            hash = hash * 31 + (int)Weight;

            return hash;
        }

        public override bool Equals(object other)
        {
            return other is FontKey key && Equals(key);
        }

        public bool Equals(FontKey other)
        {
            return FamilyName == other.FamilyName &&
                Style == other.Style &&
                   Weight == other.Weight;
        }
    }
}

Use readonly properties instead of public fields


using System;

namespace ZBuildLights.Core.Models
{
    public class EditProject
    {
        public Guid? ProjectId { get; set; }
        public string Name { get; set; }
        public EditProjectCruiseProject[] CruiseProjects { get; set; }
    }

    public class EditProjectCruiseProject
    {
        public string Project { get; set; }
        public Guid Server { get; set; }
    }
}

using System;

namespace ZBuildLights.Core.Models
{
    public class EditProject
    {
        public Guid? ProjectId { get; set; }
        public string Name { get; set; }
        public EditProjectCruiseProject[] CruiseProjects { get; set; }

        public EditProjectCruiseProject[] SafeProjects
        {
            get { return CruiseProjects ?? new EditProjectCruiseProject[0]; }
        }
    }

    public class EditProjectCruiseProject
    {
        public string Project { get; set; }
        public Guid Server { get; set; }
    }
}

Fix null reference exception when creating a project.


// 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.Framework.Bindables
{
    /// <summary>
    /// An interface that represents a leased bindable.
    /// </summary>
    public interface ILeasedBindable : IBindable
    {
        /// <summary>
        /// End the lease on the source <see cref="Bindable{T}"/>.
        /// </summary>
        /// <returns>
        /// Whether the lease was returned. Will be <c>false</c> if already returned.
        /// </returns>
        bool Return();
    }

    /// <summary>
    /// An interface that representes a leased bindable.
    /// </summary>
    /// <typeparam name="T">The value type of the bindable.</typeparam>
    public interface ILeasedBindable<T> : ILeasedBindable, IBindable<T>
    {
    }
}

// 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.Framework.Bindables
{
    /// <summary>
    /// An interface that represents a leased bindable.
    /// </summary>
    public interface ILeasedBindable : IBindable
    {
        /// <summary>
        /// End the lease on the source <see cref="Bindable{T}"/>.
        /// </summary>
        /// <returns>
        /// Whether the lease was returned by this call. Will be <c>false</c> if already returned.
        /// </returns>
        bool Return();
    }

    /// <summary>
    /// An interface that representes a leased bindable.
    /// </summary>
    /// <typeparam name="T">The value type of the bindable.</typeparam>
    public interface ILeasedBindable<T> : ILeasedBindable, IBindable<T>
    {
    }
}

Clarify xmldoc regarding return value

Clarify xmldoc regarding return value

Co-authored-by: Bartłomiej Dach <809709723693c4e7ecc6f5379a3099c830279741@gmail.com>


using NUnit.Framework;
using ZobShop.Models;

namespace ZobShop.Tests.Models.UserTests
{
    [TestFixture]
    public class PropertyTests
    {
        [TestCase("street")]
        [TestCase("highway")]
        [TestCase("boulevard")]
        public void TestAddressProperty_ShouldWorkCorrectly(string address)
        {
            var user = new User();
            user.Address = address;

            Assert.AreEqual(address, user.Address);
        }
    }
}

using NUnit.Framework;
using ZobShop.Models;

namespace ZobShop.Tests.Models.UserTests
{
    [TestFixture]
    public class PropertyTests
    {
        [TestCase("street")]
        [TestCase("highway")]
        [TestCase("boulevard")]
        public void TestAddressProperty_ShouldWorkCorrectly(string address)
        {
            var user = new User();
            user.Address = address;

            Assert.AreEqual(address, user.Address);
        }

        [TestCase("Pesho")]
        [TestCase("Gosho")]
        [TestCase("Stamat")]
        public void TestNameProperty_ShouldWorkCorrectly(string name)
        {
            var user = new User();
            user.Name = name;

            Assert.AreEqual(name, user.Name);
        }
    }
}

Add tests for user name

Add tests for user name


using SharpDX.Windows;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CoreTest
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            RenderForm form = new RenderForm();
            CoreTestApp app = new CoreTestApp(form);
            Application.Run(form);
        }
    }
}

using SharpDX.Windows;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CoreTest
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            NVOptimusEnabler nvEnabler = new NVOptimusEnabler();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            RenderForm form = new RenderForm();
            CoreTestApp app = new CoreTestApp(form);
            Application.Run(form);
        }
    }

    public sealed class NVOptimusEnabler
    {
        static NVOptimusEnabler()
        {
            try
            {

                if (Environment.Is64BitProcess)
                    NativeMethods.LoadNvApi64();
                else
                    NativeMethods.LoadNvApi32();
            }
            catch { } // will always fail since 'fake' entry point doesn't exists
        }
    };

    internal static class NativeMethods
    {
        [System.Runtime.InteropServices.DllImport("nvapi64.dll", EntryPoint = "fake")]
        internal static extern int LoadNvApi64();

        [System.Runtime.InteropServices.DllImport("nvapi.dll", EntryPoint = "fake")]
        internal static extern int LoadNvApi32();
    }
}

Add nv optimus enabler for core tester

Add nv optimus enabler for core tester


// 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.RealtimeMultiplayer
{
    public class MultiplayerClientState
    {
        public MultiplayerClientState(in long roomId)
        {
            CurrentRoomID = roomId;
        }

        public long CurrentRoomID { get; }
    }
}

// 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.RealtimeMultiplayer
{
    public class MultiplayerClientState
    {
        public long CurrentRoomID { get; set; }

        public MultiplayerClientState(in long roomId)
        {
            CurrentRoomID = roomId;
        }
    }
}

Fix serialization failure due to missing set


using System.IO;
using Microsoft.Extensions.Configuration;
using System.Linq;

namespace MyNatsClient.IntegrationTests
{
    public static class TestSettings
    {
        public static IConfigurationRoot Config { get; set; }

        static TestSettings()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory());

            builder.AddJsonFile("testsettings.json");
            Config = builder.Build();
        }

        public static Host[] GetHosts()
        {
            return Config.GetSection("clientIntegrationTests:hosts").GetChildren().Select(i =>
            {
                var u = i["credentials:usr"];
                var p = i["credentials:pwd"];

                return new Host(i["address"], int.Parse(i["port"]))
                {
                    Credentials = !string.IsNullOrWhiteSpace(u) ? new Credentials(u, p) : Credentials.Empty
                };
            }).ToArray();
        }
    }
}

using System;
using System.IO;
using Microsoft.Extensions.Configuration;
using System.Linq;

namespace MyNatsClient.IntegrationTests
{
    public static class TestSettings
    {
        public static IConfigurationRoot Config { get; set; }

        static TestSettings()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(AppContext.BaseDirectory);

            builder.AddJsonFile("testsettings.json");
            Config = builder.Build();
        }

        public static Host[] GetHosts()
        {
            return Config.GetSection("clientIntegrationTests:hosts").GetChildren().Select(i =>
            {
                var u = i["credentials:usr"];
                var p = i["credentials:pwd"];

                return new Host(i["address"], int.Parse(i["port"]))
                {
                    Credentials = !string.IsNullOrWhiteSpace(u) ? new Credentials(u, p) : Credentials.Empty
                };
            }).ToArray();
        }
    }
}

Fix so that dotnet test command can be used


#if DESKTOP
using System;

namespace Eto.Forms
{
	public partial interface IActionItem
	{
		MenuItem Generate(Generator generator);
	}

	public abstract partial class ActionItemBase
	{
		public abstract MenuItem Generate(Generator generator);
	}

	public partial class ActionItemSeparator : ActionItemBase
	{
		public override MenuItem Generate(Generator generator)
		{
			var mi = new SeparatorMenuItem(generator);
			if (!string.IsNullOrEmpty(MenuItemStyle))
				mi.Style = MenuItemStyle;
			return mi;
		}
	}

	public partial class ActionItemSubMenu
	{
		public override MenuItem Generate(Generator generator)
		{
			ImageMenuItem item = null;
			if (Actions.Count > 0)
			{
				item = new ImageMenuItem(generator);
				item.Text = SubMenuText;
				if (!string.IsNullOrEmpty(MenuItemStyle))
					item.Style = MenuItemStyle;
				Actions.Generate(item);
			}
			return item;
		}
	}

	public partial class ActionItem
	{
		public override MenuItem Generate(Generator generator)
		{
			var item = this.Action.GenerateMenuItem(this, generator);
			if (item != null)
			{
				if (!string.IsNullOrEmpty(MenuItemStyle))
					item.Style = MenuItemStyle;
			}
			return item;
		}
	}
}
#endif

#if DESKTOP
using System;

namespace Eto.Forms
{
	public partial interface IActionItem
	{
		MenuItem Generate(Generator generator);
	}

	public abstract partial class ActionItemBase
	{
		public abstract MenuItem Generate(Generator generator);
	}

	public partial class ActionItemSeparator : ActionItemBase
	{
		public override MenuItem Generate(Generator generator)
		{
			var mi = new SeparatorMenuItem(generator);
			if (!string.IsNullOrEmpty(MenuItemStyle))
				mi.Style = MenuItemStyle;
			return mi;
		}
	}

	public partial class ActionItemSubMenu
	{
		public override MenuItem Generate(Generator generator)
		{
			ImageMenuItem item = null;
			if (Actions.Count > 0)
			{
				item = new ImageMenuItem(generator);
				item.Text = SubMenuText;
				item.ID = this.ID;
				if (!string.IsNullOrEmpty(MenuItemStyle))
					item.Style = MenuItemStyle;
				Actions.Generate(item);
			}
			return item;
		}
	}

	public partial class ActionItem
	{
		public override MenuItem Generate(Generator generator)
		{
			var item = this.Action.GenerateMenuItem(this, generator);
			if (item != null)
			{
				if (!string.IsNullOrEmpty(MenuItemStyle))
					item.Style = MenuItemStyle;
			}
			return item;
		}
	}
}
#endif

Set the ID of a submenu.

Set the ID of a submenu.


using Microsoft.AspNetCore.Mvc;
using Promact.Trappist.DomainModel.Models.Question;
using Promact.Trappist.Repository.Questions;
using System;

namespace Promact.Trappist.Core.Controllers
{
    [Route("api/question")]
    public class QuestionsController : Controller
    {
        private readonly IQuestionRepository _questionsRepository;

        public QuestionsController(IQuestionRepository questionsRepository)
        {
            _questionsRepository = questionsRepository;
        }

        [HttpGet]
        /// <summary>
        /// Gets all questions
        /// </summary>
        /// <returns>Questions list</returns>
        public IActionResult GetQuestions()
        {
            var questions = _questionsRepository.GetAllQuestions();
            return Json(questions);
        }
    }
}

using Microsoft.AspNetCore.Mvc;
using Promact.Trappist.DomainModel.Models.Question;
using Promact.Trappist.Repository.Questions;
using System;

namespace Promact.Trappist.Core.Controllers
{
    [Route("api/question")]
    public class QuestionsController : Controller
    {
        private readonly IQuestionRepository _questionsRepository;

        public QuestionsController(IQuestionRepository questionsRepository)
        {
            _questionsRepository = questionsRepository;
        }

        [HttpGet]
        /// <summary>
        /// Gets all questions
        /// </summary>
        /// <returns>Questions list</returns>
        public IActionResult GetQuestions()
        {
            var questions = _questionsRepository.GetAllQuestions();
            return Json(questions);
        }
        [HttpPost]
        /// <summary>
        ///
        /// </summary>
        /// <param name="singleMultipleAnswerQuestion"></param>
        /// <returns></returns>
        public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
        {
            _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion);
            return Ok();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="singleMultipleAnswerQuestion"></param>
        /// <returns></returns>
        public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
        {
            _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption);
            return Ok();
        }
    }
}

Create server side API for single multiple answer question


// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

namespace Microsoft.Azure.WebJobs.Script.Description
{
    public static class CSharpConstants
    {
        public const string PrivateAssembliesFolderName = "bin";

        public const string ProjectFileName = "Project.json";

        public const string ProjectLockFileName = "Project.lock.json";

        public const string MissingFunctionEntryPointCompilationCode = "AF001";

        public const string AmbiguousFunctionEntryPointsCompilationCode = "AF002";

        public const string MissingTriggerArgumentCompilationCode = "AF003";

        public const string MissingBindingArgumentCompilationCode = "AF004";

        public const string RedundantPackageAssemblyReference = "AF005";
    }
}

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

namespace Microsoft.Azure.WebJobs.Script.Description
{
    public static class CSharpConstants
    {
        public const string PrivateAssembliesFolderName = "bin";

        public const string ProjectFileName = "project.json";

        public const string ProjectLockFileName = "project.lock.json";

        public const string MissingFunctionEntryPointCompilationCode = "AF001";

        public const string AmbiguousFunctionEntryPointsCompilationCode = "AF002";

        public const string MissingTriggerArgumentCompilationCode = "AF003";

        public const string MissingBindingArgumentCompilationCode = "AF004";

        public const string RedundantPackageAssemblyReference = "AF005";
    }
}

Correct casing of file names

Correct casing of file names


using System.Threading.Tasks;
using Microsoft.ServiceFabric.Data;

namespace ServiceFabric.Mocks
{
    /// <summary>
    /// A sequence of operations performed as a single logical unit of work.
    /// </summary>
    public class MockTransaction : ITransaction
    {
        public long CommitSequenceNumber => 0L;

        public bool IsCommitted { get; private set; }

        public bool IsAborted { get; private set; }

        public bool IsCompleted => IsCommitted || IsAborted;

        public long TransactionId => 0L;

        public void Abort()
        {
            IsAborted = true;
        }

        public Task CommitAsync()
        {
            IsCommitted = true;
            return Task.FromResult(true);
        }

        public void Dispose()
        {
            Dispose();
            IsAborted = true;
        }

        public Task<long> GetVisibilitySequenceNumberAsync()
        {
            return Task.FromResult(0L);
        }
    }
}

using System.Threading.Tasks;
using Microsoft.ServiceFabric.Data;

namespace ServiceFabric.Mocks
{
    /// <summary>
    /// A sequence of operations performed as a single logical unit of work.
    /// </summary>
    public class MockTransaction : ITransaction
    {
        public long CommitSequenceNumber => 0L;

        public bool IsCommitted { get; private set; }

        public bool IsAborted { get; private set; }

        public bool IsCompleted => IsCommitted || IsAborted;

        public long TransactionId => 0L;

        public void Abort()
        {
            IsAborted = true;
        }

        public Task CommitAsync()
        {
            IsCommitted = true;
            return Task.FromResult(true);
        }

        public void Dispose()
        {
            IsAborted = true;
        }

        public Task<long> GetVisibilitySequenceNumberAsync()
        {
            return Task.FromResult(0L);
        }
    }
}

Remove cyclical Dispose method causing error.


namespace BatteryCommander.Common.Migrations
{
    using System.Data.Entity.Migrations;

    internal sealed class Configuration : DbMigrationsConfiguration<BatteryCommander.Common.DataContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
        }

        protected override void Seed(BatteryCommander.Common.DataContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
        }
    }
}

namespace BatteryCommander.Common.Migrations
{
    using BatteryCommander.Common.Models;
    using System.Data.Entity.Migrations;

    internal sealed class Configuration : DbMigrationsConfiguration<BatteryCommander.Common.DataContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
        }

        protected override void Seed(BatteryCommander.Common.DataContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data.

            context.Qualifications.AddOrUpdate(
                q => new { q.Name, q.Description },

                // Field Artillery Qual Events

                new Qualification { Name = "FA Safety" },
                new Qualification { Name = "ASPT", Description = "Artillery Skills Proficiency Test" },
                new Qualification { Name = "GQT", Description = "Gunner's Qualification Test" },
                new Qualification { Name = "LDR VAL", Description = "Leader's Validation" },

                // Weapon Qual Events

                new Qualification { Name = "M-4 IWQ", Description = "M-4 Individual Weapons Qual" },
                new Qualification { Name = "M-240B", Description = "M-240B Crew Serve Weapons Qual" },
                new Qualification { Name = "M-2", Description = "M-2 Crew Serve Weapons Qual" },

                // Driver Quals

                // Otther individual warrior task quals

                new Qualification { Name = "CLS", Description = "Combat Life Saver" },
                new Qualification { Name = "DSCA", Description = "Defense Support of Civil authorities" }
                );

            context.Users.AddOrUpdate(
                u => u.UserName,
                new AppUser
                {
                    UserName = "mattgwagner@gmail.com",
                    EmailAddressConfirmed = true,
                    PhoneNumber = "8134136839",
                    PhoneNumberConfirmed = true
                });
        }
    }
}

Add some seed data for quals

Add some seed data for quals


// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Diagnostics.Contracts;
using Xunit;

namespace System.Diagnostics.Contracts.Tests
{
    public class BasicContractsTest
    {
        [Fact]
        public static void AssertTrueDoesNotRaiseEvent()
        {
            bool eventRaised = false;
            Contract.ContractFailed += (s, e) =>
            {
                eventRaised = true;
                e.SetHandled();
            };

            Contract.Assert(true);
            Assert.False(eventRaised, "ContractFailed event was raised");
        }

        [Fact]
        public static void AssertFalseRaisesEvent()
        {
            bool eventRaised = false;
            Contract.ContractFailed += (s, e) =>
            {
                eventRaised = true;
                e.SetHandled();
            };

            Contract.Assert(false);
            Assert.True(eventRaised, "ContractFailed event not raised");
        }

        [Fact]
        public static void AssertFalseThrows()
        {
            bool eventRaised = false;
            Contract.ContractFailed += (s, e) =>
            {
                eventRaised = true;
                e.SetUnwind();
            };

            Assert.ThrowsAny<Exception>(() =>
            {
                Contract.Assert(false, "Some kind of user message");
            });

            Assert.True(eventRaised, "Event was not raised");
        }
    }
}

// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Diagnostics.Contracts;
using Xunit;

namespace System.Diagnostics.Contracts.Tests
{
    public class BasicContractsTest
    {
        [Fact]
        public static void AssertTrueDoesNotRaiseEvent()
        {
            bool eventRaised = false;
            Contract.ContractFailed += (s, e) =>
            {
                eventRaised = true;
                e.SetHandled();
            };

            Contract.Assert(true);

            Assert.False(eventRaised, "ContractFailed event was raised");
        }

        [Fact]
        public static void AssertFalseRaisesEvent()
        {
            bool eventRaised = false;
            Contract.ContractFailed += (s, e) =>
            {
                eventRaised = true;
                e.SetHandled();
            };

            Contract.Assert(false);
#if DEBUG
            Assert.True(eventRaised, "ContractFailed event not raised");
#else
            Assert.False(eventRaised, "ContractFailed event was raised");
#endif
        }

        [Fact]
        public static void AssertFalseThrows()
        {
            bool eventRaised = false;
            Contract.ContractFailed += (s, e) =>
            {
                eventRaised = true;
                e.SetUnwind();
            };

#if DEBUG
            Assert.ThrowsAny<Exception>(() =>
            {
                Contract.Assert(false, "Some kind of user message");
            });

            Assert.True(eventRaised, "Event was not raised");
#else
            Contract.Assert(false, "Some kind of user message");

            Assert.False(eventRaised, "ContractFailed event was raised");
#endif
        }
    }
}

Update S.Diag.Contracts tests to verify behavior for DEBUG and !DEBUG

System.Diagnostics.Contracts is implemented in mscorlib.  In versions
of mscorlib compiled with the DEBUG property, the Contract.Assert
methods are active.  In versions of mscorlib compiled without the
DEBUG property, the Contract.Assert methods are no-ops.  This change
updates the test to verify the behavior based on if it was compiled
with or without the DEBUG property.  It's then important that the
configuration of the test (debug or retail) match that of the mscorlib
it is testing.


using System;
using System.Collections.Generic;
using System.Linq;

namespace SyncTool.Cli.Installation
{
    public class PathVariableInstallerStep : IInstallerStep
    {
        public void OnInitialInstall(Version version)
        {
            var value = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.User) ?? "";
            var currentValues = new HashSet<string>(value.Split(';'), StringComparer.InvariantCultureIgnoreCase);

            if (!currentValues.Contains(ApplicationInfo.RootDirectory))
            {
                Environment.SetEnvironmentVariable("PATH", value + ";" + ApplicationInfo.RootDirectory, EnvironmentVariableTarget.User);
            }

        }

        public void OnAppUpdate(Version version)
        {
        }

        public void OnAppUninstall(Version version)
        {
            var value = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.User) ?? "";
            var currentValues = new HashSet<string>(value.Split(';'), StringComparer.InvariantCultureIgnoreCase);

            var valuesToRemove = currentValues.Where(v => StringComparer.InvariantCultureIgnoreCase.Equals(v, ApplicationInfo.RootDirectory));
            foreach (var path in valuesToRemove)
            {
                value = value.Replace(path, "");
            }

            while (value.Contains(";;"))
            {
                value = value.Replace(";;", ";");
            }

            Environment.SetEnvironmentVariable("PATH", value + ";" + ApplicationInfo.RootDirectory, EnvironmentVariableTarget.User);
        }

    }
}

using System;
using System.Collections.Generic;
using System.Linq;

namespace SyncTool.Cli.Installation
{
    public class PathVariableInstallerStep : IInstallerStep
    {
        public void OnInitialInstall(Version version)
        {
            var value = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.User) ?? "";
            var currentValues = new HashSet<string>(value.Split(';'), StringComparer.InvariantCultureIgnoreCase);

            if (!currentValues.Contains(ApplicationInfo.RootDirectory))
            {
                Environment.SetEnvironmentVariable("PATH", value + ";" + ApplicationInfo.RootDirectory, EnvironmentVariableTarget.User);
            }

        }

        public void OnAppUpdate(Version version)
        {
        }

        public void OnAppUninstall(Version version)
        {
            var value = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.User) ?? "";
            var currentValues = new HashSet<string>(value.Split(';'), StringComparer.InvariantCultureIgnoreCase);

            var valuesToRemove = currentValues.Where(v => StringComparer.InvariantCultureIgnoreCase.Equals(v, ApplicationInfo.RootDirectory));
            foreach (var path in valuesToRemove)
            {
                value = value.Replace(path, "");
            }

            while (value.Contains(";;"))
            {
                value = value.Replace(";;", ";");
            }

            Environment.SetEnvironmentVariable("PATH", value, EnvironmentVariableTarget.User);
        }
    }
}

Fix removal of installation directory from PATH on uninstall


using System.Collections.Generic;
using System.IO;
using Dependinator.ModelViewing.Private.DataHandling.Dtos;
using Dependinator.ModelViewing.Private.DataHandling.Private.Parsing;

namespace Dependinator.ModelViewing.Private.DataHandling.Private
{
    internal class DataFilePaths : IDataFilePaths
    {
        private readonly IParserService parserService;

        public DataFilePaths(IParserService parserService)
        {
            this.parserService = parserService;
        }

        public IReadOnlyList<string> GetDataFilePaths(DataFile dataFile) =>
            parserService.GetDataFilePaths(dataFile);

        public IReadOnlyList<string> GetBuildPaths(DataFile dataFile) =>
            parserService.GetBuildPaths(dataFile);

        public string GetCacheFilePath(DataFile dataFile)
        {
            var dataFileName = Path.GetFileName(dataFile.FilePath);
            string cacheFileName = $"{dataFileName}.dn.json";
            return Path.Combine(dataFile.WorkFolderPath, cacheFileName);
        }

        public string GetSaveFilePath(DataFile dataFile)
        {
            string dataFileName = $"{Path.GetFileNameWithoutExtension(dataFile.FilePath)}.dpnr";
            string folderPath = Path.GetDirectoryName(dataFile.FilePath);
            //  string dataFilePath = Path.Combine(folderPath, dataJson);
            return Path.Combine(dataFile.WorkFolderPath, dataFileName);
        }
    }
}

using System.Collections.Generic;
using System.IO;
using Dependinator.ModelViewing.Private.DataHandling.Dtos;
using Dependinator.ModelViewing.Private.DataHandling.Private.Parsing;

namespace Dependinator.ModelViewing.Private.DataHandling.Private
{
    internal class DataFilePaths : IDataFilePaths
    {
        private readonly IParserService parserService;

        public DataFilePaths(IParserService parserService)
        {
            this.parserService = parserService;
        }

        public IReadOnlyList<string> GetDataFilePaths(DataFile dataFile) =>
            parserService.GetDataFilePaths(dataFile);

        public IReadOnlyList<string> GetBuildPaths(DataFile dataFile) =>
            parserService.GetBuildPaths(dataFile);

        public string GetCacheFilePath(DataFile dataFile)
        {
            var dataFileName = Path.GetFileName(dataFile.FilePath);
            string cacheFileName = $"{dataFileName}.dn.json";
            return Path.Combine(dataFile.WorkFolderPath, cacheFileName);
        }

        public string GetSaveFilePath(DataFile dataFile)
        {
            string dataFileName = $"{Path.GetFileNameWithoutExtension(dataFile.FilePath)}.dpnr";
            string folderPath = Path.GetDirectoryName(dataFile.FilePath);
            return Path.Combine(folderPath, dataFileName);

            ////  string dataFilePath = Path.Combine(folderPath, dataJson);
            //return Path.Combine(dataFile.WorkFolderPath, dataFileName);
        }
    }
}

Use layout file next to data file

Use layout file next to data file


// 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.Beatmaps.Legacy
{
    internal enum LegacyStoryLayer
    {
        Background = 0,
        Fail = 1,
        Pass = 2,
        Foreground = 3,
        Video = 4
    }
}

// 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.Beatmaps.Legacy
{
    internal enum LegacyStoryLayer
    {
        Background = 0,
        Fail = 1,
        Pass = 2,
        Foreground = 3,
        Overlay = 4,
        Video = 5
    }
}

Add overlay layer to enumeration type

Add overlay layer to enumeration type


using Glimpse.Agent;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using System;
using System.Collections.Generic;
using Glimpse.Agent.Web;
using Glimpse.Agent.Web.Options;
using Microsoft.Framework.OptionsModel;

namespace Glimpse
{
    public class GlimpseAgentWebServices
    {
        public static IServiceCollection GetDefaultServices()
        {
            var services = new ServiceCollection();

            //
            // Options
            //
            services.AddTransient<IConfigureOptions<GlimpseAgentWebOptions>, GlimpseAgentWebOptionsSetup>();
            services.AddSingleton<IIgnoredUrisProvider, DefaultIgnoredUrisProvider>();
            services.AddSingleton<IIgnoredStatusCodeProvider, DefaultIgnoredStatusCodeProvider>();
            services.AddSingleton<IIgnoredContentTypeProvider, DefaultIgnoredContentTypeProvider>();
            services.AddSingleton<IIgnoredRequestProvider, DefaultIgnoredRequestProvider>();

            return services;
        }
    }
}

using Glimpse.Agent;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using System;
using System.Collections.Generic;
using Glimpse.Agent.Web;
using Glimpse.Agent.Web.Options;
using Microsoft.Framework.OptionsModel;

namespace Glimpse
{
    public class GlimpseAgentWebServices
    {
        public static IServiceCollection GetDefaultServices()
        {
            var services = new ServiceCollection();

            //
            // Options
            //
            services.AddTransient<IConfigureOptions<GlimpseAgentWebOptions>, GlimpseAgentWebOptionsSetup>();
            services.AddSingleton<IIgnoredUrisProvider, DefaultIgnoredUrisProvider>();
            services.AddSingleton<IIgnoredStatusCodeProvider, DefaultIgnoredStatusCodeProvider>();
            services.AddSingleton<IIgnoredContentTypeProvider, DefaultIgnoredContentTypeProvider>();
            services.AddSingleton<IIgnoredRequestProvider, DefaultIgnoredRequestProvider>();
            services.AddSingleton<IRequestProfilerProvider, DefaultRequestProfilerProvider>();

            return services;
        }
    }
}

Switch service registration over to using new RequestProfile provider


using System.Reflection;

namespace Loyc.Compatibility
{
	#if NetStandard20 || DotNet45

	/// <summary>Defines ITuple in .NET Standard 2.0. System.Runtime.CompilerServices.ITuple
	/// was added to .NET Core 2.0 and .NET Framework 4.7.1, but it wasn't added to .NET
	/// Standard 2.0. ITuple was added to .NET Standard 2.1, but this requires .NET Core 3.</summary>
	public interface ITuple
	{
		object this[int index] { get; }
		int Length { get; }
	}

	#endif
}

using System.Reflection;

namespace Loyc.Compatibility
{
#if NetStandard20 || DotNet45

	/// Defines ITuple in .NET Standard 2.0. System.Runtime.CompilerServices.ITuple
	/// was added to .NET Core 2.0 and .NET Framework 4.7.1, but it wasn't added to .NET
	/// Standard 2.0. ITuple was added to .NET Standard 2.1, but this requires .NET Core 3.
	public interface ITuple
	{
		object this[int index] { get; }
		int Length { get; }
	}

	#else

	/// Ensure `using Loyc.Compatibility` is not an error
	public interface __ThisEnsuresTheNamespaceIsNotEmpty { }

	#endif
}

Fix the build some more

Fix the build some more


using System.Collections.Generic;
using System.Management.Automation.Runspaces;

using Aggregator.Core.Interfaces;
using Aggregator.Core.Monitoring;

namespace Aggregator.Core
{
    /// <summary>
    /// Invokes Powershell scripting engine
    /// </summary>
    public class PsScriptEngine : ScriptEngine
    {
        private readonly Dictionary<string, string> scripts = new Dictionary<string, string>();

        public PsScriptEngine(IWorkItemRepository store, ILogEvents logger, bool debug)
            : base(store, logger, debug)
        {
        }

        public override bool Load(string scriptName, string script)
        {
            this.scripts.Add(scriptName, script);
            return true;
        }

        public override bool LoadCompleted()
        {
            return true;
        }

        public override void Run(string scriptName, IWorkItem workItem)
        {
            string script = this.scripts[scriptName];

            var config = RunspaceConfiguration.Create();
            using (var runspace = RunspaceFactory.CreateRunspace(config))
            {
                runspace.Open();

                runspace.SessionStateProxy.SetVariable("self", workItem);
                runspace.SessionStateProxy.SetVariable("store", this.Store);
                runspace.SessionStateProxy.SetVariable("logger", this.Logger);

                Pipeline pipeline = runspace.CreatePipeline();
                pipeline.Commands.AddScript(script);

                // execute
                var results = pipeline.Invoke();

                this.Logger.ResultsFromScriptRun(scriptName, results);
            }
        }
    }
}

using System.Collections.Generic;
using System.Management.Automation.Runspaces;

using Aggregator.Core.Interfaces;
using Aggregator.Core.Monitoring;

namespace Aggregator.Core
{
    /// <summary>
    /// Invokes Powershell scripting engine
    /// </summary>
    public class PsScriptEngine : ScriptEngine
    {
        private readonly Dictionary<string, string> scripts = new Dictionary<string, string>();

        public PsScriptEngine(IWorkItemRepository store, ILogEvents logger, bool debug)
            : base(store, logger, debug)
        {
        }

        public override bool Load(string scriptName, string script)
        {
            this.scripts.Add(scriptName, script);
            return true;
        }

        public override bool LoadCompleted()
        {
            return true;
        }

        public override void Run(string scriptName, IWorkItem workItem)
        {
            string script = this.scripts[scriptName];

            var config = RunspaceConfiguration.Create();
            using (var runspace = RunspaceFactory.CreateRunspace(config))
            {
                runspace.Open();

                runspace.SessionStateProxy.SetVariable("self", workItem);
                runspace.SessionStateProxy.SetVariable("store", this.Store);
                runspace.SessionStateProxy.SetVariable("logger", this.Logger.ScriptLogger);

                Pipeline pipeline = runspace.CreatePipeline();
                pipeline.Commands.AddScript(script);

                // execute
                var results = pipeline.Invoke();

                this.Logger.ResultsFromScriptRun(scriptName, results);
            }
        }
    }
}

FIX Logger object on Powershell engine

FIX Logger object on Powershell engine


using System;
using System.IO;
using System.Text;
using DelimitedDataParser;

namespace WindowsEncoding
{
    internal class Program
    {
        private static void Main()
        {
            // When using DelimitedDataParser in a .NET Core app,
            // be sure to include the NuGet package System.Text.Encoding.CodePages.
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            // Attempting to obtain the Windows-1252 encoding will fail on .NET Core
            // if the required // code page is not correctly registered.
            var windows1252 = Encoding.GetEncoding(1252);

            // Try and ensure the console's encoding matches the character encoding
            // of the file input data.
            Console.OutputEncoding = windows1252;

            var parser = new Parser
            {
                UseFirstRowAsColumnHeaders = false
            };

            using (var stream = new StreamReader("Windows1252.txt", windows1252))
            using (var reader = parser.ParseReader(stream))
            {
                while (reader.Read())
                {
                    Console.WriteLine(reader[0]);
                }
            }
        }
    }
}

using System;
using System.IO;
using System.Text;
using DelimitedDataParser;

namespace WindowsEncoding
{
    internal class Program
    {
        private static void Main()
        {
            // If code page based character encodings are required when using
            // DelimitedDataParser in a .NET Core app, be sure to include the
            // NuGet package System.Text.Encoding.CodePages.
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            // Attempting to obtain the Windows-1252 encoding will fail on .NET Core
            // if the required code page based encoding is not correctly registered.
            var windows1252 = Encoding.GetEncoding(1252);

            // Try and ensure the console's encoding matches the character encoding
            // of the file input data.
            Console.OutputEncoding = windows1252;

            var parser = new Parser
            {
                UseFirstRowAsColumnHeaders = false
            };

            using (var stream = new StreamReader("Windows1252.txt", windows1252))
            using (var reader = parser.ParseReader(stream))
            {
                while (reader.Read())
                {
                    Console.WriteLine(reader[0]);
                }
            }
        }
    }
}

Clarify comment in sample app

Clarify comment in sample app


using System;

public enum Colors
{
    Red = 1,
    Alpha,
    Green = 13,
    Blue
}

public static class Program
{
    public static void Main(string[] Args)
    {
        Console.WriteLine((int)Colors.Red);
        Console.WriteLine((int)Colors.Alpha);
        Console.WriteLine((int)Colors.Green);
        Console.WriteLine((int)Colors.Blue);
        Console.WriteLine((long)Colors.Blue);
        Console.WriteLine((double)Colors.Blue);
    }
}

using System;

public enum Colors
{
    Red = 1,
    Alpha,
    Green = 13,
    Blue
}

public enum LongColors : long
{
    Red = 1,
    Alpha,
    Green = 13,
    Blue
}

public static class Program
{
    public static void Main(string[] Args)
    {
        Console.WriteLine((int)Colors.Red);
        Console.WriteLine((int)Colors.Alpha);
        Console.WriteLine((int)Colors.Green);
        Console.WriteLine((int)Colors.Blue);
        Console.WriteLine((long)Colors.Blue);
        Console.WriteLine((double)Colors.Blue);

        Console.WriteLine((int)LongColors.Red);
        Console.WriteLine((int)LongColors.Alpha);
        Console.WriteLine((int)LongColors.Green);
        Console.WriteLine((int)LongColors.Blue);
        Console.WriteLine((long)LongColors.Blue);
        Console.WriteLine((double)LongColors.Blue);
    }
}

Test 'long'-based 'enum' types, too

Test 'long'-based 'enum' types, too


using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nutritia
{
    public class MySqlPlatService : IPlatService
    {
        // TODO : Fonctionne pas
        private MySqlConnexion connexion;

        public Plat Retrieve(RetrievePlatArgs args)
        {

            Plat plat;

            try
            {
                connexion = new MySqlConnexion();

                string requete = string.Format("SELECT * FROM Plats WHERE idPlat = {0}", args.IdPlat);

                DataSet dataSetPlats = connexion.Query(requete);
                DataTable tablePlats = dataSetPlats.Tables[0];

                plat = ConstruirePlat(tablePlats.Rows[0]);

            }
            catch (Exception)
            {
                throw;
            }

            return plat;

        }

        private Plat ConstruirePlat(DataRow plat)
        {
            return new Plat()
            {
                // TODO : Améliorer
                IdPlat = (int)plat["idPlat"],
                // TODO : Améliorer
                Createur = new Membre(),
                Nom = (string)plat["nom"],
                Note = (int)plat["note"],
                // TODO : À voir pour le 'EstType'
                ListeIngredients = new List<Aliments>()
            };
        }
    }
}

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nutritia
{
    public class MySqlPlatService : IPlatService
    {
        // TODO : Fonctionne pas
        private MySqlConnexion connexion;

        public Plat Retrieve(RetrievePlatArgs args)
        {

            Plat plat;

            try
            {
                connexion = new MySqlConnexion();

                string requete = string.Format("SELECT * FROM Plats WHERE idPlat = {0}", args.IdPlat);

                DataSet dataSetPlats = connexion.Query(requete);
                DataTable tablePlats = dataSetPlats.Tables[0];

                plat = ConstruirePlat(tablePlats.Rows[0]);

            }
            catch (Exception)
            {
                throw;
            }

            return plat;

        }

        private Plat ConstruirePlat(DataRow plat)
        {
            return new Plat()
            {
                // TODO : Améliorer
                IdPlat = (int)plat["idPlat"],
                // TODO : Améliorer
                Createur = new Membre(),
                Nom = (string)plat["nom"],
                Note = (int)plat["note"],
                // TODO : À voir pour le 'EstType'
                ListeIngredients = new List<Aliment>()
            };
        }
    }
}

Fix du mauvais nom de classe

Fix du mauvais nom de classe


namespace BlockchainSharp.Core
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    public class BlockChain
    {
        public long number;

        public BlockChain(Block block)
        {
            if (!block.IsGenesis)
                throw new ArgumentException("Initial block should be genesis");

            this.number = block.Number;
        }

        public long BestBlockNumber { get { return this.number; } }
    }
}

namespace BlockchainSharp.Core
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    public class BlockChain
    {
        private IList<Block> blocks = new List<Block>();

        public BlockChain(Block block)
        {
            if (!block.IsGenesis)
                throw new ArgumentException("Initial block should be genesis");

            this.blocks.Add(block);
        }

        public long BestBlockNumber { get { return this.blocks.Last().Number; } }
    }
}

Refactor BlockChain to have an internal list


using Assets.Scripts.Data.Interfaces;
using System.Collections.Generic;
using Assets.Scripts.Data.Model.Objects;
using Assets.Scripts.Data.Model.Telemetrics;
using Assets.Scripts.Data.Providers.Fmk;
using UnityEngine;

namespace Assets.Scripts.Data.Providers
{
    /// <summary>
    /// The author is working in First Monitoring Company. http://firstmk.ru
    /// Current provider let to load navigation data from company's servers.
    /// This data is confidential, therefore the data transfer protocol is not present in this repository.
    /// </summary>
    public sealed class FmkDataProvider : IDataProvider
    {
        private FmkApiClient _client;

        public FmkDataProvider()
        {
            _client = new FmkApiClient(credentials.Key, credentials.Login, credentials.Password);
        }

        public List<Building> LoadBuildings()
        {
            return new List<Building>(0); // Buildings are not supported.
        }

        public List<MoveableObject> LoadMoveableObjects()
        {
            return _client.GetDevices();
        }

        public List<TrackPoint> UpdateMoveableObjectLocations()
        {
            return _client.GetLocations();
        }
    }
}

using Assets.Scripts.Data.Interfaces;
using System.Collections.Generic;
using Assets.Scripts.Data.Model.Objects;
using Assets.Scripts.Data.Model.Telemetrics;
using Assets.Scripts.Data.Providers.Fmk;
using UnityEngine;

namespace Assets.Scripts.Data.Providers
{
    /// <summary>
    /// The author is working in First Monitoring Company. http://firstmk.ru
    /// Current provider let to load navigation data from company's servers.
    /// This data is confidential, therefore the data transfer protocol is not present in this repository.
    /// </summary>
    public sealed class FmkDataProvider : IDataProvider
    {
        private FmkApiClient _client;

        public FmkDataProvider()
        {
            var credentials = Resources.Load<FmkCredentials>("Storages/FMK");
            _client = new FmkApiClient(credentials.Key, credentials.Login, credentials.Password);
        }

        public List<Building> LoadBuildings()
        {
            return new List<Building>(0); // Buildings are not supported.
        }

        public List<MoveableObject> LoadMoveableObjects()
        {
            return _client.GetDevices();
        }

        public List<TrackPoint> UpdateMoveableObjectLocations()
        {
            return _client.GetLocations();
        }
    }
}

Load FMK credentials from serialized file.


// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using osu.Framework.Allocation;
using osu.Framework.Bindables;

namespace osu.Game.Screens.Play
{
    [Cached]
    public interface ILocalUserPlayInfo
    {
        /// <summary>
        /// Whether the local user is currently playing.
        /// </summary>
        public IBindable<bool> IsPlaying { get; }
    }
}

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using osu.Framework.Allocation;
using osu.Framework.Bindables;

namespace osu.Game.Screens.Play
{
    [Cached]
    public interface ILocalUserPlayInfo
    {
        /// <summary>
        /// Whether the local user is currently playing.
        /// </summary>
        IBindable<bool> IsPlaying { get; }
    }
}

Remove unnecessary `public` prefix in interface specification


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class YoumuSlash3DEnvironmentController : MonoBehaviour
{
    [SerializeField]
    private GameObject stairObject;
    [SerializeField]
    private Vector2 stairOffset;

    [SerializeField]
    private Transform cameraParent;
    [SerializeField]
    private float cameraDollySpeed;

    Vector3 StairOffset3D => new Vector3(0f, stairOffset.y, stairOffset.x);

	//void Start ()
 //   {
 //       for (int i = 0; i < stairParent.childCount; i++)
 //       {
 //           stairParent.GetChild(i).localPosition = StairOffset3D * i;
 //       }
	//}

	void Update ()
    {
        cameraParent.position += StairOffset3D.resize(cameraDollySpeed * Time.deltaTime);
        if (cameraParent.localPosition.y > stairOffset.y)
        {
            cameraParent.localPosition -= StairOffset3D;
        }
	}
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class YoumuSlash3DEnvironmentController : MonoBehaviour
{
    [SerializeField]
    private Transform stairParent;
    [SerializeField]
    private GameObject stairObject;
    [SerializeField]
    private Vector2 stairOffset;

    [SerializeField]
    private Transform cameraParent;
    [SerializeField]
    private float cameraDollySpeed;

    private int unitsTravelled;

    Vector3 StairOffset3D => new Vector3(0f, stairOffset.y, stairOffset.x);

	void Start ()
    {
        for (int i = 0; i < stairParent.childCount; i++)
        {
            stairParent.GetChild(i).localPosition = StairOffset3D * i;
        }
        unitsTravelled = 1;
	}

	void Update ()
    {
        cameraParent.position += StairOffset3D.resize(cameraDollySpeed * Time.deltaTime);
        if (cameraParent.localPosition.y > stairOffset.y * unitsTravelled)
        {
            Transform lowestStair = stairParent.GetChild(0);
            lowestStair.SetSiblingIndex(stairParent.childCount - 1);
            lowestStair.localPosition += StairOffset3D * stairParent.childCount;
            unitsTravelled++;
        }
	}
}

Revert "YoumuSlash: Better camera looping algorithm"

This reverts commit 87a4e5ecac344e0cbc225790a6d5a4fd5210a7fb.


using SierraLib.Translation;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Articulate
{
	public sealed class FileBasedTranslation : SierraLib.Translation.FileBasedTranslation
	{
		public FileBasedTranslation(CultureInfo culture, Stream file)
			: base(culture, file)
		{

		}

		public override string this[string key]
		{
			get
			{
				return this[key, "!!!" + key];
			}
		}

		public override string this[string key, string defaultValue]
		{
			get
			{
				if (FileData.ContainsKey(key)) return FileData[key];
				else if (key.StartsWith("keyboard_"))
				{
					var keyCode = Convert.ToInt32(key.Substring("keyboard_".Length));
					return ((System.Windows.Forms.Keys)keyCode).ToString();
				}
				else if (key.StartsWith("mouse_"))
				{
					var keyCode = Convert.ToInt32(key.Substring("mouse_".Length));
					return ((System.Windows.Forms.MouseButtons)keyCode).ToString();
				}
				else return defaultValue;
			}
		}

	}
}

using SierraLib.Translation;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Articulate
{
	public sealed class FileBasedTranslation : SierraLib.Translation.FileBasedTranslation
	{
		public FileBasedTranslation(CultureInfo culture, Stream file)
			: base(culture, file)
		{

		}

		public override string this[string key]
		{
			get
			{
				if (key.StartsWith("keyboard_"))
				{
					var keyCode = Convert.ToInt32(key.Substring("keyboard_".Length));
					return this[key, ((System.Windows.Forms.Keys)keyCode).ToString()];
				}
				else if (key.StartsWith("mouse_"))
				{
					var keyCode = Convert.ToInt32(key.Substring("mouse_".Length));
					return this[key, ((System.Windows.Forms.MouseButtons)keyCode).ToString()];
				}

				return this[key, "!!!" + key];
			}
		}

		public override string this[string key, string defaultValue]
		{
			get
			{
				return FileData.ContainsKey(key) ? FileData[key] : defaultValue;
			}
		}

	}
}

Improve performance of keycode translations


namespace Content.Shared.GameObjects
{
    public static class ContentNetIDs
    {
        public const uint HANDS = 0;
    }
}

namespace Content.Shared.GameObjects
{
    public static class ContentNetIDs
    {
        public const uint HANDS = 1000;
    }
}

Make NetID use 1000+ range

Make NetID use 1000+ range


using RollbarSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LandmineWeb.App_Start
{
    public class RollbarExceptionFilter : IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            //if (filterContext.ExceptionHandled)
            //    return;

            (new RollbarClient()).SendException(filterContext.Exception);
        }
    }
}

using RollbarSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LandmineWeb.App_Start
{
    public class RollbarExceptionFilter : IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            if (filterContext.ExceptionHandled)
                return;

            (new RollbarClient()).SendException(filterContext.Exception);
        }
    }
}

Revert "LOG ALL THE ERRORS"

Revert "LOG ALL THE ERRORS"

This reverts commit 39809851fb4f05afe92ac8731c8ebc234ba3b644.


using Machine.Specifications;

namespace Stripe.Tests
{
    public class when_creating_a_charge_with_a_stripe_account
    {
        private static StripeAccount _stripeAccount;
        private static StripeCharge _stripeCharge;

        Establish context = () =>
        {
            // create a new custom account
            _stripeAccount = new StripeAccountService().Create(new StripeAccountCreateOptions()
            {
                Country = "US",
                Type = StripeAccountType.Custom
            });
        };

        Because of = () =>
        {
            // charge the customer something
            _stripeCharge = new StripeChargeService().Create(new StripeChargeCreateOptions()
            {
                Amount = 100,
                Currency = "usd",
                SourceTokenOrExistingSourceId = _stripeAccount.Id
            });
        };

        It should_have_the_right_source = () =>
            _stripeCharge.Source.Account.ShouldNotBeNull();

        It should_not_have_the_wrong_source = () =>
            _stripeCharge.Source.Card.ShouldBeNull();

        It should_have_the_right_source_type = () =>
            _stripeCharge.Source.Type.ShouldEqual(SourceType.Account);

        It should_have_the_right_id = () =>
            _stripeCharge.Source.Id.ShouldEqual(_stripeAccount.Id);
    }
}

using Machine.Specifications;

namespace Stripe.Tests
{
    public class when_creating_a_charge_with_a_stripe_account
    {
        private static StripeAccount _stripeAccount;
        private static StripeCharge _stripeCharge;

        Establish context = () =>
        {
            // create a new custom account
            _stripeAccount = new StripeAccountService().Create(new StripeAccountCreateOptions()
            {
                Country = "US",
                Type = StripeAccountType.Custom
            });
        };

        Because of = () =>
        {
            // charge the customer something
            _stripeCharge = new StripeChargeService().Create(new StripeChargeCreateOptions()
            {
                Amount = 100,
                Currency = "usd",
                SourceTokenOrExistingSourceId = _stripeAccount.Id
            });
        };

        It should_have_the_right_source = () =>
            _stripeCharge.Source.Account.ShouldNotBeNull();

        It should_not_have_the_wrong_source = () =>
            _stripeCharge.Source.Card.ShouldBeNull();

        It should_have_the_right_source_type = () =>
            _stripeCharge.Source.Type.ShouldEqual(SourceType.Account);

        It should_have_the_right_id = () =>
            _stripeCharge.Source.Id.ShouldEqual(_stripeAccount.Id);

        It should_deserialize_the_account_properly = () =>
            _stripeCharge.Source.Account.Id.ShouldEqual(_stripeAccount.Id);
    }
}

Add extra test to ensure Account deserialization