Example #1
0
        public void SingletonEqualitySane()
        {
            var a = SmallSet<string>.Create("A");
            var b = SmallSet<string>.Create(new HashSet<string> {"A"});
            var c = SmallSet<string>.Create(new[] { "A" });
            var d = new HashSet<string> {"A"};

            Assert.IsType(typeof(SmallSet<string>), a);
            Assert.IsType(typeof(SmallSet<string>), b);
            Assert.IsType(typeof(SmallSet<string>), c);
            Assert.IsNotType(typeof(SmallSet<string>), d);

            var diff = SmallSet<string>.Create("B");

            Assert.Equal(a, b);
            Assert.True(a.SetEquals(b));
            Assert.Equal(a, c);
            Assert.Equal(b, c);
            Assert.True(a.SetEquals(d));
            Assert.True(d.SetEquals(a));
            Assert.True(d.SetEquals(b));
            Assert.True(d.SetEquals(c));

            Assert.NotEqual(a, diff);
            Assert.NotEqual(b, diff);
            Assert.NotEqual(c, diff);

            Assert.False(diff.SetEquals(a));
            Assert.False(a.SetEquals(diff));
            Assert.False(diff.SetEquals(b));
            Assert.False(diff.SetEquals(c));
            Assert.False(diff.SetEquals(d));
        }
Example #2
0
        public void AddTest()
        {
            var tree = new ShieldedTree<int, object>();

            Assert.Throws<InvalidOperationException>(() =>
                tree.Add(1, new object()));
            Assert.Throws<InvalidOperationException>(() =>
                ((ICollection<KeyValuePair<int, object>>)tree).Add(
                    new KeyValuePair<int, object>(1, new object())));

            var objectA = new object();
            var objectB = new object();
            Shield.InTransaction(() => {
                tree.Add(1, objectA);
                ((ICollection<KeyValuePair<int, object>>)tree).Add(
                    new KeyValuePair<int, object>(2, objectB));
                Assert.AreEqual(2, tree.Count);
                Assert.AreEqual(objectA, tree[1]);
                Assert.AreEqual(objectB, tree[2]);
            });
            Assert.AreEqual(2, tree.Count);
            Assert.AreEqual(objectA, tree[1]);
            Assert.AreEqual(objectB, tree[2]);

            var objectA2 = new object();
            var expectedValues = new HashSet<object>(new object[] { objectA, objectA2 });
            Shield.InTransaction(() => {
                tree.Add(1, objectA2);
                Assert.AreEqual(3, tree.Count);
                Assert.IsTrue(expectedValues.SetEquals(tree.Range(1, 1).Select(kvp => kvp.Value)));
            });
            Assert.AreEqual(3, tree.Count);
            Shield.InTransaction(
                () => Assert.IsTrue(expectedValues.SetEquals(tree.Range(1, 1).Select(kvp => kvp.Value))));
        }
Example #3
0
        public void BigSetSane()
        {
            var values = new[] { "A", "B" };
            var a = SmallSet<string>.Create(values);
            var b = new HashSet<string>(values);
            var c = SmallSet<string>.Create(b);

            Assert.IsNotType(typeof(SmallSet<string>), a);
            Assert.IsNotType(typeof(SmallSet<string>), c);
            Assert.True(a.SetEquals(b));
            Assert.True(b.SetEquals(a));
            Assert.True(b.SetEquals(c));
        }
        public int GetPrefixSuffixSetCount(int[] set)
        {
            int output = 0;

            var prefixesNumbersUsed = new HashSet<int>();
            var suffixNumbersUsed = new HashSet<int>();

            foreach (var rangePair in GetPrefixSuffixIndexRanges(set))
            {
                var prefixRange = rangePair.Prefix;
                var suffixRange = rangePair.Suffix;

                prefixesNumbersUsed.Add(prefixRange.Number);
                suffixNumbersUsed.Add(suffixRange.Number);

                if (prefixesNumbersUsed.SetEquals(suffixNumbersUsed))
                {
                    //No need to keep comparing values that worked already
                    prefixesNumbersUsed.Clear();
                    suffixNumbersUsed.Clear();
                    output += (prefixRange.Range * suffixRange.Range);
                }

                if (output > TOO_LARGE)
                    return TOO_LARGE;
            }

            return output;
        }
        public void ShuffleRange()
        {
            var set = new HashSet<int>(Enumerable.Range(0, 100));
            var result = RandomHelper.ShuffleRange(100).ToArray();

            Assert.IsTrue(set.SetEquals(result));
        }
Example #6
0
        public void ScanForTestClasses()
        {
            Assembly assembly = Assembly.GetAssembly(typeof(AssemblyTestMock1));

            HashSet<Type> expectedTestClasses = new HashSet<Type> {typeof(AssemblyTestMock1), typeof(AssemblyTestMock2)};
            AssertEx.That(expectedTestClasses.SetEquals(AssemblyScanner.GetTestClassesIn(assembly)), Is.True());
        }
Example #7
0
        static void Main(string[] args)
        {
            var one = new HashSet<MailAddress> { new MailAddress("[email protected]"), new MailAddress("[email protected]") };
            var two = new HashSet<MailAddress> { new MailAddress("[email protected]"), new MailAddress("[email protected]"), };

            var equal = one.SetEquals(two);

            var sink = Observable
                .FromEventPattern<NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>(x => oc.CollectionChanged += x, y => oc.CollectionChanged -= y)
                .Where(e => e.EventArgs.Action == NotifyCollectionChangedAction.Add);

            var window = sink.Window(10).Subscribe(x => { if(oc.Count >= 10) Send("window"); });
            var throttle = sink.Throttle(TimeSpan.FromSeconds(2)).Subscribe(x => Send("throttle"));

            unchecked
            {
                for(int i = 1; i <= 3; i++)
                    Seed(i * 1000, i.ToString());
            }

            Console.WriteLine("Press any key to exit..");
            Console.ReadKey(true);

            window.Dispose();
            throttle.Dispose();
        }
Example #8
0
        public bool Add(Vertex[] Edge1, Vertex[] Edge2)
        {
            PointF[] edge1 = new PointF[2];
            PointF[] edge2 = new PointF[2];

            edge1 = VertToPoint(Edge1);
            edge2 = VertToPoint(Edge2);

            HashSet<PointF> crossing = new HashSet<PointF>();
            crossing.Add(edge1[0]);
            crossing.Add(edge1[1]);
            crossing.Add(edge2[0]);
            crossing.Add(edge2[1]);

            foreach (HashSet<PointF> storedCrossing in set)
            {
                if (crossing.SetEquals(storedCrossing))
                // Crossing already exists in set, so return false and don't add
                {
                    return false;
                }
            }

            set.Add(crossing);
            return true;
        }
        static void Main(string[] args)
        {
            var bigCities = new HashSet<string>
            {
                "New York",
                "Manchester",
                "Sheffield",
                "Paris"
            };

            var citiesInUK = new HashSet<string>
            {
                "Sheffield",
                "Ripon",
                "Truro",
                "Manchester"
            };

            var bigCitiesArray = new string[]
            {
                "New York",
                "Manchester",
                "Sheffield",
                "Paris"
            };

            // The order in the array or the set does not matter since a set does not know the position of the values.
            bool areEqual = bigCities.SetEquals(bigCitiesArray);
            Console.WriteLine("bigcities = bigCitiesArray ? {0}", areEqual);

            bool areEqualUK = citiesInUK.SetEquals(bigCitiesArray);
            Console.WriteLine("citiesInUK = BigCitiesArray? {0}", areEqualUK);
        }
		public async Task LookupService() {
			Exception lastFailure = new Exception("No reference source URLs defined");
			foreach (var url in urls) {
				string assemblyList;
				try {
					using (var http = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true }))
						assemblyList = await http.GetStringAsync(url + "/assemblies.txt");
					// Format:
					// AssemblyName; ProjectIndex; DependentAssemblies
					var assemblies = new HashSet<string>(
						assemblyList.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
									.Select(s => s.Remove(s.IndexOf(';')))
					);

					// If nothing changed, don't spam the log
					if (assemblies.SetEquals(this.AvailableAssemblies) && url == this.baseUrl)
						return;
					AvailableAssemblies = assemblies;
					baseUrl = url;
					logger.Log("Using reference source from " + url + " with " + AvailableAssemblies.Count + " assemblies");
					return;
				} catch (Exception ex) {
					lastFailure = ex;
					continue;
				}
			}
			logger.Log("Errors occurred while trying all reference URLs; Ref12 will not work", lastFailure);
			AvailableAssemblies = new HashSet<string>();
		}
 public ShortTestResultEntity GetShortTestResult(TestCompletedEntity testCompletedEntity)
 {
     ShortTestResultEntity shortTestResult = new ShortTestResultEntity()
     {
         TestName = testCompletedEntity.Test.Name,
         DateTimeStart = testCompletedEntity.DateTimeStart,
         DateTimeFinish = testCompletedEntity.DateTimeFinish,
         User = testCompletedEntity.User
     };
     foreach (var questionEntity in testCompletedEntity.Test.Questions)
     {
         QuestionResultEntity questionResult = new QuestionResultEntity()
         {
             Text = questionEntity.Text
         };
         var answersSet = new HashSet<int>(questionEntity.Options.Where(m => m.IsAnswer).Select(m => m.Id));
         var pickedSet =
             new HashSet<int>(testCompletedEntity.Answers.Where(m => m.QuestionId == questionEntity.Id).Select(m => m.Id));
         questionResult.IsAnsweredCorrectly = answersSet.SetEquals(pickedSet);
         shortTestResult.QuestionResults.Add(questionResult);
     }
     shortTestResult.Questions = testCompletedEntity.Test.Questions.Count;
     shortTestResult.RightAnsweredQuestions = shortTestResult.QuestionResults.Count(m => m.IsAnsweredCorrectly);
     return shortTestResult;
 }
        public static ApiDescription GetApiDescription(HttpConfiguration config, string controllerName, string actionName, params string[] parameterNames)
        {
            if (config == null)
            {
                config = new HttpConfiguration();
                config.Formatters.Clear();
                config.Formatters.Add(new XmlMediaTypeFormatter());
                config.Formatters.Add(new JsonMediaTypeFormatter());
                config.Routes.MapHttpRoute("Default", "{controller}");
            }
            HashSet<string> parameterSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
            foreach (var apiDescription in config.Services.GetApiExplorer().ApiDescriptions)
            {
                HttpActionDescriptor actionDescriptor = apiDescription.ActionDescriptor;
                if (String.Equals(actionDescriptor.ControllerDescriptor.ControllerName, controllerName, StringComparison.OrdinalIgnoreCase) &&
                    String.Equals(actionDescriptor.ActionName, actionName, StringComparison.OrdinalIgnoreCase))
                {
                    HashSet<string> actionParameterSet = new HashSet<string>(actionDescriptor.GetParameters().Select(p => p.ParameterName), StringComparer.OrdinalIgnoreCase);
                    if (parameterSet.SetEquals(actionParameterSet))
                    {
                        return apiDescription;
                    }
                }
            }

            return null;
        }
        public void Permissions_ReturnsExpectedValues()
        {
            string[] permissions = new[] { "email", "user_likes", "friends_likes" };
            FacebookAuthorizeAttribute authorizeAttribute = new FacebookAuthorizeAttribute(permissions);
            HashSet<string> permissionSet = new HashSet<string>(permissions);

            Assert.True(permissionSet.SetEquals(authorizeAttribute.Permissions));
        }
Example #14
0
        public void Test_DynamicProperty_NewDP_Pass(string expression, string[] expectedResult)
        {
            var kb = TestFactory.PopulatedTestMemory();
            kb.RegistDynamicProperty((Name)"Concat", Test_Concat_Dynamic_Property);

            var results = new HashSet<Name>(kb.AskPossibleProperties((Name)expression, Name.SELF_SYMBOL, null).Select(r => r.Item1));
            var expected = new HashSet<Name>(expectedResult.Select(s => (Name) s));
            Assert.True(results.SetEquals(expected));
        }
        /// <summary>
        /// Gets the product which contains exactly the given set of modules.
        /// </summary>
        /// <param name="modules">A set of modules</param>
        /// <returns>Name of the matching product, or <c>null</c></returns>
        public string GetProductName(IEnumerable<Module> modules)
        {
            var set1 = new HashSet<Module>(modules);

            return (
                from product in suite.Products 
                let set2 = new HashSet<Module>(product.Modules) 
                where set1.SetEquals(set2) 
                select product.Name).FirstOrDefault();
        }
            public void IgnoresSingleValuesAfterCompletion()
            {
                var left = new[] { 1, 2, 1 };
                var right = new[] { 2, 1, 2 };
                var expected = new HashSet<Pair<int>>(Enumerable.Range(1, 2).Select(x => new Pair<int>(x, x)));

                var results = left.ToObservable().MatchPair(right.ToObservable(), x => x).ToEnumerable().ToList();

                Assert.True(expected.SetEquals(results));
            }
            public void PairsValues()
            {
                var left = new[] { 0, 2, 4, 1, 3, 5 }.ToObservable();
                var right = new[] { 0, 3, 5, 4, 2, 1 }.ToObservable();
                var expected = new HashSet<Pair<int>>(Enumerable.Range(0, 6).Select(x => new Pair<int>(x, x)));

                var results = left.MatchPair(right, x => x).ToEnumerable();

                Assert.True(expected.SetEquals(results));
            }
Example #18
0
        public void Should_shuffle_array()
        {
            var randomIntegers = Fake.Create<int>().Generate(100);
            var shuffled = randomIntegers.Shuffle().ToList();
            Assert.AreEqual(randomIntegers.Count, shuffled.Count);
            Assert.False(randomIntegers.SequenceEqual(shuffled));

            var hashset1 = new HashSet<int>(randomIntegers);
            var hashset2 = new HashSet<int>(shuffled);
            Assert.True(hashset1.SetEquals(hashset2));
        }
Example #19
0
        public void GivenBundlesAdded_WhenEnumerated_ThenBundlesReturned()
        {
            var bundle1 = new TestableBundle("~/test1");
            var bundle2 = new TestableBundle("~/test2");
            bundles.Add(bundle1);
            bundles.Add(bundle2);

            var set = new HashSet<Bundle>(bundles);

            set.SetEquals(new[] { bundle1, bundle2 }).ShouldBeTrue();
        }
Example #20
0
        private bool IsRoyalFlush(Hand hand)
        {
            bool isFlush = HandEvaluatorHelper.IsFlush(hand);

            if (!isFlush)
            {
                return false;
            }

            var cardsValues = new HashSet<CardValue>(hand.Cards.Select(card => card.Value));
            return cardsValues.SetEquals(this.NeededCardValues);
        }
Example #21
0
        public void MethodManagement()
        {
            TestClassSession classSession = new TestClassSession(typeof(TestClassMock));

            classSession.Add(typeof(TestClassMock).GetMethod("FirstTestMethod"));
            HashSet<MethodInfo> expectedMethods = new HashSet<MethodInfo> { typeof(TestClassMock).GetMethod("FirstTestMethod") };
            Assert.IsTrue(expectedMethods.SetEquals(classSession.TestsToRun));

            classSession.AddAll();
            expectedMethods.Add(typeof(TestClassMock).GetMethod("SecondTestMethod"));
            Assert.IsTrue(expectedMethods.SetEquals(classSession.TestsToRun));
        }
        public StandardDeck(IShuffler shuffler, string gameId)
            : base()
        {
            _gameid = gameId;
            Shuffler = shuffler;
            Cards = new HashSet<Card>();
            PokerCalculator.PokerLib.init_deck(deck);

            var ed = new HashSet<int>(expectedDeck);
            var actDeck = new HashSet<int>(deck);
            if (!actDeck.SetEquals(ed)) throw new ApplicationException("The deck returned from the PokerLib is corrupt");
        }
Example #23
0
        public async Task TestSetDataWithMultipleInstanceIds()
        {
            ICloudBlob blob = await CreateEmptyBlob();
            string leaseId = blob.AcquireLease(null, null);
            UpdateBlobWrapper updateBlobWrapper = await UpdateBlobWrapper.Create(blob);
            
            var instanceIds = new HashSet<string>(new[] {"instanceId1"});
            await updateBlobWrapper.SetData(leaseId, "1", instanceIds);

            Assert.AreEqual("1", updateBlobWrapper.GetUpdateDomain());
            Assert.IsTrue(instanceIds.SetEquals(updateBlobWrapper.GetInstanceIds()));
        }
Example #24
0
        public void GivenMinAndNonMinScripts_WhenFindFiles_ThenOnlyIncludeNonMinScripts()
        {
            CreateFile("jquery.js");
            CreateFile("jquery.min.js");
            CreateFile("jquery-ui.js");
            CreateFile("jquery-ui.min.js");

            var search = new FileSearch { Pattern = "*.js" };
            var files = search.FindFiles(directory).ToArray();

            var names = new HashSet<string>(files.Select(f => f.FullPath));
            names.SetEquals(new[] { "~/jquery.js", "~/jquery-ui.js" });
        }
Example #25
0
 private void CheckSheetConsistence(DataSheet sheet)
 {
     var columnNames = new HashSet<string>(sheet.Rows[0].Keys);
     foreach (var row in sheet.Rows)
     {
         if (!columnNames.SetEquals(row.Keys))
         {
             throw new Exception(
                 string.Format("{0} columns mismatch: ({1}),({2})",
                 sheet.Name, JsonOperation.Serialize(columnNames), JsonOperation.Serialize(row)));
         }
     }
 }
        public SaveResponse Update(IUnitOfWork uow, RolePermissionUpdateRequest request)
        {
            Check.NotNull(request, "request");
            Check.NotNull(request.RoleID, "roleID");
            Check.NotNull(request.Permissions, "permissions");

            var roleID = request.RoleID.Value;
            var oldList = new HashSet<string>(
                GetExisting(uow.Connection, roleID, request.Module, request.Submodule)
                .Select(x => x.PermissionKey), StringComparer.OrdinalIgnoreCase);

            var newList = new HashSet<string>(request.Permissions.ToList(),
                StringComparer.OrdinalIgnoreCase);

            var allowedKeys = new UserPermissionRepository().ListPermissionKeys()
                .Entities.ToDictionary(x => x);
            if (newList.Any(x => !allowedKeys.ContainsKey(x)))
                throw new AccessViolationException();

            if (oldList.SetEquals(newList))
                return new SaveResponse();

            foreach (var k in oldList)
            {
                if (newList.Contains(k))
                    continue;

                new SqlDelete(fld.TableName)
                    .Where(
                        new Criteria(fld.RoleId) == roleID &
                        new Criteria(fld.PermissionKey) == k)
                    .Execute(uow.Connection);
            }

            foreach (var k in newList)
            {
                if (oldList.Contains(k))
                    continue;

                uow.Connection.Insert(new MyRow
                {
                    RoleId = roleID,
                    PermissionKey = k
                });
            }

            BatchGenerationUpdater.OnCommit(uow, fld.GenerationKey);
            BatchGenerationUpdater.OnCommit(uow, Entities.UserPermissionRow.Fields.GenerationKey);

            return new SaveResponse();
        }
 public void AddTest1Test()
 {
     DependencyGraph t = new DependencyGraph();
     t.AddDependency("A1", "A2");
     t.AddDependency("A1", "A3");
     t.RemoveDependency("A1", "A2");
     Assert.AreEqual(1, t.Size);
     t.AddDependency("A1", "A4");
     Assert.AreEqual(2, t.Size);
     HashSet<string> test = new HashSet<string>();
     test.Add("A3");
     test.Add("A4");
     Assert.AreEqual(true, test.SetEquals(t.GetDependents("A1")));
 }
        private static async Task TestRemindersHashInterval(IReminderTable reminderTable, uint beginHash, uint endHash,
            uint[] remindersHashes)
        {
            var rowsTask = reminderTable.ReadRows(beginHash, endHash);
            var expectedHashes = beginHash < endHash
                ? remindersHashes.Where(r => r > beginHash && r <= endHash)
                : remindersHashes.Where(r => r > beginHash || r <= endHash);

            HashSet<uint> expectedSet = new HashSet<uint>(expectedHashes);
            var returnedHashes = (await rowsTask).Reminders.Select(r => r.GrainRef.GetUniformHashCode());
            var returnedSet = new HashSet<uint>(returnedHashes);

            Assert.IsTrue(returnedSet.SetEquals(expectedSet));
        }
Example #29
0
    public bool BoxesChanged(ImportedCloud orig)
    {
        // FIXME this is too sensitive
        #if false
        HashSet<Matrix4x4> oldBoxes = new HashSet<Matrix4x4>( boxes );
        HashSet<Matrix4x4> newBoxes = new HashSet<Matrix4x4>();

        Matrix4x4 cloud2world = orig.transform.localToWorldMatrix;
        foreach(Transform box in orig.transform.FindChild("CutBoxes"))
            newBoxes.Add(box.worldToLocalMatrix * cloud2world);
        return ! oldBoxes.SetEquals( newBoxes );
        #endif
        return false;
    }
Example #30
0
        public void CreateSessionForAssembly()
        {
            Assembly assembly = Assembly.GetAssembly(typeof(AssemblyTestMock1));

            HashSet<TestClassSession> expectedClassSessions = new HashSet<TestClassSession>();
            TestClassSession classSession = new TestClassSession(typeof(AssemblyTestMock1));
            classSession.AddAll();
            expectedClassSessions.Add(classSession);
            classSession = new TestClassSession(typeof(AssemblyTestMock2));
            classSession.AddAll();
            expectedClassSessions.Add(classSession);

            AssertEx.That(expectedClassSessions.SetEquals(AssemblyScanner.CreateSessionFor(assembly).TestClassSessions), Is.True());
        }