Compare() public method

public Compare ( KeyValuePair x, KeyValuePair y ) : int
x KeyValuePair
y KeyValuePair
return int
Esempio n. 1
1
        public static void Ctor_CultureInfo(object a, object b, int expected)
        {
            var culture = new CultureInfo("en-US");
            var comparer = new Comparer(culture);

            Assert.Equal(expected, Math.Sign(comparer.Compare(a, b)));
        }
        private static unsafe int QuickSortPartion(TemplateStructType* array, int start, int end, Comparer<TemplateStructType> comparer)
        {
            TemplateStructType pivot, startValue, endValue;
            pivot = array[start];
            while (start < end)
            {
                startValue = array[start];
                while (start < end && comparer.Compare(startValue, pivot) > 0)
                {
                    start++;
                    startValue = array[start];
                }

                endValue = array[end];
                while (start < end && comparer.Compare(endValue, pivot) < 0)
                {
                    end--;
                    endValue = array[end];
                }

                if (start < end)
                {
                    array[end] = startValue;
                    array[start] = endValue;
                }
            }

            return start;
        }
Esempio n. 3
0
        public static void TestCtor_CultureInfo(object a, object b, int expected)
        {
            var culture = new CultureInfo("en-US");
            var comparer = new Comparer(culture);

            Assert.Equal(expected, Helpers.NormalizeCompare(comparer.Compare(a, b)));
        }
Esempio n. 4
0
		internal static bool GetPassword(IDataAccess dataAccess, int userId, out byte[] password, out byte[] passwordSalt, out bool isApproved, out bool isSuspended)
		{
			var entity = new UserEntity();
			var oql = new OQL(entity);
			var comparer = new Comparer(oql);

			comparer = comparer.Compare(entity.UserId, "=", userId);

			return GetPasswordCore(dataAccess, comparer, entity, out password, out passwordSalt, out isApproved, out isSuspended) != 0;
		}
Esempio n. 5
0
        public void Compare()
        {
            var list = new List<string>
                {
                    "76561197975995523", // ice_mouton
                    "76561197962208538", // dubispacebar
                    "76561197965572012", // siliticx
                };

            var c = new Comparer(_api);
            var games = c.Compare(list);

            Assert.IsTrue(games.Count > 0);
        }
        public void NoChange_SameOrderOfElements()
        {
            //Arrange
            var xml1 = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<root>
  <elem1>This is element 1</elem1>
  <elem2>This is element 2</elem2>
<add name=""name1"" value=""value1"" />
</root>
";

            var xml2 = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<root>
  <elem1>This is element 1</elem1>
  <elem2>This is element 2</elem2>
<add name=""name1"" value=""value1""/>
</root>
";

            var mockHandler = new Mock<IXmlCompareHandler>(MockBehavior.Strict);
            //mockHandler.Setup(a => a.AttributeAdded(It.IsAny<string>(),It.IsAny<XAttribute>()));
            //mockHandler.Setup(a => a.AttributeChanged(It.IsAny<string>(),It.IsAny<XAttribute>(), It.IsAny<XAttribute>()));
            //mockHandler.Setup(a => a.AttributeRemoved(It.IsAny<string>(),It.IsAny<XAttribute>()));
            //mockHandler.Setup(a => a.ElementAdded(It.IsAny<string>(),It.IsAny<XElement>()));
            //mockHandler.Setup(a => a.ElementChanged(It.IsAny<string>(),It.IsAny<XElement>(), It.IsAny<XElement>()));
            //mockHandler.Setup(a => a.ElementRemoved(It.IsAny<string>(),It.IsAny<XElement>()));

            var comparer = new Comparer(mockHandler.Object);

            //act
            comparer.Compare(GetStream(xml1), GetStream(xml2), mockHandler.Object);

            //assert

            mockHandler.Verify(a => a.AttributeAdded(It.IsAny<AttributeAddedEventArgs>()), Times.Never);
            mockHandler.Verify(a => a.AttributeChanged(It.IsAny<AttributeChangedEventArgs>()), Times.Never);
            mockHandler.Verify(a => a.AttributeRemoved(It.IsAny<AttributeRemovedEventArgs>()), Times.Never);
            mockHandler.Verify(a => a.ElementAdded(It.IsAny<ElementAddedEventArgs>()), Times.Never);
            mockHandler.Verify(a => a.ElementChanged(It.IsAny<ElementChangedEventArgs>()), Times.Never);
            mockHandler.Verify(a => a.ElementRemoved(It.IsAny<ElementRemovedEventArgs>()), Times.Never);

        }
        static void Main(string[] args)
        {
            try
            {
                var file1 = @".\TestFiles\a1.config";
                var file2 = @".\TestFiles\a2.config";

                var handler = new TestXmlCompareHandler();

                using (var comparer = new Comparer(handler))
                {
                    comparer.Compare(file1, file2, handler);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR: " + ex);
            }
            Console.Write("Press RETURN to close...");
            Console.ReadLine();
        }
 public int Compare(TEntity first, TEntity second)
 {
     return(Comparer.Compare(ExtractValue(first), ExtractValue(second)));
 }
        public void GeneralElement_ElementChanged()
        {
            //Arrange

            #region sample values

            var xml1 = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<root>
  <elem1 name=""MyLogger"">This is element 1</elem1>
  <elem2>This is element 2</elem2>
<add name=""name1"" value=""value1"" oldAttribute=""to be deleted""/>
</root>
";

            var xml2 = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<root>
  <elem1 name=""MyLogger"">This is element 1 but changed now</elem1>
  <elem2>This is element 2</elem2>
<add name=""name1"" value=""value1"" oldAttribute=""to be deleted""/>
</root>
";
            #endregion

            var oldValue = string.Empty;
            var newValue = string.Empty;

            var mockHandler = new Mock<IXmlCompareHandler>(MockBehavior.Strict);
            mockHandler.Setup(a => a.ElementChanged(It.IsAny<ElementChangedEventArgs>()))
                .Callback<ElementChangedEventArgs>((e) => { oldValue = e.LeftElement.ToString(); newValue = e.RightElement.ToString(); });

            var comparer = new Comparer(mockHandler.Object);

            //act
            comparer.Compare(GetStream(xml1), GetStream(xml2), mockHandler.Object);

            //assert

            mockHandler.Verify(a => a.AttributeAdded(It.IsAny<AttributeAddedEventArgs>()), Times.Never);
            mockHandler.Verify(a => a.AttributeChanged(It.IsAny<AttributeChangedEventArgs>()), Times.Never);
            mockHandler.Verify(a => a.AttributeRemoved(It.IsAny<AttributeRemovedEventArgs>()), Times.Never);
            mockHandler.Verify(a => a.ElementAdded(It.IsAny<ElementAddedEventArgs>()), Times.Never);
            mockHandler.Verify(a => a.ElementChanged(It.IsAny<ElementChangedEventArgs>()), Times.Once);
            mockHandler.Verify(a => a.ElementRemoved(It.IsAny<ElementRemovedEventArgs>()), Times.Never);

            Assert.AreEqual(@"<elem1 name=""MyLogger"">This is element 1 but changed now</elem1>", newValue);

        }
        public void GeneralElement_ChildElementChanged_WithNamespace()
        {
            //Arrange

            #region sample values

            var xml1 = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<root xmlns:ns1=""http://www.example.com/ns1"">
   <elem1>This does not change</elem1>
  <ns1:elem3 attr1=""attr1""><child>This is old child in element 3</child></ns1:elem3>
</root>
";

            var xml2 = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<root xmlns:ns1=""http://www.example.com/ns1"">
   <elem1>This does not change</elem1>
  <ns1:elem3 attr1=""attr1""><child>This is new child in element 3</child></ns1:elem3>
</root>
";

            #endregion

            var oldValue = string.Empty;
            var newValue = string.Empty;

            var mockHandler = new Mock<IXmlCompareHandler>(MockBehavior.Strict);
            mockHandler.Setup(a => a.ElementChanged(It.IsAny<ElementChangedEventArgs>()))
                .Callback<ElementChangedEventArgs>((e) => { oldValue = e.LeftElement.ToString(); newValue = e.RightElement.ToString(); });

            var comparer = new Comparer(mockHandler.Object);

            //act
            comparer.Compare(GetStream(xml1), GetStream(xml2), mockHandler.Object);

            //assert

            mockHandler.Verify(a => a.AttributeAdded(It.IsAny<AttributeAddedEventArgs>()), Times.Never);
            mockHandler.Verify(a => a.AttributeChanged(It.IsAny<AttributeChangedEventArgs>()), Times.Never);
            mockHandler.Verify(a => a.AttributeRemoved(It.IsAny<AttributeRemovedEventArgs>()), Times.Never);
            mockHandler.Verify(a => a.ElementAdded(It.IsAny<ElementAddedEventArgs>()), Times.Never);
            mockHandler.Verify(a => a.ElementChanged(It.IsAny<ElementChangedEventArgs>()), Times.Once);
            mockHandler.Verify(a => a.ElementRemoved(It.IsAny<ElementRemovedEventArgs>()), Times.Never);

            Assert.AreEqual(@"<child>This is new child in element 3</child>", newValue);

        }
Esempio n. 11
0
 public int Compare(T x, T y)
 {
     return(Comparer.Compare(x.Seq, y.Seq));
 }
Esempio n. 12
0
 public int Compare(Vector2D x, Vector2D y)
 {
     return(comparer.Compare(Math.Atan2(x.y, x.x), Math.Atan2(y.y, y.x)));
 }
Esempio n. 13
0
        /// <remarks/>
        public override bool IsMatch(SyslogMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            object property;

            switch (propertyName)
            {
            case Property.Severity:
            {
                property = message.Severity;
                break;
            }

            case Property.Facility:
            {
                property = message.Facility;
                break;
            }

            case Property.Timestamp:
            {
                property = message.Timestamp;
                break;
            }

            case Property.Host:
            {
                property = message.Host;
                break;
            }

            case Property.ApplicationName:
            {
                property = message.ApplicationName;
                break;
            }

            case Property.ProcessID:
            {
                property = message.ProcessID;
                break;
            }

            case Property.MessageID:
            {
                property = message.MessageId;
                break;
            }

            case Property.Data:
            {
                throw new NotSupportedException("Data is structured. Cannot be compared");
            }

            case Property.Text:
            {
                property = message.Text;
                break;
            }

            default:
            {
                throw new ArgumentException("Invalid property");
            }
            }

            if (property == null)
            {
                return(false);
            }
            if (property is IComparable)
            {
                Comparer cmp    = Comparer.DefaultInvariant;
                int      result = cmp.Compare(property, targetvalue);
                switch (comparison)
                {
                case ComparisonOperator.eq:
                {
                    return(result == 0);
                }

                case ComparisonOperator.geq:
                {
                    return(result >= 0);
                }

                case ComparisonOperator.gt:
                {
                    return(result > 0);
                }

                case ComparisonOperator.leq:
                {
                    return(result <= 0);
                }

                case ComparisonOperator.lt:
                {
                    return(result < 0);
                }

                case ComparisonOperator.neq:
                {
                    return(result != 0);
                }

                default:
                {
                    throw new InvalidOperationException();
                }
                }
            }

            if (property is int)
            {
                switch (comparison)
                {
                case ComparisonOperator.eq:
                {
                    return((int)property == (int)targetvalue);
                }

                case ComparisonOperator.geq:
                {
                    return((int)property >= (int)targetvalue);
                }

                case ComparisonOperator.gt:
                {
                    return((int)property > (int)targetvalue);
                }

                case ComparisonOperator.leq:
                {
                    return((int)property <= (int)targetvalue);
                }

                case ComparisonOperator.lt:
                {
                    return((int)property < (int)targetvalue);
                }

                case ComparisonOperator.neq:
                {
                    return((int)property != (int)targetvalue);
                }

                default:
                {
                    throw new InvalidOperationException();
                }
                }
            }

            if (property is DateTime)
            {
                switch (comparison)
                {
                case ComparisonOperator.eq:
                {
                    return((DateTime)property == (DateTime)targetvalue);
                }

                case ComparisonOperator.geq:
                {
                    return((DateTime)property >= (DateTime)targetvalue);
                }

                case ComparisonOperator.gt:
                {
                    return((DateTime)property > (DateTime)targetvalue);
                }

                case ComparisonOperator.leq:
                {
                    return((DateTime)property <= (DateTime)targetvalue);
                }

                case ComparisonOperator.lt:
                {
                    return((DateTime)property < (DateTime)targetvalue);
                }

                case ComparisonOperator.neq:
                {
                    return((DateTime)property != (DateTime)targetvalue);
                }

                default:
                {
                    throw new InvalidOperationException();
                }
                }
            }
            throw new InvalidProgramException("Software bug!");
        }
Esempio n. 14
0
        public static Pair <TSource, TSource> MinMax <TSource>(this IEnumerable <TSource> source)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            var valueMin = default(TSource);
            var valueMax = default(TSource);

            Comparer <TSource> comparer = Comparer <TSource> .Default;
            TSource            value    = default(TSource);

            if (value == null)
            {
                using (var e = source.GetEnumerator())
                {
                    do
                    {
                        if (!e.MoveNext())
                        {
                            return(new Pair <TSource, TSource>(value, value));
                        }

                        value = e.Current;
                    }while (value == null);

                    valueMin = valueMax = value;

                    while (e.MoveNext())
                    {
                        TSource x = e.Current;
                        if (x != null)
                        {
                            if (comparer.Compare(x, valueMin) < 0)
                            {
                                valueMin = x;
                            }
                            else if (comparer.Compare(x, valueMax) > 0)
                            {
                                valueMax = x;
                            }
                        }
                    }
                }
            }
            else
            {
                using (var e = source.GetEnumerator())
                {
                    if (!e.MoveNext())
                    {
                        throw new ArgumentException("No elements");
                    }

                    valueMin = valueMax = e.Current;

                    while (e.MoveNext())
                    {
                        TSource x = e.Current;
                        if (comparer.Compare(x, valueMin) < 0)
                        {
                            valueMin = x;
                        }
                        else if (comparer.Compare(x, valueMax) > 0)
                        {
                            valueMax = x;
                        }
                    }
                }
            }

            return(new Pair <TSource, TSource>(valueMin, valueMax));
        }
Esempio n. 15
0
 public void Sort(Comparer <RenderOrderKey> keyComparer)
 {
     _indices.Sort(
         (RenderItemIndex first, RenderItemIndex second)
         => keyComparer.Compare(first.Key, second.Key));
 }
Esempio n. 16
0
        public void Invariant()
        {
            Comparer c = Comparer.DefaultInvariant;

            Assert.IsTrue(c.Compare("a", "A") < 0);
        }
Esempio n. 17
0
 public override int Compare(RngmedValIndex x, RngmedValIndex y)
 {
     return(_comparer.Compare(x.Data, y.Data));
 }
Esempio n. 18
0
        public static int?Compare <T>(Comparer <T> comparer, T first, T second)
        {
            var ret = comparer.Compare(first, second);

            return(ret == 0 ? new int?() : ret);
        }
Esempio n. 19
0
 int IComparer <PittsburgElementofStorage> .Compare(PittsburgElementofStorage x, PittsburgElementofStorage y)
 {
     return(noReverse.Compare(x.LearnError, y.LearnError));
 }
Esempio n. 20
0
 int IComparer <double> .Compare(double x, double y)
 {
     return(noReverse.Compare(y, x));
 }
 public static T MaxBy <T, TKey>(this IEnumerable <T> src, Func <T, TKey> key, Comparer <TKey> keyComparer) =>
 src.Aggregate((a, b) => keyComparer.Compare(key(a), key(b)) > 0 ? a : b);
Esempio n. 22
0
        void MoveTo(TK key, bool backwards)
        {
            var entries = Entries(this.CurrentNode) as IEnumerable <Entry <TK> >;

            var childrenAddresses = ChildrenAddresses(this.CurrentNode) as IEnumerable <Int64>;

            if (backwards)
            {
                entries           = entries.Reverse();
                childrenAddresses = childrenAddresses.Reverse();
            }

            int i = -1;

            if (!backwards)
            {
                i = entries.TakeWhile(entry => Comparer.Compare(key, entry.Key) > 0).Count();
            }
            else
            {
                i = entries.TakeWhile(entry => Comparer.Compare(key, entry.Key) < 0).Count();
            }

            int absoluteIndex = backwards ? (entries.Count() - 1) - i : i;

            if (i < entries.Count() &&
                Comparer.Compare(entries.ElementAt(i).Key, key) == 0)
            {
                //found it
                this.CurrentEntryIndex = absoluteIndex;
                return;
            }
            else if (this.CurrentNode.IsLeaf)
            {
                //it's a leaf, but no entry matches
                this.CurrentEntryIndex = absoluteIndex;
                return;
            }
            else if (i >= childrenAddresses.Count())
            {
                //tree seems unbalanced
                this.CurrentEntryIndex = absoluteIndex;
                return;
            }

            //push the breadcrumb
            var breadCrumb = new BreadCrumb()
            {
                CurrentEntryIndex = backwards ? absoluteIndex : absoluteIndex - 1,
                Node = CurrentNode
            };

            this.BreadCrumbs.Push(breadCrumb);

            // set the target child as current node

            this.CurrentNode = this.DataProvider.GetNode(childrenAddresses.ElementAt(i));

            //and search in childnode
            MoveTo(key, backwards);
        }
Esempio n. 23
0
        public void Constructor()
        {
            Comparer c = new Comparer(CultureInfo.InvariantCulture);

            Assert.IsTrue(c.Compare("a", "A") < 0);
        }
Esempio n. 24
0
 /// <inheritdoc />
 protected sealed override int Compare(TKey x, TKey y)
 {
     return(Comparer.Compare(x, y));
 }
Esempio n. 25
0
 public int Compare(ReqPriority x, ReqPriority y)
 {
     return(-1 * Comparer.Compare(x, y));
 }
Esempio n. 26
0
        public static Pair <TResult, TResult> MinMax <TSource, TResult>(this IEnumerable <TSource> source, Func <TSource, TResult> selector)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (selector == null)
            {
                throw new ArgumentNullException(nameof(selector));
            }

            TResult valueMin = default(TResult);
            TResult valueMax = default(TResult);

            Comparer <TResult> comparer = Comparer <TResult> .Default;
            TResult            value    = default(TResult);

            if (value == null)
            {
                using (IEnumerator <TSource> e = source.GetEnumerator())
                {
                    do
                    {
                        if (!e.MoveNext())
                        {
                            return(new Pair <TResult, TResult>(value, value));
                        }

                        value = selector(e.Current);
                    }while (value == null);

                    valueMin = valueMax = value;

                    while (e.MoveNext())
                    {
                        TResult x = selector(e.Current);
                        if (x != null)
                        {
                            if (comparer.Compare(x, valueMin) < 0)
                            {
                                valueMin = x;
                            }
                            else if (comparer.Compare(x, valueMax) > 0)
                            {
                                valueMax = x;
                            }
                        }
                    }
                }
            }
            else
            {
                using (IEnumerator <TSource> e = source.GetEnumerator())
                {
                    if (!e.MoveNext())
                    {
                        throw new ArgumentException("No Elements");
                    }

                    valueMin = valueMax = selector(e.Current);
                    while (e.MoveNext())
                    {
                        TResult x = selector(e.Current);
                        if (comparer.Compare(x, valueMin) < 0)
                        {
                            valueMin = x;
                        }
                        else if (comparer.Compare(x, valueMax) > 0)
                        {
                            valueMax = x;
                        }
                    }
                }
            }

            return(new Pair <TResult, TResult>(valueMin, valueMax));
        }
Esempio n. 27
0
 public int Compare(T x, T y)
 {
     CompareCount++;
     return(Asc ? Comparer.Compare(x, y) : -Compare(x, y));
 }
Esempio n. 28
0
        internal static Func <IDictionary <string, object>, bool> GetComparer <T>(string rangeParamName, T fromValue, T toValue) where T : IComparable
        {
            Comparer comparer    = Comparer.DefaultInvariant;
            bool     sameRange   = comparer.Compare(fromValue, toValue) == 0; // FromValue == ToValue
            bool     insideRange = comparer.Compare(fromValue, toValue) < 0;  // FromValue < ToValue
            Func <IDictionary <string, object>, bool> compareClause;

            if (sameRange)
            {
                compareClause = data =>
                {
                    if (data == null || data.Count <= 0)
                    {
                        return(false);
                    }

                    if (!data.ContainsKey(rangeParamName))
                    {
                        var error = string.Format("Cannot find column '{0}' for range query from {1} to {2} in Data={3}",
                                                  rangeParamName, fromValue, toValue, StorageProviderUtils.PrintData(data));
                        throw new KeyNotFoundException(error);
                    }
                    T obj = (T)data[rangeParamName];
                    return(comparer.Compare(obj, fromValue) == 0);
                };
            }
            else if (insideRange)
            {
                compareClause = data =>
                {
                    if (data == null || data.Count <= 0)
                    {
                        return(false);
                    }

                    if (!data.ContainsKey(rangeParamName))
                    {
                        var error = string.Format("Cannot find column '{0}' for range query from {1} to {2} in Data={3}",
                                                  rangeParamName, fromValue, toValue, StorageProviderUtils.PrintData(data));
                        throw new KeyNotFoundException(error);
                    }
                    T obj = (T)data[rangeParamName];
                    return(comparer.Compare(obj, fromValue) >= 0 && comparer.Compare(obj, toValue) <= 0);
                };
            }
            else
            {
                compareClause = data =>
                {
                    if (data == null || data.Count <= 0)
                    {
                        return(false);
                    }

                    if (!data.ContainsKey(rangeParamName))
                    {
                        var error = string.Format("Cannot find column '{0}' for range query from {1} to {2} in Data={3}",
                                                  rangeParamName, fromValue, toValue, StorageProviderUtils.PrintData(data));
                        throw new KeyNotFoundException(error);
                    }
                    T obj = (T)data[rangeParamName];
                    return(comparer.Compare(obj, fromValue) >= 0 || comparer.Compare(obj, toValue) <= 0);
                };
            }
            return(compareClause);
        }
        public void NameValueElement_WithNamespace_AttributeChanged()
        {
            //Arrange

            #region sample values

            var xml1 = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<root xmlns:ns1=""http://www.example.com/ns1"">
  <elem1>This is element 1</elem1>
  <elem2>This is element 2</elem2>
<add name=""name1"" value=""value1"" newAttribute=""old value"" ns1:newAttribute=""old value in ns1""/>
</root>
";

            var xml2 = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<root xmlns:ns1=""http://www.example.com/ns1"">
  <elem1>This is element 1</elem1>
  <elem2>This is element 2</elem2>
<add name=""name1"" value=""value1"" newAttribute=""new value"" ns1:newAttribute=""new value in ns1""/>
</root>
";
            #endregion

            var oldValue1 = string.Empty;
            var newValue1 = string.Empty;

            var oldValue2 = string.Empty;
            var newValue2 = string.Empty;

            var mockHandler = new Mock<IXmlCompareHandler>(MockBehavior.Strict);
            mockHandler.Setup(a => a.AttributeChanged(It.IsAny<AttributeChangedEventArgs>()))
                .Callback<AttributeChangedEventArgs>((e) =>
                {
                    if (e.LeftAttribute.Name.Namespace == "")
                    {
                        oldValue1 = e.LeftAttribute.Value;
                    }
                    if (e.LeftAttribute.Name.Namespace == "http://www.example.com/ns1")
                    {
                        oldValue2 = e.LeftAttribute.Value;
                    }

                    if (e.RightAttribute.Name.Namespace == "")
                    {
                        newValue1 = e.RightAttribute.Value;
                    }
                    if (e.RightAttribute.Name.Namespace == "http://www.example.com/ns1")
                    {
                        newValue2 = e.RightAttribute.Value;
                    }
                });

            var comparer = new Comparer(mockHandler.Object);

            //act
            comparer.Compare(GetStream(xml1), GetStream(xml2), mockHandler.Object);

            //assert

            mockHandler.Verify(a => a.AttributeAdded(It.IsAny<AttributeAddedEventArgs>()), Times.Never);
            mockHandler.Verify(a => a.AttributeChanged(It.IsAny<AttributeChangedEventArgs>()), Times.Exactly(2));
            mockHandler.Verify(a => a.AttributeRemoved(It.IsAny<AttributeRemovedEventArgs>()), Times.Never);
            mockHandler.Verify(a => a.ElementAdded(It.IsAny<ElementAddedEventArgs>()), Times.Never);
            mockHandler.Verify(a => a.ElementChanged(It.IsAny<ElementChangedEventArgs>()), Times.Never);
            mockHandler.Verify(a => a.ElementRemoved(It.IsAny<ElementRemovedEventArgs>()), Times.Never);

            Assert.AreEqual("old value", oldValue1);
            Assert.AreEqual("new value", newValue1);

            Assert.AreEqual("old value in ns1", oldValue2);
            Assert.AreEqual("new value in ns1", newValue2);

        }
        /// <inheritdoc />
        public override void AddRange(IEnumerable <KeyValuePair <TKey, TValue> > items)
        {
            if (items == null)
            {
                throw new ArgumentNullException(nameof(items));
            }

            var NewItems = items.Select(item => new RangeKeyValue(item.Key, item.Value)).ToArray();

            if (NewItems.Length == 0)
            {
                return;
            }

            Array.Sort(NewItems, CompareRange);

            // Check the new items don't have any duplicates
            {
                var Index = 0;

                var CurrentItem = NewItems[0];

                while (++Index < NewItems.Length)
                {
                    var LastItem = CurrentItem;
                    CurrentItem = NewItems[Index];

                    if (Comparer.Compare(LastItem.Key, CurrentItem.Key) == 0)
                    {
                        throw new ArgumentException("Input collection has duplicates");
                    }
                }
            }

            // No duplicates in the new items. Check the keys aren't already in the Dictionary
            for (var Index = 0; Index < NewItems.Length; Index++)
            {
                var CurrentItem = NewItems[Index];
                var InnerIndex  = Array.BinarySearch(_Keys, 0, _Size, CurrentItem.Key);

                // No exact match?
                if (InnerIndex >= 0)
                {
                    throw new ArgumentException("An item with the same key has already been added.");
                }

                NewItems[Index].EstimatedIndex = ~InnerIndex;
            }

            // Ensure we have enough space for the new items
            EnsureCapacity(_Size + NewItems.Length);

            var ItemsNotify = new KeyValuePair <TKey, TValue> [NewItems.Length];

            // Add the new items
            for (var Index = 0; Index < NewItems.Length; Index++)
            {
                var CurrentItem = NewItems[Index];

                // We need to adjust where we're inserting since these are the old indexes
                // Since the new items are ordered by key, we can just add the number of already added items
                var NewIndex = CurrentItem.EstimatedIndex + Index;

                // Move things up, unless we're adding at the end
                if (NewIndex < _Size)
                {
                    Array.Copy(_Keys, NewIndex, _Keys, NewIndex + 1, _Size - NewIndex);
                    Array.Copy(_Values, NewIndex, _Values, NewIndex + 1, _Size - NewIndex);
                }

                _Keys[NewIndex]    = CurrentItem.Key;
                _Values[NewIndex]  = CurrentItem.Value;
                ItemsNotify[Index] = new KeyValuePair <TKey, TValue>(CurrentItem.Key, CurrentItem.Value);

                _Size++;
            }

            OnCollectionChanged(NotifyCollectionChangedAction.Add, ItemsNotify);
        }
 public int Compare(STuple <T1> x, STuple <T1> y)
 {
     return(Comparer1.Compare(x.Item1, y.Item1));
 }
        public void NameValueElement_AttributeAdded()
        {
            //Arrange

            #region sample values

            var xml1 = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<root>
  <elem1>This is element 1</elem1>
  <elem2>This is element 2</elem2>
<add name=""name1"" value=""value1"" />
</root>
";

            var xml2 = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<root>
  <elem1>This is element 1</elem1>
  <elem2>This is element 2</elem2>
<add name=""name1"" value=""value1"" newAttribute=""new value""/>
</root>
";
            #endregion

            var newValue = string.Empty;

            var mockHandler = new Mock<IXmlCompareHandler>(MockBehavior.Strict);
            mockHandler.Setup(a => a.AttributeAdded(It.IsAny<AttributeAddedEventArgs>())).Callback<AttributeAddedEventArgs>((e) => { newValue = e.Attribute.Value; });

            var comparer = new Comparer(mockHandler.Object);

            //act
            comparer.Compare(GetStream(xml1), GetStream(xml2), mockHandler.Object);

            //assert

            mockHandler.Verify(a => a.AttributeAdded(It.IsAny<AttributeAddedEventArgs>()), Times.Once);
            mockHandler.Verify(a => a.AttributeChanged(It.IsAny<AttributeChangedEventArgs>()), Times.Never);
            mockHandler.Verify(a => a.AttributeRemoved(It.IsAny<AttributeRemovedEventArgs>()), Times.Never);
            mockHandler.Verify(a => a.ElementAdded(It.IsAny<ElementAddedEventArgs>()), Times.Never);
            mockHandler.Verify(a => a.ElementChanged(It.IsAny<ElementChangedEventArgs>()), Times.Never);
            mockHandler.Verify(a => a.ElementRemoved(It.IsAny<ElementRemovedEventArgs>()), Times.Never);

            Assert.AreEqual("new value", newValue);

        }
Esempio n. 33
0
    public static Heap <T> Create <T, Key>(Func <T, Key> keySelector, Comparer <Key> keyComparer)
    {
        Comparison <T> comparison = (x, y) => keyComparer.Compare(keySelector(x), keySelector(y));

        return(new Heap <T>(comparison));
    }
Esempio n. 34
0
        // is there a element-value pair with the given element?
        public bool Contains(TEl element)
        {
            var someElement = default(TEl);

            return(TryFind(el => Comparer.Compare(el, element), out someElement));
        }
 public int Compare(T x, T y) => Comparer.Compare(_selector(x), _selector(y));
        public void GeneralElement_ElementChanged_WithNamespace()
        {
            //Arrange

            #region sample values

            var xml1 = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<root xmlns:ns1=""http://www.example.com/ns1"">
  <elem1 name=""MyLogger"">This is element 1</elem1>
  <elem2>This is element 2</elem2>
  <ns1:elem2>This is element 2 in ns1</ns1:elem2>
</root>
";

            var xml2 = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<root xmlns:ns1=""http://www.example.com/ns1"">
  <elem1 name=""MyLogger"">This is element 1 but changed now</elem1>
  <elem2>This is element 2</elem2>
  <ns1:elem2>This is element 2 in ns1 but changed now</ns1:elem2>
</root>
";
            #endregion

            var oldValue1 = string.Empty;
            var newValue1 = string.Empty;

            var oldValue2 = string.Empty;
            var newValue2 = string.Empty;

            var mockHandler = new Mock<IXmlCompareHandler>(MockBehavior.Strict);
            mockHandler.Setup(a => a.ElementChanged(It.IsAny<ElementChangedEventArgs>()))
                .Callback<ElementChangedEventArgs>((e) =>
                {
                    if (e.LeftElement.Name.Namespace == "")
                    {
                        oldValue1 = e.LeftElement.ToString(); 
                        newValue1 = e.RightElement.ToString();
                    }
                    if (e.LeftElement.Name.Namespace == "http://www.example.com/ns1")
                    {
                        oldValue2 = e.LeftElement.ToString();
                        newValue2 = e.RightElement.ToString();
                    }
                });

            var comparer = new Comparer(mockHandler.Object);

            //act
            comparer.Compare(GetStream(xml1), GetStream(xml2), mockHandler.Object);

            //assert

            mockHandler.Verify(a => a.AttributeAdded(It.IsAny<AttributeAddedEventArgs>()), Times.Never);
            mockHandler.Verify(a => a.AttributeChanged(It.IsAny<AttributeChangedEventArgs>()), Times.Never);
            mockHandler.Verify(a => a.AttributeRemoved(It.IsAny<AttributeRemovedEventArgs>()), Times.Never);
            mockHandler.Verify(a => a.ElementAdded(It.IsAny<ElementAddedEventArgs>()), Times.Never);
            mockHandler.Verify(a => a.ElementChanged(It.IsAny<ElementChangedEventArgs>()), Times.Exactly(2));
            mockHandler.Verify(a => a.ElementRemoved(It.IsAny<ElementRemovedEventArgs>()), Times.Never);

            Assert.AreEqual(@"<elem1 name=""MyLogger"">This is element 1</elem1>", oldValue1);
            Assert.AreEqual(@"<elem1 name=""MyLogger"">This is element 1 but changed now</elem1>", newValue1);
            Assert.AreEqual(@"<ns1:elem2 xmlns:ns1=""http://www.example.com/ns1"">This is element 2 in ns1</ns1:elem2>", oldValue2);
            Assert.AreEqual(@"<ns1:elem2 xmlns:ns1=""http://www.example.com/ns1"">This is element 2 in ns1 but changed now</ns1:elem2>", newValue2);

        }
 public int Compare(T x, T y)
 {
     return(_defaultComparer.Compare(y, x));
 }
Esempio n. 38
0
    public bool runTest()
    {
        //////////// Global Variables used for all tests
        int iCountErrors = 0;
        int iCountTestcases = 0;

        Comparer comp;

        string[] str1 = { "Apple", "abc", };
        string[] str2 = { "Æble", "ABC" };

        try
        {
            do
            {
                /////////////////////////  START TESTS ////////////////////////////
                ///////////////////////////////////////////////////////////////////

                //[] Vanilla test case - The TextInfo property of the CultureInfo is used in the CaseInsensitiveHashCodeProvider
                //TextInfo has GetCaseInsensitiveHashCode() methods

                iCountTestcases++;
                var somePopularCultureNames = new string[] {
                    "cs-CZ","da-DK","de-DE","el-GR","en-US",
                    "es-ES","fi-FI","fr-FR","hu-HU","it-IT",
                    "ja-JP","ko-KR","nb-NO","nl-NL","pl-PL",
                    "pt-BR","pt-PT","ru-RU","sv-SE","tr-TR",
                    "zh-CN","zh-HK","zh-TW" };
                foreach (string cultureName in somePopularCultureNames)
                {
                    CultureInfo culture = new CultureInfo(cultureName);
                    if (culture == null)
                    {
                        continue;
                    }

                    iCountTestcases++;

                    comp = new Comparer(culture);

                    //The following cultures do this the other way round
                    //da-DK, is-IS, nb-NO, nn-NO
                    if (culture.Name != "da-DK" && culture.Name != "is-IS" && culture.Name != "nb-NO" && culture.Name != "nn-NO")
                    {
                        if (comp.Compare(str1[0], str2[0]) != 1)
                        {
                            iCountErrors++;
                            Console.WriteLine("Err_3245sdg, Wrong value returned, {0}, culture: {1}", comp.Compare(str1[0], str2[0]), culture);
                        }
                    }
                    else
                    {
                        if (comp.Compare(str1[0], str2[0]) != -1)
                        {
                            iCountErrors++;
                            Console.WriteLine("Err_297dg, Wrong value returned, {0}, culture: {1}", comp.Compare(str1[0], str2[0]), culture.Name);
                        }
                    }

                    if (comp.Compare(str1[1], str2[1]) != -1)
                    {
                        iCountErrors++;
                        Console.WriteLine("Err_3467tsg, Wrong value returned, {0}, culture: {1}", comp.Compare(str1[1], str2[1]), culture.Name);
                    }
                }

                //[] Call ctor with null CultureInfo
                try
                {
                    comp = new Comparer((CultureInfo)null);
                    iCountErrors++;
                    Console.WriteLine("Err_89743asjppn Expected ctor to throw ArgumentNullException");
                }
                catch (ArgumentNullException) { }
                catch (Exception e)
                {
                    iCountErrors++;
                    Console.WriteLine("Err_4447abcn Unexpected exceptin thrown: {0}", e);
                }
                /////////////////////////// END TESTS /////////////////////////////
            } while (false);
        }
        catch (Exception exc_general)
        {
            ++iCountErrors;
            Console.WriteLine(" : Error Err_8888yyy! exc_general==\n" + exc_general.ToString());
        }

        ////  Finish Diagnostics
        if (iCountErrors == 0)
        {
            return true;
        }
        else
        {
            Console.WriteLine("Fail! iCountErrors==" + iCountErrors);
            return false;
        }
    }
Esempio n. 39
0
 protected override bool Dominates(T x, T y)
 {
     return(Comparer.Compare(x, y) <= 0);
 }
Esempio n. 40
0
		internal static Comparer GetUserIdentityComparer(string identity, string @namespace, Comparer comparer, UserEntity entity, out UserIdentityType identityType)
		{
			if(string.IsNullOrWhiteSpace(identity))
				throw new ArgumentNullException("identity");

			string text;

			// 默认条件
			comparer = comparer & comparer.Compare(entity.Namespace, "=", TrimNamespace(@namespace));

			if(Zongsoft.Text.TextRegular.Web.Email.IsMatch(identity, out text))
			{
				identityType = UserIdentityType.Email;

				comparer = comparer & comparer.Compare(entity.Email, "=", text);
			}
			else if(Zongsoft.Text.TextRegular.Chinese.Cellphone.IsMatch(identity, out text))
			{
				identityType = UserIdentityType.Phone;

				comparer = comparer & comparer.Compare(entity.PhoneNumber, "=", text);
			}
			else
			{
				identityType = UserIdentityType.Name;

				comparer = comparer & comparer.Compare(entity.Name, "=", text);
			}

			return comparer;
		}
Esempio n. 41
0
    public bool runTest()
    {
        //////////// Global Variables used for all tests
        int iCountErrors    = 0;
        int iCountTestcases = 0;

        Comparer comp;

        string[] str1 = { "Apple", "abc", };
        string[] str2 = { "Æble", "ABC" };

        try
        {
            do
            {
                /////////////////////////  START TESTS ////////////////////////////
                ///////////////////////////////////////////////////////////////////

                //[] Vanilla test case - The TextInfo property of the CultureInfo is used in the CaseInsensitiveHashCodeProvider
                //TextInfo has GetCaseInsensitiveHashCode() methods

                iCountTestcases++;
                var somePopularCultureNames = new string[] {
                    "cs-CZ", "da-DK", "de-DE", "el-GR", "en-US",
                    "es-ES", "fi-FI", "fr-FR", "hu-HU", "it-IT",
                    "ja-JP", "ko-KR", "nb-NO", "nl-NL", "pl-PL",
                    "pt-BR", "pt-PT", "ru-RU", "sv-SE", "tr-TR",
                    "zh-CN", "zh-HK", "zh-TW"
                };
                foreach (string cultureName in somePopularCultureNames)
                {
                    CultureInfo culture = new CultureInfo(cultureName);
                    if (culture == null)
                    {
                        continue;
                    }

                    iCountTestcases++;

                    comp = new Comparer(culture);

                    //The following cultures do this the other way round
                    //da-DK, is-IS, nb-NO, nn-NO
                    if (culture.Name != "da-DK" && culture.Name != "is-IS" && culture.Name != "nb-NO" && culture.Name != "nn-NO")
                    {
                        if (comp.Compare(str1[0], str2[0]) != 1)
                        {
                            iCountErrors++;
                            Console.WriteLine("Err_3245sdg, Wrong value returned, {0}, culture: {1}", comp.Compare(str1[0], str2[0]), culture);
                        }
                    }
                    else
                    {
                        if (comp.Compare(str1[0], str2[0]) != -1)
                        {
                            iCountErrors++;
                            Console.WriteLine("Err_297dg, Wrong value returned, {0}, culture: {1}", comp.Compare(str1[0], str2[0]), culture.Name);
                        }
                    }

                    if (comp.Compare(str1[1], str2[1]) != -1)
                    {
                        iCountErrors++;
                        Console.WriteLine("Err_3467tsg, Wrong value returned, {0}, culture: {1}", comp.Compare(str1[1], str2[1]), culture.Name);
                    }
                }

                //[] Call ctor with null CultureInfo
                try
                {
                    comp = new Comparer((CultureInfo)null);
                    iCountErrors++;
                    Console.WriteLine("Err_89743asjppn Expected ctor to throw ArgumentNullException");
                }
                catch (ArgumentNullException) { }
                catch (Exception e)
                {
                    iCountErrors++;
                    Console.WriteLine("Err_4447abcn Unexpected exceptin thrown: {0}", e);
                }
                /////////////////////////// END TESTS /////////////////////////////
            } while (false);
        }
        catch (Exception exc_general)
        {
            ++iCountErrors;
            Console.WriteLine(" : Error Err_8888yyy! exc_general==\n" + exc_general.ToString());
        }

        ////  Finish Diagnostics
        if (iCountErrors == 0)
        {
            return(true);
        }
        else
        {
            Console.WriteLine("Fail! iCountErrors==" + iCountErrors);
            return(false);
        }
    }
Esempio n. 42
0
        public virtual int Compare(object x, object y)
        {
            if (x is string)
            {
                return ((string)x).CompareTo((string)y);
            }

            var comparer = new Comparer(System.Globalization.CultureInfo.InvariantCulture);
            if (x is int || y is string)
            {
                return comparer.Compare(x, y);
            }

            return -1;
        }
Esempio n. 43
0
        protected override bool MatchesImpl(IAttributeBag attributeBag, ConstraintContext context)
        {
            var element = attributeBag.GetAdapter <Element>();

            return(element != null && Comparer.Compare(IsVisible(element).ToString()));
        }
Esempio n. 44
0
 private bool MatchesKey(TKey key, SkipListNode currentNode)
 {
     return(!(currentNode is HeaderSkipListNode) && _comparer.Compare(key, currentNode.Key) == 0);
 }
Esempio n. 45
0
 public int Compare(Point x, Point y)
 {
     return(double_cmp.Compare(x.X, y.X));
 }