Example #1
0
        public static void PrioritiseOrderBooks(List<OrderBook.OrderBook> orderBooks,
                                                Comparison<OrderBook.OrderBook> orderBookComparer, //reads as "sort the OrderBooks by orderBookComparer
                                                int dedicatedThreadsPercentage = 10,    // the top 10% of the sorted OrderBooks should have dedicated threads,
                                                int threadPooledPercentage = 20)        // the next 20% of the OrderBooks use the ThreadPool
                                                                                        // and the remaining 70% will be synchronouss"
        {
            if (orderBooks == null) throw new ArgumentNullException("orderBooks");
            if (orderBookComparer == null) throw new ArgumentNullException("orderBookComparer");

            orderBooks.Sort(orderBookComparer);

            for (int i = 0; i < orderBooks.Count; ++i)
            {
                decimal percentageOfBooks = ((i + 1) / (decimal)orderBooks.Count) * 100m;
                OrderBook.OrderBook oBook = orderBooks[i];
                int limitForThreadPooled = dedicatedThreadsPercentage + threadPooledPercentage;

                if (percentageOfBooks <= dedicatedThreadsPercentage && !(oBook.OrderProcessingStrategy is DedicatedThreadsOrderProcessor))
                    oBook.OrderProcessingStrategy = new DedicatedThreadsOrderProcessor(oBook.BuyOrders, oBook.SellOrders,
                                                                                       oBook.Trades);
                else if (percentageOfBooks <= limitForThreadPooled && !(oBook.OrderProcessingStrategy is ThreadPooledOrderProcessor))
                    oBook.OrderProcessingStrategy = new ThreadPooledOrderProcessor(oBook.BuyOrders, oBook.SellOrders,
                                                                                   oBook.Trades);
                else if (!(oBook.OrderProcessingStrategy is SynchronousOrderProcessor))
                    oBook.OrderProcessingStrategy = new SynchronousOrderProcessor(oBook.BuyOrders, oBook.SellOrders,
                                                                                  oBook.Trades);
            }
        }
Example #2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DataAccess.Filter"/> class.
 /// </summary>
 /// <param name="field">Field name for filter</param>
 /// <param name="comparator">Comparator operator</param>
 /// <param name="value">Value for comparison</param>
 public Filter(string field, Comparison comparator, object value)
     : this()
 {
     Field = field;
     Comparator = comparator;
     Value = value;
 }
Example #3
0
 public Field(string name, object value, Comparison comparison, Logical? logical)
 {
     Name = name;
     Value = value;
     Comparison = comparison;
     Logical = logical;
 }
 public MatchDescription(CountSource countSource, Card cardType, Comparison comparison, int threshhold)
 {
     this.cardType = cardType;
     this.countSource = countSource;
     this.comparison = comparison;
     this.countThreshHold = threshhold;
 }
 public KnowledgeCondition(Scope scope, Comparison comparison, string name, object rhs = null)
 {
     _scope = scope;
     _comparison = comparison;
     _name = name;
     _rhs = rhs;
 }
 public static void Sort(int[][] array, Comparison<int[]> comparison)
 {
     if (comparison == null)
         throw new ArgumentNullException();
     SortAdapter comparer = new SortAdapter(comparison);
     BubbleSort(array, comparer);
 }
		internal DepthStencilState(Device device, DepthStencilStateDescription description)
			: base(device)
		{
			_description = description;
		    _isDepthEnabled = description.IsDepthEnabled;
		    _depthComparison = description.DepthComparison;
		}
		public void Sort (Comparison<ICompletionData> comparison)
		{
			lock (sortedList) {
				sortedList.Sort (comparison);
				sorted = true;
			}
		}
Example #9
0
        private void AddConstraint(string columnName, Comparison comp, object value)
        {
            Constraint c = new Constraint(ConstraintType.Where, columnName);

            if(result.Count > 1)
                c = new Constraint(ConstraintType.And, columnName);

            //c.ParameterName = columnName;

            if(comp == Comparison.StartsWith)
            {
                value = string.Format("{0}%", value);
                comp = Comparison.Like;
            }
            else if(comp == Comparison.EndsWith)
            {
                value = string.Format("%{0}", value);
                comp = Comparison.Like;
            }

            c.Comparison = comp;
            c.ParameterValue = value;

            result.Add(c);
        }
        public DepthStencilState(bool depthEnabled, bool stencilEnabled, Comparison depthComparison,
            Comparison frontFaceComparison, StencilOperation frontFaceDepthFailOp, StencilOperation frontFaceFailOp, StencilOperation frontFacePassOp,
            Comparison backFaceComparison, StencilOperation backFaceDepthFailOp, StencilOperation backFaceFailOp, StencilOperation backFacePassOp)
        {

            DepthStencilStateDescription desc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = depthEnabled,
                IsStencilEnabled = stencilEnabled,
                DepthWriteMask = SharpDX.Direct3D11.DepthWriteMask.All,
                FrontFace = new DepthStencilOperationDescription()
                {
                    Comparison = frontFaceComparison,
                    DepthFailOperation = frontFaceDepthFailOp,
                    FailOperation = frontFaceFailOp,
                    PassOperation = frontFacePassOp
                },
                BackFace = new DepthStencilOperationDescription()
                {
                    Comparison = backFaceComparison,
                    DepthFailOperation = backFaceDepthFailOp,
                    FailOperation = backFaceFailOp,
                    PassOperation = backFacePassOp
                },
                DepthComparison = depthComparison
            };

            NativeDepthStencilState = new SharpDX.Direct3D11.DepthStencilState(GraphicManager.Device, desc);

        }
 static BindingParser()
 {
     MemberComparison = OrderByMemberPriority;
     DelimeterTokens = new HashSet<TokenType>
     {
         TokenType.Comma,
         TokenType.Eof,
         TokenType.Semicolon
     };
     ResourceTokens = new HashSet<TokenType>
     {
         TokenType.Dollar,
         TokenType.DoubleDollar
     };
     LiteralConstants = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
     {
         TrueLiteral,
         FalseLiteral,
         NullLiteral
     };
     LiteralTokens = new HashSet<TokenType>
     {
         TokenType.IntegerLiteral,
         TokenType.RealLiteral,
         TokenType.StringLiteral
     };
     EmptyBindingSourceDelegates = new Func<IDataContext, IObserver>[]
     {
         BindEmptyPathSource
     };
     EmptyPathSourceDelegate = context => context.Add(BindingBuilderConstants.Sources, EmptyBindingSourceDelegates);
 }
 /// <summary>
 /// Creates the TestDseVersion object
 /// </summary>
 /// <param name="comparisonOperator">Determines if the DSE version required should be "greater or equals to" = 1, "equals to" = 0, "less than or equal to " = -1</param>
 public TestDseVersion(int major, int minor, Comparison comparison = Comparison.GreaterThanOrEqualsTo)
 {
     Major = major;
     Minor = minor;
     Build = 0;
     Comparison = comparison;
 }
Example #13
0
        public Comparator(string name, Comparison<NativeArray> comparison)
        {
            GCHandle selfHandle = default(GCHandle);
            try
            {
                var utf = Encoding.UTF8.GetBytes(name);
                NativeName = Marshal.AllocHGlobal(utf.Length + 1);
                Marshal.Copy(utf, 0, NativeName, utf.Length);

                Comparison = comparison;

                selfHandle = GCHandle.Alloc(this);

                Handle = LevelDBInterop.leveldb_comparator_create(
                    GCHandle.ToIntPtr(selfHandle),
                    Marshal.GetFunctionPointerForDelegate(Destructor),
                    Marshal.GetFunctionPointerForDelegate(Compare),
                    Marshal.GetFunctionPointerForDelegate(GetName));
                if (Handle == IntPtr.Zero)
                    throw new ApplicationException("Failed to initialize LevelDB comparator");
            }
            catch
            {
                if (selfHandle != default(GCHandle))
                    selfHandle.Free();
                if (NativeName != IntPtr.Zero)
                    Marshal.FreeHGlobal(NativeName);
                throw;
            }
        }
Example #14
0
 public ANDORWhere(Column column, object value, Comparison comp, bool useOr)
 {
     _column = column;
     _value = value;
     _comp = comp;
     _useOr = useOr;
 }
Example #15
0
		internal List<SubClause> SubClauses;    // Array of SubClause

		public WhereClause(string field, Comparison firstCompareOperator, object firstCompareValue)
		{
			FieldName = field;
			ComparisonOperator = firstCompareOperator;
			Value = firstCompareValue;
			SubClauses = new List<SubClause>();
		}
 public MatchDescription(Card card)
 {
     this.cardType = card;
     this.countSource = CountSource.Always;
     this.comparison = Comparison.Equals;
     this.countThreshHold = 1;
 }
Example #17
0
 //
 private static void CheckComparison(Comparison comparison, ComparisonResult comparisonResult, string propName, object lValue, object rValue)
 {
     Assert.AreEqual(comparisonResult, comparison.Result);
       Assert.AreEqual(propName, comparison.PropName);
       Assert.AreEqual(lValue, comparison.LValue);
       Assert.AreEqual(rValue, comparison.RValue);
 }
 public KeyCatalogFactory(Func<KeyCatalog, string> formatter,
     Comparison<KeyCatalog> nameSorter)
     : this()
 {
     ToStringFormatter = formatter;
     NameSorter = nameSorter;
 }
Example #19
0
 // Select sort
 // The way it's done here is that it creates an entirely new list (sorted) which it then begins to fill with the
 // nodes from the original list.
 public void SelectSort( Comparison< Drug > UsersDrugComparer )
 {
     //Create new "sorted" list
     DrugList sorted = new DrugList( );
     
     //While there are still nodes in the original list...
     while( this.count > 0 )
     {
         Node previous, minimum, removed;
         
         //Find the smallest node in the original list using the comparison method and return it and the one before it
         //NOTE: The comparison method in this case (found in pa4Test.cs) will actually sort it in descending order, but
         //this can be easily changed by removing the negative in the return statement in that method
         this.FindMinimalNode( out previous, out minimum, UsersDrugComparer );
         
         //Remove that node and store it in the variable "removed"
         removed = this.RemoveNode( previous, minimum );
         
         //Insert that node at the end of the sorted list
         sorted.InsertNode( removed, sorted.tail, null );
     }
     
     this.count = sorted.count;
     this.tail = sorted.tail;
     this.head = sorted.head;
 }
Example #20
0
        private void salvaScore_Click(object sender, RoutedEventArgs e)
        {
            List<itemRanking> ranking = new List<itemRanking>();
            ranking.Capacity = 3;
            itemRanking itemRanking = new itemRanking();

            itemRanking.nomeJogador = campoJogador.Text;
            itemRanking.pontuacao = this.pontuacao;

            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

            if (settings.Contains("ranking"))
            {
                ranking = (List<itemRanking>)settings["ranking"];
                ranking.Add(itemRanking);
                Comparison<itemRanking> comparador = new Comparison<itemRanking>(itemRanking.comparaPontuacao);
                ranking.Sort(comparador);
                if (ranking.Count > 3)
                {
                    ranking.RemoveAt(3);
                }
            }
            else
            {
                ranking.Add(itemRanking);
            }
            settings["ranking"] = ranking;
            settings.Save();
            NavigationService.Navigate(new Uri("/Ranking.xaml", UriKind.Relative));
        }
 public DaoSearchParameter(DbSelectParameter selectParameter, Comparison whereOperator)
     : this()
 {
     Comparison = whereOperator;
     SelectParameter = selectParameter;
     this.dateValue = selectParameter.Value is DateTime ? selectParameter.Value: null;
     this.julianValue = selectParameter.Value is DateTime ? (object)JulianDate.ToJulianDate((DateTime)this.dateValue) : null;
 }
Example #22
0
 public TypeBehaviorBuilder SortCases(Comparison<Case> comparison)
 {
     return Wrap((testClass, convention, cases, innerBehavior) =>
     {
         Array.Sort(cases, comparison);
         innerBehavior();
     });
 }
 public ModelClientValidationRequiredIfRule(string errorMessage, string otherProperty, Comparison comparison, object value, ModelMetadata metadata, ControllerContext context)
 {
     ErrorMessage = errorMessage;
     ValidationType = "requiredif";
     ValidationParameters.Add("other", BuildDependentPropertyId(metadata, context as ViewContext, otherProperty));
     ValidationParameters.Add("comp", comparison.ToString().ToLower());
     ValidationParameters.Add("value", value.ToString().ToLower());
 }
Example #24
0
 /// <summary>
 /// SqlQuery条件类构造函数
 /// </summary>
 /// <param name="ctype">查询类型,包括:Where、And、Or</param>
 /// <param name="columnname">条件列名</param>
 /// <param name="cparsion">条件表达式类型</param>
 /// <param name="value">条件值</param>
 /// <param name="isParentheses">是否加左括号</param>
 public SqlqueryCondition(ConstraintType ctype, string columnname, Comparison cparsion, object value, bool isParentheses = false)
 {
     SQConstraintType = ctype;
     SQColumnName = columnname;
     SQComparison = cparsion;
     SQValue = value;
     IsParentheses = isParentheses;
 }
 public static CardAcceptanceDescription For(Card card, int count, Card testCard, CountSource countSouce, Comparison comparison, int threshhold)
 {
     return new CardAcceptanceDescription(card, new MatchDescription[]
     {
         new MatchDescription(CountSource.CountAllOwned, card, Comparison.LessThan, count),
         new MatchDescription(countSouce, testCard, comparison, threshhold),
     });
 }
 public void SortBooks(Comparison<Book> comparison)
 {
     if (comparison == null)
     {
         throw new ArgumentNullException("comparison");
     }
     list.Sort(comparison);
 }
 public static CardAcceptanceDescription For(Card card, CountSource countSouce, Card testCard, Comparison comparison, int threshhold)
 {
     return new CardAcceptanceDescription(card, new MatchDescription[]
     {
         new MatchDescription(CountSource.Always, card, Comparison.GreaterThan, 0),
         new MatchDescription(countSouce, testCard, comparison, threshhold),
     });
 }
Example #28
0
        public void Should_convert_Comparison_to_Comparer()
        {
            Comparison<int> comparison = new Comparison<int>((x, y) => x.CompareTo(y));
            ComparisonComparer<int> adapter = new ComparisonComparer<int>(comparison);

            Assert.IsInstanceOf<IComparer<int>>(adapter);
            Assert.IsInstanceOf<IComparer>(adapter);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="RequiredIfAttribute"/> class.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="comparison">The comparison.</param>
        /// <param name="value">The value.</param>
        public RequiredIfAttribute(string name, Comparison comparison, object value)
        {
            _DependentPropertyName = name;
            _DependentPropertyComparison = comparison;
            _DependentPropertyValue = value;

            ErrorMessage = DefaultErrorMessageFormatString;
        }
 private static TypeBehaviorBuilder SortCases(this TypeBehaviorBuilder builder, Comparison<Case> comparison)
 {
     return builder.Wrap((testClass, convention, cases, innerBehavior) =>
     {
         Array.Sort(cases, comparison);
         innerBehavior();
     });
 }
Example #31
0
 internal ComparisonComparer(Comparison <T> comparison)
 {
     this.comparison = comparison;
 }
Example #32
0
        public static int Compare <T>(this IList <T> list, int listOffset, IList <T> other, int otherOffset, int length, Comparison <T> comparison)
        {
            if (other == null)
            {
                throw new ArgumentNullException("other");
            }

            if (comparison == null)
            {
                throw new ArgumentNullException("comparison");
            }

            return(CompareInternal(list, listOffset, other, otherOffset, length, comparison));
        }
Example #33
0
File: Font.cs Project: xxami/Pulsus
        private void GenerateTextures(ushort characterCount)
        {
            Log.Info("Font: Generating font textures");

            byte[] textureData = new byte[textureSize * textureSize * 4];
            textures.Add(new Texture2D(textureSize, textureSize));

            // sort the glyphs starting form widest one, prioritize
            // ASCII characters into first texture

            Comparison <ushort> glyphComparison = new Comparison <ushort>((g1, g2) =>
            {
                if (glyphs[g1].width < glyphs[g2].width && glyphs[g1].height < glyphs[g2].height)
                {
                    return(1);
                }
                else if
                (glyphs[g1].width > glyphs[g2].width && glyphs[g1].height > glyphs[g2].height)
                {
                    return(-1);
                }
                else
                {
                    return(0);
                }
            });

            List <ushort> sortedGlyphs = new List <ushort>(characterCount);

            for (ushort i = 0; i < Math.Min((ushort)256, characterCount); ++i)
            {
                sortedGlyphs.Add(i);
            }

            sortedGlyphs.Sort(glyphComparison);

            if (characterCount > 256)
            {
                List <ushort> sortedGlyphs2 = new List <ushort>(characterCount - 256);
                for (ushort i = 256; i < characterCount; ++i)
                {
                    sortedGlyphs2.Add(i);
                }

                sortedGlyphs2.Sort(glyphComparison);

                sortedGlyphs.AddRange(sortedGlyphs2);
            }

            // render glyphs

            int[]     columnPixels   = new int[textureSize];
            int       x              = 0;
            int       currentTexture = 0;
            Texture2D texture        = textures[0];

            for (ushort g = 0; g < sortedGlyphs.Count; ++g)
            {
                ushort i = sortedGlyphs[g];
                if (glyphs[i].width * glyphs[i].height <= 0)
                {
                    continue;
                }

                IntPtr surface = GetGlyphSurface(i);
                if (surface == IntPtr.Zero)
                {
                    continue;
                }

                int    surfaceWidth, surfaceHeight;
                byte[] glyphData = GetGlyphData(surface, glyphs[i], out surfaceWidth, out surfaceHeight);
                SDL.SDL_FreeSurface(surface);

                if (x + surfaceWidth >= textureSize)
                {
                    x = 0;                     // place the pen position back to left
                }
                // find free spot
                int y = columnPixels[x];
                for (int j = x + 1; j < x + surfaceWidth; j++)
                {
                    if (columnPixels[j] > y)
                    {
                        y = columnPixels[j];
                    }
                }

                if (y + surfaceHeight >= textureSize)
                {
                    // texture is full, update it and move to next texture

                    UpdateTexture(textureData, texture, currentTexture, textureSize, textureSize);

                    for (int j = 0; j < textureSize * textureSize * 4; j++)
                    {
                        textureData[j] = 0;
                    }

                    for (int j = 0; j < textureSize; j++)
                    {
                        columnPixels[j] = 0;
                    }

                    textures.Add(new Texture2D(textureSize, textureSize));
                    currentTexture++;
                    texture = textures[currentTexture];

                    x = 0;
                    y = 0;
                }

                glyphs[i].textureId = currentTexture;
                glyphs[i].textureX  = x;
                glyphs[i].textureY  = y;

                // copy glyph data
                for (int j = 0; j < surfaceHeight; j++)
                {
                    Array.Copy(glyphData, j * surfaceWidth * 4, textureData, (j * textureSize * 4) + (y * textureSize * 4) + (x * 4), surfaceWidth * 4);
                }

                for (int j = x; j < x + surfaceWidth; j++)
                {
                    columnPixels[j] = y + surfaceHeight;
                }

                x += surfaceWidth;
            }

            UpdateTexture(textureData, texture, currentTexture, textureSize, textureSize);
        }
 //---------------------------------------------------
 public RandomEvent(string n, string succeed, string fail, CharacterGroup char1, CharacterGroup char2, Room?rReq, TimeOfDay?tod, Comparison comp1, Comparison comp2, StatEffect[] succEff, StatEffect[] failEff)
 {
     mName = n; succeedString = succeed; failString = fail; mCharacter1 = char1; mCharacter2 = char2; mRoomReq = rReq; mTimeReq = tod; statCheck1 = comp1; statCheck2 = comp2; succeedEffects = succEff; failEffects = failEff;
 }
Example #35
0
 public MinHeap(Comparison <T> comparison) : this(DEFAULT_CAPACITY, comparison)
 {
 }
Example #36
0
 public void Sort(Comparison <object> /*!*/ comparison)
 {
     Mutate();
     Array.Sort(_content, _start, _count, ArrayUtils.ToComparer(comparison));
 }
 public void SortTransfers(Comparison <TransferSyntax> comparison)
 {
     _transfers.Sort(comparison);
 }
Example #38
0
        public static ReportTree FromList(IEnumerable <ReportRegistry.Report> reports,
                                          string rootPath = null, string categoryOrder = null)
        {
            if (reports == null)
            {
                throw new ArgumentNullException("reports");
            }

            rootPath      = rootPath ?? "";
            categoryOrder = categoryOrder ?? "";

            var tree = new ReportTree();

            var categoryByKey = new Dictionary <string, ReportTree.Category>(StringComparer.CurrentCultureIgnoreCase);

            foreach (var report in reports)
            {
                ReportTree.Category category;
                if (categoryByKey.TryGetValue(report.Category.Key ?? "", out category))
                {
                    category.Reports.Add(report);
                    continue;
                }

                var parts = (report.Category.Key ?? "Other")
                            .Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

                string current = "";
                category = null;
                foreach (var part in parts)
                {
                    string prior = current;

                    if (current.Length > 0)
                    {
                        current += "/";
                    }

                    current += part;

                    if (current.Length <= rootPath.Length)
                    {
                        continue;
                    }

                    if (!categoryByKey.TryGetValue(current ?? "", out category))
                    {
                        category               = new ReportTree.Category();
                        category.Key           = current;
                        category.Title         = ReportRegistry.GetReportCategoryTitle(current);
                        categoryByKey[current] = category;

                        if (!categoryByKey.ContainsKey(prior))
                        {
                            tree.Root.SubCategories.Add(category);
                        }
                        else
                        {
                            var x = categoryByKey[prior];
                            x.SubCategories.Add(category);
                        }
                    }
                }

                if (category == null)
                {
                    tree.Root.Reports.Add(report);
                }
                else
                {
                    category.Reports.Add(report);
                }
            }

            var order = new Dictionary <string, int>(StringComparer.OrdinalIgnoreCase);
            var i     = 0;

            foreach (var x in categoryOrder.Split(new char[] { ';' }))
            {
                var xt = x.TrimToNull();
                if (xt != null)
                {
                    order[xt] = i++;
                }
            }

            Comparison <ReportTree.Category> sort = (x, y) =>
            {
                var c = 0;

                if (x.Key != y.Key)
                {
                    var c1 = order.ContainsKey(x.Key) ? (Int32?)order[x.Key] : null;
                    var c2 = order.ContainsKey(y.Key) ? (Int32?)order[y.Key] : null;
                    if (c1 != null && c2 != null)
                    {
                        c = c1.Value - c2.Value;
                    }
                    else if (c1 != null)
                    {
                        c = -1;
                    }
                    else if (c2 != null)
                    {
                        c = 1;
                    }
                }

                if (c == 0)
                {
                    c = String.Compare(x.Title, y.Title, StringComparison.CurrentCultureIgnoreCase);
                }

                return(c);
            };

            foreach (var category in categoryByKey.Values)
            {
                if (category.SubCategories != null)
                {
                    category.SubCategories.Sort(sort);
                }
            }

            tree.Root.SubCategories.Sort(sort);

            return(tree);
        }
Example #39
0
 public PriorityQueue(int capacity, Comparison <T> comparison)
 {
     this.heap    = new List <T>(capacity);
     this.compare = comparison;
 }
Example #40
0
 // Sorts an IList<T> in place.
 internal static void Sort <T>(this IList <T> list, Comparison <T> comparison)
 {
     ArrayList.Adapter((IList)list).Sort(new ComparisonComparer <T>(comparison));
 }
Example #41
0
 private KeyMappingCollection(string pp)
 {
     keyMappingList = new List <KeyMappingPair>();
     compare       += compare;
 }
Example #42
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BinaryHeap{TPriority,TValue}"/> class.
 /// </summary>
 /// <param name="priorityComparison">Priority comparer.</param>
 /// <exception cref="T:System.ArgumentNullException"><paramref name="priorityComparison"/> is <see langword="null"/>.</exception>
 public BinaryHeap([NotNull] Comparison <TPriority> priorityComparison)
     : this(DefaultCapacity, priorityComparison)
 {
 }
        /// <summary>
        /// Searches the entire <see cref="SinglyLinkedList{T}"/> for an item using the specified comparison and returns the <see cref="SinglyLinkedListNode{T}"/> of the first occurrence.
        /// </summary>
        /// <typeparam name="T">The data type of the <see cref="SinglyLinkedList{T}"/>.</typeparam>
        /// <param name="list">The <see cref="SinglyLinkedList{T}"/> containing the items for searching.</param>
        /// <param name="item">The item to search for.</param>
        /// <param name="comparison">The <see cref="Comparison{T}"/> used for comparing the elements.</param>
        /// <returns>The <see cref="SinglyLinkedListNode{T}"/> of the first occurrence of the item in the <see cref="SinglyLinkedList{T}"/>, if the item is found; otherwise null.</returns>
        public static SinglyLinkedListNode <T> LinearSearchFirstNode <T>(this SinglyLinkedList <T> list, T item, Comparison <T> comparison)
        {
            if (list.Count == 0)
            {
                return(null);
            }

            return(LinearSearchFirstNode(list, item, Comparer <T> .Create(comparison)));
        }
        /// <summary>
        /// Orders rows of the jagged array using comparer in ascending or descending order using comparison delegate
        /// </summary>
        /// <param name="jaggedArray">Given jagged array</param>
        /// <param name="compareDelegate">Given comparison method</param>
        /// <param name="isReverseOrder">Determines if order is ascending or descending</param>
        private static void BubbleSort(int[][] jaggedArray, Comparison <int[]> compareDelegate, bool isReverseOrder)
        {
            Comparer <int[]> comparer = Comparer <int[]> .Create(compareDelegate);

            BubbleSort(jaggedArray, comparer, isReverseOrder);
        }
Example #45
0
        void Branch(Expression e, bool ifTrue, Label label)
        {
            if (e is Comparison)
            {
                // Perform comparison.
                Comparison comparison = (Comparison)e;

                Opcode op; int A;
                switch (comparison.Op)
                {
                case ComparisonOp.Equal:                                op = Opcode.Eq; A = 1;  break;

                case ComparisonOp.NotEqual:                             op = Opcode.Eq; A = 0;  break;

                case ComparisonOp.LessThan:                             op = Opcode.Lt; A = 1;  break;

                case ComparisonOp.GreaterThan:                  op = Opcode.Le; A = 0;  break;

                case ComparisonOp.LessThanOrEqual:              op = Opcode.Le; A = 1;  break;

                case ComparisonOp.GreaterThanOrEqual:   op = Opcode.Lt; A = 0;  break;

                default: throw new ArgumentException();
                }

                if (!ifTrue)
                {
                    A = A != 0 ? 0 : 1;
                }

                Allocation left  = RK(comparison.Left);
                Allocation right = RK(comparison.Right);
                function.InstructionABC(e.SourceSpan, op, A, left, right);
                function.InstructionAsBx(e.SourceSpan, Opcode.Jmp, 0, label);
                right.Release();
                left.Release();
            }
            else if (e is Logical)
            {
                // Perform shortcut evaluation.
                Logical logical = (Logical)e;

                if (logical.Op == LogicalOp.And)
                {
                    if (ifTrue)
                    {
                        // left and right
                        Label noBranch = new Label("noBranch");
                        Branch(logical.Left, false, noBranch);
                        Branch(logical.Right, true, label);
                        function.Label(noBranch);
                    }
                    else
                    {
                        // not( left and right ) == not( left ) or not( right )
                        Branch(logical.Left, false, label);
                        Branch(logical.Right, false, label);
                    }
                }
                else if (logical.Op == LogicalOp.Or)
                {
                    if (ifTrue)
                    {
                        // left or right
                        Branch(logical.Left, true, label);
                        Branch(logical.Right, true, label);
                    }
                    else
                    {
                        // not( left or right ) == not( left ) and not( right )
                        Label noBranch = new Label("noBranch");
                        Branch(logical.Left, true, noBranch);
                        Branch(logical.Right, false, label);
                        function.Label(noBranch);
                    }
                }
                else
                {
                    throw new ArgumentException();
                }
            }
            else if (e is Not)
            {
                // Branch in the opposite sense.
                Branch(((Not)e).Operand, !ifTrue, label);
            }
            else
            {
                // Test an actual value.
                Allocation expression = R(e);
                function.InstructionABC(e.SourceSpan, Opcode.Test, expression, 0, ifTrue ? 1 : 0);
                function.InstructionAsBx(e.SourceSpan, Opcode.Jmp, 0, label);
                expression.Release();
            }
        }
Example #46
0
 // Methods
 public FunctorComparer(Comparison <T> comparison)
 {
     this.c          = Comparer <T> .Default;
     this.comparison = comparison;
 }
Example #47
0
 public AvlSet(Comparison <T> comparison = null) : base(comparison)
 {
 }
Example #48
0
        private static bool TryFindBestBillIngredients(Bill bill, Pawn pawn, Thing billGiver, List <ThingCount> chosen)
        {
            chosen.Clear();
            newRelevantThings.Clear();
            if (bill.recipe.ingredients.Count == 0)
            {
                return(true);
            }
            IntVec3 rootCell = GetBillGiverRootCell(billGiver, pawn);
            Region  rootReg  = rootCell.GetRegion(pawn.Map);

            if (rootReg == null)
            {
                return(false);
            }
            MakeIngredientsListInProcessingOrder(ingredientsOrdered, bill);
            relevantThings.Clear();
            processedThings.Clear();
            bool foundAll = false;
            Predicate <Thing> baseValidator = (Thing t) => t.Spawned && !t.IsForbidden(pawn) && (float)(t.Position - billGiver.Position).LengthHorizontalSquared < bill.ingredientSearchRadius * bill.ingredientSearchRadius && bill.IsFixedOrAllowedIngredient(t) && bill.recipe.ingredients.Any((IngredientCount ingNeed) => ingNeed.filter.Allows(t)) && pawn.CanReserve(t);
            bool billGiverIsPawn            = billGiver is Pawn;

            if (billGiverIsPawn)
            {
                AddEveryMedicineToRelevantThings(pawn, billGiver, relevantThings, baseValidator, pawn.Map);
                if (TryFindBestBillIngredientsInSet(relevantThings, bill, chosen))
                {
                    relevantThings.Clear();
                    ingredientsOrdered.Clear();
                    return(true);
                }
            }
            TraverseParms        traverseParams = TraverseParms.For(pawn);
            RegionEntryPredicate entryCondition = (Region from, Region r) => r.Allows(traverseParams, isDestination: false);
            int adjacentRegionsAvailable        = rootReg.Neighbors.Count((Region region) => entryCondition(rootReg, region));
            int regionsProcessed = 0;

            processedThings.AddRange(relevantThings);
            RegionProcessor regionProcessor = delegate(Region r)
            {
                List <Thing> list = r.ListerThings.ThingsMatching(ThingRequest.ForGroup(ThingRequestGroup.HaulableEver));
                for (int i = 0; i < list.Count; i++)
                {
                    Thing thing = list[i];
                    if (!processedThings.Contains(thing) && ReachabilityWithinRegion.ThingFromRegionListerReachable(thing, r, PathEndMode.ClosestTouch, pawn) && baseValidator(thing) && (!thing.def.IsMedicine || !billGiverIsPawn))
                    {
                        newRelevantThings.Add(thing);
                        processedThings.Add(thing);
                    }
                }
                regionsProcessed++;
                if (newRelevantThings.Count > 0 && regionsProcessed > adjacentRegionsAvailable)
                {
                    Comparison <Thing> comparison = delegate(Thing t1, Thing t2)
                    {
                        float num   = (float)(t1.Position - rootCell).LengthHorizontalSquared;
                        float value = (float)(t2.Position - rootCell).LengthHorizontalSquared;
                        return(num.CompareTo(value));
                    };
                    newRelevantThings.Sort(comparison);
                    relevantThings.AddRange(newRelevantThings);
                    newRelevantThings.Clear();
                    if (TryFindBestBillIngredientsInSet(relevantThings, bill, chosen))
                    {
                        foundAll = true;
                        return(true);
                    }
                }
                return(false);
            };

            RegionTraverser.BreadthFirstTraverse(rootReg, entryCondition, regionProcessor, 99999);
            relevantThings.Clear();
            newRelevantThings.Clear();
            processedThings.Clear();
            ingredientsOrdered.Clear();
            return(foundAll);
        }
    public ReadOnlyNonUniqueSortedList(IReadOnlyList <TValue> values, Func <TValue, TKey> keySelector, Comparison <TKey> comparison)
    {
        ArgumentNullException.ThrowIfNull(values);
        ArgumentNullException.ThrowIfNull(keySelector);
        ArgumentNullException.ThrowIfNull(comparison);
        Assert.ArgumentConditionIsTrue(
            values.SelectPreviousAndCurrentKey(keySelector).All(key => comparison(key.Previous, key.Current) <= 0),
            "keys must be ordered");

        _values      = values;
        _keySelector = keySelector;
        _comparison  = comparison;

        InitializeGroups();
    }
Example #50
0
 private SortKey(Comparison <FolderListViewItem> comparison)
 {
     _comparison = comparison;
 }
Example #51
0
 /// <summary>
 /// Returns the nth smallest item in linear amortized time.
 /// Partially sorts the array with respect to the nth item such that items to the left are less than or equal and items to the right are greater than or equal.
 /// </summary>
 public static T QuickSelect <T>(this T[] items, int n, Comparison <T> compare)
 {
     return(items.QuickSelect(n, 0, items.Length, compare));
 }
Example #52
0
 internal ComparisonComparer(Comparison <T> comparison)
 {
     _comparison = comparison;
 }
Example #53
0
        public static void Sort <T>(this T[] array, Comparison <T> comparison)
        {
            Verify.Argument.IsNotNull(array, "array");

            Array.Sort <T>(array, comparison);
        }
Example #54
0
 public void SetSortComparisonCallback(Comparison <UXElement> callback)
 {
     this.comparisonCallback = callback;
     this.gridComponent.NGUIGrid.onCustomSort = new Comparison <Transform>(this.NGUIOnCustomSortCallbacK);
 }
 public DelegatedComparer(Comparison <T> compareHandler) => this.compareHandler = compareHandler ?? throw new ArgumentNullException(nameof(compareHandler));
Example #56
0
        public List <Player> PlayerSort(int key)
        {
            Player[] temp = db.GetPlayers();
            var      play = new List <Player>();

            //adds all the players into the array list
            foreach (Player pl in temp)
            {
                if (pl.HasPassStats() || pl.HasReceivingStats() || pl.HasRushingStats())
                {
                    play.Add(pl);
                }
            }
            switch (key)
            {
            //sorts by Name
            case 1:
                Comparison <Player> compOne = (x, y) => x.Name.CompareTo(y.Name);
                play.Sort(compOne);
                break;

            //sorts by Team
            case 2:
                Comparison <Player> compTwo = (x, y) => x.Team.CompareTo(y.Team);
                play.Sort(compTwo);
                break;

            //sorts by Position
            case 3:
                Comparison <Player> compThree = (x, y) => x.Position.CompareTo(y.Position);
                play.Sort(compThree);
                break;

            //sorts by PassingYds
            case 4:
                Comparison <Player> compFour = (x, y) => x.SeasonStats.PassingYds.CompareTo(y.SeasonStats.PassingYds);
                play.Sort(compFour);
                break;

            //sorts by PassingTds
            case 5:
                Comparison <Player> compFive = (x, y) => x.SeasonStats.PassingTds.CompareTo(y.SeasonStats.PassingTds);
                play.Sort(compFive);
                break;

            //sorts by RushingYds
            case 6:
                Comparison <Player> compSix = (x, y) => x.SeasonStats.RushingYds.CompareTo(y.SeasonStats.RushingYds);
                play.Sort(compSix);
                break;

            //sorts by RushingTds
            case 7:
                Comparison <Player> compSeven = (x, y) => x.SeasonStats.RushingTds.CompareTo(y.SeasonStats.RushingTds);
                play.Sort(compSeven);
                break;

            //sorts by RecYds
            case 8:
                Comparison <Player> compEight = (x, y) => x.SeasonStats.RecYds.CompareTo(y.SeasonStats.RecYds);
                play.Sort(compEight);
                break;

            //sorts by RecTds
            case 9:
                Comparison <Player> compNine = (x, y) => x.SeasonStats.RecTds.CompareTo(y.SeasonStats.RecTds);
                play.Sort(compNine);
                break;

            //sorts by Catches
            case 10:
                Comparison <Player> compTen = (x, y) => x.SeasonStats.Catches.CompareTo(y.SeasonStats.Catches);
                play.Sort(compTen);
                break;

            //sorts by Fumbles
            case 11:
                Comparison <Player> compEleven = (x, y) => x.SeasonStats.Fumbles.CompareTo(y.SeasonStats.Fumbles);
                play.Sort(compEleven);
                break;

            //sorts by Interceptions
            case 12:
                Comparison <Player> compTwelve = (x, y) => x.SeasonStats.Interceptions.CompareTo(y.SeasonStats.Interceptions);
                play.Sort(compTwelve);
                break;
            }
            return(play);
        }
Example #57
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <param name="listOffset"></param>
        /// <param name="other"></param>
        /// <param name="otherOffset"></param>
        /// <param name="length"></param>
        /// <param name="comparison"></param>
        /// <returns></returns>
        private static int CompareInternal <T>(IList <T> list, int listOffset, IList <T> other, int otherOffset, int length, Comparison <T> comparison)
        {
            for (var i = 0; i < length; i++)
            {
                var ret = comparison(list[listOffset + i], other[otherOffset + i]);
                if (ret != 0)
                {
                    return(ret);
                }
            }

            return(0);
        }
Example #58
0
        /// <summary>
        /// Sort the contents of this LinkedObject using merge sort.
        /// Adapted from Simon Tatham's C implementation: https://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
        /// </summary>
        /// <typeparam name="T">Type of the objects being compared.</typeparam>
        /// <param name="comparison">Comparison function to use when sorting.</param>
        public LinkedObject SortContents <T>(Comparison <T> comparison) where T : LinkedObject
        {
            if (Items == null)
            {
                return(null);
            }

            int unitsize = 1; //size of the components we are merging; 1 for first iteration, multiplied by 2 after each iteration
            T   p = null, q = null, e = null, head = (T)Items, tail = null;

            while (true)
            {
                p = head;
                int nmerges = 0;  //number of merges done this pass
                int psize, qsize; //lengths of the components we are merging
                head = null;
                tail = null;

                while (p != null)
                {
                    nmerges++;
                    q     = p;
                    psize = 0;
                    for (int i = 0; i < unitsize; i++)
                    {
                        psize++;
                        q = (T)q.Next;
                        if (q == null)
                        {
                            break;
                        }
                    }

                    qsize = unitsize;
                    while (psize > 0 || (qsize > 0 && q != null))
                    {
                        if (psize == 0)
                        {
                            e = q;
                            q = (T)q.Next;
                            qsize--;
                        }
                        else if (qsize == 0 || q == null)
                        {
                            e = p;
                            p = (T)p.Next;
                            psize--;
                        }
                        else if (comparison(p, q) <= 0)
                        {
                            e = p;
                            p = (T)p.Next;
                            psize--;
                        }
                        else
                        {
                            e = q;
                            q = (T)q.Next;
                            qsize--;
                        }

                        if (tail != null)
                        {
                            tail.Next = e;
                        }
                        else
                        {
                            head = e;
                        }
                        e.Previous = tail;
                        tail       = e;
                    }
                    p = q;
                }
                tail.Next = null;
                if (nmerges <= 1)
                {
                    Items = head;
                    return(head);
                }
                else
                {
                    unitsize *= 2;
                }
            }
        }
Example #59
0
 public PriorityQueue(Comparison <T> comparison) : this(16, comparison)
 {
 }
Example #60
0
 // Convenience method on IEnumerable<T> to allow passing of a
 // Comparison<T> delegate to the OrderBy method.
 internal static IEnumerable <T> OrderBy <T>(this IEnumerable <T> list, Comparison <T> comparison) =>
 list.OrderBy(t => t, new ComparisonComparer <T>(comparison));