using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Resources;
using System.Text;

namespace AzureFunctions.ResxConvertor
{
    public class ResxConvertor
    {
        public void SaveResxAsTypeScriptFile(string[] resxFiles, string outputTSFilePAth)
        {
            var sb = new StringBuilder();
            sb.AppendLine("// This file is auto generated");
            sb.AppendLine("");
            sb.AppendLine("export class PortalResources");
            sb.AppendLine("{");

            foreach (var resxFile in resxFiles)
            {
                ResXResourceReader rsxr = new ResXResourceReader(resxFile);
                foreach (DictionaryEntry d in rsxr)
                {
                    sb.AppendLine(string.Format("    public static {0}: string = \"{0}\";", d.Key.ToString()));
                }

                //Close the reader.
                rsxr.Close();
            }
            sb.AppendLine("}");

            using (System.IO.StreamWriter file = new System.IO.StreamWriter(outputTSFilePAth))
            {
                file.WriteLine(sb.ToString());
            }
        }

    }
}

using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.IO;
using System.Resources;
using System.Text;

namespace AzureFunctions.ResxConvertor
{
    public class ResxConvertor
    {
        public void SaveResxAsTypeScriptFile(string[] resxFiles, string outputTSFilePAth)
        {
            var sb = new StringBuilder();
            sb.AppendLine("// This file is auto generated");
            sb.AppendLine("");
            sb.AppendLine("export class PortalResources");
            sb.AppendLine("{");

            foreach (var resxFile in resxFiles)
            {
                if (File.Exists(resxFile))
                {

                    ResXResourceReader rsxr = new ResXResourceReader(resxFile);
                    foreach (DictionaryEntry d in rsxr)
                    {
                        sb.AppendLine(string.Format("    public static {0}: string = \"{0}\";", d.Key.ToString()));
                    }

                    //Close the reader.
                    rsxr.Close();
                }
            }
            sb.AppendLine("}");

            using (System.IO.StreamWriter file = new System.IO.StreamWriter(outputTSFilePAth))
            {
                file.WriteLine(sb.ToString());
            }
        }

    }
}

Check if resx file exists

Check if resx file exists


@model EditWebhookViewModel
@using  BTCPayServer.Client.Models;
@{
    Layout = "../Shared/_NavLayout.cshtml";
    ViewData.SetActivePageAndTitle(StoreNavPages.Webhooks, "Test Webhook", Context.GetStoreData().StoreName);
}

        <form method="post">

@ViewData["PageTitle"]

                @foreach (var evt in new[]
                {
                    ("Test InvoiceCreated event", WebhookEventType.InvoiceCreated),
                    ("Test InvoiceReceivedPayment event", WebhookEventType.InvoiceReceivedPayment),
                    ("Test InvoiceProcessing event", WebhookEventType.InvoiceProcessing),
                    ("Test InvoiceExpired event", WebhookEventType.InvoiceExpired),
                    ("Test InvoiceSettled event", WebhookEventType.InvoiceSettled),
                    ("Test InvoiceInvalid event", WebhookEventType.InvoiceInvalid)
                })
                {

                        <button type="submit" name="Type" class="btn btn-primary" value="@evt.Item2">@evt.Item1</button>

                }

        </form>

@model EditWebhookViewModel
@using  BTCPayServer.Client.Models;
@{
    Layout = "../Shared/_NavLayout.cshtml";
    ViewData.SetActivePageAndTitle(StoreNavPages.Webhooks, "Send a test event to a webhook endpoint", Context.GetStoreData().StoreName);
}

        <form method="post">

@ViewData["PageTitle"]

                Event type
                <select name="Type" id="Type" class="form-control w-auto">
                    @foreach (var evt in new[]
                    {
                        WebhookEventType.InvoiceCreated,
                        WebhookEventType.InvoiceReceivedPayment,
                        WebhookEventType.InvoiceProcessing,
                        WebhookEventType.InvoiceExpired,
                        WebhookEventType.InvoiceSettled,
                        WebhookEventType.InvoiceInvalid
                    })
                    {
                        <option value="@evt">
                            @evt
                        </option>
                    }
                </select>

            <button type="submit" class="btn btn-primary">Send test webhook</button>
        </form>

Update webhook test page design

Update webhook test page design


using System.Collections.Generic;
using System.IO;
using System.Linq;
using Buzzbox_Common;
using Buzzbox_Common.Encoders;

namespace Buzzbox_Stream
{
    class StreamEncode
    {
        public bool LoopForever;
        public bool ShuffleFields;

        private MtgEncodeFormatEncoder _encoder;
        private CardCollection _cardCollection;
        private StreamWriter _stream;

        public StreamEncode(CardCollection cardCollection, StreamWriter stream)
        {
            _encoder = new MtgEncodeFormatEncoder();

            _cardCollection = cardCollection;
            _stream = stream;
        }

        public void ThreadEntry()
        {
            do
            {
                _cardCollection.Cards.Shuffle();

                foreach (var card in _cardCollection.Cards)
                {
                    var outputLine = _encoder.EncodeCard(card) + "\n\n";

                    if (ShuffleFields)
                    {
                        outputLine = ShuffleCardFields(outputLine);
                    }

                    //actually output
                    _stream.Write(outputLine);
                }

            } while (LoopForever);

            _stream.Close();
        }

        private string ShuffleCardFields(string cardLine)
        {
            cardLine = cardLine.TrimEnd('|').TrimStart('|');
            List<string> fields = cardLine.Split('|').ToList();
            fields.Shuffle();
            return $"|{string.Join("|", fields)}|";
        }
    }
}

using System;
using System.CodeDom;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Buzzbox_Common;
using Buzzbox_Common.Encoders;

namespace Buzzbox_Stream
{
    class StreamEncode
    {
        public bool LoopForever;
        public bool ShuffleFields;

        private MtgEncodeFormatEncoder _encoder;
        private CardCollection _cardCollection;
        private StreamWriter _stream;

        public StreamEncode(CardCollection cardCollection, StreamWriter stream)
        {
            _encoder = new MtgEncodeFormatEncoder();

            _cardCollection = cardCollection;
            _stream = stream;
        }

        public void ThreadEntry()
        {
            do
            {
                _cardCollection.Cards.Shuffle();

                foreach (var card in _cardCollection.Cards)
                {
                    var outputLine = _encoder.EncodeCard(card) + "\n\n";

                    if (ShuffleFields)
                    {
                        outputLine = ShuffleCardFields(outputLine);
                    }

                    //actually try to output
                    try
                    {
                        _stream.Write(outputLine);
                    }
                    catch (Exception)
                    {
                        //fd was probably closed or otherwise no longer available
                        return;
                    }

                }

            } while (LoopForever);

            _stream.Close();
        }

        private string ShuffleCardFields(string cardLine)
        {
            cardLine = cardLine.TrimEnd('|').TrimStart('|');
            List<string> fields = cardLine.Split('|').ToList();
            fields.Shuffle();
            return $"|{string.Join("|", fields)}|";
        }
    }
}

Handle closed /proc/self/fd/ in stream encode.


using System;
using System.ComponentModel.DataAnnotations;
using FluentNHibernate.Mapping;
using UCDArch.Core.DomainModel;

namespace Commencement.Core.Domain
{
    public class Attachment : DomainObject
    {
        public Attachment()
        {
            PublicGuid = Guid.NewGuid();
        }

        [Required]
        public virtual byte[] Contents { get; set; }
        [Required]
        [StringLength(50)]
        public virtual string ContentType { get; set; }

        [StringLength(250)]
        public virtual string FileName { get; set; }

        public virtual Guid PublicGuid { get; set; }
    }

    public class AttachmentMap : ClassMap<Attachment>
    {
        public AttachmentMap()
        {
            Id(x => x.Id);

            Map(x => x.Contents).CustomSqlType("BinaryBlob");
            Map(x => x.ContentType);
            Map(x => x.FileName);
            Map(x => x.PublicGuid);
        }
    }
}

using System;
using System.ComponentModel.DataAnnotations;
using FluentNHibernate.Mapping;
using UCDArch.Core.DomainModel;

namespace Commencement.Core.Domain
{
    public class Attachment : DomainObject
    {
        public Attachment()
        {
            PublicGuid = Guid.NewGuid();
        }

        [Required]
        public virtual byte[] Contents { get; set; }
        [Required]
        [StringLength(50)]
        public virtual string ContentType { get; set; }

        [StringLength(250)]
        public virtual string FileName { get; set; }

        public virtual Guid PublicGuid { get; set; }
    }

    public class AttachmentMap : ClassMap<Attachment>
    {
        public AttachmentMap()
        {
            Id(x => x.Id);

            Map(x => x.Contents).Length(Int32.MaxValue);
            Map(x => x.ContentType);
            Map(x => x.FileName);
            Map(x => x.PublicGuid);
        }
    }
}

Update how byte[] is mapped.

Update how byte[] is mapped.


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

using osu.Framework.Graphics;
using osu.Game.Graphics.Sprites;
using System;
using osu.Framework.Allocation;
using osu.Game.Graphics;

namespace osu.Game.Screens.Edit.Components
{
    public class TimeInfoContainer : BottomBarContainer
    {
        private readonly OsuSpriteText trackTimer;

        [Resolved]
        private EditorClock editorClock { get; set; }

        public TimeInfoContainer()
        {
            Children = new Drawable[]
            {
                trackTimer = new OsuSpriteText
                {
                    Origin = Anchor.BottomLeft,
                    RelativePositionAxes = Axes.Y,
                    Font = OsuFont.GetFont(size: 22, fixedWidth: true),
                    Y = 0.5f,
                }
            };
        }

        protected override void Update()
        {
            base.Update();

            trackTimer.Text = TimeSpan.FromMilliseconds(editorClock.CurrentTime).ToString(@"mm\:ss\:fff");
        }
    }
}

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

using osu.Framework.Graphics;
using osu.Game.Graphics.Sprites;
using System;
using osu.Framework.Allocation;
using osu.Game.Graphics;

namespace osu.Game.Screens.Edit.Components
{
    public class TimeInfoContainer : BottomBarContainer
    {
        private readonly OsuSpriteText trackTimer;

        [Resolved]
        private EditorClock editorClock { get; set; }

        public TimeInfoContainer()
        {
            Children = new Drawable[]
            {
                trackTimer = new OsuSpriteText
                {
                    Anchor = Anchor.CentreRight,
                    Origin = Anchor.CentreRight,
                    // intentionally fudged centre to avoid movement of the number portion when
                    // going negative.
                    X = -35,
                    Font = OsuFont.GetFont(size: 25, fixedWidth: true),
                }
            };
        }

        protected override void Update()
        {
            base.Update();

            var timespan = TimeSpan.FromMilliseconds(editorClock.CurrentTime);
            trackTimer.Text = $"{(timespan < TimeSpan.Zero ? "-" : string.Empty)}{timespan:mm\\:ss\\:fff}";
        }
    }
}

Fix editor not showing sign when time goes negative


// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using System;
using Microsoft.EntityFrameworkCore.Storage;

namespace osu.Game.Database
{
    public class DatabaseWriteUsage : IDisposable
    {
        public readonly OsuDbContext Context;
        private readonly IDbContextTransaction transaction;
        private readonly Action<DatabaseWriteUsage> usageCompleted;

        public DatabaseWriteUsage(OsuDbContext context, Action<DatabaseWriteUsage> onCompleted)
        {
            Context = context;
            transaction = Context.BeginTransaction();
            usageCompleted = onCompleted;
        }

        public bool PerformedWrite { get; private set; }

        private bool isDisposed;

        protected void Dispose(bool disposing)
        {
            if (isDisposed) return;
            isDisposed = true;

            PerformedWrite |= Context.SaveChanges(transaction) > 0;
            usageCompleted?.Invoke(this);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~DatabaseWriteUsage()
        {
            Dispose(false);
        }
    }
}

// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using System;
using Microsoft.EntityFrameworkCore.Storage;

namespace osu.Game.Database
{
    public class DatabaseWriteUsage : IDisposable
    {
        public readonly OsuDbContext Context;
        private readonly IDbContextTransaction transaction;
        private readonly Action<DatabaseWriteUsage> usageCompleted;

        public DatabaseWriteUsage(OsuDbContext context, Action<DatabaseWriteUsage> onCompleted)
        {
            Context = context;
            transaction = Context.BeginTransaction();
            usageCompleted = onCompleted;
        }

        public bool PerformedWrite { get; private set; }

        private bool isDisposed;

        protected void Dispose(bool disposing)
        {
            if (isDisposed) return;
            isDisposed = true;

            try
            {
                PerformedWrite |= Context.SaveChanges(transaction) > 0;
            }
            catch (Exception e)
            {
                transaction?.Rollback();
                throw;
            }
            finally
            {
                usageCompleted?.Invoke(this);
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~DatabaseWriteUsage()
        {
            Dispose(false);
        }
    }
}

Add proper transaction rollback logic on exception


using System;
using Newtonsoft.Json;
using RestSharp;

namespace Rollbar {
    public class RollbarPayload {
        public RollbarPayload(string accessToken, RollbarData data) {
            if (string.IsNullOrWhiteSpace(accessToken)) {
                throw new ArgumentNullException("accessToken");
            }
            if (data == null) {
                throw new ArgumentNullException("data");
            }
            AccessToken = accessToken;
            RollbarData = data;
        }

        public void Send() {
            var http = new RestClient("https://api.rollbar.com");
            var request = new RestRequest("/api/1/item/", Method.POST);
            request.AddParameter("application/json", JsonConvert.SerializeObject(this), ParameterType.RequestBody);
            http.Execute(request);
        }

        [JsonProperty("access_token", Required = Required.Always)]
        public string AccessToken { get; private set; }

        [JsonProperty("data", Required = Required.Always)]
        public RollbarData RollbarData { get; private set; }
    }
}

using System;
using Newtonsoft.Json;

namespace Rollbar {
    public class RollbarPayload {
        public RollbarPayload(string accessToken, RollbarData data) {
            if (string.IsNullOrWhiteSpace(accessToken)) {
                throw new ArgumentNullException("accessToken");
            }
            if (data == null) {
                throw new ArgumentNullException("data");
            }
            AccessToken = accessToken;
            RollbarData = data;
        }

        public string ToJson() {
            return JsonConvert.SerializeObject(this);
        }

        [JsonProperty("access_token", Required = Required.Always)]
        public string AccessToken { get; private set; }

        [JsonProperty("data", Required = Required.Always)]
        public RollbarData RollbarData { get; private set; }
    }
}

Replace Send with ToJson so the library is independent from how you send it


using System;
using System.Diagnostics;
using System.Text;
using ReClassNET.Util;

namespace ReClassNET.MemorySearcher.Comparer
{
	public class StringMemoryComparer : IMemoryComparer
	{
		public SearchCompareType CompareType => SearchCompareType.Equal;
		public bool CaseSensitive { get; }
		public Encoding Encoding { get; }
		public string Value { get; }
		public int ValueSize => Value.Length * Encoding.GetSimpleByteCountPerChar();

		public StringMemoryComparer(string value, Encoding encoding, bool caseSensitive)
		{
			Value = value;
			Encoding = encoding;
			CaseSensitive = caseSensitive;
		}

		public bool Compare(byte[] data, int index, out SearchResult result)
		{
			result = null;

			var value = Encoding.GetString(data, index, Value.Length);

			if (!Value.Equals(value, CaseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase))
			{
				return false;
			}

			result = new StringSearchResult(value, Encoding);

			return true;
		}

		public bool Compare(byte[] data, int index, SearchResult previous, out SearchResult result)
		{
#if DEBUG
			Debug.Assert(previous is StringSearchResult);
#endif

			return Compare(data, index, out result);
		}
	}
}

using System;
using System.Diagnostics;
using System.Text;
using ReClassNET.Util;

namespace ReClassNET.MemorySearcher.Comparer
{
	public class StringMemoryComparer : IMemoryComparer
	{
		public SearchCompareType CompareType => SearchCompareType.Equal;
		public bool CaseSensitive { get; }
		public Encoding Encoding { get; }
		public string Value { get; }
		public int ValueSize { get; }

		public StringMemoryComparer(string value, Encoding encoding, bool caseSensitive)
		{
			Value = value;
			Encoding = encoding;
			CaseSensitive = caseSensitive;
			ValueSize = Value.Length * Encoding.GetSimpleByteCountPerChar();
		}

		public bool Compare(byte[] data, int index, out SearchResult result)
		{
			result = null;

			var value = Encoding.GetString(data, index, Value.Length);

			if (!Value.Equals(value, CaseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase))
			{
				return false;
			}

			result = new StringSearchResult(value, Encoding);

			return true;
		}

		public bool Compare(byte[] data, int index, SearchResult previous, out SearchResult result)
		{
#if DEBUG
			Debug.Assert(previous is StringSearchResult);
#endif

			return Compare(data, index, out result);
		}
	}
}

Reduce number of function calls.

Reduce number of function calls.


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

public class UsageController : MonoBehaviour
{
	private Rigidbody2D rb2d;

	private UsableObjectCS collidingWith = null;

	private bool startedUsing = false;
	private bool stoppedUsing = false;

	// Use this for initialization
	void Start ()
	{
		rb2d = GetComponent<Rigidbody2D> ();
	}

	void Update ()
	{
		if (!UISystem.Instance.CutSceneDisplaying ()) {
			startedUsing = Input.GetButtonDown ("Action");
			stoppedUsing = Input.GetButtonUp ("Action");
		}
	}

	void LateUpdate ()
	{
		if (!UISystem.Instance.CutSceneDisplaying ()) {
			if (null != collidingWith) {
				if (startedUsing) {
					collidingWith.StartUsing (gameObject);
				} else if (stoppedUsing) {
					collidingWith.StopUsing (gameObject);
				}
			}
		}
	}

	void OnTriggerEnter2D (Collider2D other)
	{
		collidingWith = other.gameObject.GetComponent<UsableObjectCS> ();
		if (null != collidingWith) {
			Debug.Log ("Colliding with usable object.");
		}
	}

	void OnTriggerExit2D (Collider2D other)
	{
		collidingWith = null;
	}
}

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

public class UsageController : MonoBehaviour
{
	private Rigidbody2D rb2d;

	private UsableObjectCS collidingWith = null;

	private bool isUsing = false;
	private bool startedUsing = false;
	private bool stoppedUsing = false;

	// Use this for initialization
	void Start ()
	{
		rb2d = GetComponent<Rigidbody2D> ();
	}

	void Update ()
	{
		if (!UISystem.Instance.CutSceneDisplaying ()) {
			startedUsing = Input.GetButtonDown ("Action");
			stoppedUsing = Input.GetButtonUp ("Action");
		}
	}

	void LateUpdate ()
	{
		if (!UISystem.Instance.CutSceneDisplaying ()) {
			if (null != collidingWith) {
				if (startedUsing) {
					isUsing = true;
					collidingWith.StartUsing (gameObject);
				} else if (stoppedUsing) {
					isUsing = false;
					collidingWith.StopUsing (gameObject);
				}
			}
		}
	}

	void OnTriggerEnter2D (Collider2D other)
	{
		collidingWith = other.gameObject.GetComponent<UsableObjectCS> ();
		if (null != collidingWith) {
			Debug.Log ("Colliding with usable object.");
		}
	}

	void OnTriggerExit2D (Collider2D other)
	{
		if ( isUsing && null != collidingWith) {
			collidingWith.StopUsing (gameObject);
		}
		collidingWith = null;
	}
}

Fix stop using on exit

Fix stop using on exit


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

using System;
using Microsoft.AspNet.Http.Features;

namespace Microsoft.AspNet.Http.Extensions
{
    public static class ResponseExtensions
    {
        public static void Clear(this HttpResponse response)
        {
            if (response.HasStarted)
            {
                throw new InvalidOperationException("The response cannot be cleared, it has already started sending.");
            }
            response.StatusCode = 200;
            response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = null;
            response.Headers.Clear();
            if (response.Body.CanSeek)
            {
                response.Body.SetLength(0);
            }
        }
    }
}

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

using System;
using Microsoft.AspNet.Http.Features;

namespace Microsoft.AspNet.Http
{
    public static class ResponseExtensions
    {
        public static void Clear(this HttpResponse response)
        {
            if (response.HasStarted)
            {
                throw new InvalidOperationException("The response cannot be cleared, it has already started sending.");
            }
            response.StatusCode = 200;
            response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = null;
            response.Headers.Clear();
            if (response.Body.CanSeek)
            {
                response.Body.SetLength(0);
            }
        }
    }
}

Fix namespace for Clear extension.

Fix namespace for Clear extension.


#region using

using Irony.Compiler;
using System.Collections;
using ScriptNET.Runtime;
using System;
#endregion

namespace ScriptNET.Ast
{
  /// <summary>
  /// ForEachStatement
  /// </summary>
  internal class ScriptForEachStatement : ScriptStatement
  {
    private Token name;
    private ScriptExpr expr;
    private ScriptStatement statement;

    public ScriptForEachStatement(AstNodeArgs args)
        : base(args)
    {
      name = (Token)ChildNodes[1];
      expr = (ScriptExpr)ChildNodes[3];
      statement = (ScriptStatement)ChildNodes[4];
    }

    public override void Evaluate(IScriptContext context)
    {
      expr.Evaluate(context);

      IEnumerable enumeration = context.Result as IEnumerable;
      IEnumerator enumerator = null;

      if (enumeration != null)
      {
        enumerator = enumeration.GetEnumerator();
      }
      else
      {
        IObjectBind bind = RuntimeHost.Binder.BindToMethod(context.Result, "GetEnumerator",new Type[0], new object[0]);
        if (bind != null)
          enumerator = bind.Invoke(context, null) as IEnumerator;
      }

      if (enumerator == null)
        throw new ScriptException("GetEnumerator() method did not found in object: " + context.Result.ToString());

      enumerator.Reset();

      while(enumerator.MoveNext())
      {
        context.SetItem(name.Text, enumerator.Current);
        statement.Evaluate(context);
        if (context.IsBreak() || context.IsReturn())
        {
          context.SetBreak(false);
          break;
        }
        if (context.IsContinue())
        {
          context.SetContinue(false);
        }
      }

    }
  }
}

#region using

using Irony.Compiler;
using System.Collections;
using ScriptNET.Runtime;
using System;
#endregion

namespace ScriptNET.Ast
{
  /// <summary>
  /// ForEachStatement
  /// </summary>
  internal class ScriptForEachStatement : ScriptStatement
  {
    private Token name;
    private ScriptExpr expr;
    private ScriptStatement statement;

    public ScriptForEachStatement(AstNodeArgs args)
        : base(args)
    {
      name = (Token)ChildNodes[1];
      expr = (ScriptExpr)ChildNodes[3];
      statement = (ScriptStatement)ChildNodes[4];
    }

    public override void Evaluate(IScriptContext context)
    {
      expr.Evaluate(context);

      IEnumerable enumeration = context.Result as IEnumerable;
      IEnumerator enumerator = null;

      if (enumeration != null)
      {
        enumerator = enumeration.GetEnumerator();
      }
      else
      {
        IObjectBind bind = RuntimeHost.Binder.BindToMethod(context.Result, "GetEnumerator",new Type[0], new object[0]);
        if (bind != null)
          enumerator = bind.Invoke(context, null) as IEnumerator;
      }

      if (enumerator == null)
        throw new ScriptException("GetEnumerator() method did not found in object: " + context.Result.ToString());

      // enumerator.Reset();

      while(enumerator.MoveNext())
      {
        context.SetItem(name.Text, enumerator.Current);
        statement.Evaluate(context);
        if (context.IsBreak() || context.IsReturn())
        {
          context.SetBreak(false);
          break;
        }
        if (context.IsContinue())
        {
          context.SetContinue(false);
        }
      }

    }
  }
}

Remove unnecessary enumerator.Reset() from foreach() handling -- causes problems with IEnumerable created from LINQ


using System;
using System.IO;
using System.Linq;

namespace DotVVM.Compiler
{
    public static class Program
    {
        private static void PrintHelp(TextWriter? writer = null)
        {
            var executableName = Path.GetFileNameWithoutExtension(Environment.GetCommandLineArgs()[0]);
            writer ??= Console.Error;
            writer.Write(
$@"Usage: {executableName} [OPTIONS] <ASSEMBLY> <PROJECT_DIR>

Arguments:
  <ASSEMBLY>     Path to a DotVVM project assembly.
  <PROJECT_DIR>  Path to a DotVVM project directory.

Options:
  -h|-?|--help   Print this help text.
  --list-props   Print a list of DotVVM properties inside the assembly.
");
        }

        public static int Main(string[] args)
        {
#if NETCOREAPP3_1_OR_GREATER
            var r = Microsoft.Extensions.DependencyModel.DependencyContext.Default.RuntimeLibraries
                .Where(l => l.Name.Contains("DotVVM")).ToArray();
            var c = Microsoft.Extensions.DependencyModel.DependencyContext.Default.CompileLibraries
                .Where(l => l.Name.Contains("DotVVM")).ToArray();
            foreach(var context in System.Runtime.Loader.AssemblyLoadContext.All)
            {
                context.Resolving += (c, n) => {
                    return null;
                };
            }
#endif

            if (!CompilerArgs.TryParse(args, out var parsed))
            {
                PrintHelp(Console.Error);
                return 1;
            }

            if (parsed.IsHelp)
            {
                PrintHelp(Console.Out);
                return 0;
            }

            var executor = ProjectLoader.GetExecutor(parsed.AssemblyFile.FullName);
            var success = executor.ExecuteCompile(parsed);
            return success ? 0 : 1;
        }
    }
}

using System;
using System.IO;
using System.Linq;

namespace DotVVM.Compiler
{
    public static class Program
    {
        private static void PrintHelp(TextWriter? writer = null)
        {
            var executableName = Path.GetFileNameWithoutExtension(Environment.GetCommandLineArgs()[0]);
            writer ??= Console.Error;
            writer.Write(
$@"Usage: {executableName} [OPTIONS] <ASSEMBLY> <PROJECT_DIR>

Arguments:
  <ASSEMBLY>     Path to a DotVVM project assembly.
  <PROJECT_DIR>  Path to a DotVVM project directory.

Options:
  -h|-?|--help   Print this help text.
  --list-props   Print a list of DotVVM properties inside the assembly.
");
        }

        public static int Main(string[] args)
        {
            if (!CompilerArgs.TryParse(args, out var parsed))
            {
                PrintHelp(Console.Error);
                return 1;
            }

            if (parsed.IsHelp)
            {
                PrintHelp(Console.Out);
                return 0;
            }

            var executor = ProjectLoader.GetExecutor(parsed.AssemblyFile.FullName);
            var success = executor.ExecuteCompile(parsed);
            return success ? 0 : 1;
        }
    }
}

Remove some forgotten debugging code

Remove some forgotten debugging code


using NuGet.OutputWindowConsole;
using NuGetConsole;

namespace NuGet.Dialog.PackageManagerUI {
    internal class SmartOutputConsoleProvider : IOutputConsoleProvider {

        private readonly IOutputConsoleProvider _baseProvider;
        private bool _isFirstTime = true;

        public SmartOutputConsoleProvider(IOutputConsoleProvider baseProvider) {
            _baseProvider = baseProvider;
        }

        public IConsole CreateOutputConsole(bool requirePowerShellHost) {
            IConsole console = _baseProvider.CreateOutputConsole(requirePowerShellHost);

            if (_isFirstTime) {
                // the first time the console is accessed after dialog is opened, we clear the console.
                console.Clear();
            }
            else {
                _isFirstTime = false;
            }

            return console;
        }
    }
}

using NuGet.OutputWindowConsole;
using NuGetConsole;

namespace NuGet.Dialog.PackageManagerUI {
    internal class SmartOutputConsoleProvider : IOutputConsoleProvider {

        private readonly IOutputConsoleProvider _baseProvider;
        private bool _isFirstTime = true;

        public SmartOutputConsoleProvider(IOutputConsoleProvider baseProvider) {
            _baseProvider = baseProvider;
        }

        public IConsole CreateOutputConsole(bool requirePowerShellHost) {
            IConsole console = _baseProvider.CreateOutputConsole(requirePowerShellHost);

            if (_isFirstTime) {
                // the first time the console is accessed after dialog is opened, we clear the console.
                console.Clear();
                _isFirstTime = false;
            }

            return console;
        }
    }
}

Fix the wrong conditional statement.

Fix the wrong conditional statement.

--HG--
branch : 1.1


@section Title {Homepage}
@section Description{Chess Variants Training is a website where you can improve at chess variants.}
Homepage of Chess Variants Training.

@section Title {Homepage}
@section Description{Chess Variants Training is a website where you can improve at chess variants.}

Chess Variants Training

Welcome to Chess Variants Training! Here you can improve at chess variants. We support these variants: Antichess, Atomic chess, King of the Hill, Three-check, Horde chess and Racing Kings.

@Html.ActionLink("Puzzles", "Index", "Puzzle")

You can improve your tactics by doing tactics puzzles, created by the users of Chess Variants Training.

@Html.ActionLink("Timed training", "Index", "TimedTraining")

Improve your speed! You get a position and you have to find the winning move (or for antichess, the forced capture) as quickly as possible. How many positions can you do in one minute?

@Html.ActionLink("Endgames", "Index", "Endgames")

For atomic and antichess, we also have endgame training! You get a won endgame position and have to do the right moves to win it. Can you do this before the 50-move rule makes the game a draw?

@Html.ActionLink("Register", "Register", "User")

If you sign up for an account, your puzzle rating and timed training statistics will be stored, you can comment on puzzles and you can add puzzles yourself!

Contact

If you have a question, suggestion or bug report, don't hesitate to contact us and drop a line to chessvariantstraining(at)gmail(dot)com

We wish you a lot of fun here on Chess Variants Training!

Put actual content on home page

Put actual content on home page


@model PackageListViewModel
@{
    ViewBag.Title = String.IsNullOrWhiteSpace(Model.SearchTerm) ? "Packages" : "Packages matching " + Model.SearchTerm;
    ViewBag.Tab = "Packages";
}

    @if (!String.IsNullOrEmpty(Model.SearchTerm))
    {

Search for @Model.SearchTerm returned @Model.TotalCount @if (Model.TotalCount == 1)
                                                                      {
                                                                          <text>package</text>
                                                                      }
                                                                      else
                                                                      {
                                                                          <text>packages</text>
                                                                      }

    }
    else
    {

@if (Model.TotalCount == 1)
            {
                <text>There is @Model.TotalCount package</text>
            }
            else
            {
                <text>There are @Model.TotalCount packages</text>
            }

    }
    @if (@Model.LastResultIndex > 0)
    {

Displaying results @Model.FirstResultIndex - @Model.LastResultIndex.

    }

Sorted by Recent Installs

    @foreach (var package in Model.Items)
    {

            @Html.Partial("_ListPackage", package)

    }

@ViewHelpers.PreviousNextPager(Model.Pager)

@model PackageListViewModel
@{
    ViewBag.Title = String.IsNullOrWhiteSpace(Model.SearchTerm) ? "Packages" : "Packages matching " + Model.SearchTerm;
    ViewBag.SortText = String.IsNullOrWhiteSpace(Model.SearchTerm) ? "recent installs" : "relevance";
    ViewBag.Tab = "Packages";
}

    @if (!String.IsNullOrEmpty(Model.SearchTerm))
    {

Search for @Model.SearchTerm returned @Model.TotalCount @if (Model.TotalCount == 1)
                                                                      {
                                                                          <text>package</text>
                                                                      }
                                                                      else
                                                                      {
                                                                          <text>packages</text>
                                                                      }

    }
    else
    {

@if (Model.TotalCount == 1)
            {
                <text>There is @Model.TotalCount package</text>
            }
            else
            {
                <text>There are @Model.TotalCount packages</text>
            }

    }
    @if (@Model.LastResultIndex > 0)
    {

Displaying results @Model.FirstResultIndex - @Model.LastResultIndex.

    }

sorted by @ViewBag.SortText

    @foreach (var package in Model.Items)
    {

            @Html.Partial("_ListPackage", package)

    }

@ViewHelpers.PreviousNextPager(Model.Pager)

Change the sort text based on if there's a term or not


using System.Linq;
using System.Text;
using TeamCitySharp;
using TeamCitySharp.Locators;

namespace DTMF.Logic
{
    public class TeamCity
    {
        public static bool IsRunning(StringBuilder sb, string appName)
        {
            //skip if not configured
            if (System.Configuration.ConfigurationManager.AppSettings["TeamCityServer"] == string.Empty) return false;
            //Check for running builds
            var client = new TeamCityClient(System.Configuration.ConfigurationManager.AppSettings["TeamCityServer"]);
            client.ConnectAsGuest();
            var builds = client.Builds.ByBuildLocator(BuildLocator.RunningBuilds());
            if (builds.Any(f=>f.BuildTypeId.Contains(appName)))
            {
                Utilities.AppendAndSend(sb, "Build in progress. Sync disabled");
                //foreach (var build in builds)
                //{
                //    Utilities.AppendAndSend(sb, "<li>" + build.BuildTypeId + " running</li>");
                //}
                return true;
            }
            return false;
        }

    }
}

using System.Linq;
using System.Text;
using TeamCitySharp;
using TeamCitySharp.Locators;

namespace DTMF.Logic
{
    public class TeamCity
    {
        public static bool IsRunning(StringBuilder sb, string appName)
        {
            //remove prefix and suffixes from app names so same app can go to multiple places
            appName = appName.Replace(".Production", "");
            appName = appName.Replace(".Development", "");
            appName = appName.Replace(".Staging", "");
            appName = appName.Replace(".Test", "");

            //skip if not configured
            if (System.Configuration.ConfigurationManager.AppSettings["TeamCityServer"] == string.Empty) return false;
            //Check for running builds
            var client = new TeamCityClient(System.Configuration.ConfigurationManager.AppSettings["TeamCityServer"]);
            client.ConnectAsGuest();
            var builds = client.Builds.ByBuildLocator(BuildLocator.RunningBuilds());
            if (builds.Any(f=>f.BuildTypeId.Contains(appName)))
            {
                Utilities.AppendAndSend(sb, "Build in progress. Sync disabled");
                //foreach (var build in builds)
                //{
                //    Utilities.AppendAndSend(sb, "<li>" + build.BuildTypeId + " running</li>");
                //}
                return true;
            }
            return false;
        }

    }
}

Replace app name for special cases in team city check


using System;
using Flame.Compiler;
using LLVMSharp;
using static LLVMSharp.LLVM;

namespace Flame.LLVM.Codegen
{
    /// <summary>
    /// A code block implementation that returns a value from a method.
    /// </summary>
    public sealed class ReturnBlock : CodeBlock
    {
        public ReturnBlock(
            LLVMCodeGenerator CodeGenerator,
            CodeBlock ReturnValue)
        {
            this.codeGen = CodeGenerator;
            this.retVal = ReturnValue;
        }

        private LLVMCodeGenerator codeGen;
        private CodeBlock retVal;

        /// <inheritdoc/>
        public override ICodeGenerator CodeGenerator => codeGen;

        /// <inheritdoc/>
        public override IType Type => PrimitiveTypes.Void;

        /// <inheritdoc/>
        public override BlockCodegen Emit(BasicBlockBuilder BasicBlock)
        {
            var retValCodegen = retVal.Emit(BasicBlock);
            BasicBlock = retValCodegen.BasicBlock;
            if (retVal.Type == PrimitiveTypes.Void)
            {
                var retVoid = BuildRetVoid(BasicBlock.Builder);
                return new BlockCodegen(BasicBlock, retVoid);
            }
            else
            {
                var ret = BuildRet(BasicBlock.Builder, retValCodegen.Value);
                return new BlockCodegen(BasicBlock, ret);
            }
        }
    }
}

using System;
using Flame.Compiler;
using LLVMSharp;
using static LLVMSharp.LLVM;

namespace Flame.LLVM.Codegen
{
    /// <summary>
    /// A code block implementation that returns a value from a method.
    /// </summary>
    public sealed class ReturnBlock : CodeBlock
    {
        public ReturnBlock(
            LLVMCodeGenerator CodeGenerator,
            CodeBlock ReturnValue)
        {
            this.codeGen = CodeGenerator;
            this.retVal = ReturnValue;
        }

        private LLVMCodeGenerator codeGen;
        private CodeBlock retVal;

        /// <inheritdoc/>
        public override ICodeGenerator CodeGenerator => codeGen;

        /// <inheritdoc/>
        public override IType Type => PrimitiveTypes.Void;

        private BlockCodegen EmitRetVoid(BasicBlockBuilder BasicBlock)
        {
            var retVoid = BuildRetVoid(BasicBlock.Builder);
            return new BlockCodegen(BasicBlock);
        }

        /// <inheritdoc/>
        public override BlockCodegen Emit(BasicBlockBuilder BasicBlock)
        {
            if (retVal == null)
            {
                return EmitRetVoid(BasicBlock);
            }

            var retValCodegen = retVal.Emit(BasicBlock);
            BasicBlock = retValCodegen.BasicBlock;
            if (retVal.Type == PrimitiveTypes.Void)
            {
                return EmitRetVoid(BasicBlock);
            }
            else
            {
                var ret = BuildRet(BasicBlock.Builder, retValCodegen.Value);
                return new BlockCodegen(BasicBlock, ret);
            }
        }
    }
}

Fix a bug in the 'ret void' implementation


using System;

namespace ShadowsOfShadows.Items
{
	public abstract class Item
	{
      protected String Name { get; set; }
      protected String StatsString { get; set; }

		  public Item(String name, String stats)
		  {
            Name = name;
            StatsString = stats;
		  }
      public override String ToString()
      {
          String result = Name + "\n" + "Statistics:\n" + StatsString;
          return result;
      }

	    public abstract AllowedItem Allowed { get; }

	    public virtual bool IsLike(Item item)
	    {
	        return false;
	    }
	}
}

using System;

namespace ShadowsOfShadows.Items
{
    public abstract class Item
    {
        protected string Name { get; set; }
        protected string StatsString { get; set; }

        public Item(string name, string stats)
        {
            Name = name;
            StatsString = stats;
        }

        public override string ToString() => Name;

        public string Details()
        {
            string result = Name + "\n" + "Statistics:\n" + StatsString;
            return result;
        }

        public abstract AllowedItem Allowed { get; }

        public virtual bool IsLike(Item item)
        {
            return false;
        }
    }
}

Make ToString() short and provide Details()


#region Using

using System;

#endregion

namespace PortableExtensions
{
    /// <summary>
    ///     Class containing some extension methods for <see cref="DateTime" />.
    /// </summary>
    public static partial class DateTimeEx
    {
        /// <summary>
        ///     Calculates the difference between the year of the current and the given date time.
        /// </summary>
        /// <param name="dateTime">The date time value.</param>
        /// <returns>The difference between the year of the current and the given date time.</returns>
        public static Int32 Age( this DateTime dateTime )
        {
            if ( DateTime.Today.Month < dateTime.Month
                 || DateTime.Today.Month == dateTime.Month && DateTime.Today.Day < dateTime.Day )
                return DateTime.Today.Year - dateTime.Year - 1;

            return DateTime.Today.Year - dateTime.Year;
        }
    }
}

#region Using

using System;

#endregion

namespace PortableExtensions
{
    /// <summary>
    ///     Class containing some extension methods for <see cref="DateTime" />.
    /// </summary>
    public static partial class DateTimeEx
    {
        /// <summary>
        ///     Calculates the difference between the year of the current and the given date time.
        /// </summary>
        /// <remarks>
        /// <paramref name="now"/> can be samller than <paramref name="dateTime"/>, which results in negative results.
        /// </remarks>
        /// <param name="dateTime">The date time value.</param>
        /// <param name="now">The 'current' date used to caluculate the age, or null tu use <see cref="DateTime.Now" />.</param>
        /// <returns>The difference between the year of the current and the given date time.</returns>
        public static Int32 Age(this DateTime dateTime, DateTime? now = null)
        {
            var currentDate = now ?? DateTime.Now;

            if (dateTime.Year == currentDate.Year)
                return 0;

            var age = currentDate.Year - dateTime.Year;

            if (dateTime > currentDate && (currentDate.Month > dateTime.Month || currentDate.Day > dateTime.Day))
                age ++;
            else if (  (currentDate.Month < dateTime.Month || (currentDate.Month == dateTime.Month && currentDate.Day < dateTime.Day)))
                age--;

            return age;
        }
    }
}

Fix bug causing incorrect results when dateTime was >= dateTime.Now + 363d


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

namespace ChamberLib
{
    public static class Collection
    {
        public static void AddRange<T>(ICollection<T> collection, IEnumerable<T> items)
        {
            foreach (T item in items)
            {
                collection.Add(item);
            }
        }

        public static void RemoveRange<T>(ICollection<T> collection, IEnumerable<T> items)
        {
            foreach (T item in items)
            {
                collection.Remove(item);
            }
        }

        public static void AddRange<T, U>(this ICollection<T> collection, IEnumerable<U> items)
            where U : T
        {
            foreach (U item in items)
            {
                collection.Add(item);
            }
        }
        public static void RemoveRange<T, U>(this ICollection<T> collection, IEnumerable<U> items)
            where U : T
        {
            foreach (U item in items)
            {
                collection.Remove(item);
            }
        }
        public static void RemoveKeys<TKey, TValue, U>(this IDictionary<TKey, TValue> dictionary, IEnumerable<U> keys)
            where U : TKey
        {
            foreach (U key in keys)
            {
                dictionary.Remove(key);
            }
        }
        public static void EnqueueRange<T>(this Queue<T> queue, IEnumerable<T> items)
        {
            foreach (T item in items)
            {
                queue.Enqueue(item);
            }
        }
    }
}

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

namespace ChamberLib
{
    public static class Collection
    {
        public static void AddRange<T>(ICollection<T> collection, IEnumerable<T> items)
        {
            foreach (T item in items)
            {
                collection.Add(item);
            }
        }

        public static void RemoveRange<T>(ICollection<T> collection, IEnumerable<T> items)
        {
            foreach (T item in items)
            {
                collection.Remove(item);
            }
        }

        public static void AddRange<T, U>(this ICollection<T> collection, IEnumerable<U> items)
            where U : T
        {
            foreach (U item in items)
            {
                collection.Add(item);
            }
        }
        public static void RemoveRange<T, U>(this ICollection<T> collection, IEnumerable<U> items)
            where U : T
        {
            foreach (U item in items)
            {
                collection.Remove(item);
            }
        }
        public static void RemoveKeys<TKey, TValue, U>(this IDictionary<TKey, TValue> dictionary, IEnumerable<U> keys)
            where U : TKey
        {
            foreach (U key in keys)
            {
                dictionary.Remove(key);
            }
        }
        public static void EnqueueRange<T>(this Queue<T> queue, IEnumerable<T> items)
        {
            foreach (T item in items)
            {
                queue.Enqueue(item);
            }
        }

        // This method is useful if you intend to modify a collection while/after iterating over it.
        public static IEnumerable<T> GetEnumeratorOfCopy<T>(this IEnumerable<T> collection)
        {
            var array = collection.ToArray();
            foreach (var item in array)
            {
                yield return item;
            }
        }
    }
}

Add the GetEnumeratorOfCopy extension method.


using System;
using System.Collections.Concurrent;
using System.Linq;
using KafkaNet.Model;
using KafkaNet.Protocol;

namespace KafkaNet
{
    public class DefaultPartitionSelector : IPartitionSelector
    {
        private readonly ConcurrentDictionary<string, Partition> _roundRobinTracker = new ConcurrentDictionary<string, Partition>();
        public Partition Select(Topic topic, string key)
        {
            if (topic == null) throw new ArgumentNullException("topic");
            if (topic.Partitions.Count <= 0) throw new ApplicationException(string.Format("Topic ({0}) has no partitions.", topic));

            //use round robing
            var partitions = topic.Partitions;
            if (key == null)
            {
                return _roundRobinTracker.AddOrUpdate(topic.Name, x => partitions.First(), (s, i) =>
                    {
                        var index = partitions.FindIndex(0, p => p.Equals(i));
                        if (index == -1) return partitions.First();
                        if (++index >= partitions.Count) return partitions.First();
                        return partitions[index];
                    });
            }

            //use key hash
            var partitionId = Math.Abs(key.GetHashCode()) % partitions.Count;
            var partition = partitions.FirstOrDefault(x => x.PartitionId == partitionId);

            if (partition == null)
                throw new InvalidPartitionException(string.Format("Hash function return partition id: {0}, but the available partitions are:{1}",
                                                                            partitionId, string.Join(",", partitions.Select(x => x.PartitionId))));

            return partition;
        }
    }
}

using System;
using System.Collections.Concurrent;
using System.Linq;
using KafkaNet.Model;
using KafkaNet.Protocol;

namespace KafkaNet
{
    public class DefaultPartitionSelector : IPartitionSelector
    {
        private readonly ConcurrentDictionary<string, Partition> _roundRobinTracker = new ConcurrentDictionary<string, Partition>();
        public Partition Select(Topic topic, string key)
        {
            if (topic == null) throw new ArgumentNullException("topic");
            if (topic.Partitions.Count <= 0) throw new ApplicationException(string.Format("Topic ({0}) has no partitions.", topic.Name));

            //use round robing
            var partitions = topic.Partitions;
            if (key == null)
            {
                return _roundRobinTracker.AddOrUpdate(topic.Name, x => partitions.First(), (s, i) =>
                    {
                        var index = partitions.FindIndex(0, p => p.Equals(i));
                        if (index == -1) return partitions.First();
                        if (++index >= partitions.Count) return partitions.First();
                        return partitions[index];
                    });
            }

            //use key hash
            var partitionId = Math.Abs(key.GetHashCode()) % partitions.Count;
            var partition = partitions.FirstOrDefault(x => x.PartitionId == partitionId);

            if (partition == null)
                throw new InvalidPartitionException(string.Format("Hash function return partition id: {0}, but the available partitions are:{1}",
                                                                            partitionId, string.Join(",", partitions.Select(x => x.PartitionId))));

            return partition;
        }
    }
}

Fix exception not recording topic name.

Fix exception not recording topic name.


using System;
using ServiceStack;
using ServiceStack.Logging;

namespace DiscourseAutoApprove.ServiceInterface
{
    public interface IServiceStackAccountClient
    {
        UserServiceResponse GetUserSubscription(string emailAddress);
    }

    public class ServiceStackAccountClient : IServiceStackAccountClient
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(ServiceStackAccountClient));

        private readonly string serviceUrl;
        public ServiceStackAccountClient(string url)
        {
            serviceUrl = url;
        }

        public UserServiceResponse GetUserSubscription(string emailAddress)
        {
            UserServiceResponse result = null;
            try
            {
                result = serviceUrl.Fmt(emailAddress).GetJsonFromUrl()
                    .FromJson<UserServiceResponse>();
            }
            catch (Exception e)
            {
                Log.Error(e.Message);
            }

            return result;
        }
    }

    public class UserServiceResponse
    {
        public DateTime? Expiry { get; set; }
    }
}

using System;
using ServiceStack;
using ServiceStack.Logging;

namespace DiscourseAutoApprove.ServiceInterface
{
    public interface IServiceStackAccountClient
    {
        UserServiceResponse GetUserSubscription(string emailAddress);
    }

    public class ServiceStackAccountClient : IServiceStackAccountClient
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(ServiceStackAccountClient));

        private readonly string serviceUrl;
        public ServiceStackAccountClient(string url)
        {
            serviceUrl = url;
        }

        public UserServiceResponse GetUserSubscription(string emailAddress)
        {
            UserServiceResponse result = null;
            try
            {
                result = serviceUrl.Fmt(emailAddress).GetJsonFromUrl()
                    .FromJson<UserServiceResponse>();
            }
            catch (Exception e)
            {
                Log.Error(e.Message);
                throw;
            }

            return result;
        }
    }

    public class UserServiceResponse
    {
        public DateTime? Expiry { get; set; }
    }
}

Throw when error form account service.

Throw when error form account service.


using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Angora;

namespace Producer
{
    class Program
    {
        const int numberOfMessages = 1_000_000;

        static async Task Main()
        {
            var factory = new ConnectionFactory
            {
                HostName = "rabbit"
            };

            var connection = await factory.CreateConnection("Producer");

            var channel = await connection.CreateChannel();

            await channel.Queue.Declare("test", false, true, false, false, null);

            Console.WriteLine("Producer started. Press any key to send messages.");
            Console.ReadKey();

            for (int i = 0; i < numberOfMessages; i++)
            {
                var properties = new MessageProperties()
                {
                    ContentType = "message",
                    AppId = "123",
                    Timestamp = DateTime.UtcNow,
                    Headers = new Dictionary<string, object>
                    {
                        {"MessageId",  i}
                    }
                };

                await channel.Basic.Publish("", "test", true, properties, System.Text.Encoding.UTF8.GetBytes("Message Payload"));
            }

            await channel.Close();

            await connection.Close();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Angora;

namespace Producer
{
    class Program
    {
        const int numberOfMessages = 1_000_000;

        static async Task Main()
        {
            var factory = new ConnectionFactory
            {
                HostName = "rabbit"
            };

            var connection = await factory.CreateConnection("Producer");

            var channel = await connection.CreateChannel();

            await channel.Queue.Declare("test", false, true, false, false, null);

            Console.WriteLine("Producer started. Press any key to send messages.");
            Console.ReadKey();

            for (int i = 0; i < numberOfMessages; i++)
            {
                var properties = new MessageProperties()
                {
                    ContentType = "message",
                    AppId = "123",
                    Timestamp = DateTime.UtcNow,
                    Headers = new Dictionary<string, object>
                    {
                        {"MessageId",  i}
                    }
                };

                await channel.Basic.Publish("", "test", true, properties, System.Text.Encoding.UTF8.GetBytes($"Message Payload {i}"));
            }

            await channel.Close();

            await connection.Close();
        }
    }
}

Add number to message payload

Add number to message payload


// 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;

namespace osu.Game.Rulesets.Edit
{
    [Flags]
    public enum SnapType
    {
        NearbyObjects = 0,
        Grids = 1,
        All = NearbyObjects | Grids,
    }
}

// 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;

namespace osu.Game.Rulesets.Edit
{
    [Flags]
    public enum SnapType
    {
        None = 0,
        NearbyObjects = 1 << 0,
        Grids = 1 << 1,
        All = NearbyObjects | Grids,
    }
}

Add "None" snap type to fix flags not working correctly


using System;
using System.Linq;
using Nuke.Common;
using Nuke.Common.Git;
using Nuke.Common.Tools.GitVersion;
using Nuke.Core;
using static Nuke.Common.Tools.DotNet.DotNetTasks;
using static Nuke.Core.IO.FileSystemTasks;
using static Nuke.Core.IO.PathConstruction;
using static Nuke.Core.EnvironmentInfo;

class Build : NukeBuild
{
    // Auto-injection fields:
    //  - [GitVersion] must have 'GitVersion.CommandLine' referenced
    //  - [GitRepository] parses the origin from git config
    //  - [Parameter] retrieves its value from command-line arguments or environment variables
    //
    //[GitVersion] readonly GitVersion GitVersion;
    //[GitRepository] readonly GitRepository GitRepository;
    //[Parameter] readonly string MyGetApiKey;

    // This is the application entry point for the build.
    // It also defines the default target to execute.
    public static int Main () => Execute<Build>(x => x.Compile);

    Target Clean => _ => _
            // Disabled for safety.
            .OnlyWhen(() => false)
            .Executes(() =>
            {
                DeleteDirectories(GlobDirectories(SourceDirectory, "**/bin", "**/obj"));
                EnsureCleanDirectory(OutputDirectory);
            });

    Target Restore => _ => _
            .DependsOn(Clean)
            .Executes(() =>
            {
                DotNetRestore(SolutionDirectory);
            });

    Target Compile => _ => _
            .DependsOn(Restore)
            .Executes(() =>
            {
                DotNetBuild(SolutionDirectory);
            });
}

using System;
using System.Linq;
using Nuke.Common;
using Nuke.Common.Git;
using Nuke.Common.Tools.GitVersion;
using Nuke.Core;
using static Nuke.Common.Tools.DotNet.DotNetTasks;
using static Nuke.Core.IO.FileSystemTasks;
using static Nuke.Core.IO.PathConstruction;
using static Nuke.Core.EnvironmentInfo;

class Build : NukeBuild
{
    // Auto-injection fields:
    //  - [GitVersion] must have 'GitVersion.CommandLine' referenced
    //  - [GitRepository] parses the origin from git config
    //  - [Parameter] retrieves its value from command-line arguments or environment variables
    //
    //[GitVersion] readonly GitVersion GitVersion;
    //[GitRepository] readonly GitRepository GitRepository;
    //[Parameter] readonly string MyGetApiKey;

    // This is the application entry point for the build.
    // It also defines the default target to execute.
    public static int Main () => Execute<Build>(x => x.Compile);

    Target Clean => _ => _
            // Disabled for safety.
            .OnlyWhen(() => false)
            .Executes(() =>
            {
                DeleteDirectories(GlobDirectories(SourceDirectory, "**/bin", "**/obj"));
                EnsureCleanDirectory(OutputDirectory);
            });

    Target Restore => _ => _
            .DependsOn(Clean)
            .Executes(() =>
            {
                DotNetRestore(s => DefaultDotNetRestore);
            });

    Target Compile => _ => _
            .DependsOn(Restore)
            .Executes(() =>
            {
                DotNetBuild(s => DefaultDotNetCompile);
            });
}

Update default build for .NET Core.

Update default build for .NET Core.


// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE

using System;

namespace osu.Framework.Configuration
{
    public abstract class BindableNumberWithPrecision<T> : BindableNumber<T>
        where T : struct
    {
        /// <summary>
        /// An event which is raised when <see cref="Precision"/> has changed (or manually via <see cref="TriggerPrecisionChange"/>).
        /// </summary>
        public event Action<T> PrecisionChanged;

        private T precision;

        /// <summary>
        /// The precision up to which the value of this bindable should be rounded.
        /// </summary>
        public T Precision
        {
            get => precision;
            set
            {
                if (precision.Equals(value))
                    return;
                precision = value;

                TriggerPrecisionChange();
            }
        }

        protected BindableNumberWithPrecision(T value = default(T))
            : base(value)
        {
            precision = DefaultPrecision;
        }

        public override void TriggerChange()
        {
            base.TriggerChange();

            TriggerPrecisionChange(false);
        }

        protected void TriggerPrecisionChange(bool propagateToBindings = true)
        {
            PrecisionChanged?.Invoke(MinValue);
            if (propagateToBindings) Bindings?.ForEachAlive(b =>
            {
                if (b is BindableNumberWithPrecision<T> other)
                    other.Precision = Precision;
            });
        }

        protected abstract T DefaultPrecision { get; }
    }
}

// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE

using System;

namespace osu.Framework.Configuration
{
    public abstract class BindableNumberWithPrecision<T> : BindableNumber<T>
        where T : struct
    {
        /// <summary>
        /// An event which is raised when <see cref="Precision"/> has changed (or manually via <see cref="TriggerPrecisionChange"/>).
        /// </summary>
        public event Action<T> PrecisionChanged;

        private T precision;

        /// <summary>
        /// The precision up to which the value of this bindable should be rounded.
        /// </summary>
        public T Precision
        {
            get => precision;
            set
            {
                if (precision.Equals(value))
                    return;
                precision = value;

                TriggerPrecisionChange();
            }
        }

        protected BindableNumberWithPrecision(T value = default(T))
            : base(value)
        {
            precision = DefaultPrecision;
        }

        public override void TriggerChange()
        {
            base.TriggerChange();

            TriggerPrecisionChange(false);
        }

        protected void TriggerPrecisionChange(bool propagateToBindings = true)
        {
            PrecisionChanged?.Invoke(MinValue);

            if (!propagateToBindings)
                return;

            Bindings?.ForEachAlive(b =>
            {
                if (b is BindableNumberWithPrecision<T> other)
                    other.Precision = Precision;
            });
        }

        protected abstract T DefaultPrecision { get; }
    }
}

Make if block more readable

Make if block more readable


using System;
using ServiceStack.ServiceHost;
using ServiceStack.FluentValidation;
using ServiceStack.ServiceInterface.ServiceModel;
using ServiceStack.Validation;
using ServiceStack.WebHost.Endpoints;
using ServiceStack.WebHost.Endpoints.Extensions;

namespace ServiceStack.ServiceInterface.Validation
{
	public class ValidationFilter
	{
		public void ValidateRequest(IHttpRequest req, IHttpResponse res, object requestDto)
		{
			var validatorType = typeof(IValidator<>).MakeGenericType(requestDto.GetType());
			var resolver = typeof(IHttpRequest).GetMethod("TryResolve")
				.MakeGenericMethod(validatorType);

			var validator = (IValidator)resolver.Invoke(req, new object[0]);
			if (validator != null)
			{
				string ruleSet = req.HttpMethod;
				var validationResult = validator.Validate(
					new ValidationContext(requestDto, null, new MultiRuleSetValidatorSelector(ruleSet)));

				if (validationResult.IsValid) return;

				var responseStatus = ResponseStatusTranslator.Instance.Parse(validationResult.AsSerializable());

				var errorResponse = ServiceUtils.CreateErrorResponse(
					requestDto,
					new ValidationError(validationResult.AsSerializable()),
					responseStatus);

				res.WriteToResponse(req, errorResponse);
			}
		}
	}
}

using System;
using ServiceStack.ServiceHost;
using ServiceStack.FluentValidation;
using ServiceStack.ServiceInterface.ServiceModel;
using ServiceStack.Validation;
using ServiceStack.WebHost.Endpoints;
using ServiceStack.WebHost.Endpoints.Extensions;

namespace ServiceStack.ServiceInterface.Validation
{
	public class ValidationFilter
	{
		public void ValidateRequest(IHttpRequest req, IHttpResponse res, object requestDto)
		{
			var validator = ValidatorCache.GetValidator(req, requestDto.GetType());
			if (validator != null)
			{
				string ruleSet = req.HttpMethod;
				var validationResult = validator.Validate(
					new ValidationContext(requestDto, null, new MultiRuleSetValidatorSelector(ruleSet)));

				if (validationResult.IsValid) return;

				var responseStatus = ResponseStatusTranslator.Instance.Parse(validationResult.AsSerializable());

				var errorResponse = ServiceUtils.CreateErrorResponse(
					requestDto,
					new ValidationError(validationResult.AsSerializable()),
					responseStatus);

				res.WriteToResponse(req, errorResponse);
			}
		}
	}
}

Use cache to avoid runtime reflection.

Use cache to avoid runtime reflection.


using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace Codenesium.DataConversionExtensions
{
    public static class HTTPResponseHelper
    {
        public static HttpResponseMessage ToJSONResponse(this object obj, System.Net.HttpStatusCode statusCode)
        {
            var response = new HttpResponseMessage()
            {
                StatusCode = statusCode,
                Content = new StringContent(JsonConvert.SerializeObject(obj))
            };

            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return response;
        }
    }
}

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace Codenesium.DataConversionExtensions
{
    public static class HTTPResponseHelper
    {
        public static HttpResponseMessage ToJSONResponse(this object obj, System.Net.HttpStatusCode statusCode)
        {
            var response = new HttpResponseMessage()
            {
                StatusCode = statusCode,
                Content = new StringContent(JsonConvert.SerializeObject(obj))
            };

            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return response;
        }

	    public static string GetHeaderValue(this HttpResponseMessage message,string key)
        {
            IEnumerable<string> values;
            string value = string.Empty;
            if (message.Headers.TryGetValues(key, out values))
            {
                value = values.FirstOrDefault();
            }
            return value;
        }
    }
}

Add method to return a header value from a HTTP response


// 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 System.Runtime.CompilerServices;

namespace System
{
    // MathF emulation on platforms which don't support it natively.
    internal static class MathF
    {
        public const float PI = (float)Math.PI;

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static float Abs(float x)
        {
            return Math.Abs(x);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static float Acos(float x)
        {
            return (float)Math.Acos(x);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static float Cos(float x)
        {
            return (float)Math.Cos(x);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static float IEEERemainder(float x, float y)
        {
            return (float)Math.IEEERemainder(x, y);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static float Sin(float x)
        {
            return (float)Math.Sin(x);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static float Sqrt(float x)
        {
            return (float)Math.Sqrt(x);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static float Tan(float x)
        {
            return (float)Math.Tan(x);
        }
    }
}

// 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 System.Runtime.CompilerServices;

namespace System
{
    // MathF emulation on platforms which don't support it natively.
    internal static class MathF
    {
        public const float PI = (float)Math.PI;

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static float Abs(float x)
        {
            return Math.Abs(x);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static float Acos(float x)
        {
            return (float)Math.Acos(x);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static float Cos(float x)
        {
            return (float)Math.Cos(x);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static float IEEERemainder(float x, float y)
        {
            return (float)Math.IEEERemainder(x, y);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static float Pow(float x, float y)
        {
            return (float)Math.Pow(x, y);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static float Sin(float x)
        {
            return (float)Math.Sin(x);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static float Sqrt(float x)
        {
            return (float)Math.Sqrt(x);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static float Tan(float x)
        {
            return (float)Math.Tan(x);
        }
    }
}

Add Pow to MathF compat file.

Add Pow to MathF compat file.


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

public class Spacecraft : MonoBehaviour {

}
SYNTAX ERROR :D

Fix the syntax error Travis works :D

Fix the syntax error
Travis works :D


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

public class SkillTree_Manager : MonoBehaviour
{
	// Use this for initialization
	void Start ()
    {

	}

	// Update is called once per frame
	void Update ()
    {

	}
}

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

public class SkillTree_Manager : MonoBehaviour
{
    public GameObject amountXPObject;

    Text amountXPText;

	// Use this for initialization
	void Start ()
    {
        amountXPText = amountXPObject.GetComponent<Text>();
	}

	// Update is called once per frame
	void Update ()
    {
        amountXPText.text = Game.thePlayer.XP.ToString();
    }
}

Update XP in skills page

Update XP in skills page


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace IceBuilder
{

    public interface UpgradeProgressCallback
    {
        bool Canceled { get; set; }
        void Finished();
        void ReportProgress(String project, int index);
    }

    public partial class UpgradeDialogProgress : Form, UpgradeProgressCallback
    {
        public UpgradeDialogProgress(int total)
        {
            InitializeComponent();
            ProgressBar.Maximum = total;
        }

        private void CancelButton_Clicked(object sender, EventArgs e)
        {
            Canceled = true;
        }

        public bool Canceled
        {
            get;
            set;
        }

        public void ReportProgress(String project, int index)
        {
            InfoLabel.Text = String.Format("Upgrading project: {0}", project);
            ProgressBar.Value = index;
        }

        public void Finished()
        {
            Close();
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace IceBuilder
{

    public interface UpgradeProgressCallback
    {
        bool Canceled { get; set; }
        void Finished();
        void ReportProgress(String project, int index);
    }

    public partial class UpgradeDialogProgress : Form, UpgradeProgressCallback
    {
        public UpgradeDialogProgress(int total)
        {
            InitializeComponent();
            _canceled = false;
            ProgressBar.Maximum = total;
        }

        private void CancelButton_Clicked(object sender, EventArgs e)
        {
            Canceled = true;
        }

        private bool _canceled;
        public bool Canceled
        {
            get
            {
                lock (this)
                {
                    return _canceled;
                }
            }
            set
            {
                lock (this)
                {
                    _canceled = value;
                }
            }
        }

        public void ReportProgress(String project, int index)
        {
            InfoLabel.Text = String.Format("Upgrading project: {0}", project);
            ProgressBar.Value = index;
        }

        public void Finished()
        {
            Close();
        }
    }
}

Fix possible race condition in the Upgrade Callback


// stylecop.header
using Strinken.Parser;

namespace Strinken.Filters
{
    /// <summary>
    /// This filter takes some couples of arguments, and replace each occurrence of each first argument by the second.
    /// </summary>
    public class ReplaceFilter : IFilter
    {
        /// <inheritdoc/>
        public string Description => "This filter takes some couples of arguments, and replace each occurrence of each first argument by the second.";

        /// <inheritdoc/>
        public string Name => "Replace";

        /// <inheritdoc/>
        public string Usage => "{tag:replace+value1,replaceValue1,value2,replaceValue2...}";

        /// <inheritdoc/>
        public string Resolve(string value, string[] arguments)
        {
            var newValue = value;
            for (int i = 0; i < arguments.Length / 2; i++)
            {
                newValue = newValue.Replace(arguments[i * 2], arguments[(i * 2) + 1]);
            }

            return newValue;
        }

        /// <inheritdoc/>
        public bool Validate(string[] arguments) => arguments?.Length > 0 && arguments?.Length % 2 == 0;
    }
}

// stylecop.header
using Strinken.Parser;

namespace Strinken.Filters
{
    /// <summary>
    /// This filter takes some couples of arguments, and replace each occurrence of each first argument by the second.
    /// </summary>
    internal class ReplaceFilter : IFilter
    {
        /// <inheritdoc/>
        public string Description => "This filter takes some couples of arguments, and replace each occurrence of each first argument by the second.";

        /// <inheritdoc/>
        public string Name => "Replace";

        /// <inheritdoc/>
        public string Usage => "{tag:replace+value1,replaceValue1,value2,replaceValue2...}";

        /// <inheritdoc/>
        public string Resolve(string value, string[] arguments)
        {
            var newValue = value;
            for (int i = 0; i < arguments.Length / 2; i++)
            {
                newValue = newValue.Replace(arguments[i * 2], arguments[(i * 2) + 1]);
            }

            return newValue;
        }

        /// <inheritdoc/>
        public bool Validate(string[] arguments) => arguments?.Length > 0 && arguments?.Length % 2 == 0;
    }
}

Move the replace filter to internal

Move the replace filter to internal


namespace NuGet.VisualStudio {
    public class PowerShellScripts {
        public static readonly string Install = "install.ps1";
        public static readonly string Uninstall = "uninstall.ps1";
        public static readonly string Init = "init.ps1";
    }
}

namespace NuGet.VisualStudio {
    public static class PowerShellScripts {
        public static readonly string Install = "install.ps1";
        public static readonly string Uninstall = "uninstall.ps1";
        public static readonly string Init = "init.ps1";
    }
}

Make PowerShellScripts class static per review.


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

using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("Microsoft Azure Traffic Manager Management Library")]
[assembly: AssemblyDescription("Provides Microsoft Azure Traffic Manager management functions for managing the Microsoft Azure Traffic Manager service.")]

[assembly: AssemblyVersion("2.2.0.0")]
[assembly: AssemblyFileVersion("2.2.0.0")]

[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Microsoft Azure .NET SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]

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

using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("Microsoft Azure Traffic Manager Management Library")]
[assembly: AssemblyDescription("Provides Microsoft Azure Traffic Manager management functions for managing the Microsoft Azure Traffic Manager service.")]

[assembly: AssemblyVersion("2.1.0.0")]
[assembly: AssemblyFileVersion("2.2.0.0")]

[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Microsoft Azure .NET SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]

Revert AssemblyVersion to 2.1.0 because there are no breaking changes in this version


// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

namespace osu.Game.Rulesets.Mania.Judgements
{
    public class HoldNoteTickJudgement : ManiaJudgement
    {
    }
}

// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

namespace osu.Game.Rulesets.Mania.Judgements
{
    public class HoldNoteTickJudgement : ManiaJudgement
    {
        public override int NumericResultForScore(ManiaHitResult result) => 20;
        public override int NumericResultForAccuracy(ManiaHitResult result) => 0; // Don't count ticks into accuracy
    }
}

Add hold note tick judgement.

Add hold note tick judgement.


namespace TraktApiSharp.Tests.Experimental.Requests.Calendars.OAuth
{
    using FluentAssertions;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using TraktApiSharp.Experimental.Requests.Calendars.OAuth;
    using TraktApiSharp.Objects.Get.Calendars;

    [TestClass]
    public class TraktCalendarUserDVDMoviesRequestTests
    {
        [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("With OAuth"), TestCategory("Movies")]
        public void TestTraktCalendarUserDVDMoviesRequestIsNotAbstract()
        {
            typeof(TraktCalendarUserDVDMoviesRequest).IsAbstract.Should().BeFalse();
        }

        [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("With OAuth"), TestCategory("Movies")]
        public void TestTraktCalendarUserDVDMoviesRequestIsSealed()
        {
            typeof(TraktCalendarUserDVDMoviesRequest).IsSealed.Should().BeTrue();
        }

        [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("With OAuth"), TestCategory("Movies")]
        public void TestTraktCalendarUserDVDMoviesRequestIsSubclassOfATraktCalendarUserRequest()
        {
            typeof(TraktCalendarUserDVDMoviesRequest).IsSubclassOf(typeof(ATraktCalendarUserRequest<TraktCalendarMovie>)).Should().BeTrue();
        }
    }
}

namespace TraktApiSharp.Tests.Experimental.Requests.Calendars.OAuth
{
    using FluentAssertions;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using TraktApiSharp.Experimental.Requests.Calendars.OAuth;
    using TraktApiSharp.Objects.Get.Calendars;
    using TraktApiSharp.Requests;

    [TestClass]
    public class TraktCalendarUserDVDMoviesRequestTests
    {
        [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("With OAuth"), TestCategory("Movies")]
        public void TestTraktCalendarUserDVDMoviesRequestIsNotAbstract()
        {
            typeof(TraktCalendarUserDVDMoviesRequest).IsAbstract.Should().BeFalse();
        }

        [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("With OAuth"), TestCategory("Movies")]
        public void TestTraktCalendarUserDVDMoviesRequestIsSealed()
        {
            typeof(TraktCalendarUserDVDMoviesRequest).IsSealed.Should().BeTrue();
        }

        [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("With OAuth"), TestCategory("Movies")]
        public void TestTraktCalendarUserDVDMoviesRequestIsSubclassOfATraktCalendarUserRequest()
        {
            typeof(TraktCalendarUserDVDMoviesRequest).IsSubclassOf(typeof(ATraktCalendarUserRequest<TraktCalendarMovie>)).Should().BeTrue();
        }

        [TestMethod, TestCategory("Requests"), TestCategory("Calendars"), TestCategory("With OAuth"), TestCategory("Movies")]
        public void TestTraktCalendarUserDVDMoviesRequestHasAuthorizationRequired()
        {
            var request = new TraktCalendarUserDVDMoviesRequest(null);
            request.AuthorizationRequirement.Should().Be(TraktAuthorizationRequirement.Required);
        }
    }
}

Make sure that authorization of TraktCalendarUserDVDMoviesRequest is required


using System;
using Agiil.Domain.Auth;
using Agiil.Web.Models.Shared;
using CSF.ORM;

namespace Agiil.Web.Services.Auth
{
    public class LoginStateReader
    {
        readonly IIdentityReader userReader;
        readonly IEntityData data;

        public LoginStateModel GetLoginState()
        {
            var userInfo = userReader.GetCurrentUserInfo();

            return new LoginStateModel {
                UserInfo = userInfo,
                IsSiteAdmin = (userInfo != null)? data.Get(userInfo.Identity).SiteAdministrator : false,
            };
        }

        public LoginStateReader(IIdentityReader userReader, IEntityData data)
        {
            this.userReader = userReader ?? throw new ArgumentNullException(nameof(userReader));
            this.data = data ?? throw new ArgumentNullException(nameof(data));
        }
    }
}

using System;
using Agiil.Domain.Auth;
using Agiil.Web.Models.Shared;
using CSF.ORM;

namespace Agiil.Web.Services.Auth
{
    public class LoginStateReader
    {
        readonly IIdentityReader userReader;
        readonly IEntityData data;

        public LoginStateModel GetLoginState()
        {
            var userInfo = userReader.GetCurrentUserInfo();
            var user = (userInfo?.Identity != null) ? data.Get(userInfo.Identity) : null;

            return new LoginStateModel {
                UserInfo = userInfo,
                IsSiteAdmin = user?.SiteAdministrator == true,
            };
        }

        public LoginStateReader(IIdentityReader userReader, IEntityData data)
        {
            this.userReader = userReader ?? throw new ArgumentNullException(nameof(userReader));
            this.data = data ?? throw new ArgumentNullException(nameof(data));
        }
    }
}

Fix crash error when login state is invalid

I think this was caused by having an existing browser cookie for the domain,
indicating that I am logged-in as a user which does not exist in the current
database.

This caused it to fail to retrieve a user from the DB and as a result crashed
because it had expected to find a user.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace Wheeels
{
    static class Program
    {
        /// <summary>
        /// Point d'entrée principal de l'application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());

            int a = 12;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace Wheeels
{
    static class Program
    {
        /// <summary>
        /// Point d'entrée principal de l'application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

Revert "ajout d'une variable locale"

Revert "ajout d'une variable locale"

This reverts commit 41bad3b26a9866733ff2cedbda76e6e1a7eb8fba.


                GC Handicapping System

                New GC Handicapping System comes into effect 3 April, 2017

Add sticky note 'GC Handicapping System'


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

namespace WebApp.Tests
{
    static class WebAppUrl
    {
        public const string EnsureBasicUser = "/app/ensureBasicUser";

        public const string StartLoginUri = "/.webfront/c/startLogin";
        public const string BasicLoginUri = "/.webfront/c/basicLogin";
        public const string LoginUri = "/.webfront/c/unsafeDirectLogin";
        public const string RefreshUri = "/.webfront/c/refresh";
        public const string LogoutUri = "/.webfront/c/logout";
        public const string TokenExplainUri = "/.webfront/token";

    }
}

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

namespace WebApp.Tests
{
    static class WebAppUrl
    {
        public const string EnsureBasicUser = "/ensureBasicUser";

        public const string StartLoginUri = "/.webfront/c/startLogin";
        public const string BasicLoginUri = "/.webfront/c/basicLogin";
        public const string LoginUri = "/.webfront/c/unsafeDirectLogin";
        public const string RefreshUri = "/.webfront/c/refresh";
        public const string LogoutUri = "/.webfront/c/logout";
        public const string TokenExplainUri = "/.webfront/token";

    }
}

Fix tests: difference was that the db was initialized in local and "/app/ensureBasicUser" is now "/ensureBasicUser".


// 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 System;

// GitHub 20040: operand ordering bug with GT_INDEX_ADDR
// Requires minopts/tier0 to repro

namespace GitHub_20040
{
    class Program
    {
        static int Main(string[] args)
        {
            var array = new byte[] {0x00, 0x01};
            var reader = new BinaryTokenStreamReader(array);

            var val = reader.ReadByte();

            if (val == 0x01)
            {
                Console.WriteLine("Pass");
                return 100;
            }
            else
            {
                Console.WriteLine($"Fail: val=0x{val:x2}, expected 0x01");
                return 0;
            }
        }
    }

    public class BinaryTokenStreamReader
    {
        private readonly byte[] currentBuffer;

        public BinaryTokenStreamReader(byte[] input)
        {
            this.currentBuffer = input;
        }

        byte[] CheckLength(out int offset)
        {
            // In the original code, this logic is more complicated.
            // It's simplified here to demonstrate the bug.
            offset = 1;
            return currentBuffer;
        }

        public byte ReadByte()
        {
            int offset;
            var buff = CheckLength(out offset);
            return buff[offset];
        }
    }
}

// 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 System;
using System.Runtime.CompilerServices;

// GitHub 20040: operand ordering bug with GT_INDEX_ADDR
// Requires minopts/tier0 to repro

namespace GitHub_20040
{
    class Program
    {
        static int Main(string[] args)
        {
            var array = new byte[] {0x00, 0x01};
            var reader = new BinaryTokenStreamReader(array);

            var val = reader.ReadByte();

            if (val == 0x01)
            {
                Console.WriteLine("Pass");
                return 100;
            }
            else
            {
                Console.WriteLine($"Fail: val=0x{val:x2}, expected 0x01");
                return 0;
            }
        }
    }

    public class BinaryTokenStreamReader
    {
        private readonly byte[] currentBuffer;

        public BinaryTokenStreamReader(byte[] input)
        {
            this.currentBuffer = input;
        }

        byte[] CheckLength(out int offset)
        {
            // In the original code, this logic is more complicated.
            // It's simplified here to demonstrate the bug.
            offset = 1;
            return currentBuffer;
        }

        [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)]
        public byte ReadByte()
        {
            int offset;
            var buff = CheckLength(out offset);
            return buff[offset];
        }
    }
}

Fix test for GT_INDEX_ADDR to forcibly compile with minopts

Update test introduced in #20047 so that the key method `ReadBytes` is compiled
with minopts by default.


using Data;
using Ninject;
using Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace LCAToolAPI.API
{
    public class FragmentTraversalController : ApiController
    {
        [Inject]
        private readonly IFragmentTraversal _fragmentTraversal ;

        public FragmentTraversalController(IFragmentTraversal fragmentTraversal)
        {

            if (fragmentTraversal == null)
            {
                throw new ArgumentNullException("fragmentTraversal is null");
            }

            _fragmentTraversal = fragmentTraversal;

        }

        int scenarioId = 1;

        //GET api/<controller>
        [System.Web.Http.AcceptVerbs("GET", "POST")]
        [System.Web.Http.HttpGet]
        public void Traversal()
        {
            _fragmentTraversal.Traverse(scenarioId);
        }

        //// GET api/<controller>
        //public IEnumerable<string> Get()
        //{
        //    return new string[] { "value1", "value2" };
        //}

        //// GET api/<controller>/5
        //public string Get(int id)
        //{
        //    return "value";
        //}

        //// POST api/<controller>
        //public void Post([FromBody]string value)
        //{
        //}

        //// PUT api/<controller>/5
        //public void Put(int id, [FromBody]string value)
        //{
        //}

        //// DELETE api/<controller>/5
        //public void Delete(int id)
        //{
        //}

    }
}

using Data;
using Ninject;
using Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace LCAToolAPI.API
{
    public class FragmentTraversalController : ApiController
    {
        [Inject]
        private readonly IFragmentTraversal _fragmentTraversal ;

        public FragmentTraversalController(IFragmentTraversal fragmentTraversal)
        {

            if (fragmentTraversal == null)
            {
                throw new ArgumentNullException("fragmentTraversal is null");
            }

            _fragmentTraversal = fragmentTraversal;

        }

        //int scenarioId = 1;

        //GET api/<controller>
        [Route("api/scenarios/{scenarioID}/updatecaches")]
        [System.Web.Http.AcceptVerbs("GET", "POST")]
        [System.Web.Http.HttpGet]
        public void Traversal(int scenarioId)
        {
            _fragmentTraversal.Traverse(scenarioId);
        }

        //// GET api/<controller>
        //public IEnumerable<string> Get()
        //{
        //    return new string[] { "value1", "value2" };
        //}

        //// GET api/<controller>/5
        //public string Get(int id)
        //{
        //    return "value";
        //}

        //// POST api/<controller>
        //public void Post([FromBody]string value)
        //{
        //}

        //// PUT api/<controller>/5
        //public void Put(int id, [FromBody]string value)
        //{
        //}

        //// DELETE api/<controller>/5
        //public void Delete(int id)
        //{
        //}

    }
}

WebAPI: Add route for updating caches via fragment traversal