#region Copyright & License Information
/*
 * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
 * This file is part of OpenRA, which is free software. It is made
 * available to you under the terms of the GNU General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version. For more
 * information, see COPYING.
 */
#endregion

using System;
using System.Collections.Generic;
using System.IO;
using OpenRA.FileSystem;
using OpenRA.Primitives;
using FS = OpenRA.FileSystem.FileSystem;

namespace OpenRA.Mods.Cnc.FileSystem
{
	public class BigLoader : IPackageLoader
	{
		sealed class BigFile : IReadOnlyPackage
		{
			public string Name { get; private set; }
			public IEnumerable<string> Contents { get { return index.Keys; } }

			readonly Dictionary<string, Entry> index = new Dictionary<string, Entry>();
			readonly Stream s;

			public BigFile(Stream s, string filename)
			{
				Name = filename;
				this.s = s;

				try
				{
					/* var signature = */ s.ReadASCII(4);

					// Total archive size.
					s.ReadUInt32();

					var entryCount = s.ReadUInt32();
					if (BitConverter.IsLittleEndian)
						entryCount = int2.Swap(entryCount);

					// First entry offset? This is apparently bogus for EA's .big files
					// and we don't have to try seeking there since the entries typically start next in EA's .big files.
					s.ReadUInt32();

					for (var i = 0; i < entryCount; i++)
					{
						var entry = new Entry(s);
						index.Add(entry.Path, entry);
					}
				}
				catch
				{
					Dispose();
					throw;
				}
			}

			class Entry
			{
				public readonly uint Offset;
				public readonly uint Size;
				public readonly string Path;

				public Entry(Stream s)
				{
					Offset = s.ReadUInt32();
					Size = s.ReadUInt32();
					if (BitConverter.IsLittleEndian)
					{
						Offset = int2.Swap(Offset);
						Size = int2.Swap(Size);
					}

					Path = s.ReadASCIIZ();
				}
			}

			public Stream GetStream(string filename)
			{
				var entry = index[filename];
				return SegmentStream.CreateWithoutOwningStream(s, entry.Offset, (int)entry.Size);
			}

			public bool Contains(string filename)
			{
				return index.ContainsKey(filename);
			}

			public IReadOnlyPackage OpenPackage(string filename, FS context)
			{
				// Not implemented
				return null;
			}

			public void Dispose()
			{
				s.Dispose();
			}
		}

		bool IPackageLoader.TryParsePackage(Stream s, string filename, FS context, out IReadOnlyPackage package)
		{
			// Take a peek at the file signature
			var signature = s.ReadASCII(4);
			s.Position -= 4;

			if (signature != "BIGF")
			{
				package = null;
				return false;
			}

			package = new BigFile(s, filename);
			return true;
		}
	}
}


#region Copyright & License Information
/*
 * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
 * This file is part of OpenRA, which is free software. It is made
 * available to you under the terms of the GNU General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version. For more
 * information, see COPYING.
 */
#endregion

using System;
using System.IO;
using OpenRA.Mods.Common.FileFormats;

namespace OpenRA.Mods.Common.AudioLoaders
{
	public class WavLoader : ISoundLoader
	{
		bool IsWave(Stream s)
		{
			var start = s.Position;
			var type = s.ReadASCII(4);
			s.Position += 4;
			var format = s.ReadASCII(4);
			s.Position = start;

			return type == "RIFF" && format == "WAVE";
		}

		bool ISoundLoader.TryParseSound(Stream stream, out ISoundFormat sound)
		{
			try
			{
				if (IsWave(stream))
				{
					sound = new WavFormat(stream);
					return true;
				}
			}
			catch
			{
				// Not a (supported) WAV
			}

			sound = null;
			return false;
		}
	}

	public sealed class WavFormat : ISoundFormat
	{
		public int Channels { get { return channels; } }
		public int SampleBits { get { return sampleBits; } }
		public int SampleRate { get { return sampleRate; } }
		public float LengthInSeconds { get { return WavReader.WaveLength(sourceStream); } }
		public Stream GetPCMInputStream() { return wavStreamFactory(); }
		public void Dispose() { sourceStream.Dispose(); }

		readonly Stream sourceStream;
		readonly Func<Stream> wavStreamFactory;
		readonly short channels;
		readonly int sampleBits;
		readonly int sampleRate;

		public WavFormat(Stream stream)
		{
			sourceStream = stream;

			if (!WavReader.LoadSound(stream, out wavStreamFactory, out channels, out sampleBits, out sampleRate))
				throw new InvalidDataException();
		}
	}
}


namespace BurningKnight.debug {
	public class TileCommand : ConsoleCommand {
		public TileCommand() {
			Name = "tile";
			ShortName = "t";
		}

		public override void Run(Console Console, string[] Args) {
			var level = state.Run.Level;

			if (level != null) {
				// level.Resize(level.Width, level.Height);
				level.RefreshSurfaces();
				level.TileUp(true);
			}
		}
	}
}


using BurningKnight.entity.component;
using Lens.util.timer;

namespace BurningKnight.entity.projectile.controller {
	public static class SlowdownProjectileController {
		public static ProjectileUpdateCallback Make(float speed = 1, float time = 1f, float vmin = 0.1f) {
			var stopped = false;

			return (p, dt) => {
				if (stopped) {
					return;
				}

				var b = p.GetAnyComponent<BodyComponent>();
				var v = b.Velocity;

				b.Velocity -= v * (speed * dt * 2);

				if (b.Velocity.Length() < vmin) {
					stopped = true;
					Timer.Add(() => { p.Break(); }, time);
				}
			};
		}
	}
}


using BurningKnight.entity.component;
using BurningKnight.entity.events;
using BurningKnight.level;
using BurningKnight.level.entities;
using BurningKnight.physics;
using BurningKnight.util;
using Lens.entity;
using Lens.graphics;
using Lens.util.camera;
using Lens.util.tween;
using Microsoft.Xna.Framework;
using MonoGame.Extended;
using MonoGame.Extended.Sprites;

namespace BurningKnight.entity.projectile {
	public class Missile : Projectile {
		private const float MinUpTime = 2f;

		private Entity target;
		private bool goingDown;
		private float toY;
		private float shadowSize;
		private bool exploded;
		public bool HurtOwner = true;

		public Missile(Entity owner, Entity tar) {
			target = tar;
			Owner = owner;
		}

		public override void AddComponents() {
			Slice = "missile";
			base.AddComponents();

			AlwaysVisible = true;
			AlwaysActive = true;

			var graphics = new ProjectileGraphicsComponent("projectiles", Slice);
			AddComponent(graphics);

			var w = graphics.Sprite.Source.Width;
			var h = graphics.Sprite.Source.Height;

			Width = w;
			Height = h;
			Center = Owner.Center;

			AddComponent(BodyComponent = new RectBodyComponent(0, 0, w, h));

			BodyComponent.Body.IsBullet = true;
			BodyComponent.Body.LinearVelocity = new Vector2(0, -100f);

			Owner.HandleEvent(new ProjectileCreatedEvent {
				Owner = Owner,
				Projectile = this
			});

			Depth = Layers.TileLights;

			CollisionFilterComponent.Add(this, (p, e) => {
				if (e is Level || e is Prop) {
					return CollisionResult.Disable;
				}

				return CollisionResult.Default;
			});
		}

		public override bool HandleEvent(Event e) {
			if (e is CollisionStartedEvent) {
				return false; // Ignore all collision
			}

			return base.HandleEvent(e);
		}

		public override void Update(float dt) {
			base.Update(dt);
			Position += BodyComponent.Velocity * dt;

			if (goingDown) {
				if (Bottom >= toY && !exploded) {
					AnimateDeath(null);
				}
			} else if (T >= MinUpTime && Bottom < Camera.Instance.Y) {
				goingDown = true;
				CenterX = target.CenterX;
				toY = target.Bottom;
				GraphicsComponent.FlippedVerticaly = true;
				BodyComponent.Body.LinearVelocity = new Vector2(0, 100f);

				Tween.To(16, 0, x => shadowSize = x, 1f);
			}
		}

		protected override void AnimateDeath(Entity e, bool timeout = false) {
			base.AnimateDeath(e, timeout);

			ExplosionMaker.Make(this, damageOwner: HurtOwner);
			exploded = true;
		}

		protected override void RenderShadow() {
			if (goingDown) {
				Graphics.Batch.DrawCircle(CenterX, toY, shadowSize, 16, ColorUtils.WhiteColor, 2f);
				Graphics.Batch.DrawCircle(CenterX, toY, shadowSize * 0.5f, 16, ColorUtils.WhiteColor, 2f);
			}
		}

		public override bool BreaksFrom(Entity entity, BodyComponent body) {
			return false;
		}

		public override bool ShouldCollide(Entity entity) {
			return false;
		}
	}
}


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

using System.Collections.Specialized;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Caching;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Lines;
using osu.Framework.Platform;
using osu.Game.Graphics;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Models;
using osu.Game.Tournament.Screens.Editors;
using osu.Game.Tournament.Screens.Ladder.Components;
using osuTK.Graphics;

namespace osu.Game.Tournament.Screens.Ladder
{
    public class LadderScreen : TournamentScreen, IProvideVideo
    {
        protected Container<DrawableTournamentMatch> MatchesContainer;
        private Container<Path> paths;
        private Container headings;

        protected LadderDragContainer ScrollContent;

        protected Container Content;

        [BackgroundDependencyLoader]
        private void load(OsuColour colours, Storage storage)
        {
            normalPathColour = Color4Extensions.FromHex("#66D1FF");
            losersPathColour = Color4Extensions.FromHex("#FFC700");

            RelativeSizeAxes = Axes.Both;

            InternalChild = Content = new Container
            {
                RelativeSizeAxes = Axes.Both,
                Children = new Drawable[]
                {
                    new TourneyVideo("ladder")
                    {
                        RelativeSizeAxes = Axes.Both,
                        Loop = true,
                    },
                    new DrawableTournamentHeaderText
                    {
                        Y = 100,
                        Anchor = Anchor.TopCentre,
                        Origin = Anchor.TopCentre,
                    },
                    ScrollContent = new LadderDragContainer
                    {
                        RelativeSizeAxes = Axes.Both,
                        Children = new Drawable[]
                        {
                            paths = new Container<Path> { RelativeSizeAxes = Axes.Both },
                            headings = new Container { RelativeSizeAxes = Axes.Both },
                            MatchesContainer = new Container<DrawableTournamentMatch> { RelativeSizeAxes = Axes.Both },
                        }
                    },
                }
            };

            void addMatch(TournamentMatch match) =>
                MatchesContainer.Add(new DrawableTournamentMatch(match, this is LadderEditorScreen)
                {
                    Changed = () => layout.Invalidate()
                });

            foreach (var match in LadderInfo.Matches)
                addMatch(match);

            LadderInfo.Rounds.CollectionChanged += (_, __) => layout.Invalidate();
            LadderInfo.Matches.CollectionChanged += (_, args) =>
            {
                switch (args.Action)
                {
                    case NotifyCollectionChangedAction.Add:
                        foreach (var p in args.NewItems.Cast<TournamentMatch>())
                            addMatch(p);
                        break;

                    case NotifyCollectionChangedAction.Remove:
                        foreach (var p in args.OldItems.Cast<TournamentMatch>())
                        {
                            foreach (var d in MatchesContainer.Where(d => d.Match == p))
                                d.Expire();
                        }

                        break;
                }

                layout.Invalidate();
            };
        }

        private readonly Cached layout = new Cached();

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

            if (!layout.IsValid)
                UpdateLayout();
        }

        private Color4 normalPathColour;
        private Color4 losersPathColour;

        protected virtual bool DrawLoserPaths => false;

        protected virtual void UpdateLayout()
        {
            paths.Clear();
            headings.Clear();

            int id = 1;

            foreach (var match in MatchesContainer.OrderBy(d => d.Y).ThenBy(d => d.X))
            {
                match.Match.ID = id++;

                if (match.Match.Progression.Value != null)
                {
                    var dest = MatchesContainer.FirstOrDefault(p => p.Match == match.Match.Progression.Value);

                    if (dest == null)
                        // clean up outdated progressions.
                        match.Match.Progression.Value = null;
                    else
                        paths.Add(new ProgressionPath(match, dest) { Colour = match.Match.Losers.Value ? losersPathColour : normalPathColour });
                }

                if (DrawLoserPaths)
                {
                    if (match.Match.LosersProgression.Value != null)
                    {
                        var dest = MatchesContainer.FirstOrDefault(p => p.Match == match.Match.LosersProgression.Value);

                        if (dest == null)
                            // clean up outdated progressions.
                            match.Match.LosersProgression.Value = null;
                        else
                            paths.Add(new ProgressionPath(match, dest) { Colour = losersPathColour.Opacity(0.1f) });
                    }
                }
            }

            foreach (var round in LadderInfo.Rounds)
            {
                var topMatch = MatchesContainer.Where(p => !p.Match.Losers.Value && p.Match.Round.Value == round).OrderBy(p => p.Y).FirstOrDefault();

                if (topMatch == null) continue;

                headings.Add(new DrawableTournamentRound(round)
                {
                    Position = headings.ToLocalSpace((topMatch.ScreenSpaceDrawQuad.TopLeft + topMatch.ScreenSpaceDrawQuad.TopRight) / 2),
                    Margin = new MarginPadding { Bottom = 10 },
                    Origin = Anchor.BottomCentre,
                });
            }

            foreach (var round in LadderInfo.Rounds)
            {
                var topMatch = MatchesContainer.Where(p => p.Match.Losers.Value && p.Match.Round.Value == round).OrderBy(p => p.Y).FirstOrDefault();

                if (topMatch == null) continue;

                headings.Add(new DrawableTournamentRound(round, true)
                {
                    Position = headings.ToLocalSpace((topMatch.ScreenSpaceDrawQuad.TopLeft + topMatch.ScreenSpaceDrawQuad.TopRight) / 2),
                    Margin = new MarginPadding { Bottom = 10 },
                    Origin = Anchor.BottomCentre,
                });
            }

            layout.Validate();
        }
    }
}


#region Copyright & License Information
/*
 * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
 * This file is part of OpenRA, which is free software. It is made
 * available to you under the terms of the GNU General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version. For more
 * information, see COPYING.
 */
#endregion

using System;
using OpenRA.Primitives;

namespace OpenRA.Platforms.Default
{
	static class MultiTapDetection
	{
		static Cache<(Keycode Key, Modifiers Mods), TapHistory> keyHistoryCache =
			new Cache<(Keycode, Modifiers), TapHistory>(_ => new TapHistory(DateTime.Now - TimeSpan.FromSeconds(1)));
		static Cache<byte, TapHistory> clickHistoryCache =
			new Cache<byte, TapHistory>(_ => new TapHistory(DateTime.Now - TimeSpan.FromSeconds(1)));

		public static int DetectFromMouse(byte button, int2 xy)
		{
			return clickHistoryCache[button].GetTapCount(xy);
		}

		public static int InfoFromMouse(byte button)
		{
			return clickHistoryCache[button].LastTapCount();
		}

		public static int DetectFromKeyboard(Keycode key, Modifiers mods)
		{
			return keyHistoryCache[(key, mods)].GetTapCount(int2.Zero);
		}

		public static int InfoFromKeyboard(Keycode key, Modifiers mods)
		{
			return keyHistoryCache[(key, mods)].LastTapCount();
		}
	}

	class TapHistory
	{
		public (DateTime Time, int2 Location) FirstRelease, SecondRelease, ThirdRelease;

		public TapHistory(DateTime now)
		{
			FirstRelease = SecondRelease = ThirdRelease = (now, int2.Zero);
		}

		static bool CloseEnough((DateTime Time, int2 Location) a, (DateTime Time, int2 Location) b)
		{
			return a.Time - b.Time < TimeSpan.FromMilliseconds(250)
				&& (a.Location - b.Location).Length < 4;
		}

		public int GetTapCount(int2 xy)
		{
			FirstRelease = SecondRelease;
			SecondRelease = ThirdRelease;
			ThirdRelease = (DateTime.Now, xy);

			if (!CloseEnough(ThirdRelease, SecondRelease))
				return 1;
			if (!CloseEnough(SecondRelease, FirstRelease))
				return 2;

			return 3;
		}

		public int LastTapCount()
		{
			if (!CloseEnough(ThirdRelease, SecondRelease))
				return 1;
			if (!CloseEnough(SecondRelease, FirstRelease))
				return 2;

			return 3;
		}
	}
}


using System;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Compiler;

namespace Aseprite {
	[ContentTypeWriter]
	public class AudioWriter : ContentTypeWriter<AudioFile> {
		public override string GetRuntimeType(TargetPlatform targetPlatform) {
			Type type = typeof(AsepriteReader);
			return type.Namespace + ".AudioReader, " + type.AssemblyQualifiedName;
		}

		public override string GetRuntimeReader(TargetPlatform targetPlatform) {
			Type type = typeof(AsepriteReader);
			return type.Namespace + ".AudioReader, " + type.Assembly.FullName;
		}

		protected override void Write(ContentWriter output, AudioFile value) {
			output.Write(value.Stereo);
			output.Write(value.SampleRate);
			output.Write(value.Buffer.Length);

			for (var i = 0; i < value.Buffer.Length; i++) {
				output.Write(value.Buffer[i]);
			}
		}
	}
}


#region Copyright & License Information
/*
 * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
 * This file is part of OpenRA, which is free software. It is made
 * available to you under the terms of the GNU General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version. For more
 * information, see COPYING.
 */
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using OpenRA.Primitives;
using OpenRA.Widgets;

namespace OpenRA.Mods.Common.Lint
{
	[AttributeUsage(AttributeTargets.Class)]
	public sealed class ChromeLogicArgsHotkeys : Attribute
	{
		public string[] LogicArgKeys;
		public ChromeLogicArgsHotkeys(params string[] logicArgKeys)
		{
			LogicArgKeys = logicArgKeys;
		}
	}

	[AttributeUsage(AttributeTargets.Method)]
	public sealed class CustomLintableHotkeyNames : Attribute { }

	class CheckChromeHotkeys : ILintPass
	{
		public void Run(Action<string> emitError, Action<string> emitWarning, ModData modData)
		{
			// Build the list of valid hotkey names
			var namedKeys = modData.Hotkeys.Definitions.Select(d => d.Name).ToArray();

			// Build the list of widget keys to validate
			var checkWidgetFields = modData.ObjectCreator.GetTypesImplementing<Widget>()
				.SelectMany(w => w.GetFields()
					.Where(f => f.FieldType == typeof(HotkeyReference))
					.Select(f => (w.Name.Substring(0, w.Name.Length - 6), f.Name)))
				.ToArray();

			var customLintMethods = new Dictionary<string, List<string>>();

			foreach (var w in modData.ObjectCreator.GetTypesImplementing<Widget>())
			{
				foreach (var m in w.GetMethods().Where(m => m.HasAttribute<CustomLintableHotkeyNames>()))
				{
					var p = m.GetParameters();
					if (p.Length == 3 && p[0].ParameterType == typeof(MiniYamlNode) && p[1].ParameterType == typeof(Action<string>)
							&& p[2].ParameterType == typeof(Action<string>))
						customLintMethods.GetOrAdd(w.Name.Substring(0, w.Name.Length - 6)).Add(m.Name);
				}
			}

			foreach (var filename in modData.Manifest.ChromeLayout)
			{
				var yaml = MiniYaml.FromStream(modData.DefaultFileSystem.Open(filename), filename);
				CheckInner(modData, namedKeys, checkWidgetFields, customLintMethods, yaml, filename, null, emitError, emitWarning);
			}
		}

		void CheckInner(ModData modData, string[] namedKeys, (string Widget, string Field)[] checkWidgetFields, Dictionary<string, List<string>> customLintMethods,
			List<MiniYamlNode> nodes, string filename, MiniYamlNode parent, Action<string> emitError, Action<string> emitWarning)
		{
			foreach (var node in nodes)
			{
				if (node.Value == null)
					continue;

				foreach (var x in checkWidgetFields)
				{
					if (node.Key == x.Field && parent != null && parent.Key.StartsWith(x.Widget, StringComparison.Ordinal))
					{
						// Keys are valid if they refer to a named key or can be parsed as a regular Hotkey.
						if (!namedKeys.Contains(node.Value.Value) && !Hotkey.TryParse(node.Value.Value, out var unused))
							emitError("{0} refers to a Key named `{1}` that does not exist".F(node.Location, node.Value.Value));
					}
				}

				// Check runtime-defined hotkey names
				var widgetType = node.Key.Split('@')[0];
				if (customLintMethods.TryGetValue(widgetType, out var checkMethods))
				{
					var type = modData.ObjectCreator.FindType(widgetType + "Widget");
					var keyNames = checkMethods.SelectMany(m => (IEnumerable<string>)type.GetMethod(m).Invoke(null, new object[] { node, emitError, emitWarning }));

					foreach (var name in keyNames)
						if (!namedKeys.Contains(name) && !Hotkey.TryParse(name, out var unused))
							emitError("{0} refers to a Key named `{1}` that does not exist".F(node.Location, name));
				}

				// Logic classes can declare the data key names that specify hotkeys
				if (node.Key == "Logic" && node.Value.Nodes.Any())
				{
					var typeNames = FieldLoader.GetValue<string[]>(node.Key, node.Value.Value);
					var checkArgKeys = new List<string>();
					foreach (var typeName in typeNames)
					{
						var type = Game.ModData.ObjectCreator.FindType(typeName);
						if (type == null)
							continue;

						checkArgKeys.AddRange(type.GetCustomAttributes<ChromeLogicArgsHotkeys>(true).SelectMany(x => x.LogicArgKeys));
					}

					foreach (var n in node.Value.Nodes)
						if (checkArgKeys.Contains(n.Key))
							if (!namedKeys.Contains(n.Value.Value) && !Hotkey.TryParse(n.Value.Value, out var unused))
								emitError("{0} {1}:{2} refers to a Key named `{3}` that does not exist".F(filename, node.Value.Value, n.Key, n.Value.Value));
				}

				if (node.Value.Nodes != null)
					CheckInner(modData, namedKeys, checkWidgetFields, customLintMethods, node.Value.Nodes, filename, node, emitError, emitWarning);
			}
		}
	}
}


#region Copyright & License Information
/*
 * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
 * This file is part of OpenRA, which is free software. It is made
 * available to you under the terms of the GNU General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version. For more
 * information, see COPYING.
 */
#endregion

using System.Collections.Generic;
using System.Linq;
using Eluant;
using OpenRA.Mods.Common.Traits;
using OpenRA.Primitives;
using OpenRA.Scripting;

namespace OpenRA.Mods.Common.Scripting
{
	[ScriptPropertyGroup("Player")]
	public class PlayerProperties : ScriptPlayerProperties
	{
		public PlayerProperties(ScriptContext context, Player player)
			: base(context, player) { }

		[Desc("The player's internal name.")]
		public string InternalName { get { return Player.InternalName; } }

		[Desc("The player's name.")]
		public string Name { get { return Player.PlayerName; } }

		[Desc("The player's color.")]
		public Color Color { get { return Player.Color; } }

		[Desc("The player's faction.")]
		public string Faction { get { return Player.Faction.InternalName; } }

		[Desc("The player's spawnpoint ID.")]
		public int Spawn { get { return Player.SpawnPoint; } }

		[Desc("The player's home/starting location.")]
		public CPos HomeLocation { get { return Player.HomeLocation; } }

		[Desc("The player's team ID.")]
		public int Team
		{
			get
			{
				var c = Player.World.LobbyInfo.Clients.FirstOrDefault(i => i.Index == Player.ClientIndex);
				return c?.Team ?? 0;
			}
		}

		[Desc("Returns true if the player is a bot.")]
		public bool IsBot { get { return Player.IsBot; } }

		[Desc("Returns true if the player is non combatant.")]
		public bool IsNonCombatant { get { return Player.NonCombatant; } }

		[Desc("Returns true if the player is the local player.")]
		public bool IsLocalPlayer { get { return Player == (Player.World.RenderPlayer ?? Player.World.LocalPlayer); } }

		[Desc("Returns all living actors staying inside the world for this player.")]
		public Actor[] GetActors()
		{
			return Player.World.Actors.Where(actor => actor.Owner == Player && !actor.IsDead && actor.IsInWorld).ToArray();
		}

		[Desc("Returns an array of actors representing all ground attack units of this player.")]
		public Actor[] GetGroundAttackers()
		{
			return Player.World.ActorsHavingTrait<AttackBase>()
				.Where(a => a.Owner == Player && !a.IsDead && a.IsInWorld && a.Info.HasTraitInfo<MobileInfo>())
				.ToArray();
		}

		[Desc("Returns all living actors of the specified type of this player.")]
		public Actor[] GetActorsByType(string type)
		{
			var result = new List<Actor>();

			if (!Context.World.Map.Rules.Actors.TryGetValue(type, out var ai))
				throw new LuaException("Unknown actor type '{0}'".F(type));

			result.AddRange(Player.World.Actors
				.Where(actor => actor.Owner == Player && !actor.IsDead && actor.IsInWorld && actor.Info.Name == ai.Name));

			return result.ToArray();
		}

		[Desc("Returns all living actors of the specified types of this player.")]
		public Actor[] GetActorsByTypes(string[] types)
		{
			var result = new List<Actor>();

			foreach (var type in types)
				if (!Context.World.Map.Rules.Actors.ContainsKey(type))
					throw new LuaException("Unknown actor type '{0}'".F(type));

			result.AddRange(Player.World.Actors
				.Where(actor => actor.Owner == Player && !actor.IsDead && actor.IsInWorld && types.Contains(actor.Info.Name)));

			return result.ToArray();
		}

		[Desc("Check if the player has these prerequisites available.")]
		public bool HasPrerequisites(string[] type)
		{
			var tt = Player.PlayerActor.TraitOrDefault<TechTree>();
			if (tt == null)
				throw new LuaException("Missing TechTree trait on player {0}!".F(Player));

			return tt.HasPrerequisites(type);
		}
	}
}


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

using osuTK;
using osuTK.Graphics;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Rulesets.Taiko.Objects;

namespace osu.Game.Rulesets.Taiko.UI
{
    /// <summary>
    /// A component that is displayed at the hit position in the taiko playfield.
    /// </summary>
    internal class TaikoHitTarget : Container
    {
        /// <summary>
        /// Thickness of all drawn line pieces.
        /// </summary>
        private const float border_thickness = 2.5f;

        public TaikoHitTarget()
        {
            RelativeSizeAxes = Axes.Both;

            Children = new Drawable[]
            {
                new Box
                {
                    Name = "Bar Upper",
                    Anchor = Anchor.TopCentre,
                    Origin = Anchor.TopCentre,
                    RelativeSizeAxes = Axes.Y,
                    Size = new Vector2(border_thickness, (1 - TaikoStrongableHitObject.DEFAULT_STRONG_SIZE) / 2f),
                    Alpha = 0.1f
                },
                new CircularContainer
                {
                    Name = "Strong Hit Ring",
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                    RelativeSizeAxes = Axes.Both,
                    Size = new Vector2(TaikoStrongableHitObject.DEFAULT_STRONG_SIZE),
                    Masking = true,
                    BorderColour = Color4.White,
                    BorderThickness = border_thickness,
                    Alpha = 0.1f,
                    Children = new[]
                    {
                        new Box
                        {
                            RelativeSizeAxes = Axes.Both,
                            Alpha = 0,
                            AlwaysPresent = true
                        }
                    }
                },
                new CircularContainer
                {
                    Name = "Normal Hit Ring",
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                    RelativeSizeAxes = Axes.Both,
                    Size = new Vector2(TaikoHitObject.DEFAULT_SIZE),
                    Masking = true,
                    BorderColour = Color4.White,
                    BorderThickness = border_thickness,
                    Alpha = 0.5f,
                    Children = new[]
                    {
                        new Box
                        {
                            RelativeSizeAxes = Axes.Both,
                            Alpha = 0,
                            AlwaysPresent = true
                        }
                    }
                },
                new Box
                {
                    Name = "Bar Lower",
                    Anchor = Anchor.BottomCentre,
                    Origin = Anchor.BottomCentre,
                    RelativeSizeAxes = Axes.Y,
                    Size = new Vector2(border_thickness, (1 - TaikoStrongableHitObject.DEFAULT_STRONG_SIZE) / 2f),
                    Alpha = 0.1f
                },
            };
        }
    }
}


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

using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects;
using osuTK;

namespace osu.Game.Rulesets.Osu.Skinning.Default
{
    public class CirclePiece : CompositeDrawable
    {
        [Resolved]
        private DrawableHitObject drawableObject { get; set; }

        private TrianglesPiece triangles;

        public CirclePiece()
        {
            Size = new Vector2(OsuHitObject.OBJECT_RADIUS * 2);
            Masking = true;

            CornerRadius = Size.X / 2;
            CornerExponent = 2;

            Anchor = Anchor.Centre;
            Origin = Anchor.Centre;
        }

        [BackgroundDependencyLoader]
        private void load(TextureStore textures)
        {
            InternalChildren = new Drawable[]
            {
                new Sprite
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                    Texture = textures.Get(@"Gameplay/osu/disc"),
                },
                triangles = new TrianglesPiece
                {
                    RelativeSizeAxes = Axes.Both,
                    Blending = BlendingParameters.Additive,
                    Alpha = 0.5f,
                }
            };

            drawableObject.HitObjectApplied += onHitObjectApplied;
            onHitObjectApplied(drawableObject);
        }

        private void onHitObjectApplied(DrawableHitObject obj)
        {
            if (obj.HitObject == null)
                return;

            triangles.Reset((int)obj.HitObject.StartTime);
        }

        protected override void Dispose(bool isDisposing)
        {
            base.Dispose(isDisposing);

            if (drawableObject != null)
                drawableObject.HitObjectApplied -= onHitObjectApplied;
        }
    }
}


#region Copyright & License Information
/*
 * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
 * This file is part of OpenRA, which is free software. It is made
 * available to you under the terms of the GNU General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version. For more
 * information, see COPYING.
 */
#endregion

using System;
using System.Runtime.InteropServices;

namespace OpenRA.Platforms.Default
{
	sealed class VertexBuffer<T> : ThreadAffine, IVertexBuffer<T>
			where T : struct
	{
		static readonly int VertexSize = Marshal.SizeOf(typeof(T));
		uint buffer;
		bool disposed;

		public VertexBuffer(int size)
		{
			OpenGL.glGenBuffers(1, out buffer);
			OpenGL.CheckGLError();
			Bind();

			// Generates a buffer with uninitialized memory.
			OpenGL.glBufferData(OpenGL.GL_ARRAY_BUFFER,
					new IntPtr(VertexSize * size),
					IntPtr.Zero,
					OpenGL.GL_DYNAMIC_DRAW);
			OpenGL.CheckGLError();

			// We need to zero all the memory. Let's generate a smallish array and copy that over the whole buffer.
			var zeroedArrayElementSize = Math.Min(size, 2048);
			var ptr = GCHandle.Alloc(new T[zeroedArrayElementSize], GCHandleType.Pinned);
			try
			{
				for (var offset = 0; offset < size; offset += zeroedArrayElementSize)
				{
					var length = Math.Min(zeroedArrayElementSize, size - offset);
					OpenGL.glBufferSubData(OpenGL.GL_ARRAY_BUFFER,
						new IntPtr(VertexSize * offset),
						new IntPtr(VertexSize * length),
						ptr.AddrOfPinnedObject());
					OpenGL.CheckGLError();
				}
			}
			finally
			{
				ptr.Free();
			}
		}

		public void SetData(T[] data, int length)
		{
			SetData(data, 0, 0, length);
		}

		public void SetData(T[] data, int offset, int start, int length)
		{
			Bind();

			var ptr = GCHandle.Alloc(data, GCHandleType.Pinned);
			try
			{
				OpenGL.glBufferSubData(OpenGL.GL_ARRAY_BUFFER,
					new IntPtr(VertexSize * start),
					new IntPtr(VertexSize * length),
					ptr.AddrOfPinnedObject() + VertexSize * offset);
			}
			finally
			{
				ptr.Free();
			}

			OpenGL.CheckGLError();
		}

		public void Bind()
		{
			VerifyThreadAffinity();
			OpenGL.glBindBuffer(OpenGL.GL_ARRAY_BUFFER, buffer);
			OpenGL.CheckGLError();
			OpenGL.glVertexAttribPointer(Shader.VertexPosAttributeIndex, 3, OpenGL.GL_FLOAT, false, VertexSize, IntPtr.Zero);
			OpenGL.CheckGLError();
			OpenGL.glVertexAttribPointer(Shader.TexCoordAttributeIndex, 4, OpenGL.GL_FLOAT, false, VertexSize, new IntPtr(12));
			OpenGL.CheckGLError();
			OpenGL.glVertexAttribPointer(Shader.TexMetadataAttributeIndex, 2, OpenGL.GL_FLOAT, false, VertexSize, new IntPtr(28));
			OpenGL.CheckGLError();
			OpenGL.glVertexAttribPointer(Shader.TintAttributeIndex, 3, OpenGL.GL_FLOAT, false, VertexSize, new IntPtr(36));
			OpenGL.CheckGLError();
		}

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

		void Dispose(bool disposing)
		{
			if (disposed)
				return;
			disposed = true;
			OpenGL.glDeleteBuffers(1, ref buffer);
			OpenGL.CheckGLError();
		}
	}
}


using System;
using BurningKnight.assets;
using BurningKnight.assets.lighting;
using BurningKnight.assets.particle;
using BurningKnight.assets.particle.custom;
using BurningKnight.entity.component;
using BurningKnight.state;
using BurningKnight.util;
using Lens.entity;
using Lens.graphics;
using Lens.util.file;
using Lens.util.math;
using Microsoft.Xna.Framework;

namespace BurningKnight.level.entities.decor {
	public class Torch : SolidProp {
		public bool On = true;
		public float XSpread = 1f;
		public Vector2? Target;

		private bool broken;
		private FireEmitter emitter;
		private float t;

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

			Width = 10;
			Sprite = "torch";
			t = Rnd.Float(6);
			AlwaysActive = Run.Depth < 1;
		}

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

			AddComponent(new LightComponent(this, 32f, new Color(1f, 0.8f, 0.3f, 1f)));
			AddComponent(new ShadowComponent());
			AddComponent(new RoomComponent());

			AddTag(Tags.Torch);
		}

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

			if (emitter != null) {
				emitter.Done = true;
			}
		}

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

			if (!broken) {
				Area.Add(emitter = new FireEmitter {
					Depth = Depth + 1,
					Position = new Vector2(CenterX, Y + 3),
					Scale = 0.5f
				});
			}

			UpdateSprite();
		}

		private void UpdateSprite() {
			if (broken) {
				var s = GetComponent<SliceComponent>();

				s.Sprite = CommonAse.Props.GetSlice("broken_torch");
				s.Offset = new Vector2(0, 5);
			}
		}

		public void Break() {
			if (broken) {
				return;
			}

			On = false;
			broken = true;

			if (emitter != null) {
				emitter.Done = true;
			}

			AnimationUtil.Poof(Center);
			Particles.BreakSprite(Area, GetComponent<SliceComponent>().Sprite, Position);

			UpdateSprite();
		}

		private float lastFlame;

		public override void Update(float dt) {
			base.Update(dt);

			if (!On) {
				return;
			}

			t += dt * 0.5f;
			GetComponent<LightComponent>().Light.Radius = 38f + (float) Math.Cos(t) * 6;
			lastFlame += dt;

			if (lastFlame > 0.1f) {
				Area.Add(new FireParticle {
					X = CenterX,
					Y = Y + 2,
					Target = Target,
					XChange = XSpread
				});

				lastFlame = 0;
			}
		}

		protected override Rectangle GetCollider() {
			return new Rectangle(2, 5, 6, 5);
		}

		public override void Load(FileReader stream) {
			base.Load(stream);
			broken = stream.ReadBoolean();
		}

		public override void Save(FileWriter stream) {
			base.Save(stream);
			stream.WriteBoolean(broken);
		}

		public override bool ShouldCollide(Entity entity) {
			return false;
		}
	}
}


#region Copyright & License Information
/*
 * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
 * This file is part of OpenRA, which is free software. It is made
 * available to you under the terms of the GNU General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version. For more
 * information, see COPYING.
 */
#endregion

using System.Collections.Generic;
using System.Linq;
using OpenRA.Activities;
using OpenRA.Mods.Common.Pathfinder;
using OpenRA.Mods.Common.Traits;
using OpenRA.Primitives;
using OpenRA.Traits;

namespace OpenRA.Mods.Common.Activities
{
	public class MoveAdjacentTo : Activity
	{
		static readonly List<CPos> NoPath = new List<CPos>();

		protected readonly Mobile Mobile;
		readonly IPathFinder pathFinder;
		readonly DomainIndex domainIndex;
		readonly Color? targetLineColor;

		protected Target Target
		{
			get
			{
				return useLastVisibleTarget ? lastVisibleTarget : target;
			}
		}

		Target target;
		Target lastVisibleTarget;
		protected CPos lastVisibleTargetLocation;
		bool useLastVisibleTarget;

		public MoveAdjacentTo(Actor self, in Target target, WPos? initialTargetPosition = null, Color? targetLineColor = null)
		{
			this.target = target;
			this.targetLineColor = targetLineColor;
			Mobile = self.Trait<Mobile>();
			pathFinder = self.World.WorldActor.Trait<IPathFinder>();
			domainIndex = self.World.WorldActor.Trait<DomainIndex>();
			ChildHasPriority = false;

			// The target may become hidden between the initial order request and the first tick (e.g. if queued)
			// Moving to any position (even if quite stale) is still better than immediately giving up
			if ((target.Type == TargetType.Actor && target.Actor.CanBeViewedByPlayer(self.Owner))
			    || target.Type == TargetType.FrozenActor || target.Type == TargetType.Terrain)
			{
				lastVisibleTarget = Target.FromPos(target.CenterPosition);
				lastVisibleTargetLocation = self.World.Map.CellContaining(target.CenterPosition);
			}
			else if (initialTargetPosition.HasValue)
			{
				lastVisibleTarget = Target.FromPos(initialTargetPosition.Value);
				lastVisibleTargetLocation = self.World.Map.CellContaining(initialTargetPosition.Value);
			}
		}

		protected virtual bool ShouldStop(Actor self)
		{
			return false;
		}

		protected virtual bool ShouldRepath(Actor self, CPos targetLocation)
		{
			return lastVisibleTargetLocation != targetLocation;
		}

		protected virtual IEnumerable<CPos> CandidateMovementCells(Actor self)
		{
			return Util.AdjacentCells(self.World, Target)
				.Where(c => Mobile.CanStayInCell(c));
		}

		protected override void OnFirstRun(Actor self)
		{
			QueueChild(Mobile.MoveTo(check => CalculatePathToTarget(self, check)));
		}

		public override bool Tick(Actor self)
		{
			var oldTargetLocation = lastVisibleTargetLocation;
			target = target.Recalculate(self.Owner, out var targetIsHiddenActor);
			if (!targetIsHiddenActor && target.Type == TargetType.Actor)
			{
				lastVisibleTarget = Target.FromTargetPositions(target);
				lastVisibleTargetLocation = self.World.Map.CellContaining(target.CenterPosition);
			}

			// Target is equivalent to checkTarget variable in other activities
			// value is either lastVisibleTarget or target based on visibility and validity
			var targetIsValid = Target.IsValidFor(self);
			useLastVisibleTarget = targetIsHiddenActor || !targetIsValid;

			// Target is hidden or dead, and we don't have a fallback position to move towards
			var noTarget = useLastVisibleTarget && !lastVisibleTarget.IsValidFor(self);

			// Cancel the current path if the activity asks to stop, or asks to repath
			// The repath happens once the move activity stops in the next cell
			var shouldRepath = targetIsValid && ShouldRepath(self, oldTargetLocation);
			if (ChildActivity != null && (ShouldStop(self) || shouldRepath || noTarget))
				ChildActivity.Cancel(self);

			// Target has moved, and MoveAdjacentTo is still valid.
			if (!IsCanceling && shouldRepath)
				QueueChild(Mobile.MoveTo(check => CalculatePathToTarget(self, check)));

			// The last queued childactivity is guaranteed to be the inner move, so if the childactivity
			// queue is empty it means we have reached our destination.
			return TickChild(self);
		}

		List<CPos> searchCells = new List<CPos>();
		int searchCellsTick = -1;

		List<CPos> CalculatePathToTarget(Actor self, BlockedByActor check)
		{
			var loc = self.Location;

			// PERF: Assume that CandidateMovementCells doesn't change within a tick to avoid repeated queries
			// when Move enumerates different BlockedByActor values
			if (searchCellsTick != self.World.WorldTick)
			{
				searchCells.Clear();
				searchCellsTick = self.World.WorldTick;
				foreach (var cell in CandidateMovementCells(self))
					if (domainIndex.IsPassable(loc, cell, Mobile.Locomotor) && Mobile.CanEnterCell(cell))
						searchCells.Add(cell);
			}

			if (!searchCells.Any())
				return NoPath;

			using (var fromSrc = PathSearch.FromPoints(self.World, Mobile.Locomotor, self, searchCells, loc, check))
			using (var fromDest = PathSearch.FromPoint(self.World, Mobile.Locomotor, self, loc, lastVisibleTargetLocation, check).Reverse())
				return pathFinder.FindBidiPath(fromSrc, fromDest);
		}

		public override IEnumerable<Target> GetTargets(Actor self)
		{
			if (ChildActivity != null)
				return ChildActivity.GetTargets(self);

			return Target.None;
		}

		public override IEnumerable<TargetLineNode> TargetLineNodes(Actor self)
		{
			if (targetLineColor.HasValue)
				yield return new TargetLineNode(useLastVisibleTarget ? lastVisibleTarget : target, targetLineColor.Value);
		}
	}
}


using System;
using BurningKnight.entity.component;
using BurningKnight.entity.projectile;
using BurningKnight.util;
using Lens.entity;
using Lens.util;
using Lens.util.camera;
using Lens.util.math;
using Microsoft.Xna.Framework;

namespace BurningKnight.entity {
	public static class BlankMaker {
		public const float Radius = 48f;

		public static void Make(Vector2 where, Area area, float r = Radius) {
			foreach (var p in area.Tagged[Tags.Projectile]) {
				if (p.DistanceTo(where) <= r) {
					((Projectile) p).Break();
				}
			}

			foreach (var e in area.Tagged[Tags.MustBeKilled]) {
				if (e.DistanceTo(where) <= r) {
					e.GetAnyComponent<BodyComponent>()?.KnockbackFrom(where, 10f);
				}
			}

			for (var i = 0; i < 10; i++) {
				var a = i * 0.1f * Math.PI * 2 + Rnd.Float(-0.1f, 0.1f);
				AnimationUtil.PoofFrom(where + MathUtils.CreateVector(a, r - 8), where);
			}

			for (var i = 0; i < 10; i++) {
				var a = Rnd.AnglePI();
				var d = Rnd.Float(r);

				AnimationUtil.PoofFrom(where + MathUtils.CreateVector(a, d), where);
			}

			Camera.Instance.Shake(6);
		}
	}
}


#region Copyright & License Information
/*
 * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
 * This file is part of OpenRA, which is free software. It is made
 * available to you under the terms of the GNU General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version. For more
 * information, see COPYING.
 */
#endregion

using System.Collections.Generic;
using OpenRA.Graphics;
using OpenRA.Mods.Common.Traits;
using OpenRA.Widgets;

namespace OpenRA.Mods.Common.Widgets.Logic
{
	public class HistoryLogLogic : ChromeLogic
	{
		readonly ScrollPanelWidget panel;
		readonly EditorActionManager editorActionManager;
		readonly ScrollItemWidget template;

		readonly Dictionary<EditorActionContainer, ScrollItemWidget> states = new Dictionary<EditorActionContainer, ScrollItemWidget>();

		[ObjectCreator.UseCtor]
		public HistoryLogLogic(Widget widget, World world, WorldRenderer worldRenderer, Dictionary<string, MiniYaml> logicArgs)
		{
			panel = widget.Get<ScrollPanelWidget>("HISTORY_LIST");
			template = panel.Get<ScrollItemWidget>("HISTORY_TEMPLATE");
			editorActionManager = world.WorldActor.Trait<EditorActionManager>();

			editorActionManager.ItemAdded += ItemAdded;
			editorActionManager.ItemRemoved += ItemRemoved;
		}

		void ItemAdded(EditorActionContainer editorAction)
		{
			var item = ScrollItemWidget.Setup(template, () => false, () =>
			{
				if (editorAction.Status == EditorActionStatus.History)
					editorActionManager.Rewind(editorAction.Id);
				else if (editorAction.Status == EditorActionStatus.Future)
					editorActionManager.Forward(editorAction.Id);
			});

			var titleLabel = item.Get<LabelWidget>("TITLE");
			var textColor = template.TextColor;
			var futureTextColor = template.TextColorDisabled;

			titleLabel.GetText = () => editorAction.Action.Text;
			titleLabel.GetColor = () => editorAction.Status == EditorActionStatus.Future ? futureTextColor : textColor;

			item.IsSelected = () => editorAction.Status == EditorActionStatus.Active;
			panel.AddChild(item);

			states[editorAction] = item;
		}

		void ItemRemoved(EditorActionContainer editorAction)
		{
			var widget = states[editorAction];

			panel.RemoveChild(widget);

			states.Remove(editorAction);
		}
	}
}


#region License Information (GPL v3)

/*
    ShareX - A program that allows you to take screenshots and share any file type
    Copyright (c) 2007-2020 ShareX Team

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation; either version 2
    of the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

    Optionally you can also view the license at <http://www.gnu.org/licenses/>.
*/

#endregion License Information (GPL v3)

using ShareX.HelpersLib;
using System.ComponentModel;
using System.Drawing;

namespace ShareX.ImageEffectsLib
{
    internal class Hue : ImageEffect
    {
        [DefaultValue(0f), Description("From 0 to 360")]
        public float Angle { get; set; }

        public Hue()
        {
            this.ApplyDefaultPropertyValues();
        }

        public override Bitmap Apply(Bitmap bmp)
        {
            using (bmp)
            {
                return ColorMatrixManager.Hue(Angle).Apply(bmp);
            }
        }
    }
}


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

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

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

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

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

        protected override void Update()
        {
            base.Update();
            trackTimer.Text = editorClock.CurrentTime.ToEditorFormattedString();
        }
    }
}


#region Copyright & License Information
/*
 * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
 * This file is part of OpenRA, which is free software. It is made
 * available to you under the terms of the GNU General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version. For more
 * information, see COPYING.
 */
#endregion

using OpenRA.Traits;

namespace OpenRA.Mods.Common
{
	public static class ShroudExts
	{
		public static bool AnyExplored(this Shroud shroud, (CPos Cell, SubCell SubCell)[] cells)
		{
			// PERF: Avoid LINQ.
			foreach (var cell in cells)
				if (shroud.IsExplored(cell.Cell))
					return true;

			return false;
		}

		public static bool AnyExplored(this Shroud shroud, PPos[] puvs)
		{
			// PERF: Avoid LINQ.
			foreach (var puv in puvs)
				if (shroud.IsExplored(puv))
					return true;

			return false;
		}

		public static bool AnyVisible(this Shroud shroud, (CPos Cell, SubCell SubCell)[] cells)
		{
			// PERF: Avoid LINQ.
			foreach (var cell in cells)
				if (shroud.IsVisible(cell.Cell))
					return true;

			return false;
		}
	}
}


using System;
using System.Linq;
using BurningKnight.assets.achievements;
using BurningKnight.entity.creature.npc;
using BurningKnight.entity.creature.npc.dungeon;
using BurningKnight.entity.door;
using BurningKnight.level.biome;
using BurningKnight.level.tile;
using BurningKnight.save;
using BurningKnight.state;
using BurningKnight.util.geometry;
using Lens.util;
using Lens.util.math;
using Microsoft.Xna.Framework;

namespace BurningKnight.level.rooms.special {
	public class NpcSaveRoom : SpecialRoom {
		private class NpcData {
			public NpcData(byte d, string i) {
				Depth = d;
				Id = i;
			}

			public byte Depth;
			public string Id;
		}

		private static NpcData[] npcs = {
			new NpcData(2, ShopNpc.HatTrader),
			new NpcData(2, ShopNpc.AccessoryTrader),
			new NpcData(3, ShopNpc.ActiveTrader),
			new NpcData(3, ShopNpc.WeaponTrader),
			new NpcData(4, ShopNpc.Snek),
			new NpcData(4, ShopNpc.Boxy),
			new NpcData(5, ShopNpc.Duck),
			new NpcData(6, ShopNpc.Vampire),
			new NpcData(7, ShopNpc.Elon),
			new NpcData(8, ShopNpc.Gobetta),
			new NpcData(9, ShopNpc.Nurse),
			new NpcData(10, ShopNpc.Roger),
			new NpcData(10, ShopNpc.Mike)
		};

		public override int GetMaxConnections(Connection Side) {
			return 1;
		}

		public override int GetMinConnections(Connection Side) {
			return Side == Connection.All ? 1 : 0;
		}

		public override bool CanConnect(RoomDef R) {
			return base.CanConnect(R) && !(R is NpcKeyRoom);
		}

		public override int GetMaxWidth() {
			return 10;
		}

		public override int GetMaxHeight() {
			return 10;
		}

		private static bool DefeatedBosses() {
			return Achievements.IsComplete("bk:democracy") && Achievements.IsComplete("bk:mummified") && Achievements.IsComplete("bk:ice_boss") && Achievements.IsComplete("bk:bk_no_more") && Achievements.IsComplete("bk:sting_operation");
		}

		private static string GenerateNpc() {
			var d = Run.Depth;

			foreach (var info in npcs) {
				if (info.Depth == d && GlobalSave.IsFalse(info.Id)) {
					if (info.Id == ShopNpc.Mike && !DefeatedBosses()) {
						continue;
					}

					Log.Info($"Npc {info.Id} should be generated");
					return info.Id;
				}
			}

			Log.Info($"No npc should be generated");
			return null;
		}

		public override void Paint(Level level) {
			var ice = LevelSave.BiomeGenerated is IceBiome;

			if (ice) {
				var clip = Painter.Clip;
				Painter.Clip = null;
				Painter.Rect(level, this, 0, Tile.WallB);
				Painter.Clip = clip;
			}

			var id = GenerateNpc();

			if (id == null) {
				return;
			}

			GameSave.Put("npc_appeared", true);

			var d = Connected.Values.First();
			var npc = ShopNpc.FromId(id);
			level.Area.Add(npc);

			var fl = Tiles.RandomFloorOrSpike();

			if (d.X == Left || d.X == Right) {
				var w = (int) (GetWidth() / 2f + Rnd.Int(-1, 1));
				var door = new Dot(Left + w, Rnd.Int(Top + 2, Bottom - 2));

				Painter.DrawLine(level, new Dot(Left + w, Top), new Dot(Left + w, Bottom), ice ? Tile.WallB : Tile.WallA);
				Painter.Set(level, door, fl);

				npc.Center = new Dot(Left + w + (d.X == Left ? 2 : -2), Rnd.Int(Top + 2, Bottom - 3)) * 16 + new Vector2(8);

				var dr = new CageDoor {
					Vertical = true
				};

				dr.Center = door * 16 + new Vector2(12, 0);
				level.Area.Add(dr);

				var v = (d.X == Left ? -1 : 1);

				Painter.DrawLine(level, new Dot(Left + w + v, Top + 1), new Dot(Left + w + v, Bottom - 1), Tiles.Pick(Tile.Chasm, Tile.Lava, Tile.SensingSpikeTmp));
				Painter.Set(level, door + new Dot(v, 0), fl);
			} else if (true) {
				var h = (int) (GetHeight() / 2f + Rnd.Int(-1, 1));
				var door = new Dot(Rnd.Int(Left + 2, Right - 2), Top + h);

				Painter.DrawLine(level, new Dot(Left, Top + h), new Dot(Right, Top + h), Tile.WallA);
				Painter.Set(level, door, fl);

				npc.Center = new Dot(Rnd.Int(Left + 2, Right - 2), Top + h + (d.Y == Top ? 2 : -2)) * 16 + new Vector2(8);

				var dr = new CageDoor();
				dr.Center = door * 16 + new Vector2(7, 8);
				level.Area.Add(dr);

				var v = (d.Y == Top ? -1 : 1);

				Painter.DrawLine(level, new Dot(Left + 1, Top + h + v), new Dot(Right - 1, Top + h + v), Tiles.Pick(Tile.Chasm, Tile.Lava, Tile.SensingSpikeTmp));
				Painter.Set(level, door + new Dot(0, v), fl);
			}
		}

		public static bool ShouldBeAdded() {
			if (Run.Type != RunType.Regular || GameSave.IsTrue("npc_appeared")) {
				return false;
			}

			return GenerateNpc() != null;
		}
	}
}


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

using System;
using System.Collections.Generic;
using System.Linq;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Difficulty.Preprocessing;
using osu.Game.Rulesets.Difficulty.Skills;
using osu.Game.Rulesets.Mania.Beatmaps;
using osu.Game.Rulesets.Mania.Difficulty.Preprocessing;
using osu.Game.Rulesets.Mania.Difficulty.Skills;
using osu.Game.Rulesets.Mania.MathUtils;
using osu.Game.Rulesets.Mania.Mods;
using osu.Game.Rulesets.Mania.Objects;
using osu.Game.Rulesets.Mania.Scoring;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Scoring;

namespace osu.Game.Rulesets.Mania.Difficulty
{
    public class ManiaDifficultyCalculator : DifficultyCalculator
    {
        private const double star_scaling_factor = 0.018;

        private readonly bool isForCurrentRuleset;
        private readonly double originalOverallDifficulty;

        public ManiaDifficultyCalculator(Ruleset ruleset, WorkingBeatmap beatmap)
            : base(ruleset, beatmap)
        {
            isForCurrentRuleset = beatmap.BeatmapInfo.Ruleset.Equals(ruleset.RulesetInfo);
            originalOverallDifficulty = beatmap.BeatmapInfo.BaseDifficulty.OverallDifficulty;
        }

        protected override DifficultyAttributes CreateDifficultyAttributes(IBeatmap beatmap, Mod[] mods, Skill[] skills, double clockRate)
        {
            if (beatmap.HitObjects.Count == 0)
                return new ManiaDifficultyAttributes { Mods = mods, Skills = skills };

            HitWindows hitWindows = new ManiaHitWindows();
            hitWindows.SetDifficulty(beatmap.BeatmapInfo.BaseDifficulty.OverallDifficulty);

            return new ManiaDifficultyAttributes
            {
                StarRating = skills[0].DifficultyValue() * star_scaling_factor,
                Mods = mods,
                // Todo: This int cast is temporary to achieve 1:1 results with osu!stable, and should be removed in the future
                GreatHitWindow = (int)Math.Ceiling(getHitWindow300(mods) / clockRate),
                ScoreMultiplier = getScoreMultiplier(beatmap, mods),
                MaxCombo = beatmap.HitObjects.Sum(h => h is HoldNote ? 2 : 1),
                Skills = skills
            };
        }

        protected override IEnumerable<DifficultyHitObject> CreateDifficultyHitObjects(IBeatmap beatmap, double clockRate)
        {
            var sortedObjects = beatmap.HitObjects.ToArray();

            LegacySortHelper<HitObject>.Sort(sortedObjects, Comparer<HitObject>.Create((a, b) => (int)Math.Round(a.StartTime) - (int)Math.Round(b.StartTime)));

            for (int i = 1; i < sortedObjects.Length; i++)
                yield return new ManiaDifficultyHitObject(sortedObjects[i], sortedObjects[i - 1], clockRate);
        }

        // Sorting is done in CreateDifficultyHitObjects, since the full list of hitobjects is required.
        protected override IEnumerable<DifficultyHitObject> SortObjects(IEnumerable<DifficultyHitObject> input) => input;

        protected override Skill[] CreateSkills(IBeatmap beatmap) => new Skill[]
        {
            new Strain(((ManiaBeatmap)beatmap).TotalColumns)
        };

        protected override Mod[] DifficultyAdjustmentMods
        {
            get
            {
                var mods = new Mod[]
                {
                    new ManiaModDoubleTime(),
                    new ManiaModHalfTime(),
                    new ManiaModEasy(),
                    new ManiaModHardRock(),
                };

                if (isForCurrentRuleset)
                    return mods;

                // if we are a convert, we can be played in any key mod.
                return mods.Concat(new Mod[]
                {
                    new ManiaModKey1(),
                    new ManiaModKey2(),
                    new ManiaModKey3(),
                    new ManiaModKey4(),
                    new ManiaModKey5(),
                    new MultiMod(new ManiaModKey5(), new ManiaModDualStages()),
                    new ManiaModKey6(),
                    new MultiMod(new ManiaModKey6(), new ManiaModDualStages()),
                    new ManiaModKey7(),
                    new MultiMod(new ManiaModKey7(), new ManiaModDualStages()),
                    new ManiaModKey8(),
                    new MultiMod(new ManiaModKey8(), new ManiaModDualStages()),
                    new ManiaModKey9(),
                    new MultiMod(new ManiaModKey9(), new ManiaModDualStages()),
                }).ToArray();
            }
        }

        private int getHitWindow300(Mod[] mods)
        {
            if (isForCurrentRuleset)
            {
                double od = Math.Min(10.0, Math.Max(0, 10.0 - originalOverallDifficulty));
                return applyModAdjustments(34 + 3 * od, mods);
            }

            if (Math.Round(originalOverallDifficulty) > 4)
                return applyModAdjustments(34, mods);

            return applyModAdjustments(47, mods);

            static int applyModAdjustments(double value, Mod[] mods)
            {
                if (mods.Any(m => m is ManiaModHardRock))
                    value /= 1.4;
                else if (mods.Any(m => m is ManiaModEasy))
                    value *= 1.4;

                if (mods.Any(m => m is ManiaModDoubleTime))
                    value *= 1.5;
                else if (mods.Any(m => m is ManiaModHalfTime))
                    value *= 0.75;

                return (int)value;
            }
        }

        private double getScoreMultiplier(IBeatmap beatmap, Mod[] mods)
        {
            double scoreMultiplier = 1;

            foreach (var m in mods)
            {
                switch (m)
                {
                    case ManiaModNoFail _:
                    case ManiaModEasy _:
                    case ManiaModHalfTime _:
                        scoreMultiplier *= 0.5;
                        break;
                }
            }

            var maniaBeatmap = (ManiaBeatmap)beatmap;
            int diff = maniaBeatmap.TotalColumns - maniaBeatmap.OriginalTotalColumns;

            if (diff > 0)
                scoreMultiplier *= 0.9;
            else if (diff < 0)
                scoreMultiplier *= 0.9 + 0.04 * diff;

            return scoreMultiplier;
        }
    }
}


#region License Information (GPL v3)

/*
    ShareX - A program that allows you to take screenshots and share any file type
    Copyright (c) 2007-2020 ShareX Team

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation; either version 2
    of the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

    Optionally you can also view the license at <http://www.gnu.org/licenses/>.
*/

#endregion License Information (GPL v3)

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace ShareX.HelpersLib
{
    public static class TranslatorHelper
    {
        #region Text to ...

        public static string[] TextToBinary(string text)
        {
            string[] result = new string[text.Length];

            for (int i = 0; i < text.Length; i++)
            {
                result[i] = ByteToBinary((byte)text[i]);
            }

            return result;
        }

        public static string[] TextToHexadecimal(string text)
        {
            return BytesToHexadecimal(Encoding.UTF8.GetBytes(text));
        }

        public static byte[] TextToASCII(string text)
        {
            return Encoding.ASCII.GetBytes(text);
        }

        public static string TextToBase64(string text)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(text);
            return Convert.ToBase64String(bytes);
        }

        public static string TextToHash(string text, HashType hashType, bool uppercase = false)
        {
            using (HashAlgorithm hash = HashCheck.GetHashAlgorithm(hashType))
            {
                byte[] bytes = hash.ComputeHash(Encoding.UTF8.GetBytes(text));
                string[] hex = BytesToHexadecimal(bytes);
                string result = string.Concat(hex);
                if (uppercase) result = result.ToUpperInvariant();
                return result;
            }
        }

        #endregion Text to ...

        #region Binary to ...

        public static byte BinaryToByte(string binary)
        {
            return Convert.ToByte(binary, 2);
        }

        public static string BinaryToText(string binary)
        {
            binary = Regex.Replace(binary, @"[^01]", "");

            using (MemoryStream stream = new MemoryStream())
            {
                for (int i = 0; i + 8 <= binary.Length; i += 8)
                {
                    stream.WriteByte(BinaryToByte(binary.Substring(i, 8)));
                }

                return Encoding.UTF8.GetString(stream.ToArray());
            }
        }

        #endregion Binary to ...

        #region Byte to ...

        public static string ByteToBinary(byte b)
        {
            char[] result = new char[8];
            int pos = 7;

            for (int i = 0; i < 8; i++)
            {
                if ((b & (1 << i)) != 0)
                {
                    result[pos] = '1';
                }
                else
                {
                    result[pos] = '0';
                }

                pos--;
            }

            return new string(result);
        }

        public static string[] BytesToHexadecimal(byte[] bytes)
        {
            string[] result = new string[bytes.Length];

            for (int i = 0; i < bytes.Length; i++)
            {
                result[i] = bytes[i].ToString("x2");
            }

            return result;
        }

        #endregion Byte to ...

        #region Hexadecimal to ...

        public static byte HexadecimalToByte(string hex)
        {
            return Convert.ToByte(hex, 16);
        }

        public static string HexadecimalToText(string hex)
        {
            hex = Regex.Replace(hex, @"[^0-9a-fA-F]", "");

            using (MemoryStream stream = new MemoryStream())
            {
                for (int i = 0; i + 2 <= hex.Length; i += 2)
                {
                    stream.WriteByte(HexadecimalToByte(hex.Substring(i, 2)));
                }

                return Encoding.UTF8.GetString(stream.ToArray());
            }
        }

        #endregion Hexadecimal to ...

        #region Base64 to ...

        public static string Base64ToText(string base64)
        {
            byte[] bytes = Convert.FromBase64String(base64);
            return Encoding.UTF8.GetString(bytes);
        }

        #endregion Base64 to ...

        #region ASCII to ...

        public static string ASCIIToText(string ascii)
        {
            string[] numbers = Regex.Split(ascii, @"\D+");

            using (MemoryStream stream = new MemoryStream())
            {
                foreach (string number in numbers)
                {
                    byte b;
                    if (byte.TryParse(number, out b))
                    {
                        stream.WriteByte(b);
                    }
                }

                return Encoding.ASCII.GetString(stream.ToArray());
            }
        }

        #endregion ASCII to ...
    }
}


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

using osu.Framework.Allocation;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Effects;
using osu.Framework.Graphics.Shapes;
using osu.Game.Graphics;
using osuTK.Graphics;

namespace osu.Game.Rulesets.Taiko.UI
{
    public class PlayfieldBackgroundRight : CompositeDrawable
    {
        [BackgroundDependencyLoader]
        private void load(OsuColour colours)
        {
            Name = "Transparent playfield background";
            RelativeSizeAxes = Axes.Both;
            Masking = true;
            BorderColour = colours.Gray1;

            EdgeEffect = new EdgeEffectParameters
            {
                Type = EdgeEffectType.Shadow,
                Colour = Color4.Black.Opacity(0.2f),
                Radius = 5,
            };

            InternalChildren = new Drawable[]
            {
                new Box
                {
                    RelativeSizeAxes = Axes.Both,
                    Colour = colours.Gray0,
                    Alpha = 0.6f
                },
                new Container
                {
                    Name = "Border",
                    RelativeSizeAxes = Axes.Both,
                    Masking = true,
                    MaskingSmoothness = 0,
                    BorderThickness = 2,
                    AlwaysPresent = true,
                    Children = new[]
                    {
                        new Box
                        {
                            RelativeSizeAxes = Axes.Both,
                            Alpha = 0,
                            AlwaysPresent = true
                        }
                    }
                }
            };
        }
    }
}


using System;
using System.Diagnostics;
using System.IO;
using Desktop.integration.crash;
using Lens.assets;
using Microsoft.Xna.Framework.Audio;

namespace Desktop {
	public class Program {
		private static void TryToRemove(string file) {
			if (File.Exists(file)) {
				try {
					File.Delete(file);
				} catch (Exception e) {
					Console.WriteLine(e);
				}
			}
		}

		[STAThread]
		public static void Main() {
			CrashReporter.Bind();

			if (!Environment.Is64BitOperatingSystem) {
				Console.ForegroundColor = ConsoleColor.Red;
				Console.WriteLine("Burning Knight can't run on 32 bit OS, sorry :(");
				Console.ForegroundColor = ConsoleColor.White;

				return;
			}

			var current = Process.GetCurrentProcess();
			var processes = Process.GetProcessesByName(current.ProcessName);

			Console.WriteLine($"Found a total of {processes.Length} processes with name {current.ProcessName}");

			foreach (var process in processes) {
				if (process.Id != current.Id) {
					try {
						process.CloseMainWindow();
						process.Kill();
						Console.WriteLine("Killing older process");
					} catch (Exception e) {
						Console.WriteLine($"Failed: {e}");
					}
				}
			}

			TryToRemove("burning_log.txt");
			TryToRemove("crashes.txt");

			try {
				SoundEffect.Initialize();
				Console.WriteLine("SoundEffect.Initialize() went ok");
			} catch (Exception e) {
				Assets.FailedToLoadAudio = true;
				Assets.LoadSfx = false;
				Assets.LoadMusic = false;

				Console.WriteLine($"Failed: {e}");
			}

			try {
				using (var game = new DesktopApp()) {
					game.Run();
				}
			} catch (Exception e) {
				CrashReporter.Report(e);
			}
		}
	}
}


using System;
using System.Collections.Generic;
using System.Linq;
using Jellyfin.Data.Entities;
using Jellyfin.Data.Enums;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Querying;
using Microsoft.AspNetCore.Http;

namespace Jellyfin.Api.Helpers
{
    /// <summary>
    /// Request Extensions.
    /// </summary>
    public static class RequestHelpers
    {
        /// <summary>
        /// Get Order By.
        /// </summary>
        /// <param name="sortBy">Sort By. Comma delimited string.</param>
        /// <param name="requestedSortOrder">Sort Order. Comma delimited string.</param>
        /// <returns>Order By.</returns>
        public static (string, SortOrder)[] GetOrderBy(IReadOnlyList<string> sortBy, IReadOnlyList<SortOrder> requestedSortOrder)
        {
            if (sortBy.Count == 0)
            {
                return Array.Empty<ValueTuple<string, SortOrder>>();
            }

            var result = new (string, SortOrder)[sortBy.Count];
            var i = 0;
            // Add elements which have a SortOrder specified
            for (; i < requestedSortOrder.Count; i++)
            {
                result[i] = (sortBy[i], requestedSortOrder[i]);
            }

            // Add remaining elements with the first specified SortOrder
            // or the default one if no SortOrders are specified
            var order = requestedSortOrder.Count > 0 ? requestedSortOrder[0] : SortOrder.Ascending;
            for (; i < sortBy.Count; i++)
            {
                result[i] = (sortBy[i], order);
            }

            return result;
        }

        /// <summary>
        /// Checks if the user can update an entry.
        /// </summary>
        /// <param name="authContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param>
        /// <param name="requestContext">The <see cref="HttpRequest"/>.</param>
        /// <param name="userId">The user id.</param>
        /// <param name="restrictUserPreferences">Whether to restrict the user preferences.</param>
        /// <returns>A <see cref="bool"/> whether the user can update the entry.</returns>
        internal static bool AssertCanUpdateUser(IAuthorizationContext authContext, HttpRequest requestContext, Guid userId, bool restrictUserPreferences)
        {
            var auth = authContext.GetAuthorizationInfo(requestContext);

            var authenticatedUser = auth.User;

            // If they're going to update the record of another user, they must be an administrator
            if ((!userId.Equals(auth.UserId) && !authenticatedUser.HasPermission(PermissionKind.IsAdministrator))
                || (restrictUserPreferences && !authenticatedUser.EnableUserPreferenceAccess))
            {
                return false;
            }

            return true;
        }

        internal static SessionInfo GetSession(ISessionManager sessionManager, IAuthorizationContext authContext, HttpRequest request)
        {
            var authorization = authContext.GetAuthorizationInfo(request);
            var user = authorization.User;
            var session = sessionManager.LogSessionActivity(
                authorization.Client,
                authorization.Version,
                authorization.DeviceId,
                authorization.Device,
                request.HttpContext.GetNormalizedRemoteIp(),
                user);

            if (session == null)
            {
                throw new ArgumentException("Session not found.");
            }

            return session;
        }

        internal static QueryResult<BaseItemDto> CreateQueryResult(
            QueryResult<(BaseItem, ItemCounts)> result,
            DtoOptions dtoOptions,
            IDtoService dtoService,
            bool includeItemTypes,
            User? user)
        {
            var dtos = result.Items.Select(i =>
            {
                var (baseItem, counts) = i;
                var dto = dtoService.GetItemByNameDto(baseItem, dtoOptions, null, user);

                if (includeItemTypes)
                {
                    dto.ChildCount = counts.ItemCount;
                    dto.ProgramCount = counts.ProgramCount;
                    dto.SeriesCount = counts.SeriesCount;
                    dto.EpisodeCount = counts.EpisodeCount;
                    dto.MovieCount = counts.MovieCount;
                    dto.TrailerCount = counts.TrailerCount;
                    dto.AlbumCount = counts.AlbumCount;
                    dto.SongCount = counts.SongCount;
                    dto.ArtistCount = counts.ArtistCount;
                }

                return dto;
            });

            return new QueryResult<BaseItemDto>
            {
                Items = dtos.ToArray(),
                TotalRecordCount = result.TotalRecordCount
            };
        }
    }
}


// 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.Allocation;
using osu.Framework.Graphics;
using osu.Game.Overlays.Settings.Sections.Gameplay;
using osu.Game.Rulesets;
using System.Linq;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Logging;

namespace osu.Game.Overlays.Settings.Sections
{
    public class GameplaySection : SettingsSection
    {
        public override string Header => "Gameplay";

        public override Drawable CreateIcon() => new SpriteIcon
        {
            Icon = FontAwesome.Regular.Circle
        };

        public GameplaySection()
        {
            Children = new Drawable[]
            {
                new GeneralSettings(),
                new ModsSettings(),
            };
        }

        [BackgroundDependencyLoader]
        private void load(RulesetStore rulesets)
        {
            foreach (Ruleset ruleset in rulesets.AvailableRulesets.Select(info => info.CreateInstance()))
            {
                try
                {
                    SettingsSubsection section = ruleset.CreateSettings();

                    if (section != null)
                        Add(section);
                }
                catch (Exception e)
                {
                    Logger.Error(e, "Failed to load ruleset settings");
                }
            }
        }
    }
}


// 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 osuTK;
using osuTK.Graphics;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;

namespace osu.Game.Graphics.UserInterface
{
    public class Bar : Container, IHasAccentColour
    {
        private readonly Box background;
        private readonly Box bar;

        private const int resize_duration = 250;

        private const Easing easing = Easing.InOutCubic;

        private float length;

        /// <summary>
        /// Length of the bar, ranges from 0 to 1
        /// </summary>
        public float Length
        {
            get => length;
            set
            {
                length = Math.Clamp(value, 0, 1);
                updateBarLength();
            }
        }

        public Color4 BackgroundColour
        {
            get => background.Colour;
            set => background.Colour = value;
        }

        public Color4 AccentColour
        {
            get => bar.Colour;
            set => bar.Colour = value;
        }

        private BarDirection direction = BarDirection.LeftToRight;

        public BarDirection Direction
        {
            get => direction;
            set
            {
                direction = value;
                updateBarLength();
            }
        }

        public Bar()
        {
            Children = new[]
            {
                background = new Box
                {
                    RelativeSizeAxes = Axes.Both,
                    Colour = new Color4(0, 0, 0, 0)
                },
                bar = new Box
                {
                    RelativeSizeAxes = Axes.Both,
                    Width = 0,
                },
            };
        }

        private void updateBarLength()
        {
            switch (direction)
            {
                case BarDirection.LeftToRight:
                case BarDirection.RightToLeft:
                    bar.ResizeTo(new Vector2(length, 1), resize_duration, easing);
                    break;

                case BarDirection.TopToBottom:
                case BarDirection.BottomToTop:
                    bar.ResizeTo(new Vector2(1, length), resize_duration, easing);
                    break;
            }

            switch (direction)
            {
                case BarDirection.LeftToRight:
                case BarDirection.TopToBottom:
                    bar.Anchor = Anchor.TopLeft;
                    bar.Origin = Anchor.TopLeft;
                    break;

                case BarDirection.RightToLeft:
                case BarDirection.BottomToTop:
                    bar.Anchor = Anchor.BottomRight;
                    bar.Origin = Anchor.BottomRight;
                    break;
            }
        }
    }

    [Flags]
    public enum BarDirection
    {
        LeftToRight = 1,
        RightToLeft = 1 << 1,
        TopToBottom = 1 << 2,
        BottomToTop = 1 << 3,

        Vertical = TopToBottom | BottomToTop,
        Horizontal = LeftToRight | RightToLeft,
    }
}


#region Copyright & License Information
/*
 * Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
 * This file is part of OpenRA, which is free software. It is made
 * available to you under the terms of the GNU General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version. For more
 * information, see COPYING.
 */
#endregion

using OpenRA.Traits;

namespace OpenRA.Mods.Common.Traits
{
	[Desc("This actor has a voice.")]
	public class VoicedInfo : TraitInfo
	{
		[VoiceSetReference]
		[FieldLoader.Require]
		[Desc("Which voice set to use.")]
		public readonly string VoiceSet = null;

		[Desc("Multiply volume with this factor.")]
		public readonly float Volume = 1f;

		public override object Create(ActorInitializer init) { return new Voiced(init.Self, this); }
	}

	public class Voiced : IVoiced
	{
		public readonly VoicedInfo Info;

		public Voiced(Actor self, VoicedInfo info)
		{
			Info = info;
		}

		string IVoiced.VoiceSet { get { return Info.VoiceSet; } }

		bool IVoiced.PlayVoice(Actor self, string phrase, string variant)
		{
			if (phrase == null)
				return false;

			if (string.IsNullOrEmpty(Info.VoiceSet))
				return false;

			var type = Info.VoiceSet.ToLowerInvariant();
			var volume = Info.Volume;
			return Game.Sound.PlayPredefined(SoundType.World, self.World.Map.Rules, null, self, type, phrase, variant, true, WPos.Zero, volume, true);
		}

		bool IVoiced.PlayVoiceLocal(Actor self, string phrase, string variant, float volume)
		{
			if (phrase == null)
				return false;

			if (string.IsNullOrEmpty(Info.VoiceSet))
				return false;

			var type = Info.VoiceSet.ToLowerInvariant();
			return Game.Sound.PlayPredefined(SoundType.World, self.World.Map.Rules, null, self, type, phrase, variant, false, self.CenterPosition, volume, true);
		}

		bool IVoiced.HasVoice(Actor self, string voice)
		{
			if (string.IsNullOrEmpty(Info.VoiceSet))
				return false;

			var voices = self.World.Map.Rules.Voices[Info.VoiceSet.ToLowerInvariant()];
			return voices != null && voices.Voices.ContainsKey(voice);
		}
	}
}


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

using System.Linq;
using System.Threading;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osuTK;

namespace osu.Game.Overlays.News.Displays
{
    public class FrontPageDisplay : CompositeDrawable
    {
        [Resolved]
        private IAPIProvider api { get; set; }

        private FillFlowContainer content;
        private ShowMoreButton showMore;

        private GetNewsRequest request;
        private Cursor lastCursor;

        [BackgroundDependencyLoader]
        private void load()
        {
            RelativeSizeAxes = Axes.X;
            AutoSizeAxes = Axes.Y;
            Padding = new MarginPadding
            {
                Vertical = 20,
                Left = 30,
                Right = 50
            };

            InternalChild = new FillFlowContainer
            {
                RelativeSizeAxes = Axes.X,
                AutoSizeAxes = Axes.Y,
                Direction = FillDirection.Vertical,
                Spacing = new Vector2(0, 10),
                Children = new Drawable[]
                {
                    content = new FillFlowContainer
                    {
                        Anchor = Anchor.TopCentre,
                        Origin = Anchor.TopCentre,
                        RelativeSizeAxes = Axes.X,
                        AutoSizeAxes = Axes.Y,
                        Direction = FillDirection.Vertical,
                        Spacing = new Vector2(0, 10)
                    },
                    showMore = new ShowMoreButton
                    {
                        Anchor = Anchor.TopCentre,
                        Origin = Anchor.TopCentre,
                        Margin = new MarginPadding
                        {
                            Top = 15
                        },
                        Action = performFetch,
                        Alpha = 0
                    }
                }
            };

            performFetch();
        }

        private void performFetch()
        {
            request?.Cancel();

            request = new GetNewsRequest(lastCursor);
            request.Success += response => Schedule(() => onSuccess(response));
            api.PerformAsync(request);
        }

        private CancellationTokenSource cancellationToken;

        private void onSuccess(GetNewsResponse response)
        {
            cancellationToken?.Cancel();

            lastCursor = response.Cursor;

            var flow = new FillFlowContainer<NewsCard>
            {
                RelativeSizeAxes = Axes.X,
                AutoSizeAxes = Axes.Y,
                Direction = FillDirection.Vertical,
                Spacing = new Vector2(0, 10),
                Children = response.NewsPosts.Select(p => new NewsCard(p)).ToList()
            };

            LoadComponentAsync(flow, loaded =>
            {
                content.Add(loaded);
                showMore.IsLoading = false;
                showMore.Show();
            }, (cancellationToken = new CancellationTokenSource()).Token);
        }

        protected override void Dispose(bool isDisposing)
        {
            request?.Cancel();
            cancellationToken?.Cancel();
            base.Dispose(isDisposing);
        }
    }
}


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

using System.Diagnostics;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Skinning;
using osuTK;

namespace osu.Game.Rulesets.Osu.Objects.Drawables
{
    public class DrawableSliderTail : DrawableOsuHitObject, IRequireTracking, ITrackSnaking
    {
        public new SliderTailCircle HitObject => (SliderTailCircle)base.HitObject;

        [CanBeNull]
        public Slider Slider => DrawableSlider?.HitObject;

        protected DrawableSlider DrawableSlider => (DrawableSlider)ParentHitObject;

        /// <summary>
        /// The judgement text is provided by the <see cref="DrawableSlider"/>.
        /// </summary>
        public override bool DisplayResult => false;

        public bool Tracking { get; set; }

        private SkinnableDrawable circlePiece;
        private Container scaleContainer;

        public DrawableSliderTail()
            : base(null)
        {
        }

        public DrawableSliderTail(SliderTailCircle tailCircle)
            : base(tailCircle)
        {
        }

        [BackgroundDependencyLoader]
        private void load()
        {
            Origin = Anchor.Centre;
            Size = new Vector2(OsuHitObject.OBJECT_RADIUS * 2);

            InternalChildren = new Drawable[]
            {
                scaleContainer = new Container
                {
                    RelativeSizeAxes = Axes.Both,
                    Origin = Anchor.Centre,
                    Anchor = Anchor.Centre,
                    Children = new Drawable[]
                    {
                        // no default for this; only visible in legacy skins.
                        circlePiece = new SkinnableDrawable(new OsuSkinComponent(OsuSkinComponents.SliderTailHitCircle), _ => Empty())
                    }
                },
            };

            ScaleBindable.BindValueChanged(scale => scaleContainer.Scale = new Vector2(scale.NewValue));
        }

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

            circlePiece.FadeInFromZero(HitObject.TimeFadeIn);
        }

        protected override void UpdateHitStateTransforms(ArmedState state)
        {
            base.UpdateHitStateTransforms(state);

            Debug.Assert(HitObject.HitWindows != null);

            switch (state)
            {
                case ArmedState.Idle:
                    this.Delay(HitObject.TimePreempt).FadeOut(500);
                    break;

                case ArmedState.Miss:
                    this.FadeOut(100);
                    break;

                case ArmedState.Hit:
                    // todo: temporary / arbitrary
                    this.Delay(800).FadeOut();
                    break;
            }
        }

        protected override void CheckForResult(bool userTriggered, double timeOffset)
        {
            if (!userTriggered && timeOffset >= 0)
                ApplyResult(r => r.Type = Tracking ? r.Judgement.MaxResult : r.Judgement.MinResult);
        }

        public void UpdateSnakingPosition(Vector2 start, Vector2 end) =>
            Position = HitObject.RepeatIndex % 2 == 0 ? end : start;
    }
}


/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you 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.
 */

package org.apache.cxf.maven_plugin.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import org.apache.cxf.tools.common.ToolContext;
import org.apache.cxf.tools.wadlto.WADLToJava;

//TODO: Move to the common plugin module
public final class ForkOnceCodeGenerator {
    private ForkOnceCodeGenerator() {
        //utility
    }
    public static void main(String[] args) throws Exception {
        File file = new File(args[0]);
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line = reader.readLine();
        while (line != null) {
            int i = Integer.parseInt(line);
            if (i == -1) {
                reader.close();
                return;
            }
            String[] wargs = new String[i];
            for (int x = 0; x < i; x++) {
                wargs[x] = reader.readLine();
            }

            new WADLToJava(wargs).run(new ToolContext());

            line = reader.readLine();
        }
        reader.close();
    }
}


/*
Copyright 2011-2016 Google Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.Tag.Component.Help;

import java.net.URL;

import com.google.security.zynamics.binnavi.Help.CHelpFunctions;
import com.google.security.zynamics.binnavi.Help.IHelpInformation;

/**
 * Context-sensitive help information for fields that show tag names.
 */
public final class CNameHelp implements IHelpInformation {
  @Override
  public String getText() {
    return "In this field you can edit the name of the tag.";
  }

  @Override
  public URL getUrl() {
    return CHelpFunctions.urlify(CHelpFunctions.MAIN_WINDOW_FILE);
  }
}


/*****************************************************************
 *   Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you 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.
 ****************************************************************/
package org.apache.cayenne.di;

/**
 * A runtime exception thrown on DI misconfiguration.
 *
 * @since 4.0
 */
public class DIRuntimeException extends RuntimeException {

	private static final long serialVersionUID = 396131653561690312L;

	/**
     * Creates new ConfigurationException without detail message.
     */
    public DIRuntimeException() {
    }

    /**
     * Constructs an exception with the specified message with an optional list
     * of message formatting arguments. Message formatting rules follow
     * "String.format(..)" conventions.
     */
    public DIRuntimeException(String messageFormat, Object... messageArgs) {
        super(String.format(messageFormat, messageArgs));
    }

    /**
     * Constructs an exception wrapping another exception thrown elsewhere.
     */
    public DIRuntimeException(Throwable cause) {
        super(cause);
    }

    public DIRuntimeException(String messageFormat, Throwable cause, Object... messageArgs) {
        super(String.format(messageFormat, messageArgs), cause);
    }
}


/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */

package org.apache.ignite.internal.visor.node;

import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.internal.visor.VisorDataTransferObject;
import org.jetbrains.annotations.Nullable;

import static org.apache.ignite.internal.visor.util.VisorTaskUtils.compactArray;

/**
 * Data transfer object for node lifecycle configuration properties.
 */
public class VisorLifecycleConfiguration extends VisorDataTransferObject{
    /** */
    private static final long serialVersionUID = 0L;

    /** Lifecycle beans. */
    private String beans;

    /**
     * Default constructor.
     */
    public VisorLifecycleConfiguration() {
        // No-op.
    }

    /**
     * Create data transfer object for node lifecycle configuration properties.
     *
     * @param c Grid configuration.
     */
    public VisorLifecycleConfiguration(IgniteConfiguration c) {
        beans = compactArray(c.getLifecycleBeans());
    }

    /**
     * @return Lifecycle beans.
     */
    @Nullable public String getBeans() {
        return beans;
    }

    /** {@inheritDoc} */
    @Override protected void writeExternalData(ObjectOutput out) throws IOException {
        U.writeString(out, beans);
    }

    /** {@inheritDoc} */
    @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {
        beans = U.readString(in);
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return S.toString(VisorLifecycleConfiguration.class, this);
    }
}


/*
 * Copyright 2016 the original author or authors.
 *
 * 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.
 */
package org.springframework.statemachine.data;

/**
 * Generic base class representing guard entity.
 *
 * @author Janne Valkealahti
 *
 */
public abstract class RepositoryGuard extends BaseRepositoryEntity {

	/**
	 * Gets the name.
	 *
	 * @return the name
	 */
	public abstract String getName();

	/**
	 * Gets the spel.
	 *
	 * @return the spel
	 */
	public abstract String getSpel();
}