Esempio n. 1
0
            internal override Expression MakeCompareExpression(Expression lhs, Expression rhs)
            {
                var tProperty   = typeof(TProperty);
                var lhsProperty = GetProperty.MakeInvocation(lhs);
                var rhsProperty = GetProperty.MakeInvocation(rhs);

                if (Comparer == null)
                {
                    var compareTo = tProperty.GetMethod(
                        "CompareTo", new [] { tProperty }
                        );
                    if (compareTo != null)
                    {
                        return(Expression.Call(
                                   lhsProperty, compareTo, rhsProperty
                                   ));
                    }
                }

                var compare = RuntimeComparer.GetType().GetMethod("Compare", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

                return(Expression.Call(
                           Expression.Constant(RuntimeComparer),
                           compare, lhsProperty, rhsProperty
                           ));
            }
Esempio n. 2
0
 static void SortAndPrint(Person[] persons, IComparer <Person> theComparer)
 {
     Console.WriteLine("==================");
     Console.WriteLine($"== Sort by {theComparer.GetType()}");
     Console.WriteLine("==================");
     Array.Sort(persons, theComparer);
     PrintPersons(persons);
 }
Esempio n. 3
0
        private static string GetComparerName <T>(IComparer <T> comparer)
        {
            string comparerStr = comparer.ToString();

            if (comparerStr == comparer.GetType().ToString())
            {
                comparerStr = comparer.GetType().Name;
            }

            comparerStr = AssertUtility.FormatArgument(comparerStr);

            if (comparer == EqualityComparer <T> .Default)
            {
                comparerStr += " (default)";
            }

            return(comparerStr);
        }
Esempio n. 4
0
 /// <summary>
 /// Modifies the constraint to use an <see cref="IComparer{T}"/> and returns self.
 /// </summary>
 public CollectionOrderedConstraint Using <T>(IComparer <T> comparer)
 {
     if (_activeStep.ComparerName != null)
     {
         throw new InvalidOperationException("Only one Using modifier may be used");
     }
     _activeStep.Comparer     = ComparisonAdapter.For(comparer);
     _activeStep.ComparerName = comparer.GetType().FullName;
     return(this);
 }
Esempio n. 5
0
        public bool Remove <T>(IComparer <T> comparer)
        {
            if (comparer == null)
            {
                return(false);
            }

            Type type = comparer.GetType().GetGenericArguments()[0];

            return(Remove(type));
        }
Esempio n. 6
0
        public void Add <T>(IComparer <T> comparer)
        {
            if (comparer == null)
            {
                return;
            }

            Type type = comparer.GetType().GetGenericArguments()[0];

            Cache.AddOrUpdate(type, comparer as IComparer);
        }
Esempio n. 7
0
        private void TestSpeed(IEnumerable <INode> nodes, IComparer <INode> comparer, bool expectFaster)
        {
            List <INode> defaultSorted = new List <INode>(nodes);
            Stopwatch    timer         = new Stopwatch();

            timer.Start();
            defaultSorted.Sort();
            timer.Stop();

            Console.WriteLine("Default Sort: " + timer.Elapsed);
            long defTime = timer.ElapsedTicks;

            defaultSorted.Clear();
            defaultSorted = null;
            GC.GetTotalMemory(true);

            List <INode> custSorted = new List <INode>(nodes);

            timer.Reset();
            timer.Start();
            custSorted.Sort(comparer);
            timer.Stop();

            custSorted.Clear();
            custSorted = null;
            GC.GetTotalMemory(true);

            Console.WriteLine(comparer.GetType().Name + " Sort: " + timer.Elapsed);
            long custTime = timer.ElapsedTicks;

            if (expectFaster)
            {
                Console.WriteLine("Speed Up: " + ((double)defTime) / ((double)custTime));
                Assert.True(custTime <= defTime, comparer.GetType().Name + " should be faster");
            }
            else
            {
                Console.WriteLine("Slow Down: " + ((double)defTime) / ((double)custTime));
                Assert.True(defTime <= custTime, comparer.GetType().Name + " should be slower");
            }
        }
Esempio n. 8
0
 void CorrectOnOneTransactionTypeExists()
 {
     if (CurrentPriceIndex == -1 && transactions.Count != 0)
     {
         int    lastIndex       = transactions.Count - 1;
         string transantionType = transactions[0].Bid == 0 ? "Bid" : "Ask";
         int    volume          = transactions[lastIndex].Volume + 5;
         double price;
         if (comparer.GetType() == typeof(PriceAscedingComparer))
         {
             price = IsDownMoving(transantionType) ? transactions[lastIndex].Price + 0.5 : transactions[0].Price - 0.5;
         }
         else
         {
             price = IsDownMoving(transantionType) ? transactions[lastIndex].Price - 0.5 : transactions[0].Price + 0.5;
         }
         TransactionData tdvm = new TransactionData(transantionType, volume, price);
         transactions.Add(tdvm);
         CurrentPriceIndex = transactions.IndexOf(tdvm);
     }
 }
Esempio n. 9
0
        public override void OnResponse(NetState sender, RelayInfo info)
        {
            base.OnResponse(sender, info);

            PlayerMobile pm = sender.Mobile as PlayerMobile;

            if (pm == null || !IsMember(pm, guild))
            {
                return;
            }

            int id = info.ButtonID;

            switch (id)
            {
            case 5:                     //Filter
            {
                TextRelay t = info.GetTextEntry(1);
                pm.SendGump(GetResentGump(player, guild, m_Comparer, m_Ascending, (t == null) ? "" : t.Text, 0));
                break;
            }

            case 6:                     //Back
            {
                pm.SendGump(GetResentGump(player, guild, m_Comparer, m_Ascending, m_Filter, m_StartNumber - itemsPerPage));
                break;
            }

            case 7:                     //Forward
            {
                pm.SendGump(GetResentGump(player, guild, m_Comparer, m_Ascending, m_Filter, m_StartNumber + itemsPerPage));
                break;
            }
            }

            if (id >= 100 && id < (100 + m_Fields.Length))
            {
                IComparer <T> comparer = m_Fields[id - 100].Comparer;

                if (m_Comparer.GetType() == comparer.GetType())
                {
                    m_Ascending = !m_Ascending;
                }

                pm.SendGump(GetResentGump(player, guild, comparer, m_Ascending, m_Filter, 0));
            }
            else if (id >= 200 && id < (200 + m_List.Count))
            {
                pm.SendGump(GetObjectInfoGump(player, guild, m_List[id - 200]));
            }
        }
        protected bool GetComparerExpression(Expression arg, out Expression comparerExpression)
        {
            if (_comparer != null)
            {
                var compareInfo = GetComparerCompareMethodInfo(_comparer.GetType());
                comparerExpression = _compareExpression(
                    Expression.Call(Expression.Constant(_comparer), compareInfo,
                                    arg, Expression.Constant(Limit, typeof(T))),
                    Expression.Constant(0));
                return(true);
            }

            comparerExpression = null;
            return(false);
        }
Esempio n. 11
0
        private void ShowOrdering(IEnumerable<INode> nodes, IComparer<INode> comparer)
        {
            Console.WriteLine("Standard Ordering");
            NTriplesFormatter formatter = new NTriplesFormatter();
            foreach (INode n in nodes.OrderBy(x => x))
            {
                Console.WriteLine(n.ToString(formatter));
            }
            Console.WriteLine();

            Console.WriteLine(comparer.GetType().Name + " Ordering");
            foreach (INode n in nodes.OrderBy(x => x, comparer))
            {
                Console.WriteLine(n.ToString(formatter));
            }
            Console.WriteLine();
        }
Esempio n. 12
0
        private ParetoRanked doOneRanking(IEnumerable <T> scores, IComparer <T> comparer)
        {
            if (scores.Count() == 0)
            {
                throw new ArgumentException("Cannot (pareto) rank on an array of zero length");
            }
            List <T> nonDominated = new List <T>();
            List <T> dominated    = new List <T>();

            foreach (var scoreA in scores)
            {
                bool isNonDominant = true;
                foreach (var scoreB in scores)
                {
                    if (object.ReferenceEquals(scoreB, scoreA))
                    {
                        continue;
                    }
                    int comparison = comparer.Compare(scoreA, scoreB);
                    if (comparison > 0) // then scores[j] dominates score[i].
                    {
                        isNonDominant = false;
                        break;
                    }
                }
                if (isNonDominant)
                {
                    nonDominated.Add(scoreA);
                }
                else
                {
                    dominated.Add(scoreA);
                }
            }
            if (nonDominated.Count == 0)
            {
                throw new Exception("Invalid result: the Pareto front should always have at least one element. The comparer " +
                                    comparer.GetType().FullName + " may have errors");
            }
            return(new ParetoRanked(nonDominated.ToArray(), dominated.ToArray()));
        }
Esempio n. 13
0
        internal override Pair <MethodInfo, Expression[]> GetOperator()
        {
            Type       sourceType = this.m_keySelector.Parameters[0].Type;
            MethodInfo operation  = TypeSystem.FindStaticMethod(
                typeof(Microsoft.Research.DryadLinq.HpcLinqQueryable), "RangePartition",
                new Type[] { typeof(IQueryable <>).MakeGenericType(sourceType),
                             m_keySelector.GetType(),
                             m_partitionKeys.GetType(),
                             m_comparer.GetType(),
                             typeof(bool) },
                new Type[] { sourceType, typeof(TKey) });

            Expression[] arguments = new Expression[] {
                this.m_keySelector,
                Expression.Constant(this.m_partitionKeys),
                Expression.Constant(this.m_comparer, typeof(IComparer <TKey>)),
                Expression.Constant(this.m_isDescending)
            };

            return(new Pair <MethodInfo, Expression[]>(operation, arguments));
        }
Esempio n. 14
0
        private void InternalCompareSort(IComparer <T> comparer)
        {
            this._list = this._list.OrderBy(item => item, comparer).ToList();

            if (this._from != null)
            {
                if (comparer is IComparer)
                {
                    System.Reflection.MethodInfo compareSortMethod = this._from.GetType().GetMethod("InternalCompareSort2", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                    compareSortMethod.Invoke(this._from, new object[] { comparer });
                }
                else
                {
                    Type toType = this._from.GetType().GetProperty("ValueType").GetValue(this._from) as Type;
                    throw new InvalidCastException(string.Format("Cannot cast from {0} to System.Collections.Generic.IComparer<{1}>", comparer.GetType(), toType));
                }
            }
        }
Esempio n. 15
0
        protected virtual async Task SortItems(IComparer <PlaylistItem> comparer, bool descending)
        {
            Logger.Write(this, LogLevel.Debug, "Sorting playlist using comparer: \"{0}\"", comparer.GetType().Name);
            using (var transaction = this.Database.BeginTransaction(this.Database.PreferredIsolationLevel))
            {
                var set           = this.Database.Set <PlaylistItem>(transaction);
                var playlistItems = set.ToArray();
                Array.Sort(playlistItems, comparer);
                if (descending)
                {
                    Logger.Write(this, LogLevel.Debug, "Sort is descending, reversing sequence.");
                    Array.Reverse(playlistItems);
                }
                for (var a = 0; a < playlistItems.Length; a++)
                {
                    playlistItems[a].Sequence = a;
                }
                await EntityHelper <PlaylistItem> .Create(
                    this.Database,
                    this.Database.Tables.PlaylistItem,
                    transaction
                    ).UpdateAsync(
                    playlistItems,
                    new[] { nameof(PlaylistItem.Sequence) }
                    ).ConfigureAwait(false);

                if (transaction.HasTransaction)
                {
                    transaction.Commit();
                }
            }
        }
Esempio n. 16
0
        private void CheckCombinations(List<INode> nodes, IComparer<INode> comparer)
        {
            if (nodes.Count == 0) Assert.Fail("No Input");

            Console.WriteLine("INode Typed Tests");
            for (int i = 0; i < nodes.Count; i++)
            {
                for (int j = 0; j < nodes.Count; j++)
                {
                    INode a = nodes[i];
                    INode b = nodes[j];
                    if (i == j || ReferenceEquals(a, b))
                    {
                        Assert.AreEqual(0, a.CompareTo(b), i + " == " + j + " was expected");
                        Assert.AreEqual(0, b.CompareTo(a), j + " == " + i + " was expected");
                        Console.WriteLine(i + " compareTo " + j + " => i == j");

                        Assert.AreEqual(0, comparer.Compare(a, b), i + " == " + j + " was expected (" + comparer.GetType().Name + ")");
                        Assert.AreEqual(0, comparer.Compare(b, a), j + " == " + i + " was expected (" + comparer.GetType().Name + ")");
                    }
                    else
                    {
                        int c = a.CompareTo(b);
                        int d = comparer.Compare(a, b);
                        Assert.AreEqual(c * -1, b.CompareTo(a), j + " compare " + i + " was expected to be inverse of " + i + " compareTo " + j);
                        Assert.AreEqual(d * -1, comparer.Compare(b, a), j + " compare " + i + " was expected to be inverse of " + i + " compareTo " + j + " (" + comparer.GetType().Name + ")");

                        if (c > 0)
                        {
                            Console.WriteLine(i + " compareTo " + j + " => i > j");
                        }
                        else if (c == 0)
                        {
                            Console.WriteLine(i + " compareTo " + j + " => i == j");
                        }
                        else
                        {
                            Console.WriteLine(i + " compareTo " + j + " => i < j");
                        }
                    }
                }
                Console.WriteLine();
            }
            Console.WriteLine();
        }
Esempio n. 17
0
 void SortAndLog(IComparer <IVIEntry> cmp)
 {
     dir.Entries.Sort(cmp);
     Debug.Log("Sorted by " + cmp.GetType().FullName + " ...");
     LogDentries();
 }
Esempio n. 18
0
        public override void PopulateGump()
        {
            base.PopulateGump();

            List <T> list = m_List;

            if (WillFilter)
            {
                m_List = new List <T>();
                for (int i = 0; i < list.Count; i++)
                {
                    if (!IsFiltered(list[i], m_Filter))
                    {
                        m_List.Add(list[i]);
                    }
                }
            }
            else
            {
                m_List = new List <T>(list);
            }

            m_List.Sort(m_Comparer);
            m_StartNumber = Math.Max(Math.Min(m_StartNumber, m_List.Count - 1), 0);



            AddBackground(130, 75, 385, 30, 0xBB8);
            AddTextEntry(135, 80, 375, 30, 0x481, 1, m_Filter);
            AddButton(520, 75, 0x867, 0x868, 5, GumpButtonType.Reply, 0);               //Filter Button

            int width = 0;

            for (int i = 0; i < m_Fields.Length; i++)
            {
                InfoField <T> f = m_Fields[i];

                AddImageTiled(65 + width, 110, f.Width + 10, 26, 0xA40);
                AddImageTiled(67 + width, 112, f.Width + 6, 22, 0xBBC);
                AddHtmlText(70 + width, 113, f.Width, 20, f.Name, false, false);

                bool isComparer = (m_Fields[i].Comparer.GetType() == m_Comparer.GetType());

                int ButtonID = (isComparer) ? (m_Ascending ? 0x983 : 0x985) : 0x2716;

                AddButton(59 + width + f.Width, 117, ButtonID, ButtonID + (isComparer ? 1 : 0), 100 + i, GumpButtonType.Reply, 0);

                width += (f.Width + 12);
            }

            if (m_StartNumber <= 0)
            {
                AddButton(65, 80, 0x15E3, 0x15E7, 0, GumpButtonType.Page, 0);
            }
            else
            {
                AddButton(65, 80, 0x15E3, 0x15E7, 6, GumpButtonType.Reply, 0);                          // Back
            }
            if (m_StartNumber + itemsPerPage > m_List.Count)
            {
                AddButton(95, 80, 0x15E1, 0x15E5, 0, GumpButtonType.Page, 0);
            }
            else
            {
                AddButton(95, 80, 0x15E1, 0x15E5, 7, GumpButtonType.Reply, 0);                          // Forward
            }
            int itemNumber = 0;

            if (m_Ascending)
            {
                for (int i = m_StartNumber; i < m_StartNumber + itemsPerPage && i < m_List.Count; i++)
                {
                    DrawEntry(m_List[i], i, itemNumber++);
                }
            }
            else             //descending, go from bottom of list to the top
            {
                for (int i = m_List.Count - 1 - m_StartNumber; i >= 0 && i >= (m_List.Count - itemsPerPage - m_StartNumber); i--)
                {
                    DrawEntry(m_List[i], i, itemNumber++);
                }
            }

            DrawEndingEntry(itemNumber);
        }
Esempio n. 19
0
 static void PrintSortedArray(Person[] people, IComparer <Person> methodComparer)
 {
     Console.WriteLine($"Sorting by {methodComparer.GetType()}");
     Array.Sort(people, methodComparer);
     PrintPersonArray(people);
 }