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

namespace LBD2OBJLib.Types
{
	class FixedPoint
	{
		public int IntegralPart { get; set; }
		public int DecimalPart { get; set; }

		public FixedPoint(byte[] data)
		{
			if (data.Length != 2) { throw new ArgumentException("data must be 2 bytes", "data"); }

			byte[] _data = new byte[2];
			data.CopyTo(_data, 0);

			var signMask = (byte)128;
			var integralMask = (byte)112;
			var firstPartOfDecimalMask = (byte)15;

			bool isNegative = (_data[0] & signMask) == 128;
			int integralPart = (_data[0] & integralMask) * (isNegative ? -1 : 1);
			int decimalPart = (_data[0] & firstPartOfDecimalMask);
			decimalPart <<= 8;
			decimalPart += data[1];

			IntegralPart = integralPart;
			DecimalPart = decimalPart;
		}

		public override string ToString()
		{
			return IntegralPart + "." + DecimalPart;
		}
	}
}

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

namespace LBD2OBJLib.Types
{
	class FixedPoint
	{
		public int IntegralPart { get; set; }
		public int DecimalPart { get; set; }

		const byte SIGN_MASK = 128;
		const byte INTEGRAL_MASK = 112;
		const byte MANTISSA_MASK = 15;

		public FixedPoint(byte[] data)
		{
			if (data.Length != 2) { throw new ArgumentException("data must be 2 bytes", "data"); }

			byte[] _data = new byte[2];
			data.CopyTo(_data, 0);

			bool isNegative = (_data[0] & SIGN_MASK) == 128;
			int integralPart = (_data[0] & INTEGRAL_MASK) * (isNegative ? -1 : 1);
			int decimalPart = (_data[0] & MANTISSA_MASK);
			decimalPart <<= 8;
			decimalPart += data[1];

			IntegralPart = integralPart;
			DecimalPart = decimalPart;
		}

		public override string ToString()
		{
			return IntegralPart + "." + DecimalPart;
		}
	}
}

Change mask variables to const values, remove from constructor


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

using System;
using osu.Framework.Platform;
using osu.Framework;

namespace SampleGame.Desktop
{
    public static class Program
    {
        [STAThread]
        public static void Main()
        {
            using (GameHost host = Host.GetSuitableHost(@"sample-game"))
            using (Game game = new SampleGameGame())
                host.Run(game);
        }
    }
}

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

using System;
using System.Linq;
using osu.Framework;
using osu.Framework.Platform;

namespace SampleGame.Desktop
{
    public static class Program
    {
        [STAThread]
        public static void Main(string[] args)
        {
            bool useSdl = args.Contains(@"--sdl");

            using (GameHost host = Host.GetSuitableHost(@"sample-game", useSdl: useSdl))
            using (Game game = new SampleGameGame())
                host.Run(game);
        }
    }
}

Add SDL support to SampleGame

Add SDL support to SampleGame


using System.Windows.Forms;

namespace Palaso.UI.WindowsForms.WritingSystems
{
	public partial class WSPropertiesTabControl : UserControl
	{
		private WritingSystemSetupModel _model;

		public WSPropertiesTabControl()
		{
			InitializeComponent();
		}

		public void BindToModel(WritingSystemSetupModel model)
		{
			_model = model;
			_identifiersControl.BindToModel(_model);
			_fontControl.BindToModel(_model);
			_keyboardControl.BindToModel(_model);
			_sortControl.BindToModel(_model);
			_spellingControl.BindToModel(_model);
		}
	}
}

using System;
using System.Windows.Forms;

namespace Palaso.UI.WindowsForms.WritingSystems
{
	public partial class WSPropertiesTabControl : UserControl
	{
		private WritingSystemSetupModel _model;

		public WSPropertiesTabControl()
		{
			InitializeComponent();
		}

		public void BindToModel(WritingSystemSetupModel model)
		{
			 if (_model != null)
			{
				_model.SelectionChanged -= ModelChanged;
				_model.CurrentItemUpdated -= ModelChanged;
			}

			_model = model;
			_identifiersControl.BindToModel(_model);
			_fontControl.BindToModel(_model);
			_keyboardControl.BindToModel(_model);
			_sortControl.BindToModel(_model);
			_spellingControl.BindToModel(_model);

			if (_model != null)
			{
				_model.SelectionChanged+= ModelChanged;
				_model.CurrentItemUpdated += ModelChanged;
			}
			this.Disposed += OnDisposed;
		}

		private void ModelChanged(object sender, EventArgs e)
		{
		   if( !_model.CurrentIsVoice &&
				_tabControl.Controls.Contains(_spellingPage))
		   {
			   return;// don't mess if we really don't need a change
		   }

			_tabControl.Controls.Clear();
			this._tabControl.Controls.Add(this._identifiersPage);

			if( !_model.CurrentIsVoice)
			{
				this._tabControl.Controls.Add(this._spellingPage);
				this._tabControl.Controls.Add(this._fontsPage);
				this._tabControl.Controls.Add(this._keyboardsPage);
				this._tabControl.Controls.Add(this._sortingPage);
			}
		}

		void OnDisposed(object sender, EventArgs e)
		{
			if (_model != null)
				_model.SelectionChanged -= ModelChanged;
		}
	}
}

Hide irrelevant tabs when the Writing System is a voice one.


namespace TensorSharp.Operations
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    public class MultiplyIntegerIntegerOperation : IBinaryOperation<int, int, int>
    {
        public Tensor<int> Evaluate(Tensor<int> tensor1, Tensor<int> tensor2)
        {
            Tensor<int> result = new Tensor<int>();

            result.SetValue(tensor1.GetValue() * tensor2.GetValue());

            return result;
        }
    }
}

namespace TensorSharp.Operations
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    public class MultiplyIntegerIntegerOperation : IBinaryOperation<int, int, int>
    {
        public Tensor<int> Evaluate(Tensor<int> tensor1, Tensor<int> tensor2)
        {
            int[] values1 = tensor1.GetValues();
            int l = values1.Length;

            int value2 = tensor2.GetValue();

            int[] newvalues = new int[l];

            for (int k = 0; k < l; k++)
                newvalues[k] = values1[k] * value2;

            return tensor1.CloneWithNewValues(newvalues);
        }
    }
}

Refactor Multiply Integers Operation to use GetValues and CloneWithValues


using System;
using System.Linq;
using System.Threading;
using Moq;
using SignalR.Client.Transports;
using SignalR.Hosting.Memory;
using Xunit;

namespace SignalR.Client.Tests
{
    public class ConnectionFacts
    {
        public class Start
        {
            [Fact]
            public void FailsIfProtocolVersionIsNull()
            {
                var connection = new Connection("http://test");
                var transport = new Mock<IClientTransport>();
                transport.Setup(m => m.Negotiate(connection)).Returns(TaskAsyncHelper.FromResult(new NegotiationResponse
                {
                    ProtocolVersion = null
                }));

                var aggEx = Assert.Throws<AggregateException>(() => connection.Start(transport.Object).Wait());
                var ex = aggEx.Unwrap();
                Assert.IsType(typeof(InvalidOperationException), ex);
                Assert.Equal("Incompatible protocol version.", ex.Message);
            }
        }

        public class Received
        {
            [Fact]
            public void SendingBigData()
            {
                var host = new MemoryHost();
                host.MapConnection<SampleConnection>("/echo");

                var connection = new Connection("http://foo/echo");

                var wh = new ManualResetEventSlim();
                var n = 0;
                var target = 20;

                connection.Received += data =>
                {
                    n++;
                    if (n == target)
                    {
                        wh.Set();
                    }
                };

                connection.Start(host).Wait();

                var conn = host.ConnectionManager.GetConnection<SampleConnection>();

                for (int i = 0; i < target; ++i)
                {
                    var node = new BigData();
                    conn.Broadcast(node).Wait();
                    Thread.Sleep(1000);
                }

                Assert.True(wh.Wait(TimeSpan.FromMinutes(1)), "Timed out");
            }

            public class BigData
            {
                public string[] Dummy
                {
                    get
                    {
                        return Enumerable.Range(0, 1000).Select(x => new String('*', 500)).ToArray();
                    }
                }
            }

            public class SampleConnection : PersistentConnection
            {
            }
        }
    }
}

using System;
using System.Linq;
using System.Threading;
using Moq;
using SignalR.Client.Transports;
using SignalR.Hosting.Memory;
using Xunit;

namespace SignalR.Client.Tests
{
    public class ConnectionFacts
    {
        public class Start
        {
            [Fact]
            public void FailsIfProtocolVersionIsNull()
            {
                var connection = new Connection("http://test");
                var transport = new Mock<IClientTransport>();
                transport.Setup(m => m.Negotiate(connection)).Returns(TaskAsyncHelper.FromResult(new NegotiationResponse
                {
                    ProtocolVersion = null
                }));

                var aggEx = Assert.Throws<AggregateException>(() => connection.Start(transport.Object).Wait());
                var ex = aggEx.Unwrap();
                Assert.IsType(typeof(InvalidOperationException), ex);
                Assert.Equal("Incompatible protocol version.", ex.Message);
            }
        }
    }
}

Remove sending big data test.

Remove sending big data test.


using System;
using System.Collections.Generic;
using Baseline;
using Confluent.Kafka;
using Jasper.Configuration;
using Jasper.Runtime.Routing;

namespace Jasper.ConfluentKafka.Internal
{
    public class KafkaTopicRouter : TopicRouter<KafkaSubscriberConfiguration>
    {
        //Dictionary<Uri, ProducerConfig> producerConfigs;
        //public KafkaTopicRouter(Dictionary<Uri, ProducerConfig> producerConfigs)
        //{
        //}

        public override Uri BuildUriForTopic(string topicName)
        {
            var endpoint = new KafkaEndpoint
            {
                IsDurable = true,
                TopicName = topicName
            };

            return endpoint.Uri;
        }

        public override KafkaSubscriberConfiguration FindConfigurationForTopic(string topicName,
            IEndpoints endpoints)
        {
            var uri = BuildUriForTopic(topicName);
            var endpoint = endpoints.As<TransportCollection>().GetOrCreateEndpoint(uri);

            return new KafkaSubscriberConfiguration((KafkaEndpoint) endpoint);
        }

    }

}

using System;
using Baseline;
using Jasper.Configuration;
using Jasper.Runtime.Routing;

namespace Jasper.ConfluentKafka.Internal
{
    public class KafkaTopicRouter : TopicRouter<KafkaSubscriberConfiguration>
    {
        public override Uri BuildUriForTopic(string topicName)
        {
            var endpoint = new KafkaEndpoint
            {
                IsDurable = true,
                TopicName = topicName
            };

            return endpoint.Uri;
        }

        public override KafkaSubscriberConfiguration FindConfigurationForTopic(string topicName,
            IEndpoints endpoints)
        {
            var uri = BuildUriForTopic(topicName);
            var endpoint = endpoints.As<TransportCollection>().GetOrCreateEndpoint(uri);

            return new KafkaSubscriberConfiguration((KafkaEndpoint) endpoint);
        }
    }
}

Remove commented code and unused usings

Remove commented code and unused usings


using System.IO;
using MiniCover.Model;
using Newtonsoft.Json;

namespace MiniCover.CommandLine.Options
{
    class CoverageLoadedFileOption : CoverageFileOption
    {
        public InstrumentationResult Result { get; private set; }

        protected override FileInfo PrepareValue(string value)
        {
            var fileInfo = base.PrepareValue(value);

            if (!fileInfo.Exists)
                throw new FileNotFoundException($"Coverage file does not exist '{fileInfo.FullName}'");

            var coverageFileString = File.ReadAllText(fileInfo.FullName);
            Result = JsonConvert.DeserializeObject<InstrumentationResult>(coverageFileString);

            return fileInfo;
        }
    }
}

using System.IO;
using MiniCover.Exceptions;
using MiniCover.Model;
using Newtonsoft.Json;

namespace MiniCover.CommandLine.Options
{
    class CoverageLoadedFileOption : CoverageFileOption
    {
        public InstrumentationResult Result { get; private set; }

        protected override FileInfo PrepareValue(string value)
        {
            var fileInfo = base.PrepareValue(value);

            if (!fileInfo.Exists)
                throw new ValidationException($"Coverage file does not exist '{fileInfo.FullName}'");

            var coverageFileString = File.ReadAllText(fileInfo.FullName);
            Result = JsonConvert.DeserializeObject<InstrumentationResult>(coverageFileString);

            return fileInfo;
        }
    }
}

Improve error message when coverage is not found


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

public class FollowTarget : MonoBehaviour
{
    [Inject]
    public ForceSelector ForceSelector { get; set; }

    public Rigidbody targetRb;
    public float distanceToReset = 0.1f;
    public float velocityThresh;
    public float moveToTargetSpeed;
    public bool isAtTarget;

    void Update ()
    {
        isAtTarget = Vector3.Distance(targetRb.transform.position, transform.position) <= distanceToReset;

        if (targetRb.velocity.magnitude < velocityThresh && !isAtTarget)
        {
            transform.position = Vector3.Lerp(transform.position, targetRb.transform.position, moveToTargetSpeed);
        }

        ForceSelector.IsRunning = isAtTarget;
	}
}

using System;
using System.Collections;
using System.Collections.Generic;
using UniRx;
using UnityEngine;
using Zenject;

public class FollowTarget : MonoBehaviour
{
    [Inject]
    public ForceSelector ForceSelector { get; set; }

    public Rigidbody targetRb;
    public float velocityThresh;
    public float moveToTargetSpeed;
    public float distanceToResume;
    public float distanceToReset;
    private IDisposable sub;

    void Start()
    {
        sub = Observable
            .IntervalFrame(5)
            .Select(_ => Vector3.Distance(targetRb.transform.position, transform.position))
            .Hysteresis((d, referenceDist) => d - referenceDist, distanceToResume, distanceToReset)
            .Subscribe(isMoving =>
            {
                ForceSelector.IsRunning = !isMoving;
            });
    }

    void OnDestroy()
    {
        if (sub != null)
        {
            sub.Dispose();
            sub = null;
        }
    }

    void Update ()
    {
        if (targetRb.velocity.magnitude < velocityThresh && !ForceSelector.IsRunning)
        {
            transform.position = Vector3.Lerp(transform.position, targetRb.transform.position, moveToTargetSpeed);
        }

	}

}

Fix force selector reset clipping error.


using Bands.Output;
using System;

namespace Bands.GettingStarted
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Getting started with Bands!");
            var payload = new CounterPayload();
            var innerConsoleBand = new ConsoleWriterBand<CounterPayload>(CallAddTwo);
            var incrementableBand = new IncrementableBand<CounterPayload>(innerConsoleBand);
            var outerConsoleBand = new ConsoleWriterBand<CounterPayload>(incrementableBand);
            outerConsoleBand.Enter(payload);
            Console.WriteLine("Kinda badass, right?");
            Console.Read();
        }

        public static void CallAddTwo(CounterPayload payload)
        {
            Console.WriteLine("Calling payload.AddTwo()");
            payload.AddTwo();
        }
    }
}

using Bands.Output;
using System;

namespace Bands.GettingStarted
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Getting started with Bands!");
            var payload = new CounterPayload();
            var innerConsoleBand = new ConsoleWriterBand<CounterPayload>(CallAddTwo);
            var incrementableBand = new IncrementableBand<CounterPayload>(innerConsoleBand);
            var outerConsoleBand = new ConsoleWriterBand<CounterPayload>(incrementableBand);
            outerConsoleBand.Enter(payload);
            Console.WriteLine("Kinda awesome, right?");
            Console.Read();
        }

        public static void CallAddTwo(CounterPayload payload)
        {
            Console.WriteLine("Calling payload.AddTwo()");
            payload.AddTwo();
        }
    }
}

Remove profanity - don't want to alienate folk


using NUnit.Framework;
using System;
using System.Linq.Expressions;
using TestStack.FluentMVCTesting.Internal;

namespace TestStack.FluentMVCTesting.Tests.Internal
{
    [TestFixture]
    public class ExpressionInspectorShould
    {
        [Test]
        public void Correctly_parse_equality_comparison_with_string_operands()
        {
            Expression<Func<string, bool>> func = text => text == "any";
            ExpressionInspector sut = new ExpressionInspector();
            var actual = sut.Inspect(func);
            Assert.AreEqual("text => text == \"any\"", actual);
        }

        [Test]
        public void Correctly_parse_equality_comparison_with_int_operands()
        {
            Expression<Func<int, bool>> func = number => number == 5;
            ExpressionInspector sut = new ExpressionInspector();
            var actual = sut.Inspect(func);
            Assert.AreEqual("number => number == 5", actual);
        }
    }
}

using NUnit.Framework;
using System;
using System.Linq.Expressions;
using TestStack.FluentMVCTesting.Internal;

namespace TestStack.FluentMVCTesting.Tests.Internal
{
    [TestFixture]
    public class ExpressionInspectorShould
    {
        [Test]
        public void Correctly_parse_equality_comparison_with_string_operands()
        {
            Expression<Func<string, bool>> func = text => text == "any";
            ExpressionInspector sut = new ExpressionInspector();
            var actual = sut.Inspect(func);
            Assert.AreEqual("text => text == \"any\"", actual);
        }

        [Test]
        public void Correctly_parse_equality_comparison_with_int_operands()
        {
            Expression<Func<int, bool>> func = number => number == 5;
            ExpressionInspector sut = new ExpressionInspector();
            var actual = sut.Inspect(func);
            Assert.AreEqual("number => number == 5", actual);
        }

        [Test]
        public void Correctly_parse_inequality_comparison_with_int_operands()
        {
            Expression<Func<int, bool>> func = number => number != 5;
            ExpressionInspector sut = new ExpressionInspector();
            var actual = sut.Inspect(func);
            Assert.AreEqual("number => number != 5", actual);
        }
    }
}

Support for parsing inequality operator with integral operands.


using indice.Edi.Serialization;
using System;
using System.Collections.Generic;

namespace indice.Edi.Tests.Models
{

    public class Interchange_ORDRSP
    {
        public Message_ORDRSP Message { get; set; }
    }

    [EdiMessage]
    public class Message_ORDRSP
    {
        [EdiCondition("Z01", Path = "IMD/1/0")]
        [EdiCondition("Z10", Path = "IMD/1/0")]
        public List<IMD> IMD_List { get; set; }

        [EdiCondition("Z01", "Z10", CheckFor = EdiConditionCheckType.NotEqual, Path = "IMD/1/0")]
        public IMD IMD_Other { get; set; }

        /// <summary>
        /// Item Description
        /// </summary>
        [EdiSegment, EdiPath("IMD")]
        public class IMD
        {
            [EdiValue(Path = "IMD/0")]
            public string FieldA { get; set; }

            [EdiValue(Path = "IMD/1")]
            public string FieldB { get; set; }

            [EdiValue(Path = "IMD/2")]
            public string FieldC { get; set; }
        }
    }
}

using indice.Edi.Serialization;
using System;
using System.Collections.Generic;

namespace indice.Edi.Tests.Models
{

    public class Interchange_ORDRSP
    {
        public Message_ORDRSP Message { get; set; }
    }

    [EdiMessage]
    public class Message_ORDRSP
    {
        [EdiCondition("Z01", "Z10", Path = "IMD/1/0")]
        public List<IMD> IMD_List { get; set; }

        [EdiCondition("Z01", "Z10", CheckFor = EdiConditionCheckType.NotEqual, Path = "IMD/1/0")]
        public IMD IMD_Other { get; set; }

        /// <summary>
        /// Item Description
        /// </summary>
        [EdiSegment, EdiPath("IMD")]
        public class IMD
        {
            [EdiValue(Path = "IMD/0")]
            public string FieldA { get; set; }

            [EdiValue(Path = "IMD/1")]
            public string FieldB { get; set; }

            [EdiValue(Path = "IMD/2")]
            public string FieldC { get; set; }
        }
    }
}

Fix failing test ORDRSP after change on Condition stacking behavior


using System;
using System.Diagnostics;
using Serilog;
using Topshelf;

namespace Thinktecture.Relay.OnPremiseConnectorService
{
	internal static class Program
	{
		private static void Main(string[] args)
		{
			Log.Logger = new LoggerConfiguration()
				.ReadFrom.AppSettings()
				.CreateLogger();

			try
			{
				HostFactory.Run(config =>
				{
					config.UseSerilog();
					config.Service<OnPremisesService>(settings =>
					{
						settings.ConstructUsing(_ => new OnPremisesService());
						settings.WhenStarted(async s => await s.StartAsync().ConfigureAwait(false));
						settings.WhenStopped(s => s.Stop());
					});
					config.RunAsNetworkService();

					config.SetDescription("Thinktecture Relay OnPremises Service");
					config.SetDisplayName("Thinktecture Relay OnPremises Service");
					config.SetServiceName("TTRelayOnPremisesService");
				});
			}
			catch (Exception ex)
			{
				Log.Logger.Fatal(ex, "Service crashed");
			}
			finally
			{
				Log.CloseAndFlush();
			}

			Log.CloseAndFlush();

#if DEBUG
			if (Debugger.IsAttached)
			{
				// ReSharper disable once LocalizableElement
				Console.WriteLine("\nPress any key to close application window...");
				Console.ReadKey(true);
			}
#endif
		}
	}
}

using System;
using System.Diagnostics;
using Serilog;
using Topshelf;

namespace Thinktecture.Relay.OnPremiseConnectorService
{
	internal static class Program
	{
		private static void Main(string[] args)
		{
			Log.Logger = new LoggerConfiguration()
				.ReadFrom.AppSettings()
				.CreateLogger();

			try
			{
				HostFactory.Run(config =>
				{
					config.UseSerilog();
					config.EnableShutdown();
					config.Service<OnPremisesService>(settings =>
					{
						settings.ConstructUsing(_ => new OnPremisesService());
						settings.WhenStarted(async s => await s.StartAsync().ConfigureAwait(false));
						settings.WhenStopped(s => s.Stop());
						settings.WhenShutdown(s => s.Stop());
					});
					config.RunAsNetworkService();

					config.SetDescription("Thinktecture Relay OnPremises Service");
					config.SetDisplayName("Thinktecture Relay OnPremises Service");
					config.SetServiceName("TTRelayOnPremisesService");
				});
			}
			catch (Exception ex)
			{
				Log.Logger.Fatal(ex, "Service crashed");
			}
			finally
			{
				Log.CloseAndFlush();
			}

			Log.CloseAndFlush();

#if DEBUG
			if (Debugger.IsAttached)
			{
				// ReSharper disable once LocalizableElement
				Console.WriteLine("\nPress any key to close application window...");
				Console.ReadKey(true);
			}
#endif
		}
	}
}

Make sure that On-Premise Connector cleans up on Windows shutdown


namespace Suriyun.UnityIAP
{
    public class IAPNetworkMessageId
    {
        public const short ToServerBuyProductMsgId = 3000;
        public const short ToServerRequestProducts = 3001;
        public const short ToClientResponseProducts = 3002;
    }
}

using UnityEngine.Networking;

namespace Suriyun.UnityIAP
{
    public class IAPNetworkMessageId
    {
        // Developer can changes these Ids to avoid hacking while hosting
        public const short ToServerBuyProductMsgId = MsgType.Highest + 201;
        public const short ToServerRequestProducts = MsgType.Highest + 202;
        public const short ToClientResponseProducts = MsgType.Highest + 203;
    }
}

Set message id by official's highest

Set message id by official's highest


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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mania.Objects.Drawables;
using osu.Game.Rulesets.Mania.Objects.Drawables.Pieces;
using OpenTK.Graphics;

namespace osu.Game.Rulesets.Mania.Edit.Layers.Selection.Overlays
{
    public class HoldNoteMask : HitObjectMask
    {
        private readonly BodyPiece body;

        public HoldNoteMask(DrawableHoldNote hold)
            : base(hold)
        {
            Position = hold.Position;

            var holdObject = hold.HitObject;

            InternalChildren = new Drawable[]
            {
                new NoteMask(hold.Head),
                new NoteMask(hold.Tail),
                body = new BodyPiece
                {
                    AccentColour = Color4.Transparent
                },
            };

            holdObject.ColumnChanged += _ => Position = hold.Position;
        }

        [BackgroundDependencyLoader]
        private void load(OsuColour colours)
        {
            body.BorderColour = colours.Yellow;
        }
    }
}

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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mania.Objects.Drawables;
using osu.Game.Rulesets.Mania.Objects.Drawables.Pieces;
using OpenTK.Graphics;

namespace osu.Game.Rulesets.Mania.Edit.Layers.Selection.Overlays
{
    public class HoldNoteMask : HitObjectMask
    {
        private readonly BodyPiece body;

        public HoldNoteMask(DrawableHoldNote hold)
            : base(hold)
        {
            var holdObject = hold.HitObject;

            InternalChildren = new Drawable[]
            {
                new HoldNoteNoteMask(hold.Head),
                new HoldNoteNoteMask(hold.Tail),
                body = new BodyPiece
                {
                    AccentColour = Color4.Transparent
                },
            };

            holdObject.ColumnChanged += _ => Position = hold.Position;
        }

        [BackgroundDependencyLoader]
        private void load(OsuColour colours)
        {
            body.BorderColour = colours.Yellow;
        }

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

            Size = HitObject.DrawSize;
            Position = Parent.ToLocalSpace(HitObject.ScreenSpaceDrawQuad.TopLeft);
        }

        private class HoldNoteNoteMask : NoteMask
        {
            public HoldNoteNoteMask(DrawableNote note)
                : base(note)
            {
                Select();
            }

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

                Position = HitObject.DrawPosition;
            }
        }
    }
}

Fix hold note masks not working

Fix hold note masks not working


using RimWorld;
using Verse;

namespace PrepareLanding.Defs
{

    /// <summary>
    /// This class is called from a definition file when clicking the "World" button on the bottom menu bar while playing
    /// (see "PrepareLanding/Defs/Misc/MainButtonDefs/MainButtons.xml").
    /// </summary>
    public class MainButtonWorkerToggleWorld : MainButtonWorker_ToggleWorld
    {
        public override void Activate()
        {

            // default behavior
            base.Activate();

            // do not show the main window if in tutorial mode
            if (TutorSystem.TutorialMode)
            {
                Log.Message(
                    "[PrepareLanding] MainButtonWorkerToggleWorld: Tutorial mode detected: not showing main window.");
                return;
            }

            // show the main window, minimized.
            PrepareLanding.Instance.MainWindow.Show(true);
        }
    }
}

using RimWorld;
using Verse;

namespace PrepareLanding.Defs
{

    /// <summary>
    /// This class is called from a definition file when clicking the "World" button on the bottom menu bar while playing
    /// (see "PrepareLanding/Defs/Misc/MainButtonDefs/MainButtons.xml").
    /// </summary>
    public class MainButtonWorkerToggleWorld : MainButtonWorker_ToggleWorld
    {
        public override void Activate()
        {
            // default behavior (go to the world map)
            base.Activate();

            // do not show the main window if in tutorial mode
            if (TutorSystem.TutorialMode)
            {
                Log.Message(
                    "[PrepareLanding] MainButtonWorkerToggleWorld: Tutorial mode detected: not showing main window.");
                return;
            }

            // don't add a new window if the window is already there; if it's not create a new one.
            if (PrepareLanding.Instance.MainWindow == null)
                PrepareLanding.Instance.MainWindow = new MainWindow(PrepareLanding.Instance.GameData);

            // show the main window, minimized.
            PrepareLanding.Instance.MainWindow.Show(true);
        }
    }
}

Fix bug where window instance was null on world map.


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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Configuration;

namespace osu.Game.Overlays.Settings.Sections.Gameplay
{
    public class GeneralSettings : SettingsSubsection
    {
        protected override string Header => "General";

        [BackgroundDependencyLoader]
        private void load(OsuConfigManager config)
        {
            Children = new Drawable[]
            {
                new SettingsSlider<double>
                {
                    LabelText = "Background dim",
                    Bindable = config.GetBindable<double>(OsuSetting.DimLevel),
                    KeyboardStep = 0.1f
                },
                new SettingsSlider<double>
                {
                    LabelText = "Background blur",
                    Bindable = config.GetBindable<double>(OsuSetting.BlurLevel),
                    KeyboardStep = 0.1f
                },
                new SettingsCheckbox
                {
                    LabelText = "Show score overlay",
                    Bindable = config.GetBindable<bool>(OsuSetting.ShowInterface)
                },
                new SettingsCheckbox
                {
                    LabelText = "Always show key overlay",
                    Bindable = config.GetBindable<bool>(OsuSetting.KeyOverlay)
                },
                new SettingsCheckbox
                {
                    LabelText = "Show approach circle on first \"Hidden\" object",
                    Bindable = config.GetBindable<bool>(OsuSetting.IncreaseFirstObjectVisibility)
                },
            };
        }
    }
}

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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Configuration;

namespace osu.Game.Overlays.Settings.Sections.Gameplay
{
    public class GeneralSettings : SettingsSubsection
    {
        protected override string Header => "General";

        [BackgroundDependencyLoader]
        private void load(OsuConfigManager config)
        {
            Children = new Drawable[]
            {
                new SettingsSlider<double>
                {
                    LabelText = "Background dim",
                    Bindable = config.GetBindable<double>(OsuSetting.DimLevel),
                    KeyboardStep = 0.1f
                },
                new SettingsSlider<double>
                {
                    LabelText = "Background blur",
                    Bindable = config.GetBindable<double>(OsuSetting.BlurLevel),
                    KeyboardStep = 0.1f
                },
                new SettingsCheckbox
                {
                    LabelText = "Show score overlay",
                    Bindable = config.GetBindable<bool>(OsuSetting.ShowInterface)
                },
                new SettingsCheckbox
                {
                    LabelText = "Always show key overlay",
                    Bindable = config.GetBindable<bool>(OsuSetting.KeyOverlay)
                },
                new SettingsCheckbox
                {
                    LabelText = "Increase visibility of first object with \"Hidden\" mod",
                    Bindable = config.GetBindable<bool>(OsuSetting.IncreaseFirstObjectVisibility)
                },
            };
        }
    }
}

Reword settings text to be ruleset agnostic


using System.Collections.Generic;
using System.Linq;
using Mirage.Urbanization.ZoneStatisticsQuerying;
using System.Collections.Immutable;

namespace Mirage.Urbanization.Simulation.Persistence
{
    public class PersistedCityStatisticsCollection
    {
        private ImmutableQueue<PersistedCityStatisticsWithFinancialData> _persistedCityStatistics = ImmutableQueue<PersistedCityStatisticsWithFinancialData>.Empty;

        private PersistedCityStatisticsWithFinancialData _mostRecentStatistics;

        public void Add(PersistedCityStatisticsWithFinancialData statistics)
        {
            _persistedCityStatistics = _persistedCityStatistics.Enqueue(statistics);
            if (_persistedCityStatistics.Count() > 5200)
                _persistedCityStatistics = _persistedCityStatistics.Dequeue();

            _mostRecentStatistics = statistics;
        }

        public QueryResult<PersistedCityStatisticsWithFinancialData> GetMostRecentPersistedCityStatistics()
        {
            return QueryResult<PersistedCityStatisticsWithFinancialData>.Create(_mostRecentStatistics);
        }

        public IEnumerable<PersistedCityStatisticsWithFinancialData> GetAll()
        {
            return _persistedCityStatistics;
        }
    }
}

using System.Collections.Generic;
using System.Linq;
using Mirage.Urbanization.ZoneStatisticsQuerying;
using System.Collections.Immutable;

namespace Mirage.Urbanization.Simulation.Persistence
{
    public class PersistedCityStatisticsCollection
    {
        private ImmutableQueue<PersistedCityStatisticsWithFinancialData> _persistedCityStatistics = ImmutableQueue<PersistedCityStatisticsWithFinancialData>.Empty;

        private PersistedCityStatisticsWithFinancialData _mostRecentStatistics;

        public void Add(PersistedCityStatisticsWithFinancialData statistics)
        {
            _persistedCityStatistics = _persistedCityStatistics.Enqueue(statistics);
            if (_persistedCityStatistics.Count() > 960)
                _persistedCityStatistics = _persistedCityStatistics.Dequeue();

            _mostRecentStatistics = statistics;
        }

        public QueryResult<PersistedCityStatisticsWithFinancialData> GetMostRecentPersistedCityStatistics()
        {
            return QueryResult<PersistedCityStatisticsWithFinancialData>.Create(_mostRecentStatistics);
        }

        public IEnumerable<PersistedCityStatisticsWithFinancialData> GetAll()
        {
            return _persistedCityStatistics;
        }
    }
}

Reduce the amount of persisted city statistics


using FlaUI.Core.Definitions;
using FlaUI.Core.Patterns;

namespace FlaUI.Core.AutomationElements.PatternElements
{
    /// <summary>
    /// An element that supports the <see cref="IExpandCollapsePattern"/>.
    /// </summary>
    public class ExpandCollapseAutomationElement : AutomationElement
    {
        public ExpandCollapseAutomationElement(FrameworkAutomationElementBase frameworkAutomationElement) : base(frameworkAutomationElement)
        {
        }

        public IExpandCollapsePattern ExpandCollapsePattern => Patterns.ExpandCollapse.Pattern;

        /// <summary>
        /// Gets the current expand / collapse state.
        /// </summary>
        public ExpandCollapseState ExpandCollapseState => ExpandCollapsePattern.ExpandCollapseState;

        /// <summary>
        /// Expands the element.
        /// </summary>
        public void Expand()
        {
            ExpandCollapsePattern.Expand();
        }

        /// <summary>
        /// Collapses the element.
        /// </summary>
        public void Collapse()
        {
            ExpandCollapsePattern.Expand();
        }
    }
}

using FlaUI.Core.Definitions;
using FlaUI.Core.Patterns;

namespace FlaUI.Core.AutomationElements.PatternElements
{
    /// <summary>
    /// An element that supports the <see cref="IExpandCollapsePattern"/>.
    /// </summary>
    public class ExpandCollapseAutomationElement : AutomationElement
    {
        public ExpandCollapseAutomationElement(FrameworkAutomationElementBase frameworkAutomationElement) : base(frameworkAutomationElement)
        {
        }

        public IExpandCollapsePattern ExpandCollapsePattern => Patterns.ExpandCollapse.Pattern;

        /// <summary>
        /// Gets the current expand / collapse state.
        /// </summary>
        public ExpandCollapseState ExpandCollapseState => ExpandCollapsePattern.ExpandCollapseState;

        /// <summary>
        /// Expands the element.
        /// </summary>
        public void Expand()
        {
            ExpandCollapsePattern.Expand();
        }

        /// <summary>
        /// Collapses the element.
        /// </summary>
        public void Collapse()
        {
            ExpandCollapsePattern.Collapse();
        }
    }
}

Switch Collapse function to correctly call the Collapse function of the expand pattern


using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Core.Logging;
using DAL;
using Serilog.Events;
using Telegram.Bot;

namespace Core.Services.Crosspost
{
    public class TelegramCrosspostService : ICrossPostService
    {
        private readonly Core.Logging.ILogger _logger;
        private readonly string _token;
        private readonly string _name;

        public TelegramCrosspostService(string token, string name, ILogger logger)
        {
            _logger = logger;
            _token = token;
            _name = name;
        }

        public async Task Send(string message, Uri link, IReadOnlyCollection<string> tags)
        {
            var sb = new StringBuilder();

            sb.Append(message);
            sb.Append(Environment.NewLine);
            sb.Append(Environment.NewLine);
            sb.Append(link);
            sb.Append(Environment.NewLine);
            sb.Append(Environment.NewLine);
            sb.Append(string.Join(", ", tags));

            try
            {

                var bot = new TelegramBotClient(_token);

                await bot.SendTextMessageAsync(_name, sb.ToString());

                _logger.Write(LogEventLevel.Information, $"Message was sent to Telegram channel `{_name}`: `{sb}`");

            }
            catch (Exception ex)
            {
                _logger.Write(LogEventLevel.Error, $"Error during send message to Telegram: `{sb}`", ex);
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Core.Logging;
using DAL;
using Serilog.Events;
using Telegram.Bot;

namespace Core.Services.Crosspost
{
    public class TelegramCrosspostService : ICrossPostService
    {
        private readonly Core.Logging.ILogger _logger;
        private readonly string _token;
        private readonly string _name;

        public TelegramCrosspostService(string token, string name, ILogger logger)
        {
            _logger = logger;
            _token = token;
            _name = name;
        }

        public async Task Send(string message, Uri link, IReadOnlyCollection<string> tags)
        {
            var sb = new StringBuilder();

            sb.Append(message);
            sb.Append(Environment.NewLine);
            sb.Append(Environment.NewLine);
            sb.Append(link);
            sb.Append(Environment.NewLine);
            sb.Append(Environment.NewLine);
            sb.Append(string.Join(" ", tags));

            try
            {

                var bot = new TelegramBotClient(_token);

                await bot.SendTextMessageAsync(_name, sb.ToString());

                _logger.Write(LogEventLevel.Information, $"Message was sent to Telegram channel `{_name}`: `{sb}`");

            }
            catch (Exception ex)
            {
                _logger.Write(LogEventLevel.Error, $"Error during send message to Telegram: `{sb}`", ex);
            }
        }
    }
}

Fix tag line for Telegram

Fix tag line for Telegram


using System.IO;

namespace OmniSharp.DotNetTest.Helpers
{
    internal class ProjectPathResolver
    {
        public static string GetProjectPathFromFile(string filepath)
        {
            // TODO: revisit this logic, too clumsy
            var projectFolder = Path.GetDirectoryName(filepath);
            while (!File.Exists(Path.Combine(projectFolder, "project.json")))
            {
                var parent = Path.GetDirectoryName(filepath);
                if (parent == projectFolder)
                {
                    break;
                }
                else
                {
                    projectFolder = parent;
                }
            }

            return projectFolder;
        }
    }
}

using System.IO;

namespace OmniSharp.DotNetTest.Helpers
{
    internal class ProjectPathResolver
    {
        public static string GetProjectPathFromFile(string filepath)
        {
            // TODO: revisit this logic, too clumsy
            var projectFolder = Path.GetDirectoryName(filepath);
            while (!File.Exists(Path.Combine(projectFolder, "project.json")))
            {
                var parent = Path.GetDirectoryName(projectFolder);
                if (parent == projectFolder)
                {
                    break;
                }
                else
                {
                    projectFolder = parent;
                }
            }

            return projectFolder;
        }
    }
}

Fix incorrect project path resolver

Fix incorrect project path resolver


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

#nullable disable

using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu;

namespace osu.Game.Tests.Visual.Gameplay
{
    public abstract class SkinnableHUDComponentTestScene : SkinnableTestScene
    {
        protected override Ruleset CreateRulesetForSkinProvider() => new OsuRuleset();

        [SetUp]
        public void SetUp() => Schedule(() =>
        {
            SetContents(skin =>
            {
                var implementation = skin != null
                    ? CreateLegacyImplementation()
                    : CreateDefaultImplementation();

                implementation.Anchor = Anchor.Centre;
                implementation.Origin = Anchor.Centre;
                return implementation;
            });
        });

        protected abstract Drawable CreateDefaultImplementation();
        protected abstract Drawable CreateLegacyImplementation();
    }
}

// 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 NUnit.Framework;
using osu.Framework.Graphics;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu;
using osu.Game.Skinning;

namespace osu.Game.Tests.Visual.Gameplay
{
    public abstract class SkinnableHUDComponentTestScene : SkinnableTestScene
    {
        protected override Ruleset CreateRulesetForSkinProvider() => new OsuRuleset();

        [SetUp]
        public void SetUp() => Schedule(() =>
        {
            SetContents(skin =>
            {
                var implementation = skin is not TrianglesSkin
                    ? CreateLegacyImplementation()
                    : CreateDefaultImplementation();

                implementation.Anchor = Anchor.Centre;
                implementation.Origin = Anchor.Centre;
                return implementation;
            });
        });

        protected abstract Drawable CreateDefaultImplementation();
        protected abstract Drawable CreateLegacyImplementation();
    }
}

Fix test failure due to triangle skin no longer being null intests


using AutoMapper;
using Umbraco.Core.Models;
using Umbraco.Web.Composing;
using Umbraco.Web.Models.ContentEditing;
using Umbraco.Web.Routing;

namespace Umbraco.Web.Models.Mapping
{
    internal class RedirectUrlMapperProfile : Profile
    {

        public RedirectUrlMapperProfile(IUmbracoContextAccessor umbracoContextAccessor)
        {
            CreateMap<IRedirectUrl, ContentRedirectUrl>()
                .ForMember(x => x.OriginalUrl, expression => expression.MapFrom(item => Current.UmbracoContext.UrlProvider.GetUrlFromRoute(item.ContentId, item.Url, item.Culture)))
                .ForMember(x => x.DestinationUrl, expression => expression.MapFrom(item => item.ContentId > 0 ? GetUrl(umbracoContextAccessor, item) : "#"))
                .ForMember(x => x.RedirectId, expression => expression.MapFrom(item => item.Key));
        }

        private static string GetUrl(IUmbracoContextAccessor umbracoContextAccessor, IRedirectUrl item) => umbracoContextAccessor?.UmbracoContext?.UrlProvider?.GetUrl(item.ContentId, item.Culture);
    }
}

using AutoMapper;
using Umbraco.Core.Models;
using Umbraco.Web.Composing;
using Umbraco.Web.Models.ContentEditing;
using Umbraco.Web.Routing;

namespace Umbraco.Web.Models.Mapping
{
    internal class RedirectUrlMapperProfile : Profile
    {

        public RedirectUrlMapperProfile(IUmbracoContextAccessor umbracoContextAccessor)
        {
            CreateMap<IRedirectUrl, ContentRedirectUrl>()
                .ForMember(x => x.OriginalUrl, expression => expression.MapFrom(item => Current.UmbracoContext.UrlProvider.GetUrlFromRoute(item.ContentId, item.Url, item.Culture)))
                .ForMember(x => x.DestinationUrl, expression => expression.MapFrom(item => item.ContentId > 0 ? GetUrl(umbracoContextAccessor, item) : "#"))
                .ForMember(x => x.RedirectId, expression => expression.MapFrom(item => item.Key));
        }

        private static string GetUrl(IUmbracoContextAccessor umbracoContextAccessor, IRedirectUrl item) => umbracoContextAccessor?.UmbracoContext?.UrlProvider?.GetUrl(item.Id, item.Culture);
    }
}

Revert "the wrong id was used for getting the correct destination url."

This reverts commit 5d1fccb2c426349fae9523084949b6af60532581.


using CommandLine;
using CSharpLLVM.Compilation;
using System.IO;

namespace CSharpLLVM
{
    class Program
    {
        /// <summary>
        /// Entrypoint.
        /// </summary>
        /// <param name="args">Arguments.</param>
        static void Main(string[] args)
        {
            Options options = new Options();
            Parser parser = new Parser(setSettings);
            if (parser.ParseArguments(args, options))
            {
                string moduleName = Path.GetFileNameWithoutExtension(options.InputFile);
                Compiler compiler = new Compiler(options);
                compiler.Compile(moduleName);
            }
        }

        /// <summary>
        /// Sets the settings.
        /// </summary>
        /// <param name="settings">The settings.</param>
        private static void setSettings(ParserSettings settings)
        {
            settings.MutuallyExclusive = true;
        }
    }
}

using CommandLine;
using CSharpLLVM.Compilation;
using System;
using System.IO;

namespace CSharpLLVM
{
    class Program
    {
        /// <summary>
        /// Entrypoint.
        /// </summary>
        /// <param name="args">Arguments.</param>
        static void Main(string[] args)
        {
            Options options = new Options();
            Parser parser = new Parser(setSettings);
            if (parser.ParseArguments(args, options))
            {
                string moduleName = Path.GetFileNameWithoutExtension(options.InputFile);
                Compiler compiler = new Compiler(options);
                compiler.Compile(moduleName);
            }
            else
            {
                Console.WriteLine(options.GetUsage());
            }
        }

        /// <summary>
        /// Sets the settings.
        /// </summary>
        /// <param name="settings">The settings.</param>
        private static void setSettings(ParserSettings settings)
        {
            settings.MutuallyExclusive = true;
        }
    }
}

Print usage when parsing did not go right.


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

namespace Snowflake.Ajax
{
    public class JSResponse : IJSResponse
    {
        public IJSRequest Request { get; private set; }
        public dynamic Payload { get; private set; }
        public bool Success { get; set; }
        public JSResponse(IJSRequest request, dynamic payload, bool success = true)
        {
            this.Request = request;
            this.Payload = payload;
            this.Success = success;
        }

        public string GetJson()
        {
            return JSResponse.ProcessJSONP(this.Payload, this.Success, this.Request);
        }
        private static string ProcessJSONP(dynamic output, bool success, IJSRequest request)
        {
            if (request.MethodParameters.ContainsKey("jsoncallback"))
            {
                return request.MethodParameters["jsoncallback"] + "(" + JsonConvert.SerializeObject(new Dictionary<string, object>(){
                    {"payload", output},
                    {"success", success}
                }) + ");";
            }
            else
            {
                return JsonConvert.SerializeObject(new Dictionary<string, object>(){
                    {"payload", output},
                    {"success", success}
                });
            }
        }
    }
}

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

namespace Snowflake.Ajax
{
    public class JSResponse : IJSResponse
    {
        public IJSRequest Request { get; private set; }
        public dynamic Payload { get; private set; }
        public bool Success { get; set; }
        public JSResponse(IJSRequest request, dynamic payload, bool success = true)
        {
            this.Request = request;
            this.Payload = payload;
            this.Success = success;
        }

        public string GetJson()
        {
            return JSResponse.ProcessJSONP(this.Payload, this.Success, this.Request);
        }
        private static string ProcessJSONP(dynamic output, bool success, IJSRequest request)
        {
            if (request.MethodParameters.ContainsKey("jsoncallback"))
            {
                return request.MethodParameters["jsoncallback"] + "(" + JsonConvert.SerializeObject(new Dictionary<string, object>(){
                    {"request", request},
                    {"payload", output},
                    {"success", success},
                    {"type", "methodresponse"}
                }) + ");";
            }
            else
            {
                return JsonConvert.SerializeObject(new Dictionary<string, object>(){
                    {"request", request},
                    {"payload", output},
                    {"success", success},
                    {"type", "methodresponse"}
                });
            }
        }
    }
}

JSAPI: Add request and 'methodresponse' type in JSON body to account for other response types using the WebSocket APIs


using System.Web.Mvc;
using System.Net;
using Newtonsoft.Json;
using System.IO;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using System.Linq;
using System.Web.Caching;
using System;

namespace Website.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

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

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

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

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

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

        public ActionResult Donate()
        {
            var contributors = HttpContext.Cache.Get("github.contributors") as IEnumerable<Contributor>;

            if (contributors == null)
            {
                var url = "https://api.github.com/repos/andrewdavey/cassette/contributors";
                var client = new WebClient();
                var json = client.DownloadString(url);
                contributors = JsonConvert.DeserializeObject<IEnumerable<Contributor>>(json);

                HttpContext.Cache.Insert("github.contributors", contributors, null, Cache.NoAbsoluteExpiration, TimeSpan.FromDays(1));
            }

            ViewBag.Contributors = contributors;
            return View();
        }

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

    public class Contributor
    {
        public string avatar_url { get; set; }
        public string login { get; set; }
        public string url { get; set; }
    }
}

using System;
using System.Collections.Generic;
using System.Net;
using System.Web.Caching;
using System.Web.Mvc;
using Newtonsoft.Json;

namespace Website.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

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

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

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

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

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

        public ActionResult Donate()
        {
            var contributors = GetContributors();

            ViewBag.Contributors = contributors;
            return View();
        }

        IEnumerable<Contributor> GetContributors()
        {
            const string cacheKey = "github.contributors";

            var contributors = HttpContext.Cache.Get(cacheKey) as IEnumerable<Contributor>;
            if (contributors != null) return contributors;

            var json = DownoadContributorsJson();
            contributors = JsonConvert.DeserializeObject<IEnumerable<Contributor>>(json);

            HttpContext.Cache.Insert(
                cacheKey,
                contributors,
                null,
                Cache.NoAbsoluteExpiration,
                TimeSpan.FromDays(1)
            );

            return contributors;
        }

        static string DownoadContributorsJson()
        {
            using (var client = new WebClient())
            {
                return client.DownloadString("https://api.github.com/repos/andrewdavey/cassette/contributors");
            }
        }

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

    public class Contributor
    {
        public string avatar_url { get; set; }
        public string login { get; set; }
        public string url { get; set; }
    }
}

Tidy up github api calling code

Tidy up github api calling code


using System.Reflection;

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision

[assembly: AssemblyVersion("6.1.*")]
[assembly: AssemblyFileVersion("6.1.*")]

using System.Reflection;

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision

[assembly: AssemblyVersion("6.2.*")]
[assembly: AssemblyFileVersion("6.2.*")]

Change version number for breaking change.


// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Management.Compute.Models;
using Newtonsoft.Json;

namespace Microsoft.Azure.Commands.Compute.Models
{
    enum EncryptionStatus
    {
        Encrypted,
        NotEncrypted,
        NotMounted,
        EncryptionInProgress,
        VMRestartPending,
        Unknown
    }

    class AzureDiskEncryptionStatusContext
    {
        public EncryptionStatus OsVolumeEncrypted { get; set; }
        public DiskEncryptionSettings OsVolumeEncryptionSettings { get; set; }
        public EncryptionStatus DataVolumesEncrypted { get; set; }
        public string ProgressMessage { get; set; }
    }
}

// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Management.Compute.Models;
using Newtonsoft.Json;

namespace Microsoft.Azure.Commands.Compute.Models
{
    enum EncryptionStatus
    {
        Encrypted,
        NotEncrypted,
        NotMounted,
        DecryptionInProgress,
        EncryptionInProgress,
        VMRestartPending,
        Unknown
    }

    class AzureDiskEncryptionStatusContext
    {
        public EncryptionStatus OsVolumeEncrypted { get; set; }
        public DiskEncryptionSettings OsVolumeEncryptionSettings { get; set; }
        public EncryptionStatus DataVolumesEncrypted { get; set; }
        public string ProgressMessage { get; set; }
    }
}

Add DecryptionInProgress for EncryptionStatus enum


@using CkanDotNet.Api.Model
@using CkanDotNet.Web.Models
@using CkanDotNet.Web.Models.Helpers
@model Package

@{
    bool editable = Convert.ToBoolean(ViewData["editable"]);
    string ratingId = GuidHelper.GetUniqueKey(16);
}

@if (Model.RatingsAverage.HasValue || editable)
{

    @{
    int rating = 0;
    if (Model.RatingsAverage.HasValue)
    {
        rating = (int)Math.Round(Model.RatingsAverage.Value);
    }
    }
    @for (int i = 1; i <= 5; i++)
    {
        @Html.RadioButton("newrate", i, rating == i)
    }

}

@if (editable)
{

}

Add analytics event for package rate

Add analytics event for package rate

Record and event when a user submits a
package rating.


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

using System;
using EndlessClient.HUD;
using EOLib;
using Microsoft.Xna.Framework;
using XNAControls;

namespace EndlessClient.UIControls
{
    public class StatusBarLabel : XNALabel
    {
        private const int STATUS_LABEL_DISPLAY_TIME_MS = 3000;

        private readonly IStatusLabelTextProvider _statusLabelTextProvider;

        public StatusBarLabel(IClientWindowSizeProvider clientWindowSizeProvider,
                              IStatusLabelTextProvider statusLabelTextProvider)
            : base(GetPositionBasedOnWindowSize(clientWindowSizeProvider), Constants.FontSize07)
        {
            _statusLabelTextProvider = statusLabelTextProvider;
        }

        public override void Update(GameTime gameTime)
        {
            if (Text != _statusLabelTextProvider.StatusText)
            {
                Text = _statusLabelTextProvider.StatusText;
                Visible = true;
            }

            if ((DateTime.Now - _statusLabelTextProvider.SetTime).TotalMilliseconds > STATUS_LABEL_DISPLAY_TIME_MS)
                Visible = false;

            base.Update(gameTime);
        }

        private static Rectangle GetPositionBasedOnWindowSize(IClientWindowSizeProvider clientWindowSizeProvider)
        {
            return new Rectangle(97, clientWindowSizeProvider.Height - 25, 1, 1);
        }
    }
}

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

using System;
using EndlessClient.HUD;
using EOLib;
using Microsoft.Xna.Framework;
using XNAControls;

namespace EndlessClient.UIControls
{
    public class StatusBarLabel : XNALabel
    {
        private const int STATUS_LABEL_DISPLAY_TIME_MS = 3000;

        private readonly IStatusLabelTextProvider _statusLabelTextProvider;

        private readonly bool _constructed;

        public StatusBarLabel(IClientWindowSizeProvider clientWindowSizeProvider,
                              IStatusLabelTextProvider statusLabelTextProvider)
            : base(GetPositionBasedOnWindowSize(clientWindowSizeProvider), Constants.FontSize07)
        {
            _statusLabelTextProvider = statusLabelTextProvider;
            _constructed = true;
        }

        public override void Update(GameTime gameTime)
        {
            if (!_constructed)
                return;

            if (Text != _statusLabelTextProvider.StatusText)
            {
                Text = _statusLabelTextProvider.StatusText;
                Visible = true;
            }

            if ((DateTime.Now - _statusLabelTextProvider.SetTime).TotalMilliseconds > STATUS_LABEL_DISPLAY_TIME_MS)
                Visible = false;

            base.Update(gameTime);
        }

        private static Rectangle GetPositionBasedOnWindowSize(IClientWindowSizeProvider clientWindowSizeProvider)
        {
            return new Rectangle(97, clientWindowSizeProvider.Height - 25, 1, 1);
        }
    }
}

Check if status label is constructed before executing update

Fixes weird race condition where sometimes Update() will throw a NullReferenceException because the status bar label is still being constructed but has already been added to the game's components.


using System;
using System.ServiceModel.Channels;

namespace Microsoft.ApplicationInsights.Wcf.Implementation
{
    internal static class WcfExtensions
    {
        public static HttpRequestMessageProperty GetHttpRequestHeaders(this IOperationContext operation)
        {
            if ( operation.HasIncomingMessageProperty(HttpRequestMessageProperty.Name) )
            {
                return (HttpRequestMessageProperty)operation.GetIncomingMessageProperty(HttpRequestMessageProperty.Name);
            }
            return null;
        }
        public static HttpResponseMessageProperty GetHttpResponseHeaders(this IOperationContext operation)
        {
            if ( operation.HasOutgoingMessageProperty(HttpResponseMessageProperty.Name) )
            {
                return (HttpResponseMessageProperty)operation.GetOutgoingMessageProperty(HttpResponseMessageProperty.Name);
            }
            return null;
        }
    }
}

using System;
using System.ServiceModel.Channels;

namespace Microsoft.ApplicationInsights.Wcf.Implementation
{
    internal static class WcfExtensions
    {
        public static HttpRequestMessageProperty GetHttpRequestHeaders(this IOperationContext operation)
        {
            try
            {
                if ( operation.HasIncomingMessageProperty(HttpRequestMessageProperty.Name) )
                {
                    return (HttpRequestMessageProperty)operation.GetIncomingMessageProperty(HttpRequestMessageProperty.Name);
                }
            } catch ( ObjectDisposedException )
            {
                // WCF message is already disposed, just avoid it
            }
            return null;
        }
        public static HttpResponseMessageProperty GetHttpResponseHeaders(this IOperationContext operation)
        {
            try
            {
                if ( operation.HasOutgoingMessageProperty(HttpResponseMessageProperty.Name) )
                {
                    return (HttpResponseMessageProperty)operation.GetOutgoingMessageProperty(HttpResponseMessageProperty.Name);
                }
            } catch ( ObjectDisposedException )
            {
                // WCF message is already disposed, just avoid it
            }
            return null;
        }
    }
}

Handle ObjectDisposedException just in case we do end up trying to read properties of a closed message


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Arf.Services;
using Microsoft.ProjectOxford.Vision.Contract;

namespace Arf.Console
{
    class Program
    {
        public static bool IsProcessing;
        public static void Main(string[] args)
        {
            System.Console.ForegroundColor = ConsoleColor.Yellow;
            System.Console.WriteLine("Please write image Url or local path");

            while (true)
            {
                if (IsProcessing) continue;
                System.Console.ResetColor();
                var imgPath = System.Console.ReadLine();
                Run(imgPath);
                System.Console.ForegroundColor = ConsoleColor.DarkGray;
                System.Console.WriteLine("It takes a few time.Please wait!");
                System.Console.ResetColor();
            }
        }

        public static async void Run(string imgPath)
        {
            IsProcessing = true;
            var isUpload = imgPath != null && !imgPath.StartsWith("http");

            var service = new VisionService();
            var analysisResult = isUpload
                ? await service.UploadAndDescripteImage(imgPath)
                : await service.DescripteUrl(imgPath);

            System.Console.ForegroundColor = ConsoleColor.DarkGreen;
            System.Console.WriteLine(string.Join(" ", analysisResult.Description.Tags.Select(s => s = "#" + s)));
            System.Console.ResetColor();
            IsProcessing = false;
        }

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Arf.Services;
using Microsoft.ProjectOxford.Vision.Contract;

namespace Arf.Console
{
    class Program
    {
        public static bool IsProcessing;
        public static void Main(string[] args)
        {
            System.Console.ForegroundColor = ConsoleColor.Yellow;
            System.Console.WriteLine("Please write image Url or local path");

            while (true)
            {
                if (IsProcessing) continue;
                System.Console.ResetColor();
                var imgPath = System.Console.ReadLine();
                Run(imgPath);
                System.Console.ForegroundColor = ConsoleColor.DarkGray;
                System.Console.WriteLine("It takes a few time.Please wait!");
                System.Console.ResetColor();
            }
        }

        public static async void Run(string imgPath)
        {
            IsProcessing = true;
            var isUpload = imgPath != null && !imgPath.StartsWith("http");

            var service = new VisionService();
            var analysisResult = isUpload
                ? await service.UploadAndDescripteImage(imgPath)
                : await service.DescripteUrl(imgPath);

            System.Console.ForegroundColor = ConsoleColor.DarkGreen;
            System.Console.WriteLine(string.Join(" ", analysisResult.Description.Tags.Select(s => $"#{s}")));
            System.Console.ResetColor();
            IsProcessing = false;
        }

    }
}

Test console Run method updated

Test console Run method updated


using System;

namespace DarkMultiPlayerServer
{
    public class DarkLog
    {
        public static void Debug(string message)
        {
#if DEBUG
            float currentTime = Server.serverClock.ElapsedMilliseconds / 1000f;
            Console.WriteLine("[" + currentTime + "] Debug: " + message);
#endif
        }
        public static void Normal(string message)
        {
            float currentTime = Server.serverClock.ElapsedMilliseconds / 1000f;
            Console.WriteLine("[" + currentTime + "] Normal: " + message);
        }
    }
}

using System;

namespace DarkMultiPlayerServer
{
    public class DarkLog
    {
        public static void Debug(string message)
        {
            float currentTime = Server.serverClock.ElapsedMilliseconds / 1000f;
            Console.WriteLine("[" + currentTime + "] Debug: " + message);
        }
        public static void Normal(string message)
        {
            float currentTime = Server.serverClock.ElapsedMilliseconds / 1000f;
            Console.WriteLine("[" + currentTime + "] Normal: " + message);
        }
    }
}

Make debugging output show up on release builds


using static System.Console;
using CIV.Ccs;
using CIV.Interfaces;

namespace CIV
{
    class Program
    {
        static void Main(string[] args)
        {
  			var text = System.IO.File.ReadAllText(args[0]);

			var processes = CcsFacade.ParseAll(text);
            var trace = CcsFacade.RandomTrace(processes["Prison"], 450);
            foreach (var action in trace)
            {
                WriteLine(action);
            }
        }
    }
}

using static System.Console;
using CIV.Ccs;
using CIV.Hml;

namespace CIV
{
    class Program
    {
        static void Main(string[] args)
        {
  			var text = System.IO.File.ReadAllText(args[0]);

			var processes = CcsFacade.ParseAll(text);
			var hmlText = "[[ack]][[ack]][[ack]](<<ack>>tt and [[freeAll]]ff)";
			var prova = HmlFacade.ParseAll(hmlText);
			WriteLine(prova.Check(processes["Prison"]));

		}
    }
}

Remove RandomTrace stuff from Main

Remove RandomTrace stuff from Main


To: @Model.To
From: example@website.com
Reply-To: another@website.com
Subject: @Model.Subject

@* NOTE: There MUST be a blank like after the headers and before the content. *@
Hello,
This email was generated using Postal for asp.net mvc on @Model.Date.ToShortDateString()
Message follows:
@Model.Message

Thanks!

To: @Model.To
From: example@website.com
Reply-To: another@website.com
Subject: @Model.Subject

@* NOTE: There MUST be a blank line after the headers and before the content. *@
Hello,
This email was generated using Postal for asp.net mvc on @Model.Date.ToShortDateString()
Message follows:
@Model.Message

Thanks!

Fix typo in example comment.

Fix typo in example comment.


// Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

namespace MartinCostello.ProjectEuler.Puzzles
{
    using System;
    using System.Linq;

    /// <summary>
    /// A class representing the solution to <c>https://projecteuler.net/problem=10</c>. This class cannot be inherited.
    /// </summary>
    internal sealed class Puzzle010 : Puzzle
    {
        /// <inheritdoc />
        public override string Question => "Find the sum of all the primes below the specified value.";

        /// <inheritdoc />
        protected override int MinimumArguments => 1;

        /// <inheritdoc />
        protected override int SolveCore(string[] args)
        {
            int max;

            if (!TryParseInt32(args[0], out max) || max < 2)
            {
                Console.Error.WriteLine("The specified number is invalid.");
                return -1;
            }

            Answer = Enumerable.Range(2, max - 2)
                .Where((p) => Maths.IsPrime(p))
                .Select((p) => (long)p)
                .Sum();

            return 0;
        }
    }
}

// Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

namespace MartinCostello.ProjectEuler.Puzzles
{
    using System;

    /// <summary>
    /// A class representing the solution to <c>https://projecteuler.net/problem=10</c>. This class cannot be inherited.
    /// </summary>
    internal sealed class Puzzle010 : Puzzle
    {
        /// <inheritdoc />
        public override string Question => "Find the sum of all the primes below the specified value.";

        /// <inheritdoc />
        protected override int MinimumArguments => 1;

        /// <inheritdoc />
        protected override int SolveCore(string[] args)
        {
            int max;

            if (!TryParseInt32(args[0], out max) || max < 2)
            {
                Console.Error.WriteLine("The specified number is invalid.");
                return -1;
            }

            long sum = 0;

            for (int n = 2; n < max - 2; n++)
            {
                if (Maths.IsPrime(n))
                {
                    sum += n;
                }
            }

            Answer = sum;

            return 0;
        }
    }
}

Refactor puzzle 10 to not use LINQ

Refactor puzzle 10 to not use LINQ


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Data;

namespace TramlineFive.Common.Converters
{
    public class TimingConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            string[] timings = (string[])value;
            StringBuilder builder = new StringBuilder();
            foreach (string singleTiming in timings)
            {
                TimeSpan timing;
                if (TimeSpan.TryParse((string)singleTiming, out timing))
                {
                    TimeSpan timeLeft = timing - DateTime.Now.TimeOfDay;
                    builder.AppendFormat("{0} ({1} мин), ", singleTiming, timeLeft.Minutes);
                }
            }

            builder.Remove(builder.Length - 2, 2);
            return builder.ToString();
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            return String.Empty;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Data;

namespace TramlineFive.Common.Converters
{
    public class TimingConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            string[] timings = (string[])value;
            StringBuilder builder = new StringBuilder();
            foreach (string singleTiming in timings)
            {
                TimeSpan timing;
                if (TimeSpan.TryParse((string)singleTiming, out timing))
                {
                    TimeSpan timeLeft = timing - DateTime.Now.TimeOfDay;
                    builder.AppendFormat("{0} ({1} мин), ", singleTiming, timeLeft.Minutes < 0 ? 0 : timeLeft.Minutes);
                }
            }

            builder.Remove(builder.Length - 2, 2);
            return builder.ToString();
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            return String.Empty;
        }
    }
}

Fix some arrivals showing negative ETA minutes.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Metrics.Reporters.GoogleAnalytics.Tracker.Model.MeasurementProtocol;
using Metrics.Reporters.GoogleAnalytics.Tracker.Model.MeasurementProtocol.Values;

namespace Metrics.Reporters.GoogleAnalytics.Tracker.Model
{
    public abstract class Metric : ICanReportToGoogleAnalytics
    {
        public abstract string Name { get; }

        protected string TrackableName
        {
            get
            {
                return this.Name.Replace('[', '~').Replace(']', '~');
            }
        }

        public virtual ParameterTextValue HitType
        {
            get
            {
                return HitTypeValue.Event;
            }
        }

        public virtual IEnumerable<Parameter> Parameters
        {
            get
            {
                return new Parameter[] {
                    Parameter.Boolean(ParameterName.HitNonInteractive, ParameterBooleanValue.True),
                    Parameter.Text(ParameterName.EventLabel, new EventLabelValue(this.TrackableName))
                };
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Metrics.Reporters.GoogleAnalytics.Tracker.Model.MeasurementProtocol;
using Metrics.Reporters.GoogleAnalytics.Tracker.Model.MeasurementProtocol.Values;

namespace Metrics.Reporters.GoogleAnalytics.Tracker.Model
{
    public abstract class Metric : ICanReportToGoogleAnalytics
    {
        public abstract string Name { get; }

        public virtual ParameterTextValue HitType
        {
            get
            {
                return HitTypeValue.Event;
            }
        }

        public virtual IEnumerable<Parameter> Parameters
        {
            get
            {
                return new Parameter[] {
                    Parameter.Boolean(ParameterName.HitNonInteractive, ParameterBooleanValue.True),
                    Parameter.Text(ParameterName.EventLabel, new EventLabelValue(this.Name))
                };
            }
        }
    }
}

Revert "Try fix for tracking metrics with square brackets in name"

This reverts commit 9d62eeab95b733795473c1ecee24ce217166726e.


using System;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using SilentHunter.FileFormats.Dat.Controllers;
using SilentHunter.FileFormats.DependencyInjection;

namespace SilentHunter.Controllers.Compiler.DependencyInjection
{
	public static class ControllerConfigurerExtensions
	{
		public static SilentHunterParsersConfigurer CompileFrom(this ControllerConfigurer controllerConfigurer, string controllerPath, string assemblyName = null, Func<string, bool> ignorePaths = null, params string[] dependencySearchPaths)
		{
			AddCSharpCompiler(controllerConfigurer);

			return controllerConfigurer.FromAssembly(s =>
			{
				Assembly entryAssembly = Assembly.GetEntryAssembly();
				string applicationName = entryAssembly?.GetName().Name ?? "SilentHunter.Controllers";
				var assemblyCompiler = new ControllerAssemblyCompiler(s.GetRequiredService<ICSharpCompiler>(), applicationName, controllerPath)
				{
					AssemblyName = assemblyName,
					IgnorePaths = ignorePaths,
					DependencySearchPaths = dependencySearchPaths
				};
				return new ControllerAssembly(assemblyCompiler.Compile());
			});
		}

		private static void AddCSharpCompiler(IServiceCollectionProvider controllerConfigurer)
		{
			IServiceCollection services = controllerConfigurer.ServiceCollection;
#if NETFRAMEWORK
			services.TryAddTransient<ICSharpCompiler, CSharpCompiler>();
#else
			services.TryAddTransient<ICSharpCompiler, RoslynCompiler>();
#endif
		}
	}
}

using System;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using SilentHunter.FileFormats.Dat.Controllers;
using SilentHunter.FileFormats.DependencyInjection;

namespace SilentHunter.Controllers.Compiler.DependencyInjection
{
	public static class ControllerConfigurerExtensions
	{
		public static SilentHunterParsersConfigurer CompileFrom(this ControllerConfigurer controllerConfigurer, string controllerPath, string assemblyName = null, string applicationName = null, Func<string, bool> ignorePaths = null, params string[] dependencySearchPaths)
		{
			AddCSharpCompiler(controllerConfigurer);

			return controllerConfigurer.FromAssembly(s =>
			{
				Assembly entryAssembly = Assembly.GetEntryAssembly();
				string appName = applicationName ?? entryAssembly?.GetName().Name ?? "SilentHunter.Controllers";
				var assemblyCompiler = new ControllerAssemblyCompiler(s.GetRequiredService<ICSharpCompiler>(), appName, controllerPath)
				{
					AssemblyName = assemblyName,
					IgnorePaths = ignorePaths,
					DependencySearchPaths = dependencySearchPaths
				};
				return new ControllerAssembly(assemblyCompiler.Compile());
			});
		}

		private static void AddCSharpCompiler(IServiceCollectionProvider controllerConfigurer)
		{
			IServiceCollection services = controllerConfigurer.ServiceCollection;
#if NETFRAMEWORK
			services.TryAddTransient<ICSharpCompiler, CSharpCompiler>();
#else
			services.TryAddTransient<ICSharpCompiler, RoslynCompiler>();
#endif
		}
	}
}

Add option to set app name

Add option to set app name


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

namespace LSDStay
{
	public static class PSX
	{
		public static Process FindPSX()
		{
			Process psx = Process.GetProcessesByName("psxfin").FirstOrDefault();
			return psx;
		}

		public static IntPtr OpenPSX(Process psx)
		{
			int PID = psx.Id;
			IntPtr psxHandle = Memory.OpenProcess((uint)Memory.ProcessAccessFlags.All, false, PID);

		}

		public static void ClosePSX(IntPtr processHandle)
		{
			int result = Memory.CloseHandle(processHandle);
			if (result == 0)
			{
				Console.WriteLine("ERROR: Could not close psx handle");
			}
		}
	}
}

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

namespace LSDStay
{
	public static class PSX
	{
		public static Process PSXProcess;
		public static IntPtr PSXHandle;

		public static bool FindPSX()
		{
			PSXProcess = Process.GetProcessesByName("psxfin").FirstOrDefault();
			return (PSXProcess != null);
		}

		public static bool OpenPSX()
		{
			int PID = PSXProcess.Id;
			PSXHandle = Memory.OpenProcess((uint)Memory.ProcessAccessFlags.All, false, PID);
			return (PSXHandle != null);
		}

		public static void ClosePSX(IntPtr processHandle)
		{
			int result = Memory.CloseHandle(processHandle);
			if (result == 0)
			{
				Console.WriteLine("ERROR: Could not close psx handle");
			}
		}

		public static string Read(IntPtr address, ref byte[] buffer)
		{
			int bytesRead = 0;
			int absoluteAddress = Memory.PSXGameOffset + (int)address;
			//IntPtr absoluteAddressPtr = new IntPtr(absoluteAddress);

			Memory.ReadProcessMemory((int)PSXHandle, absoluteAddress, buffer, buffer.Length, ref bytesRead);

			return "Address " + address.ToString("x2") + " contains " + Memory.FormatToHexString(buffer);
		}

		public static string Write(IntPtr address, byte[] data)
		{
			int bytesWritten;
			int absoluteAddress = Memory.PSXGameOffset + (int)address;
			IntPtr absoluteAddressPtr = new IntPtr(absoluteAddress);

			Memory.WriteProcessMemory(PSXHandle, absoluteAddressPtr, data, (uint)data.Length, out bytesWritten);

			return "Address " + address.ToString("x2") + " is now " + Memory.FormatToHexString(data);
		}
	}
}

Add Read and Write methods

Add Read and Write methods


using Xunit;

namespace VulkanCore.Tests
{
    public class SizeTest
    {
        [Fact]
        public void ImplicitConversions()
        {
            const int intVal = 1;
            const long longVal = 2;

            Size intSize = intVal;
            Size longSize = longVal;

            Assert.Equal(intVal, intSize);
            Assert.Equal(longVal, longSize);
        }
    }
}

using Xunit;

namespace VulkanCore.Tests
{
    public class SizeTest
    {
        [Fact]
        public void ImplicitConversions()
        {
            const int intVal = 1;
            const long longVal = 2;

            Size intSize = intVal;
            Size longSize = longVal;

            Assert.Equal(intVal, (int)intSize);
            Assert.Equal(longVal, (long)longSize);
        }
    }
}

[Tests] Fix Size test using explicit conversions for assertions


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

namespace ArtificialNeuralNetwork
{
    [Serializable]
    public class Neuron : INeuron
    {
        private readonly ISoma _soma;
        private readonly IAxon _axon;

        public Neuron(ISoma soma, IAxon axon)
        {
            _soma = soma;
            _axon = axon;
        }

        public virtual double CalculateActivationFunction()
        {
            return 0.0;
        }

        public void Process()
        {
            _axon.ProcessSignal(_soma.CalculateSummation());
        }
    }
}

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

namespace ArtificialNeuralNetwork
{
    [Serializable]
    public class Neuron : INeuron
    {
        private readonly ISoma _soma;
        private readonly IAxon _axon;

        private Neuron(ISoma soma, IAxon axon)
        {
            _soma = soma;
            _axon = axon;
        }

        public static INeuron Create(ISoma soma, IAxon axon)
        {
            return new Neuron(soma, axon);
        }

        public void Process()
        {
            _axon.ProcessSignal(_soma.CalculateSummation());
        }
    }
}

Add static factory method for neuron

Add static factory method for neuron


namespace Discore
{
    public enum DiscordMessageType
    {
        Default = 0,
        RecipientAdd = 1,
        RecipientRemove = 2,
        Call = 3,
        ChannelNameChange = 4,
        ChannelIconChange = 5,
        ChannelPinnedMessage = 6,
        GuildMemberJoin = 7
    }
}

namespace Discore
{
    public enum DiscordMessageType
    {
        Default = 0,
        RecipientAdd = 1,
        RecipientRemove = 2,
        Call = 3,
        ChannelNameChange = 4,
        ChannelIconChange = 5,
        ChannelPinnedMessage = 6,
        GuildMemberJoin = 7,
        UserPremiumGuildSubscription = 8,
        UserPremiumGuildSubscriptionTier1 = 9,
        UserPremiumGuildSubscriptionTier2 = 10,
        UserPremiumGuildSubscriptionTier3 = 11,
        ChannelFollowAdd = 12
    }
}

Add message types for nitro boosting and channel following

#66


using NUnit.Framework;
using Rivet.Operations;

namespace Rivet.Test.Operations
{
	[TestFixture]
	public sealed class NewUserDefinedFunctionTestFixture
	{
		const string SchemaName = "schemaName";
		const string FunctionName = "functionName";
		const string Definition = "as definition";

		[SetUp]
		public void SetUp()
		{

		}

		[Test]
		public void ShouldSetPropertiesForNewStoredProcedure()
		{
			var op = new NewUserDefinedFunctionOperation(SchemaName, FunctionName, Definition);
			Assert.AreEqual(SchemaName, op.SchemaName);
			Assert.AreEqual(FunctionName, op.Name);
			Assert.AreEqual(Definition, op.Definition);
		}

		[Test]
		public void ShouldWriteQueryForNewStoredProcedure()
		{
			var op = new NewUserDefinedFunctionOperation(SchemaName, FunctionName, Definition);
			const string expectedQuery = "create function [schemaName].[functionName] as definition";
			Assert.AreEqual(expectedQuery, op.ToQuery());
		}

	}
}

using NUnit.Framework;
using Rivet.Operations;

namespace Rivet.Test.Operations
{
	[TestFixture]
	public sealed class NewUserDefinedFunctionTestFixture
	{
		const string SchemaName = "schemaName";
		const string FunctionName = "functionName";
		const string Definition = "as definition";

		[SetUp]
		public void SetUp()
		{

		}

		[Test]
		public void ShouldSetPropertiesForNewUserDefinedFunction()
		{
			var op = new NewUserDefinedFunctionOperation(SchemaName, FunctionName, Definition);
			Assert.AreEqual(SchemaName, op.SchemaName);
			Assert.AreEqual(FunctionName, op.Name);
			Assert.AreEqual(Definition, op.Definition);
		}

		[Test]
		public void ShouldWriteQueryForNewUserDefinedFunction()
		{
			var op = new NewUserDefinedFunctionOperation(SchemaName, FunctionName, Definition);
			const string expectedQuery = "create function [schemaName].[functionName] as definition";
			Assert.AreEqual(expectedQuery, op.ToQuery());
		}

	}
}

Rename function name in test fixture

Rename function name in test fixture


using System;
using System.Threading.Tasks;
using Grpc.Core;
using Hello;

namespace HelloServer
{
	class HelloServerImpl : HelloService.HelloServiceBase
	{
		public override Task<HelloResp> SayHello(HelloReq request, ServerCallContext context)
		{
			return Task.FromResult(new HelloResp { Result = "Hey " + request.Name });
		}

		public override Task<HelloResp> SayHelloStrict(HelloReq request, ServerCallContext context)
		{
			if (request.Name.Length >= 10) {
				const string msg = "Length of `Name` cannot be more than 10 characters";
				throw new RpcException(new Status(StatusCode.InvalidArgument, msg));
			}
			return Task.FromResult(new HelloResp { Result = "Hey " + request.Name });
		}
	}

	class Program
	{
		const int Port = 50051;

		public static void Main(string[] args)
		{

			Server server = new Server
			{
				Services = { HelloService.BindService(new HelloServerImpl()) },
				Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
			};

			server.Start();

			Console.WriteLine("Hello server listening on port " + Port);
			Console.WriteLine("Press any key to stop the server...");
			Console.ReadKey();

			server.ShutdownAsync().Wait();
		}
	}
}

using System;
using System.Threading.Tasks;
using Grpc.Core;
using Hello;

namespace HelloServer
{
	class HelloServerImpl : HelloService.HelloServiceBase
	{
		public override Task<HelloResp> SayHello(HelloReq request, ServerCallContext context)
		{
			return Task.FromResult(new HelloResp { Result = "Hey, " + request.Name + "!"});
		}

		public override Task<HelloResp> SayHelloStrict(HelloReq request, ServerCallContext context)
		{
			if (request.Name.Length >= 10) {
				const string msg = "Length of `Name` cannot be more than 10 characters";
				throw new RpcException(new Status(StatusCode.InvalidArgument, msg));
			}
			return Task.FromResult(new HelloResp { Result = "Hey, " + request.Name + "!"});
		}
	}

	class Program
	{
		const int Port = 50051;

		public static void Main(string[] args)
		{

			Server server = new Server
			{
				Services = { HelloService.BindService(new HelloServerImpl()) },
				Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
			};

			server.Start();

			Console.WriteLine("Hello server listening on port " + Port);
			Console.WriteLine("Press any key to stop the server...");
			Console.ReadKey();

			server.ShutdownAsync().Wait();
		}
	}
}

Update server to send proper response

Update server to send proper response


namespace Stripe
{
    using Newtonsoft.Json;
    using Stripe.Infrastructure;

    public class ChargePaymentMethodDetailsCardThreeDSecure : StripeEntity
    {
    }
}

namespace Stripe
{
    using Newtonsoft.Json;
    using Stripe.Infrastructure;

    public class ChargePaymentMethodDetailsCardThreeDSecure : StripeEntity
    {
        [JsonProperty("succeeded")]
        public bool Succeeded { get; set; }

        [JsonProperty("version")]
        public string Version { get; set; }
    }
}

Add basic fields in Charge's PMD 3DS field


using System.Text;
using AzureStorage.Blob;
using Common;

namespace CompetitionPlatform.Data.AzureRepositories.Settings
{
    public static class GeneralSettingsReader
    {
        public static T ReadGeneralSettings<T>(string connectionString, string container, string fileName)
        {
            var settingsStorage = new AzureBlobStorage(connectionString);
            var settingsData = settingsStorage.GetAsync(container, fileName).Result.ToBytes();
            var str = Encoding.UTF8.GetString(settingsData);

            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(str);
        }
    }
}

using System.Net.Http;
using System.Text;
using AzureStorage.Blob;
using Common;
using Newtonsoft.Json;

namespace CompetitionPlatform.Data.AzureRepositories.Settings
{
    public static class GeneralSettingsReader
    {
        public static T ReadGeneralSettings<T>(string connectionString, string container, string fileName)
        {
            var settingsStorage = new AzureBlobStorage(connectionString);
            var settingsData = settingsStorage.GetAsync(container, fileName).Result.ToBytes();
            var str = Encoding.UTF8.GetString(settingsData);

            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(str);
        }

        public static T ReadGeneralSettingsFromUrl<T>(string settingsUrl)
        {
            var httpClient = new HttpClient();
            var settingsString = httpClient.GetStringAsync(settingsUrl).Result;
            var serviceBusSettings = JsonConvert.DeserializeObject<T>(settingsString);
            return serviceBusSettings;
        }
    }
}

Add a method to get settings from a url.


// 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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Configuration;
using osu.Framework.Platform;

namespace osu.Framework.Tests.Visual.Platform
{
    [Ignore("This test does not cover correct GL context acquire/release when run headless.")]
    public class TestSceneExecutionModes : FrameworkTestScene
    {
        private Bindable<ExecutionMode> executionMode;

        [BackgroundDependencyLoader]
        private void load(FrameworkConfigManager configManager)
        {
            executionMode = configManager.GetBindable<ExecutionMode>(FrameworkSetting.ExecutionMode);
        }

        [Test]
        public void ToggleModeSmokeTest()
        {
            AddRepeatStep("toggle execution mode", () => executionMode.Value = executionMode.Value == ExecutionMode.MultiThreaded
                ? ExecutionMode.SingleThread
                : ExecutionMode.MultiThreaded, 2);
        }
    }
}

// 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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Configuration;
using osu.Framework.Platform;
using osu.Framework.Threading;

namespace osu.Framework.Tests.Visual.Platform
{
    [Ignore("This test does not cover correct GL context acquire/release when run headless.")]
    public class TestSceneExecutionModes : FrameworkTestScene
    {
        private Bindable<ExecutionMode> executionMode;

        [BackgroundDependencyLoader]
        private void load(FrameworkConfigManager configManager)
        {
            executionMode = configManager.GetBindable<ExecutionMode>(FrameworkSetting.ExecutionMode);
        }

        [Test]
        public void ToggleModeSmokeTest()
        {
            AddRepeatStep("toggle execution mode", () => executionMode.Value = executionMode.Value == ExecutionMode.MultiThreaded
                ? ExecutionMode.SingleThread
                : ExecutionMode.MultiThreaded, 2);
        }

        [Test]
        public void TestRapidSwitching()
        {
            ScheduledDelegate switchStep = null;
            int switchCount = 0;

            AddStep("install quick switch step", () =>
            {
                switchStep = Scheduler.AddDelayed(() =>
                {
                    executionMode.Value = executionMode.Value == ExecutionMode.MultiThreaded ? ExecutionMode.SingleThread : ExecutionMode.MultiThreaded;
                    switchCount++;
                }, 0, true);
            });

            AddUntilStep("switch count sufficiently high", () => switchCount > 1000);

            AddStep("remove", () => switchStep.Cancel());
        }
    }
}

Add test covering horrible fail scenario