text:
using System;
using System.Linq;

using LinqToDB;

using NUnit.Framework;
using Tests.Model;

namespace Tests.Linq
{
	[TestFixture]
	public class ConvertExpressionTests : TestBase
	{
		[Test]
		public void Select1([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent
					let children = p.Children.Where(c => c.ParentID > 1)
					select children.Sum(c => c.ChildID),
					from p in db.Parent
					let children = p.Children.Where(c => c.ParentID > 1)
					select children.Sum(c => c.ChildID));
		}

		[Test]
		public void Select2([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent
					let children1 = p.Children.Where(c => c.ParentID > 1)
					let children2 = children1.Where(c => c.ParentID < 10)
					select children2.Sum(c => c.ChildID),
					from p in db.Parent
					let children1 = p.Children.Where(c => c.ParentID > 1)
					let children2 = children1.Where(c => c.ParentID < 10)
					select children2.Sum(c => c.ChildID));
		}

		[Test]
		public void Select3([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					Parent
						.Select(p => new { children1 = p.Children. Where(c => c.ParentID > 1)  })
						.Select(t => new { children2 = t.children1.Where(c => c.ParentID < 10) })
						.Select(t => t.children2.Sum(c => c.ChildID)),
					db.Parent
						.Select(p => new { children1 = p.Children. Where(c => c.ParentID > 1)  })
						.Select(t => new { children2 = t.children1.Where(c => c.ParentID < 10) })
						.Select(t => t.children2.Sum(c => c.ChildID)));
		}

		[Test]
		public void Select4([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					Parent
						.Select(p => p.Children. Where(c => c.ParentID > 1))
						.Select(t => t.Where(c => c.ParentID < 10))
						.Select(t => t.Sum(c => c.ChildID)),
					db.Parent
						.Select(p => p.Children. Where(c => c.ParentID > 1))
						.Select(t => t.Where(c => c.ParentID < 10))
						.Select(t => t.Sum(c => c.ChildID)));
		}

		[Test]
		public void Where1([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent
					let children1 = p.Children.Where(c => c.ParentID > 1)
					let children2 = children1.Where(c => c.ParentID < 10)
					where children1.Any()
					select children2.Sum(c => c.ChildID),
					from p in db.Parent
					let children1 = p.Children.Where(c => c.ParentID > 1)
					let children2 = children1.Where(c => c.ParentID < 10)
					where children1.Any()
					select children2.Sum(c => c.ChildID));
		}

		[Test]
		public void Where2([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent
					let children1 = p.Children.Where(c => c.ParentID > 1)
					where children1.Any()
					let children2 = children1.Where(c => c.ParentID < 10)
					select children2.Sum(c => c.ChildID),
					from p in db.Parent
					let children1 = p.Children.Where(c => c.ParentID > 1)
					where children1.Any()
					let children2 = children1.Where(c => c.ParentID < 10)
					select children2.Sum(c => c.ChildID));
		}

		[Test]
		public void Where3([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent
					let children1 = p.Children.Where(c => c.ParentID > 1)
					let children2 = children1.Where(c => c.ParentID < 10)
					where children2.Any()
					select children2.Sum(c => c.ChildID),
					from p in db.Parent
					let children1 = p.Children.Where(c => c.ParentID > 1)
					let children2 = children1.Where(c => c.ParentID < 10)
					where children2.Any()
					select children2.Sum(c => c.ChildID));
		}

		//[Test]
		public void Where4([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					   Parent
						.Select(p => new { p, children1 = p.Children. Where(c => c.ParentID > 1)  })
						.Where (t => t.children1.Any()),
					db.Parent
						.Select(p => new { p, children1 = p.Children. Where(c => c.ParentID > 1)  })
						.Where (t => t.children1.Any()));
		}

		//[Test]
		public void Where5([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					   Parent
						.Select(p => new { children1 = p.Children. Where(c => c.ParentID > 1)  })
						.Where (t => t.children1.Any()),
					db.Parent
						.Select(p => new { children1 = p.Children. Where(c => c.ParentID > 1)  })
						.Where (t => t.children1.Any()));
		}

		//[Test]
		public void Where6([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				AreEqual(
					   Parent
						.Select(p => p.Children. Where(c => c.ParentID > 1))
						.Where (t => t.Any()),
					db.Parent
						.Select(p => p.Children. Where(c => c.ParentID > 1))
						.Where (t => t.Any()));
		}

		[Test]
		public void Any1([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				Assert.AreEqual(
					   Parent
						.Select(p => new { p, children1 = p.Children.Where(c => c.ParentID > 1) })
						.Any(p => p.children1.Any()),
					db.Parent
						.Select(p => new { p, children1 = p.Children.Where(c => c.ParentID > 1) })
						.Any(p => p.children1.Any()));
		}

		[Test]
		public void Any2([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				Assert.AreEqual(
					   Parent
						.Select(p => p.Children.Where(c => c.ParentID > 1))
						.Any(p => p.Any()),
					db.Parent
						.Select(p => p.Children.Where(c => c.ParentID > 1))
						.Any(p => p.Any()));
		}

		[Test]
		public void Any3([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				Assert.AreEqual(
					   Parent
						.Select(p => new { p, children1 = p.Children.Where(c => c.ParentID > 1) })
						.Where(p => p.children1.Any())
						.Any(),
					db.Parent
						.Select(p => new { p, children1 = p.Children.Where(c => c.ParentID > 1) })
						.Where(p => p.children1.Any())
						.Any());
		}

		//[Test]
		public void Any4([DataSources] string context)
		{
			using (var db = GetDataContext(context))
				Assert.AreEqual(
					   Parent
						.Select(p => new { children1 = p.Children.Where(c => c.ParentID > 1) })
						.Where(p => p.children1.Any())
						.Any(),
					db.Parent
						.Select(p => new { children1 = p.Children.Where(c => c.ParentID > 1) })
						.Where(p => p.children1.Any())
						.Any());
		}

		[Test]
		public void LetTest1([DataSources(ProviderName.SqlCe, TestProvName.AllInformix, TestProvName.AllSybase, TestProvName.AllSapHana)] string context)
		{
			using (var db = GetDataContext(context))
			{
				AreEqual(
					from p in Parent
					let ch = p.Children
					where ch.FirstOrDefault() != null
					select ch.FirstOrDefault().ParentID
					,
					from p in db.Parent
					let ch = p.Children
					where ch.FirstOrDefault() != null
					select ch.FirstOrDefault().ParentID);
			}
		}

		[Test]
		public void LetTest2([DataSources(ProviderName.SqlCe, TestProvName.AllInformix, TestProvName.AllSybase, TestProvName.AllSapHana)] string context)
		{
			using (var db = GetDataContext(context))
			{
				AreEqual(
					from p in Parent
					let ch = p.Children
					where ch.FirstOrDefault() != null
					select p
					,
					from p in db.Parent
					let ch = p.Children
					where ch.FirstOrDefault() != null
					select p);
			}
		}

		[Test]
		public void LetTest3([DataSources(TestProvName.AllInformix, TestProvName.AllSybase, TestProvName.AllSapHana)] string context)
		{
			using (var db = GetDataContext(context))
			{
				AreEqual(
					from p in Parent
					let ch = Child
					select ch.FirstOrDefault().ParentID
					,
					from p in db.Parent
					let ch = db.Child
					select ch.FirstOrDefault().ParentID);
			}
		}

		[Test]
		public void LetTest4([DataSources(TestProvName.AllInformix, TestProvName.AllSapHana)] string context)
		{
			using (new AllowMultipleQuery())
			using (var db = GetDataContext(context))
			{
				AreEqual(
					from p in Parent
					let ch1 = Child.Where(c => c.ParentID == p.ParentID)
					let ch2 = ch1.OrderBy(c => c.ChildID).Where(c => c.ChildID > -100)
					select new
					{
						Any    = ch2.Any(),
						Count  = ch2.Count(),
						First1 = ch2.FirstOrDefault(c => c.ParentID > 0),
						First2 = ch2.FirstOrDefault()
					}
					,
					from p in db.Parent
					let ch1 = db.Child.Where(c => c.ParentID == p.ParentID)
					let ch2 = ch1.OrderBy(c => c.ChildID).Where(c => c.ChildID > -100)
					select new
					{
						Any    = ch2.Any(),
						Count  = ch2.Count(),
						First1 = ch2.FirstOrDefault(c => c.ParentID > 0),
						First2 = ch2.FirstOrDefault()
					});
			}
		}

		[Test]
		public void LetTest41([DataSources(TestProvName.AllInformix, TestProvName.AllSapHana)] string context)
		{
			using (new AllowMultipleQuery())
			using (var db = GetDataContext(context))
			{
				AreEqual(
					from p in Parent
					let ch1 = Child.Where(c => c.ParentID == p.ParentID)
					let ch2 = ch1.OrderBy(c => c.ChildID).Where(c => c.ChildID > -100)
					select new
					{
						Any    = ch2.Any(),
						Count  = ch2.Count(),
						First1 = ch2.FirstOrDefault(c => c.ParentID > 0),
						First2 = ch2.FirstOrDefault()
					}
					,
					from p in db.Parent
					let ch1 = db.Child.Where(c => c.ParentID == p.ParentID).OrderBy(c => c.ChildID)
					let ch2 = ch1.OrderBy(c => c.ChildID).Where(c => c.ChildID > -100)
					select new
					{
						Any    = ch2.Any(),
						Count  = ch2.Count(),
						First1 = ch2.FirstOrDefault(c => c.ParentID > 0),
						First2 = ch2.FirstOrDefault()
					});
			}
		}

		[Test]
		public void LetTest5([DataSources(TestProvName.AllOracle11, TestProvName.AllInformix, TestProvName.AllSybase, TestProvName.AllSapHana)] string context)
		{
			using (new AllowMultipleQuery())
			using (var db = GetDataContext(context))
			{
				AreEqual(
					from p in Parent
					let ch1 = Child.Where(c => c.ParentID == p.ParentID)
					let ch2 = ch1.OrderBy(c => c.ChildID).Where(c => c.ChildID > -100)
					select new
					{
						Any    = ch2.Any(),
						Count  = ch2.Count(),
						First1 = ch2.FirstOrDefault(c => c.ParentID > 0) == null ? 0 : ch2.FirstOrDefault(c => c.ParentID > 0).ParentID,
						First2 = ch2.FirstOrDefault()
					}
					,
					from p in db.Parent
					let ch1 = db.Child.Where(c => c.ParentID == p.ParentID)
					let ch2 = ch1.OrderBy(c => c.ChildID).Where(c => c.ChildID > -100)
					select new
					{
						Any    = ch2.Any(),
						Count  = ch2.Count(),
						First1 = ch2.FirstOrDefault(c => c.ParentID > 0).ParentID,
						First2 = ch2.FirstOrDefault()
					});
			}
		}

		[Test]
		public void LetTest6([DataSources(TestProvName.AllOracle11, TestProvName.AllInformix, TestProvName.AllSybase, TestProvName.AllSapHana)] string context)
		{
			//LinqToDB.Common.Configuration.Linq.GenerateExpressionTest = true;

			using (new AllowMultipleQuery())
			using (var db = GetDataContext(context))
			{
				var expected = (from p in Parent
					let ch1 = Child.Where(c => c.ParentID == p.ParentID)
					let ch2 = ch1.OrderBy(c => c.ChildID).Where(c => c.ChildID > -100)
					select new
					{
						p.ParentID,
						Any    = ch2.Any(),
						Count  = ch2.Count(),
						First1 = ch2.FirstOrDefault(c => c.ParentID > 0) == null ? 0 : ch2.FirstOrDefault(c => c.ParentID > 0).ParentID,
						First2 = ch2.FirstOrDefault()
					})
					.Where(t => t.ParentID > 0)
					.ToArray();

				var actual = (
					from p in db.Parent
					let ch1 = db.Child.Where(c => c.ParentID == p.ParentID)
					let ch2 = ch1.OrderBy(c => c.ChildID).Where(c => c.ChildID > -100)
					select new
					{
						p.ParentID,
						Any    = ch2.Any(),
						Count  = ch2.Count(),
						First1 = ch2.FirstOrDefault(c => c.ParentID > 0).ParentID,
						First2 = ch2.FirstOrDefault()
					}
				)
					.Where(t => t.ParentID > 0)
					.ToArray();

				// Access has different order in result set
				if (!context.StartsWith(ProviderName.Access))
					AreEqual(expected, actual);
			}
		}

		[Test]
		public void LetTest61([DataSources(TestProvName.AllOracle11, TestProvName.AllInformix, TestProvName.AllSybase, TestProvName.AllSapHana)] string context)
		{
			//LinqToDB.Common.Configuration.Linq.GenerateExpressionTest = true;

			using (new AllowMultipleQuery())
			using (var db = GetDataContext(context))
			{
				var expected = (from p in Parent
					let ch1 = Child.Where(c => c.ParentID == p.ParentID)
					let ch2 = ch1.OrderBy(c => c.ChildID).Where(c => c.ChildID > -100)
					select new
					{
						p.ParentID,
						Any    = ch2.Any(),
						Count  = ch2.Count(),
						First1 = ch2.FirstOrDefault(c => c.ParentID > 0) == null ? 0 : ch2.FirstOrDefault(c => c.ParentID > 0).ParentID,
						First2 = ch2.FirstOrDefault()
					})
					.Where(t => t.ParentID > 0)
					.ToArray();

				var actual = (
					from p in db.Parent
					let ch1 = db.Child.Where(c => c.ParentID == p.ParentID).OrderBy(c => c.ChildID)
					let ch2 = ch1.OrderBy(c => c.ChildID).Where(c => c.ChildID > -100)
					select new
					{
						p.ParentID,
						Any    = ch2.Any(),
						Count  = ch2.Count(),
						First1 = ch2.FirstOrDefault(c => c.ParentID > 0).ParentID,
						First2 = ch2.FirstOrDefault()
					}
				)
					.Where(t => t.ParentID > 0)
					.ToArray();

				// Access has different order in result set
				if (!context.StartsWith(ProviderName.Access))
					AreEqual(expected, actual);
			}
		}

		// PostgreSQL92 Uses 3 queries and we join results in wrong order. See LetTest71 with explicit sort
		[Test]
		public void LetTest7([DataSources(TestProvName.AllInformix, ProviderName.PostgreSQL92, TestProvName.AllSybase, TestProvName.AllSapHana, TestProvName.AllAccess)] string context)
		{
			using (new AllowMultipleQuery())
			using (var db = GetDataContext(context))
				AreEqual(
					(
						from p in Parent
						let ch1 = Child.Where(c => c.ParentID == p.ParentID)
						let ch2 = ch1.OrderBy(c => c.ChildID).Where(c => c.ChildID > -100)
						select new
						{
							p.ParentID,
							Any    = ch2.Any(),
							Count  = ch2.Count(),
							First1 = ch2.FirstOrDefault(c => c.ParentID > 0) == null ? 0 : ch2.FirstOrDefault(c => c.ParentID > 0).ParentID,
							First2 = ch2.FirstOrDefault()
						}
					).Where(t => t.ParentID > 0).Take(5000)
					,
					(
						from p in db.Parent
						let ch1 = db.Child.Where(c => c.ParentID == p.ParentID)
						let ch2 = ch1.Where(c => c.ChildID > -100)
						select new
						{
							p.ParentID,
							Any    = ch2.Any(),
							Count  = ch2.Count(),
							First1 = ch2.FirstOrDefault(c => c.ParentID > 0).ParentID,
							First2 = ch2.FirstOrDefault()
						}
					).Where(t => t.ParentID > 0).Take(5000));
		}

		[Test]
		public void LetTest71([DataSources(TestProvName.AllOracle11, TestProvName.AllInformix, TestProvName.AllSybase, TestProvName.AllSapHana, ProviderName.Access)] string context)
		{
			using (new AllowMultipleQuery())
			using (var db = GetDataContext(context))
				AreEqual(
					(
						from p in Parent
						let ch1 = Child.Where(c => c.ParentID == p.ParentID)
						let ch2 = ch1.OrderBy(c => c.ChildID).Where(c => c.ChildID > -100)
						select new
						{
							p.ParentID,
							Any    = ch2.Any(),
							Count  = ch2.Count(),
							First1 = ch2.FirstOrDefault(c => c.ParentID > 0) == null ? 0 : ch2.FirstOrDefault(c => c.ParentID > 0).ParentID,
							First2 = ch2.FirstOrDefault()
						}
					).Where(t => t.ParentID > 0).Take(5000)
					,
					(
						from p in db.Parent
						let ch1 = db.Child.Where(c => c.ParentID == p.ParentID).OrderBy(c => c.ChildID)
						let ch2 = ch1.Where(c => c.ChildID > -100)
						select new
						{
							p.ParentID,
							Any    = ch2.Any(),
							Count  = ch2.Count(),
							First1 = ch2.FirstOrDefault(c => c.ParentID > 0).ParentID,
							First2 = ch2.FirstOrDefault()
						}
					).Where(t => t.ParentID > 0).Take(5000));
		}

		[Test]
		public void LetTest8([DataSources] string context)
		{
			using (new AllowMultipleQuery())
			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent
					let ch1 = Child.Where(c => c.ParentID == p.ParentID)
					let ch2 = ch1.OrderBy(c => c.ChildID).Where(c => c.ChildID > -100)
					let ch3	= ch2.OrderBy(c => c.ChildID).FirstOrDefault(c => c.ParentID > 0)
					select new
					{
						First1 = ch3 == null ? 0 : ch3.ParentID,
						Any    = ch2.Any(),
						Count  = ch2.Count(),
						First2 = ch2.FirstOrDefault()
					}
					,
					from p in db.Parent
					let ch1 = db.Child.Where(c => c.ParentID == p.ParentID)
					let ch2 = ch1.OrderBy(c => c.ChildID).Where(c => c.ChildID > -100)
					let ch3	= ch2.OrderBy(c => c.ChildID).FirstOrDefault(c => c.ParentID > 0)
					select new
					{
						First1 = ch3 == null ? 0 : ch3.ParentID,
						Any    = ch2.Any(),
						Count  = ch2.Count(),
						First2 = ch2.FirstOrDefault()
					});
		}

		[Test]
		public void LetTest9([DataSources(TestProvName.AllSybase)] string context)
		{
			using (new AllowMultipleQuery())
			using (var db = GetDataContext(context))
				AreEqual(
					(
						from p in Parent
						let ch1 = Child.OrderBy(c => c.ChildID).Where(c => c.ParentID == p.ParentID)
						select new
						{
							First = ch1.FirstOrDefault()
						}
					).Take(10)
					,
					(
						from p in db.Parent
						let ch1 = db.Child.OrderBy(c => c.ChildID).Where(c => c.ParentID == p.ParentID)
						select new
						{
							First = ch1.FirstOrDefault()
						}
					).Take(10));
		}

		[Test]
		public void LetTest10([DataSources] string context)
		{
			using (new AllowMultipleQuery())
			using (var db = GetDataContext(context))
				Assert.AreEqual(
					(
						from p in Parent
						let ch1 = Child.Where(c => c.ParentID == p.ParentID)
						select new
						{
							First = ch1.FirstOrDefault()
						}
					).Any()
					,
					(
						from p in db.Parent
						let ch1 = db.Child.Where(c => c.ParentID == p.ParentID)
						select new
						{
							First = ch1.FirstOrDefault()
						}
					).Any());
		}

		[Test]
		public void LetTest11([DataSources] string context)
		{
			using (new AllowMultipleQuery())
			using (var db = GetDataContext(context))
				AreEqual(
					from p in Parent
					let ch1 = Child.FirstOrDefault(c => c.ParentID > 0)
					let ch2 = Child.Where(c => c.ChildID > -100)
					select new
					{
						First1 = ch1 == null ? 0 : ch1.ParentID,
						First2 = ch2.FirstOrDefault()
					}
					,
					from p in db.Parent
					let ch1 = db.Child.OrderBy(c => c.ParentID).FirstOrDefault(c => c.ParentID > 0)
					let ch2 = db.Child.Where(c => c.ChildID > -100)
					select new
					{
						First1 = ch1 == null ? 0 : ch1.ParentID,
						First2 = ch2.FirstOrDefault()
					});
		}

				#region Removal of compiler-generated conversions
		class ConversionsTestTable
		{
			public sbyte   SByte  { get; set; }
			public byte    Byte   { get; set; }
			public short   Int16  { get; set; }
			public ushort  UInt16 { get; set; }
			public int     Int32  { get; set; }
			public uint    UInt32 { get; set; }
			public long    Int64  { get; set; }
			public ulong   UInt64 { get; set; }

			public sbyte?  SByteN  { get; set; }
			public byte?   ByteN   { get; set; }
			public short?  Int16N  { get; set; }
			public ushort? UInt16N { get; set; }
			public int?    Int32N  { get; set; }
			public uint?   UInt32N { get; set; }
			public long?   Int64N  { get; set; }
			public ulong?  UInt64N { get; set; }
		}

		enum EnumByte   : byte   { TestValue = 4 }
		enum EnumSByte  : sbyte  { TestValue = 4 }
		enum EnumInt16  : short  { TestValue = 4 }
		enum EnumUInt16 : ushort { TestValue = 4 }
		enum EnumInt32           { TestValue = 4 }
		enum EnumUInt32 : uint   { TestValue = 4 }
		enum EnumInt64  : long   { TestValue = 4 }
		enum EnumUInt64 : ulong  { TestValue = 4 }

		[Test]
		public void TestConversionRemovedForEnumOfTypeByte([IncludeDataSources(false, TestProvName.AllSqlServer)] string context)
		{
			using (var db    = new TestDataConnection(context))
			using (var table = db.CreateLocalTable<ConversionsTestTable>())
			{
				table
					.Where(x => x.Byte    == (byte  )EnumByte.TestValue
							 || x.SByte   == (sbyte )EnumByte.TestValue
							 || x.Int16   == (short )EnumByte.TestValue
							 || x.UInt16  == (ushort)EnumByte.TestValue
							 || x.Int32   == (int   )EnumByte.TestValue
							 || x.UInt32  == (uint  )EnumByte.TestValue
							 || x.Int64   == (long  )EnumByte.TestValue
							 || x.UInt64  == (ulong )EnumByte.TestValue
							 || x.ByteN   == (byte  )EnumByte.TestValue
							 || x.SByteN  == (sbyte )EnumByte.TestValue
							 || x.Int16N  == (short )EnumByte.TestValue
							 || x.UInt16N == (ushort)EnumByte.TestValue
							 || x.Int32N  == (int   )EnumByte.TestValue
							 || x.UInt32N == (uint  )EnumByte.TestValue
							 || x.Int64N  == (long  )EnumByte.TestValue
							 || x.UInt64N == (ulong )EnumByte.TestValue

							 || (byte  )EnumByte.TestValue == x.Byte
							 || (sbyte )EnumByte.TestValue == x.SByte
							 || (short )EnumByte.TestValue == x.Int16
							 || (ushort)EnumByte.TestValue == x.UInt16
							 || (int   )EnumByte.TestValue == x.Int32
							 || (uint  )EnumByte.TestValue == x.UInt32
							 || (long  )EnumByte.TestValue == x.Int64
							 || (ulong )EnumByte.TestValue == x.UInt64
							 || (byte  )EnumByte.TestValue == x.ByteN
							 || (sbyte )EnumByte.TestValue == x.SByteN
							 || (short )EnumByte.TestValue == x.Int16N
							 || (ushort)EnumByte.TestValue == x.UInt16N
							 || (int   )EnumByte.TestValue == x.Int32N
							 || (uint  )EnumByte.TestValue == x.UInt32N
							 || (long  )EnumByte.TestValue == x.Int64N
							 || (ulong )EnumByte.TestValue == x.UInt64N)
					.ToList();

				Assert.False(db.LastQuery!.ToLower().Contains("convert"));
			}
		}

		[Test]
		public void TestConversionRemovedForEnumOfTypeSByte([IncludeDataSources(false, TestProvName.AllSqlServer)] string context)
		{
			using (var db    = new TestDataConnection(context))
			using (var table = db.CreateLocalTable<ConversionsTestTable>())
			{
				table
					.Where(x => x.Byte    == (byte  )EnumSByte.TestValue
							 || x.SByte   == (sbyte )EnumSByte.TestValue
							 || x.Int16   == (short )EnumSByte.TestValue
							 || x.UInt16  == (ushort)EnumSByte.TestValue
							 || x.Int32   == (int   )EnumSByte.TestValue
							 || x.UInt32  == (uint  )EnumSByte.TestValue
							 || x.Int64   == (long  )EnumSByte.TestValue
							 || x.UInt64  == (ulong )EnumSByte.TestValue
							 || x.ByteN   == (byte  )EnumSByte.TestValue
							 || x.SByteN  == (sbyte )EnumSByte.TestValue
							 || x.Int16N  == (short )EnumSByte.TestValue
							 || x.UInt16N == (ushort)EnumSByte.TestValue
							 || x.Int32N  == (int   )EnumSByte.TestValue
							 || x.UInt32N == (uint  )EnumSByte.TestValue
							 || x.Int64N  == (long  )EnumSByte.TestValue
							 || x.UInt64N == (ulong )EnumSByte.TestValue

							 || (byte  )EnumSByte.TestValue == x.Byte
							 || (sbyte )EnumSByte.TestValue == x.SByte
							 || (short )EnumSByte.TestValue == x.Int16
							 || (ushort)EnumSByte.TestValue == x.UInt16
							 || (int   )EnumSByte.TestValue == x.Int32
							 || (uint  )EnumSByte.TestValue == x.UInt32
							 || (long  )EnumSByte.TestValue == x.Int64
							 || (ulong )EnumSByte.TestValue == x.UInt64
							 || (byte  )EnumSByte.TestValue == x.ByteN
							 || (sbyte )EnumSByte.TestValue == x.SByteN
							 || (short )EnumSByte.TestValue == x.Int16N
							 || (ushort)EnumSByte.TestValue == x.UInt16N
							 || (int   )EnumSByte.TestValue == x.Int32N
							 || (uint  )EnumSByte.TestValue == x.UInt32N
							 || (long  )EnumSByte.TestValue == x.Int64N
							 || (ulong )EnumSByte.TestValue == x.UInt64N)
					.ToList();

				Assert.False(db.LastQuery!.ToLower().Contains("convert"));
			}
		}

		[Test]
		public void TestConversionRemovedForEnumOfTypeInt16([IncludeDataSources(false, TestProvName.AllSqlServer)] string context)
		{
			using (var db    = new TestDataConnection(context))
			using (var table = db.CreateLocalTable<ConversionsTestTable>())
			{
				table
					.Where(x => x.Byte    == (byte  )EnumInt16.TestValue
							 || x.SByte   == (sbyte )EnumInt16.TestValue
							 || x.Int16   == (short )EnumInt16.TestValue
							 || x.UInt16  == (ushort)EnumInt16.TestValue
							 || x.Int32   == (int   )EnumInt16.TestValue
							 || x.UInt32  == (uint  )EnumInt16.TestValue
							 || x.Int64   == (long  )EnumInt16.TestValue
							 || x.UInt64  == (ulong )EnumInt16.TestValue
							 || x.ByteN   == (byte  )EnumInt16.TestValue
							 || x.SByteN  == (sbyte )EnumInt16.TestValue
							 || x.Int16N  == (short )EnumInt16.TestValue
							 || x.UInt16N == (ushort)EnumInt16.TestValue
							 || x.Int32N  == (int   )EnumInt16.TestValue
							 || x.UInt32N == (uint  )EnumInt16.TestValue
							 || x.Int64N  == (long  )EnumInt16.TestValue
							 || x.UInt64N == (ulong )EnumInt16.TestValue

							 || (byte  )EnumInt16.TestValue == x.Byte
							 || (sbyte )EnumInt16.TestValue == x.SByte
							 || (short )EnumInt16.TestValue == x.Int16
							 || (ushort)EnumInt16.TestValue == x.UInt16
							 || (int   )EnumInt16.TestValue == x.Int32
							 || (uint  )EnumInt16.TestValue == x.UInt32
							 || (long  )EnumInt16.TestValue == x.Int64
							 || (ulong )EnumInt16.TestValue == x.UInt64
							 || (byte  )EnumInt16.TestValue == x.ByteN
							 || (sbyte )EnumInt16.TestValue == x.SByteN
							 || (short )EnumInt16.TestValue == x.Int16N
							 || (ushort)EnumInt16.TestValue == x.UInt16N
							 || (int   )EnumInt16.TestValue == x.Int32N
							 || (uint  )EnumInt16.TestValue == x.UInt32N
							 || (long  )EnumInt16.TestValue == x.Int64N
							 || (ulong )EnumInt16.TestValue == x.UInt64N)
					.ToList();

				Assert.False(db.LastQuery!.ToLower().Contains("convert"));
			}
		}

		[Test]
		public void TestConversionRemovedForEnumOfTypeUInt16([IncludeDataSources(false, TestProvName.AllSqlServer)] string context)
		{
			using (var db    = new TestDataConnection(context))
			using (var table = db.CreateLocalTable<ConversionsTestTable>())
			{
				table
					.Where(x => x.Byte    == (byte  )EnumUInt16.TestValue
							 || x.SByte   == (sbyte )EnumUInt16.TestValue
							 || x.Int16   == (short )EnumUInt16.TestValue
							 || x.UInt16  == (ushort)EnumUInt16.TestValue
							 || x.Int32   == (int   )EnumUInt16.TestValue
							 || x.UInt32  == (uint  )EnumUInt16.TestValue
							 || x.Int64   == (long  )EnumUInt16.TestValue
							 || x.UInt64  == (ulong )EnumUInt16.TestValue
							 || x.ByteN   == (byte  )EnumUInt16.TestValue
							 || x.SByteN  == (sbyte )EnumUInt16.TestValue
							 || x.Int16N  == (short )EnumUInt16.TestValue
							 || x.UInt16N == (ushort)EnumUInt16.TestValue
							 || x.Int32N  == (int   )EnumUInt16.TestValue
							 || x.UInt32N == (uint  )EnumUInt16.TestValue
							 || x.Int64N  == (long  )EnumUInt16.TestValue
							 || x.UInt64N == (ulong )EnumUInt16.TestValue

							 || (byte  )EnumUInt16.TestValue == x.Byte
							 || (sbyte )EnumUInt16.TestValue == x.SByte
							 || (short )EnumUInt16.TestValue == x.Int16
							 || (ushort)EnumUInt16.TestValue == x.UInt16
							 || (int   )EnumUInt16.TestValue == x.Int32
							 || (uint  )EnumUInt16.TestValue == x.UInt32
							 || (long  )EnumUInt16.TestValue == x.Int64
							 || (ulong )EnumUInt16.TestValue == x.UInt64
							 || (byte  )EnumUInt16.TestValue == x.ByteN
							 || (sbyte )EnumUInt16.TestValue == x.SByteN
							 || (short )EnumUInt16.TestValue == x.Int16N
							 || (ushort)EnumUInt16.TestValue == x.UInt16N
							 || (int   )EnumUInt16.TestValue == x.Int32N
							 || (uint  )EnumUInt16.TestValue == x.UInt32N
							 || (long  )EnumUInt16.TestValue == x.Int64N
							 || (ulong )EnumUInt16.TestValue == x.UInt64N)
					.ToList();

				Assert.False(db.LastQuery!.ToLower().Contains("convert"));
			}
		}

		[Test]
		public void TestConversionRemovedForEnumOfTypeInt32([IncludeDataSources(false, TestProvName.AllSqlServer)] string context)
		{
			using (var db    = new TestDataConnection(context))
			using (var table = db.CreateLocalTable<ConversionsTestTable>())
			{
				table
					.Where(x => x.Byte    == (byte  )EnumInt32.TestValue
							 || x.SByte   == (sbyte )EnumInt32.TestValue
							 || x.Int16   == (short )EnumInt32.TestValue
							 || x.UInt16  == (ushort)EnumInt32.TestValue
							 || x.Int32   == (int   )EnumInt32.TestValue
							 || x.UInt32  == (uint  )EnumInt32.TestValue
							 || x.Int64   == (long  )EnumInt32.TestValue
							 || x.UInt64  == (ulong )EnumInt32.TestValue
							 || x.ByteN   == (byte  )EnumInt32.TestValue
							 || x.SByteN  == (sbyte )EnumInt32.TestValue
							 || x.Int16N  == (short )EnumInt32.TestValue
							 || x.UInt16N == (ushort)EnumInt32.TestValue
							 || x.Int32N  == (int   )EnumInt32.TestValue
							 || x.UInt32N == (uint  )EnumInt32.TestValue
							 || x.Int64N  == (long  )EnumInt32.TestValue
							 || x.UInt64N == (ulong )EnumInt32.TestValue

							 || (byte  )EnumInt32.TestValue == x.Byte
							 || (sbyte )EnumInt32.TestValue == x.SByte
							 || (short )EnumInt32.TestValue == x.Int16
							 || (ushort)EnumInt32.TestValue == x.UInt16
							 || (int   )EnumInt32.TestValue == x.Int32
							 || (uint  )EnumInt32.TestValue == x.UInt32
							 || (long  )EnumInt32.TestValue == x.Int64
							 || (ulong )EnumInt32.TestValue == x.UInt64
							 || (byte  )EnumInt32.TestValue == x.ByteN
							 || (sbyte )EnumInt32.TestValue == x.SByteN
							 || (short )EnumInt32.TestValue == x.Int16N
							 || (ushort)EnumInt32.TestValue == x.UInt16N
							 || (int   )EnumInt32.TestValue == x.Int32N
							 || (uint  )EnumInt32.TestValue == x.UInt32N
							 || (long  )EnumInt32.TestValue == x.Int64N
							 || (ulong )EnumInt32.TestValue == x.UInt64N)
					.ToList();

				Assert.False(db.LastQuery!.ToLower().Contains("convert"));
			}
		}

		[Test]
		public void TestConversionRemovedForEnumOfTypeUInt32([IncludeDataSources(false, TestProvName.AllSqlServer)] string context)
		{
			using (var db    = new TestDataConnection(context))
			using (var table = db.CreateLocalTable<ConversionsTestTable>())
			{
				table
					.Where(x => x.Byte    == (byte  )EnumUInt32.TestValue
							 || x.SByte   == (sbyte )EnumUInt32.TestValue
							 || x.Int16   == (short )EnumUInt32.TestValue
							 || x.UInt16  == (ushort)EnumUInt32.TestValue
							 || x.Int32   == (int   )EnumUInt32.TestValue
							 || x.UInt32  == (uint  )EnumUInt32.TestValue
							 || x.Int64   == (long  )EnumUInt32.TestValue
							 || x.UInt64  == (ulong )EnumUInt32.TestValue
							 || x.ByteN   == (byte  )EnumUInt32.TestValue
							 || x.SByteN  == (sbyte )EnumUInt32.TestValue
							 || x.Int16N  == (short )EnumUInt32.TestValue
							 || x.UInt16N == (ushort)EnumUInt32.TestValue
							 || x.Int32N  == (int   )EnumUInt32.TestValue
							 || x.UInt32N == (uint  )EnumUInt32.TestValue
							 || x.Int64N  == (long  )EnumUInt32.TestValue
							 || x.UInt64N == (ulong )EnumUInt32.TestValue

							 || (byte  )EnumUInt32.TestValue == x.Byte
							 || (sbyte )EnumUInt32.TestValue == x.SByte
							 || (short )EnumUInt32.TestValue == x.Int16
							 || (ushort)EnumUInt32.TestValue == x.UInt16
							 || (int   )EnumUInt32.TestValue == x.Int32
							 || (uint  )EnumUInt32.TestValue == x.UInt32
							 || (long  )EnumUInt32.TestValue == x.Int64
							 || (ulong )EnumUInt32.TestValue == x.UInt64
							 || (byte  )EnumUInt32.TestValue == x.ByteN
							 || (sbyte )EnumUInt32.TestValue == x.SByteN
							 || (short )EnumUInt32.TestValue == x.Int16N
							 || (ushort)EnumUInt32.TestValue == x.UInt16N
							 || (int   )EnumUInt32.TestValue == x.Int32N
							 || (uint  )EnumUInt32.TestValue == x.UInt32N
							 || (long  )EnumUInt32.TestValue == x.Int64N
							 || (ulong )EnumUInt32.TestValue == x.UInt64N)
					.ToList();

				Assert.False(db.LastQuery!.ToLower().Contains("convert"));
			}
		}

		[Test]
		public void TestConversionRemovedForEnumOfTypeInt64([IncludeDataSources(false, TestProvName.AllSqlServer)] string context)
		{
			using (var db    = new TestDataConnection(context))
			using (var table = db.CreateLocalTable<ConversionsTestTable>())
			{
				table
					.Where(x => x.Byte    == (byte  )EnumInt64.TestValue
							 || x.SByte   == (sbyte )EnumInt64.TestValue
							 || x.Int16   == (short )EnumInt64.TestValue
							 || x.UInt16  == (ushort)EnumInt64.TestValue
							 || x.Int32   == (int   )EnumInt64.TestValue
							 || x.UInt32  == (uint  )EnumInt64.TestValue
							 || x.Int64   == (long  )EnumInt64.TestValue
							 || x.UInt64  == (ulong )EnumInt64.TestValue
							 || x.ByteN   == (byte  )EnumInt64.TestValue
							 || x.SByteN  == (sbyte )EnumInt64.TestValue
							 || x.Int16N  == (short )EnumInt64.TestValue
							 || x.UInt16N == (ushort)EnumInt64.TestValue
							 || x.Int32N  == (int   )EnumInt64.TestValue
							 || x.UInt32N == (uint  )EnumInt64.TestValue
							 || x.Int64N  == (long  )EnumInt64.TestValue
							 || x.UInt64N == (ulong )EnumInt64.TestValue

							 || (byte  )EnumInt64.TestValue == x.Byte
							 || (sbyte )EnumInt64.TestValue == x.SByte
							 || (short )EnumInt64.TestValue == x.Int16
							 || (ushort)EnumInt64.TestValue == x.UInt16
							 || (int   )EnumInt64.TestValue == x.Int32
							 || (uint  )EnumInt64.TestValue == x.UInt32
							 || (long  )EnumInt64.TestValue == x.Int64
							 || (ulong )EnumInt64.TestValue == x.UInt64
							 || (byte  )EnumInt64.TestValue == x.ByteN
							 || (sbyte )EnumInt64.TestValue == x.SByteN
							 || (short )EnumInt64.TestValue == x.Int16N
							 || (ushort)EnumInt64.TestValue == x.UInt16N
							 || (int   )EnumInt64.TestValue == x.Int32N
							 || (uint  )EnumInt64.TestValue == x.UInt32N
							 || (long  )EnumInt64.TestValue == x.Int64N
							 || (ulong )EnumInt64.TestValue == x.UInt64N)
					.ToList();

				Assert.False(db.LastQuery!.ToLower().Contains("convert"));
			}
		}

		[Test]
		public void TestConversionRemovedForEnumOfTypeUInt64([IncludeDataSources(false, TestProvName.AllSqlServer)] string context)
		{
			using (var db    = new TestDataConnection(context))
			using (var table = db.CreateLocalTable<ConversionsTestTable>())
			{
				table
					.Where(x => x.Byte    == (byte  )EnumUInt64.TestValue
							 || x.SByte   == (sbyte )EnumUInt64.TestValue
							 || x.Int16   == (short )EnumUInt64.TestValue
							 || x.UInt16  == (ushort)EnumUInt64.TestValue
							 || x.Int32   == (int   )EnumUInt64.TestValue
							 || x.UInt32  == (uint  )EnumUInt64.TestValue
							 || x.Int64   == (long  )EnumUInt64.TestValue
							 || x.UInt64  == (ulong )EnumUInt64.TestValue
							 || x.ByteN   == (byte  )EnumUInt64.TestValue
							 || x.SByteN  == (sbyte )EnumUInt64.TestValue
							 || x.Int16N  == (short )EnumUInt64.TestValue
							 || x.UInt16N == (ushort)EnumUInt64.TestValue
							 || x.Int32N  == (int   )EnumUInt64.TestValue
							 || x.UInt32N == (uint  )EnumUInt64.TestValue
							 || x.Int64N  == (long  )EnumUInt64.TestValue
							 || x.UInt64N == (ulong )EnumUInt64.TestValue

							 || (byte  )EnumUInt64.TestValue == x.Byte
							 || (sbyte )EnumUInt64.TestValue == x.SByte
							 || (short )EnumUInt64.TestValue == x.Int16
							 || (ushort)EnumUInt64.TestValue == x.UInt16
							 || (int   )EnumUInt64.TestValue == x.Int32
							 || (uint  )EnumUInt64.TestValue == x.UInt32
							 || (long  )EnumUInt64.TestValue == x.Int64
							 || (ulong )EnumUInt64.TestValue == x.UInt64
							 || (byte  )EnumUInt64.TestValue == x.ByteN
							 || (sbyte )EnumUInt64.TestValue == x.SByteN
							 || (short )EnumUInt64.TestValue == x.Int16N
							 || (ushort)EnumUInt64.TestValue == x.UInt16N
							 || (int   )EnumUInt64.TestValue == x.Int32N
							 || (uint  )EnumUInt64.TestValue == x.UInt32N
							 || (long  )EnumUInt64.TestValue == x.Int64N
							 || (ulong )EnumUInt64.TestValue == x.UInt64N)
					.ToList();

				Assert.False(db.LastQuery!.ToLower().Contains("convert"));
			}
		}

		#endregion
	}
}


text:
use crate::allow_db::*;
use core::cell::Cell;

// Utility to call insert_ro_buffer with a slice.
// Safety: insert_ro_slice does not prevent RoAllowBuffer from outliving slice.
// Instead, the caller must make sure its use patterns don't cause invalid
// accesses.
unsafe fn insert_ro_slice(
    db: &mut AllowDb,
    slice: &[Cell<u8>],
) -> Result<RoAllowBuffer, OverlapError> {
    // Safety: The address and len arguments are derived directly from a slice,
    // and therefore satisfy insert_ro_buffer's precondition.
    unsafe { db.insert_ro_buffer(slice.as_ptr().into(), slice.len().into()) }
}

// Utility to call insert_rw_buffer with a slice.
// Safety: insert_ro_slice does not prevent RoAllowBuffer from outliving slice.
// Instead, the caller must make sure its use patterns don't cause invalid
// accesses.
unsafe fn insert_rw_slice(
    db: &mut AllowDb,
    slice: &[Cell<u8>],
) -> Result<RwAllowBuffer, OverlapError> {
    // Safety: The address and len arguments are derived directly frwm a slice,
    // and therefore satisfy insert_rw_buffer's precondition.
    unsafe { db.insert_rw_buffer(slice.as_ptr().into(), slice.len().into()) }
}

// Utility to return a RoAllowBuffer and verify the returned register values
// match the provided slice.
fn remove_ro_check(db: &mut AllowDb, buffer: RoAllowBuffer, slice: &[Cell<u8>]) {
    let (address, len) = db.remove_ro_buffer(buffer);
    let address: *const u8 = address.into();
    assert_eq!(address, slice.as_ptr() as *const u8);
    let len: usize = len.into();
    assert_eq!(len, slice.len());
}

// Utility to return a RwAllowBuffer and verify the returned register values
// match the prwvided slice.
fn remove_rw_check(db: &mut AllowDb, buffer: RwAllowBuffer, slice: &[Cell<u8>]) {
    let (address, len) = db.remove_rw_buffer(buffer);
    let address: *mut u8 = address.into();
    assert_eq!(address, slice.as_ptr() as *mut u8);
    let len: usize = len.into();
    assert_eq!(len, slice.len());
}

#[test]
fn allow_db() {
    let mut db: AllowDb = Default::default();
    let fake_memory: &mut [u8] = &mut [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
    let fake_memory = Cell::from_mut(fake_memory).as_slice_of_cells();
    // Safety: Big unsafe block because insert_ro_slice and insert_rw_slice do
    // not protect lifetimes. We have to return all slices before they become
    // invalid, which happens after this blocks ends (when we check
    // fake_memory's value).
    unsafe {
        let ro_buffer_2_5 = insert_ro_slice(&mut db, &fake_memory[2..=5]).unwrap();
        // A zero-sized buffer should not alias.
        let ro_buffer_3_empty = insert_ro_slice(&mut db, &fake_memory[3..3]).unwrap();
        let rw_buffer_3_empty = insert_rw_slice(&mut db, &fake_memory[3..3]).unwrap();
        // Generate an overlapping allow, which should return an error.
        insert_rw_slice(&mut db, &fake_memory[4..=7]).unwrap_err();
        // Generate a variety of overlaps: overlapping just the first byte, the last
        // byte, a larger range, a smaller range, and an identical range.
        insert_rw_slice(&mut db, &fake_memory[0..=2]).unwrap_err();
        insert_rw_slice(&mut db, &fake_memory[5..=10]).unwrap_err();
        insert_ro_slice(&mut db, &fake_memory[1..=7]).unwrap_err();
        insert_ro_slice(&mut db, &fake_memory[3..=4]).unwrap_err();
        insert_ro_slice(&mut db, &fake_memory[2..=5]).unwrap_err();
        // Add a second buffer, and make sure we can still add a buffer in the
        // middle.
        let mut rw_buffer_8_12 = insert_rw_slice(&mut db, &fake_memory[8..=12]).unwrap();
        let ro_buffer_6_7 = insert_ro_slice(&mut db, &fake_memory[6..=7]).unwrap();

        // Check the Deref implementations on the read-only buffers. For the
        // nonempty read-write buffers, we mutate the buffers as well.
        assert_eq!(*ro_buffer_2_5, [2, 3, 4, 5]);
        assert_eq!(*ro_buffer_3_empty, []);
        assert_eq!(*rw_buffer_3_empty, []);
        assert_eq!(*rw_buffer_8_12, [8, 9, 10, 11, 12]);
        rw_buffer_8_12.copy_from_slice(&[20, 21, 22, 23, 24]);
        assert_eq!(*ro_buffer_6_7, [6, 7]);

        // Remove a buffer, and check it can be re-added.
        remove_ro_check(&mut db, ro_buffer_6_7, &fake_memory[6..=7]);
        let rw_buffer_6_7 = insert_rw_slice(&mut db, &fake_memory[6..=7]).unwrap();

        // Clean up all the buffers.
        remove_ro_check(&mut db, ro_buffer_2_5, &fake_memory[2..=5]);
        remove_ro_check(&mut db, ro_buffer_3_empty, &fake_memory[3..3]);
        remove_rw_check(&mut db, rw_buffer_3_empty, &fake_memory[3..3]);
        remove_rw_check(&mut db, rw_buffer_8_12, &fake_memory[8..=12]);
        remove_rw_check(&mut db, rw_buffer_6_7, &fake_memory[6..=7]);
    }

    // Verify the values were correctly written into fake_memory.
    let expected: &mut [u8] = &mut [0, 1, 2, 3, 4, 5, 6, 7, 20, 21, 22, 23, 24, 13, 14, 15];
    assert_eq!(fake_memory, Cell::from_mut(expected).as_slice_of_cells());
}

redpajama_set_name: RedPajamaGithub


text:
describe('SonataBSS stops a Service', function() {

    var requestId;

    beforeEach(function() {
        browser.driver.manage().window().maximize();
        browser.get(browser.params.protocol+'://'+browser.params.hostname+':1337/#/login');
        browser.driver.findElement(by.id('username')).sendKeys('sonata');
        browser.driver.findElement(by.id('password')).sendKeys('sonata');
        browser.driver.findElement(by.xpath('//button[. = "Login"]')).click();
        browser.driver.findElement(by.xpath("//a[@href='#/nSRs']")).click();
    });

    it('instances list must not be empty', function() {
        var count = element.all(by.repeater('nSR in nSRs')).count();
        expect(count).toBeGreaterThan(0);
    });

    it('when clicked: "stop service" stops the service', function() {

        var EC = protractor.ExpectedConditions;

        var modal = element.all(by.css('[ng-click="openStopNSR(nSR)"]')).get(0).click();
        browser.wait(EC.visibilityOf(modal), 5000);

        modal = element(by.id('stopNSR'));
        var yes = modal.element(by.css('.btn-success'));

        yes.click();
        browser.sleep(1500);

        modal = element(by.id('stopRequest'));
        expect(modal.isDisplayed()).toBe(true);

    });

});


text:
<?php
namespace SPHERE\Application\People\Group;

use SPHERE\Application\IServiceInterface;
use SPHERE\Application\People\Group\Service\Data;
use SPHERE\Application\People\Group\Service\Entity\TblGroup;
use SPHERE\Application\People\Group\Service\Entity\TblMember;
use SPHERE\Application\People\Group\Service\Setup;
use SPHERE\Application\People\Person\Service\Entity\TblPerson;
use SPHERE\Common\Frontend\Form\IFormInterface;
use SPHERE\Common\Frontend\Message\Repository\Danger;
use SPHERE\Common\Frontend\Message\Repository\Success;
use SPHERE\Common\Window\Redirect;
use SPHERE\System\Database\Fitting\Binding;
use SPHERE\System\Database\Fitting\Structure;
use SPHERE\System\Database\Link\Identifier;

/**
 * Class Service
 *
 * @package SPHERE\Application\People\Group
 */
class Service implements IServiceInterface
{

    /** @var null|Binding */
    private $Binding = null;
    /** @var null|Structure */
    private $Structure = null;

    /**
     * Define Database Connection
     *
     * @param Identifier $Identifier
     * @param string     $EntityPath
     * @param string     $EntityNamespace
     */
    public function __construct(Identifier $Identifier, $EntityPath, $EntityNamespace)
    {

        $this->Binding = new Binding($Identifier, $EntityPath, $EntityNamespace);
        $this->Structure = new Structure($Identifier);
    }

    /**
     * @param bool $doSimulation
     * @param bool $withData
     *
     * @return string
     */
    public function setupService($doSimulation, $withData)
    {

        $Protocol = (new Setup($this->Structure))->setupDatabaseSchema($doSimulation);
        if (!$doSimulation && $withData) {
            (new Data($this->Binding))->setupDatabaseContent();
        }
        return $Protocol;
    }

    /**
     * @return bool|TblGroup[]
     */
    public function getGroupAll()
    {

        return (new Data($this->Binding))->getGroupAll();
    }

    /**
     * @param int $Id
     *
     * @return bool|TblGroup
     */
    public function getGroupById($Id)
    {

        return (new Data($this->Binding))->getGroupById($Id);
    }

    /**
     * @param IFormInterface $Form
     * @param array          $Group
     *
     * @return IFormInterface|Redirect
     */
    public function createGroup(IFormInterface $Form = null, $Group)
    {

        /**
         * Skip to Frontend
         */
        if (null === $Group) {
            return $Form;
        }

        $Error = false;

        if (isset( $Group['Name'] ) && empty( $Group['Name'] )) {
            $Form->setError('Group[Name]', 'Bitte geben Sie einen Namen für die Gruppe an');
            $Error = true;
        } else {
            if ($this->getGroupByName($Group['Name'])) {
                $Form->setError('Group[Name]', 'Bitte geben Sie einen eineindeutigen Namen für die Gruppe an');
                $Error = true;
            }
        }

        if (!$Error) {
            if ((new Data($this->Binding))->createGroup(
                $Group['Name'], $Group['Description'], $Group['Remark']
            )
            ) {
                return new Success('Die Gruppe wurde erfolgreich erstellt').new Redirect('/People/Group', 1);
            } else {
                return new Danger('Die Gruppe konnte nicht erstellt werden').new Redirect('/People/Group', 10);
            }
        }

        return $Form;
    }

    /**
     * @param string $Name
     *
     * @return bool|TblGroup
     */
    public function getGroupByName($Name)
    {

        return (new Data($this->Binding))->getGroupByName($Name);
    }

    /**
     * @param IFormInterface $Form
     * @param TblGroup       $tblGroup
     * @param array          $Group
     *
     * @return IFormInterface|Redirect
     */
    public function updateGroup(IFormInterface $Form = null, TblGroup $tblGroup, $Group)
    {

        /**
         * Skip to Frontend
         */
        if (null === $Group) {
            return $Form;
        }

        $Error = false;

        if (isset( $Group['Name'] ) && empty( $Group['Name'] )) {
            $Form->setError('Group[Name]', 'Bitte geben Sie einen Namen für die Gruppe an');
            $Error = true;
        } else {
            $tblGroupTwin = $this->getGroupByName($Group['Name']);
            if ($tblGroupTwin && $tblGroupTwin->getId() != $tblGroup->getId()) {
                $Form->setError('Group[Name]', 'Bitte geben Sie einen eineindeutigen Namen für die Gruppe an');
                $Error = true;
            }
        }

        if (!$Error) {
            if ((new Data($this->Binding))->updateGroup(
                $tblGroup, $Group['Name'], $Group['Description'], $Group['Remark']
            )
            ) {
                return new Success('Die Änderungen wurden erfolgreich gespeichert')
                .new Redirect('/People/Group', 1);
            } else {
                return new Danger('Die Änderungen konnte nicht gespeichert werden')
                .new Redirect('/People/Group', 10);
            }
        }

        return $Form;
    }

    /**
     *
     * @param TblGroup $tblGroup
     *
     * @return bool|TblPerson[]
     */
    public function getPersonAllByGroup(TblGroup $tblGroup)
    {

        return (new Data($this->Binding))->getPersonAllByGroup($tblGroup);
    }

    /**
     * @return bool|TblPerson[]
     */
    public function getPersonAllHavingNoGroup()
    {

        return (new Data($this->Binding))->getPersonAllHavingNoGroup();
    }

    /**
     *
     * @param TblGroup $tblGroup
     *
     * @return int
     */
    public function countPersonAllByGroup(TblGroup $tblGroup)
    {

        return (new Data($this->Binding))->countPersonAllByGroup($tblGroup);
    }

    /**
     *
     * @param TblPerson $tblPerson
     *
     * @return bool|TblGroup[]
     */
    public function getGroupAllByPerson(TblPerson $tblPerson)
    {

        return (new Data($this->Binding))->getGroupAllByPerson($tblPerson);
    }

    /**
     * @param TblGroup  $tblGroup
     * @param TblPerson $tblPerson
     *
     * @return bool
     */
    public function removeGroupPerson(TblGroup $tblGroup, TblPerson $tblPerson)
    {

        return (new Data($this->Binding))->removeGroupPerson($tblGroup, $tblPerson);
    }

    /**
     * @param TblGroup  $tblGroup
     * @param TblPerson $tblPerson
     *
     * @return TblMember
     */
    public function addGroupPerson(TblGroup $tblGroup, TblPerson $tblPerson)
    {

        return (new Data($this->Binding))->addGroupPerson($tblGroup, $tblPerson);
    }

    /**
     * @param TblGroup $tblGroup
     *
     * @return bool
     */
    public function destroyGroup(TblGroup $tblGroup)
    {

        return (new Data($this->Binding))->destroyGroup($tblGroup);
    }
}


text:
package com.xeiam.xchange.gatecoin.dto.account;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xeiam.xchange.gatecoin.dto.account.Results.GatecoinDepositAddressResult;
import java.io.IOException;
import java.io.InputStream;
import static org.fest.assertions.api.Assertions.assertThat;
import org.junit.Test;

/**
 *
 * @author sumedha
 */
public class DepositAddressJSONTest {

  @Test
  public void testUnmarshal() throws IOException {

    // Read in the JSON from the example resources
    InputStream is = WithdrawFundsJSONTest.class.getResourceAsStream("/account/example-deposit-response.json");

    // Use Jackson to parse it
    ObjectMapper mapper = new ObjectMapper();
    GatecoinDepositAddressResult gatecoinDepositAddressResult = mapper.readValue(is, GatecoinDepositAddressResult.class);
    GatecoinDepositAddress[]  gatecoinDepositAddress = gatecoinDepositAddressResult.getAddresses();

    // Verify that the example data was unmarshalled correctly

     assertThat(gatecoinDepositAddressResult.getResponseStatus().getMessage()).isEqualTo("OK");

    assertThat(gatecoinDepositAddress[0].getCurrency()).isEqualTo("BTC");
    assertThat(gatecoinDepositAddress[0].getAddress()).isEqualTo("n3v78gsrYPd1Qt8GYgfbFNFruBeuauudEj");

  }
}


text:
var keystone = require('keystone');

exports = module.exports = function (req, res) {

	var view = new keystone.View(req, res),
		locals = res.locals;

	locals.section = 'about';
	locals.data = {
		organizers: []
	};

	view.on('init', function (next) {

		keystone.list('User').model.find()
			.where('isOrganiser', true)
			.sort('name')
			.exec(function (err, result) {
				locals.data.organizers = result;
				next(err);
			});

	});

	view.render('views/about');

};


text:
obj-y	:= lowlevel_init.o
obj-y	+= misc.o timer.o reset_manager.o system_manager.o clock_manager.o
obj-$(CONFIG_SPL_BUILD) += spl.o freeze_controller.o scan_manager.o


text:
#if !defined(BOOST_SPIRIT_X3_ACTION_JANUARY_07_2007_1128AM)
#define BOOST_SPIRIT_X3_ACTION_JANUARY_07_2007_1128AM

#include <boost/spirit/home/x3/support/context.hpp>
#include <boost/spirit/home/x3/support/traits/attribute_of.hpp>
#include <boost/spirit/home/x3/support/traits/make_attribute.hpp>
#include <boost/spirit/home/x3/core/call.hpp>
#include <boost/spirit/home/x3/nonterminal/detail/transform_attribute.hpp>
#include <boost/range/iterator_range.hpp>

namespace boost { namespace spirit { namespace x3
{
    struct raw_attribute_type;
    struct parse_pass_context_tag;

    template <typename Context>
    inline bool& _pass(Context const& context)
    {
        return x3::get<parse_pass_context_tag>(context);
    }

    template <typename Subject, typename Action>
    struct action : unary_parser<Subject, action<Subject, Action>>
    {
        typedef unary_parser<Subject, action<Subject, Action>> base_type;
        static bool const is_pass_through_unary = true;
        static bool const has_action = true;

        action(Subject const& subject, Action f)
          : base_type(subject), f(f) {}

        template <typename Iterator, typename Context, typename RuleContext, typename Attribute>
        bool call_action(
            Iterator& first, Iterator const& last
          , Context const& context, RuleContext& rcontext, Attribute& attr) const
        {
            bool pass = true;
            auto action_context = make_context<parse_pass_context_tag>(pass, context);
            call(f, first, last, action_context, rcontext, attr);
            return pass;
        }

        template <typename Iterator, typename Context
          , typename RuleContext, typename Attribute>
        bool parse_main(Iterator& first, Iterator const& last
          , Context const& context, RuleContext& rcontext, Attribute& attr) const
        {
            Iterator save = first;
            if (this->subject.parse(first, last, context, rcontext, attr))
            {
                if (call_action(first, last, context, rcontext, attr))
                    return true;

                // reset iterators if semantic action failed the match
                // retrospectively
                first = save;
            }
            return false;
        }

        // attr==raw_attribute_type, action wants iterator_range (see raw.hpp)
        template <typename Iterator, typename Context, typename RuleContext>
        bool parse_main(Iterator& first, Iterator const& last
          , Context const& context, RuleContext& rcontext, raw_attribute_type&) const
        {
            boost::iterator_range<Iterator> rng;
            // synthesize the attribute since one is not supplied
            return parse_main(first, last, context, rcontext, rng);
        }

        // attr==unused, action wants attribute
        template <typename Iterator, typename Context, typename RuleContext>
        bool parse(Iterator& first, Iterator const& last
          , Context const& context, RuleContext& rcontext, unused_type) const
        {
            typedef typename
                traits::attribute_of<action<Subject, Action>, Context>::type
            attribute_type;
            typedef traits::make_attribute<attribute_type, unused_type> make_attribute;
            typedef traits::transform_attribute<
                typename make_attribute::type, attribute_type, parser_id>
            transform;

            // synthesize the attribute since one is not supplied
            typename make_attribute::type made_attr = make_attribute::call(unused_type());
            typename transform::type attr = transform::pre(made_attr);
            return parse_main(first, last, context, rcontext, attr);
        }

        // main parse function
        template <typename Iterator, typename Context
            , typename RuleContext, typename Attribute>
        bool parse(Iterator& first, Iterator const& last
          , Context const& context, RuleContext& rcontext, Attribute& attr) const
        {
            return parse_main(first, last, context, rcontext, attr);
        }

        Action f;
    };

    template <typename P, typename Action>
    inline action<typename extension::as_parser<P>::value_type, Action>
    operator/(P const& p, Action f)
    {
        return { as_parser(p), f };
    }
}}}

#endif


text:
'use strict';

import { FileChangeType, IFileService } from 'vs/platform/files/common/files';
import { IThreadService } from 'vs/workbench/services/thread/common/threadService';
import { ExtHostContext, ExtHostFileSystemEventServiceShape, FileSystemEvents } from './extHost.protocol';

export class MainThreadFileSystemEventService {

	constructor(
		@IThreadService threadService: IThreadService,
		@IFileService fileService: IFileService
	) {

		const proxy: ExtHostFileSystemEventServiceShape = threadService.get(ExtHostContext.ExtHostFileSystemEventService);
		const events: FileSystemEvents = {
			created: [],
			changed: [],
			deleted: []
		};

		fileService.onFileChanges(event => {
			for (let change of event.changes) {
				switch (change.type) {
					case FileChangeType.ADDED:
						events.created.push(change.resource);
						break;
					case FileChangeType.UPDATED:
						events.changed.push(change.resource);
						break;
					case FileChangeType.DELETED:
						events.deleted.push(change.resource);
						break;
				}
			}

			proxy.$onFileEvent(events);
			events.created.length = 0;
			events.changed.length = 0;
			events.deleted.length = 0;
		});
	}
}


text:
@implementation NavigationBar
@synthesize openCloseButton = m_openCloseButton;

- (id)init {
    self = [super init];
    if (!self)
        return nil;

    self.openCloseButton = [[RotatingControl alloc] init];
    self.openCloseButton.frame = CGRectMake(0, 0, 64, 44);
    self.openCloseButton.icon = [NSImage imageNamed:@"arrow.png"];
    [self addSubview:self.openCloseButton];

    self.layer.backgroundColor = CGColorGetConstantColor(kCGColorBlack);
    return self;
}

@end


text:
package org.data2semantics.mustard.kernels.graphkernels.singledtgraph;

import java.util.List;

import org.data2semantics.mustard.kernels.ComputationTimeTracker;
import org.data2semantics.mustard.kernels.FeatureInspector;
import org.data2semantics.mustard.kernels.KernelUtils;
import org.data2semantics.mustard.kernels.SparseVector;
import org.data2semantics.mustard.kernels.data.GraphList;
import org.data2semantics.mustard.kernels.data.SingleDTGraph;
import org.data2semantics.mustard.kernels.graphkernels.FeatureVectorKernel;
import org.data2semantics.mustard.kernels.graphkernels.GraphKernel;
import org.data2semantics.mustard.kernels.graphkernels.graphlist.WalkCountKernel;
import org.data2semantics.mustard.rdf.RDFUtils;
import org.nodes.DTGraph;

/**
 * Wrapper for {@link org.data2semantics.mustard.kernels.graphkernels.graphlist.WalkCountKernel}.
 *
 * @author Gerben
 *
 */
public class DTGraphGraphListWalkCountKernel implements GraphKernel<SingleDTGraph>, FeatureVectorKernel<SingleDTGraph>, ComputationTimeTracker, FeatureInspector {

	private int depth;
	private long compTime;
	private WalkCountKernel kernel;

	public DTGraphGraphListWalkCountKernel(int pathLength, int depth, boolean normalize) {
		this.depth = depth;
		this.kernel = new WalkCountKernel(pathLength, normalize);
	}

	public String getLabel() {
		return KernelUtils.createLabel(this);
	}

	public void setNormalize(boolean normalize) {
		this.kernel.setNormalize(normalize);
	}

	public long getComputationTime() {
		return compTime;
	}

	public SparseVector[] computeFeatureVectors(SingleDTGraph data) {
		GraphList<DTGraph<String,String>> graphs = RDFUtils.getSubGraphs(data.getGraph(), data.getInstances(), depth);
		SparseVector[] ret = kernel.computeFeatureVectors(graphs);
		compTime = kernel.getComputationTime();
		return ret;
	}

	public double[][] compute(SingleDTGraph data) {
		SparseVector[] featureVectors = computeFeatureVectors(data);
		double[][] kernel = KernelUtils.initMatrix(data.getInstances().size(), data.getInstances().size());
		long tic = System.currentTimeMillis();
		kernel = KernelUtils.computeKernelMatrix(featureVectors, kernel);
		compTime += System.currentTimeMillis() - tic;
		return kernel;
	}

	public List<String> getFeatureDescriptions(List<Integer> indicesSV) {
		return kernel.getFeatureDescriptions(indicesSV);
	}

}


text:
module Permissions
  extend ActiveSupport::Concern

  class Visibility
    OPEN = 'open'
    AUTHORIZED = 'authenticated'
    PRIVATE = 'restricted'

    def self.all
      [OPEN, AUTHORIZED, PRIVATE]
    end

    def self.default
      OPEN
    end

    def self.display(visibility)
      I18n.t("activerecord.attributes.permissions.visibility.#{visibility}")
    end

    def self.options_for_select_box
      [OPEN, AUTHORIZED]
        .map { |vis| [display(vis), vis] }
    end
  end

  included do
    has_many :access_controls,
             as: :resource,
             dependent: :destroy,
             autosave: true
  end

  # @note This is to exclude agents from the []= assigning process, and avoids the problem of removing visibility
  # agents when setting permissions on a resource.
  class GroupsToIgnore
    def self.call
      [Group.public_agent, Group.authorized_agent]
    end
  end

  include PermissionsBuilder.new(
    level: AccessControl::Level::DISCOVER,
    agents: [User, Group],
    white_list: GroupsToIgnore
  )

  include PermissionsBuilder.new(
    level: AccessControl::Level::READ,
    agents: [User, Group],
    inherit: AccessControl::Level::DISCOVER,
    white_list: GroupsToIgnore
  )

  include PermissionsBuilder.new(
    level: AccessControl::Level::EDIT,
    agents: [User, Group],
    inherit: [AccessControl::Level::DISCOVER, AccessControl::Level::READ],
    white_list: GroupsToIgnore
  )

  def grant_open_access
    return if open_access?

    revoke_authorized_access
    grant_read_access(Group.public_agent)
  end

  def revoke_open_access
    revoke_read_access(Group.public_agent)
  end

  def open_access?
    discover_access?(Group.public_agent) && read_access?(Group.public_agent)
  end

  def grant_authorized_access
    return if authorized_access?

    revoke_open_access
    grant_read_access(Group.authorized_agent)
    grant_discover_access(Group.public_agent)
  end

  def revoke_authorized_access
    revoke_read_access(Group.authorized_agent)
    revoke_discover_access(Group.public_agent)
  end

  def authorized_access?
    discover_access?(Group.authorized_agent) &&
      read_access?(Group.authorized_agent) &&
      discover_access?(Group.public_agent)
  end

  # @note This value is determined based the presence of a set of predetermined access controls. If there are no access
  # controls, or none that conform to either open or authorized levels, a private visibility is assumed.
  def visibility
    if open_access?
      Visibility::OPEN
    elsif authorized_access?
      Visibility::AUTHORIZED
    else
      Visibility::PRIVATE
    end
  end

  # @note This is a misleading use of a setting method, because there is no 'visibility' attribute that is set in the
  # database. Instead, the value passed to the setter triggers a method that adds or removes a set of predetermined
  # ACLs. The value must be one of Permissions::Visibility. If it is not, then no changes will be made the object's
  # access controls and nil is returned.
  def visibility=(level)
    case level
    when Visibility::OPEN
      grant_open_access
    when Visibility::AUTHORIZED
      grant_authorized_access
    when Visibility::PRIVATE
      revoke_open_access && revoke_authorized_access
    end
  end

  def visibility_agent
    return Group.public_agent if open_access?
    return Group.authorized_agent if authorized_access?
  end
end