System.Collections.Generic.IEnumerable.Min(System.Func)

Here are the examples of the csharp api System.Collections.Generic.IEnumerable.Min(System.Func) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

534 Examples 7

19 Source : ClipInputTool.cs
with GNU Affero General Public License v3.0
from bigbang1112-cz

private void ProcessreplacedogAccel(IEnumerable<ControlEntry> entries, TimeSpan eventsDuration, IList<CGameCtnMediaTrack> tracks, KeyboardKey accelKey, KeyboardKey brakeKey)
        {
            // Defines the start of the first event
            var eventStartTime = new TimeSpan();

            if (!ShowAfterInteraction)
                eventStartTime = TimeSpan.FromMilliseconds(Math.Min(0, entries.Min(x => x.Time.TotalMilliseconds)));

            var trackAccelPad = CreateMediaTrack("Pad Acceleration");
            tracks.Add(trackAccelPad);

            var trackBrakePad = CreateMediaTrack("Pad Brake");
            tracks.Add(trackBrakePad);

            var accelPadQuad = default(CGameCtnMediaBlockTriangles);
            var brakePadQuad = default(CGameCtnMediaBlockTriangles);

            var lastEntry = entries.Last();

            foreach (var entry in entries)
            {
                if (entry.Equals(lastEntry))
                {
                    CompleteTheTriangle(accelPadQuad, eventsDuration);
                    CompleteTheTriangle(brakePadQuad, eventsDuration);
                }

                if (entry.Name == "Gas" || entry.Name == "AccelerateReal")
                {
                    var replacedog = (ControlEntryreplacedog)entry;

                    CompleteTheTriangle(accelPadQuad, entry.Time);

                    if (replacedog.Value > 0)
                    {
                        accelPadQuad = CreateKeyPadMoment(accelKey, replacedog.Value, entry.Time);
                        trackAccelPad.Blocks.Add(accelPadQuad);
                    }
                    else
                    {
                        accelPadQuad = null;
                    }
                }

                if (entry.Name == "Gas" || entry.Name == "BrakeReal")
                {
                    var replacedog = (ControlEntryreplacedog)entry;

                    CompleteTheTriangle(brakePadQuad, entry.Time);

                    if ((replacedog.Value > 0 && entry.Name != "Gas") || (entry.Name == "Gas" && replacedog.Value < 0))
                    {
                        brakePadQuad = CreateKeyPadMoment(brakeKey, replacedog.Value, entry.Time);
                        trackBrakePad.Blocks.Add(brakePadQuad);
                    }
                    else
                    {
                        brakePadQuad = null;
                    }
                }
            }
        }

19 Source : ClipInputTool.cs
with GNU Affero General Public License v3.0
from bigbang1112-cz

private GameBox<CGameCtnMediaClip> ProcessControlEntries(IEnumerable<ControlEntry> entries, TimeSpan eventsDuration)
        {
            if (entries == null)
                throw new NoInputsException();

            Console.WriteLine("Processing the inputs...");

            Console.WriteLine("Creating CGameCtnMediaClip...");

            var clip = new CGameCtnMediaClip()
            {
                LocalPlayerClipEntIndex = -1
            };

            switch (GameVersion)
            {
                case Game.TMUF:
                    Console.WriteLine("Creating CGameCtnMediaClip chunks 0x004, 0x005, 0x007...");
                    clip.CreateChunk<CGameCtnMediaClip.Chunk03079004>();
                    clip.CreateChunk<CGameCtnMediaClip.Chunk03079005>();
                    clip.CreateChunk<CGameCtnMediaClip.Chunk03079007>();
                    break;
                case Game.ManiaPlanet:
                    Console.WriteLine("Creating CGameCtnMediaClip chunk 0x00D...");
                    clip.CreateChunk<CGameCtnMediaClip.Chunk0307900D>();
                    break;
            }

            var tracks = new List<CGameCtnMediaTrack>();

            var hasAccelReal = false;
            var hasBrakeReal = false;
            var hasreplacedogSteering = false;

            foreach (var entry in entries)
            {
                switch (entry.Name)
                {
                    case "Accelerate":
                    case "Brake":
                    case "SteerLeft":
                    case "SteerRight":
                    case "Steer left":
                    case "Steer right":
                        break;
                    case "Gas":
                        hasAccelReal = true;
                        hasBrakeReal = true;
                        break;
                    case "AccelerateReal":
                        if ((entry as ControlEntryreplacedog).Value >= 0)
                            hasAccelReal = true;
                        break;
                    case "BrakeReal":
                        if ((entry as ControlEntryreplacedog).Value >= 0)
                            hasBrakeReal = true;
                        break;
                    case "Steer (replacedog)":
                    case "Steer":
                        hasreplacedogSteering = true;
                        break;
                }
            }

            Console.WriteLine("Processing acceleration input...");
            ProcessDigitalInput(entries, eventsDuration, tracks,
                onlyAcceleration: hasreplacedogSteering,
                usesreplacedogAccel: hasAccelReal,
                usesreplacedogBrake: hasBrakeReal);

            if (hasreplacedogSteering)
            {
                Console.WriteLine("Processing replacedog steering input...");
                ProcessreplacedogSteering(entries, eventsDuration, tracks);
            }

            if (hasAccelReal || hasBrakeReal)
            {
                Console.WriteLine("Processing replacedog acceleration/brake...");

                ProcessreplacedogAccel(entries, eventsDuration, tracks,
                    hasAccelReal ? Keys.FirstOrDefault(x => x.EntryName == "Accelerate") : null,
                    hasBrakeReal ? Keys.FirstOrDefault(x => x.EntryName == "Brake") : null);
            }

            // Defines the start of the first event
            var eventStartTime = new TimeSpan();

            if (!ShowAfterInteraction)
                eventStartTime = TimeSpan.FromMilliseconds(Math.Min(0, entries.Min(x => x.Time.TotalMilliseconds)));

            clip.Tracks = tracks;

            if (StartOffset != TimeSpan.Zero)
            {
                Console.WriteLine($"Offsetting the blocks by {StartOffset.TotalSeconds} seconds.");

                foreach (var track in tracks)
                {
                    foreach (var block in track.Blocks)
                    {
                        switch (block)
                        {
                            case CGameCtnMediaBlockImage blockImage:
                                blockImage.Effect.Keys.ForEach(x => x.Time += (float)StartOffset.TotalSeconds);
                                break;
                            case CGameCtnMediaBlockTriangles blockTriangles:
                                blockTriangles.Keys.ForEach(x => x.Time += (float)StartOffset.TotalSeconds);
                                break;
                            case CGameCtnMediaBlockText blockText:
                                blockText.Effect.Keys.ForEach(x => x.Time += (float)StartOffset.TotalSeconds);
                                break;
                        }
                    }
                }
            }

            Console.WriteLine("Building the final GBX file...");

            return new GameBox<CGameCtnMediaClip>(clip);
        }

19 Source : ClipInputTool.cs
with GNU Affero General Public License v3.0
from bigbang1112-cz

private void ProcessreplacedogSteering(IEnumerable<ControlEntry> entries, TimeSpan eventsDuration, IList<CGameCtnMediaTrack> tracks)
        {
            // Defines the start of the first event
            var eventStartTime = new TimeSpan();

            if (!ShowAfterInteraction)
                eventStartTime = TimeSpan.FromMilliseconds(Math.Min(0, entries.Min(x => x.Time.TotalMilliseconds)));

            CreatePad(Side.Left, $"{(int)Theme}_PadLeft_2.png", $"{(int)Theme}_PadLeft_2_On.png", eventStartTime, eventsDuration, tracks, entries);
            CreatePad(Side.Right, $"{(int)Theme}_PadRight_2.png", $"{(int)Theme}_PadRight_2_On.png", eventStartTime, eventsDuration, tracks, entries);

            var trackPad = CreateMediaTrack("Pad");
            tracks.Add(trackPad);

            var padQuad = default(CGameCtnMediaBlockTriangles);

            var inverse = -1;
            var lastEntry = entries.Last();

            foreach (var entry in entries)
            {
                if (entry.Name == "_FakeDontInverseAxis" && entry.IsEnabled)
                {
                    inverse = 1;
                }

                if (entry.Equals(lastEntry))
                {
                    CompleteTheTriangle(padQuad, eventsDuration);
                }

                switch (entry.Name)
                {
                    case "Steer":
                    case "Steer (replacedog)":
                        {
                            var replacedog = (ControlEntryreplacedog)entry;

                            CompleteTheTriangle(padQuad, entry.Time);

                            if (replacedog.Value > 0 || replacedog.Value < 0)
                            {
                                padQuad = CreatePadMoment(replacedog.Value * inverse, entry.Time);
                                trackPad.Blocks.Add(padQuad);
                            }
                            else
                            {
                                padQuad = null;
                            }

                            break;
                        }
                }
            }
        }

19 Source : ClipInputTool.cs
with GNU Affero General Public License v3.0
from bigbang1112-cz

private void ProcessDigitalInput(IEnumerable<ControlEntry> entries, TimeSpan eventsDuration, IList<CGameCtnMediaTrack> tracks,
            bool onlyAcceleration, bool usesreplacedogAccel, bool usesreplacedogBrake)
        {
            var trackDictionary = new Dictionary<KeyboardKey, CGameCtnMediaTrack>();
            var currentImageDictionary = new Dictionary<KeyboardKey, CGameCtnMediaBlockImage>();
            var pressedKeyDictionary = new Dictionary<KeyboardKey, bool>();

            // Defines the start of the first event
            var eventStartTime = new TimeSpan();

            if (!ShowAfterInteraction)
                eventStartTime = TimeSpan.FromMilliseconds(Math.Min(0, entries.Min(x => x.Time.TotalMilliseconds)));

            (string imageOff, string imageOn) DetermineImages(KeyboardKey key, bool isSteerInput)
            {
                var imageOff = key.ImageOff;
                var imageOn = key.ImageOn;

                if (!isSteerInput)
                {
                    if (usesreplacedogAccel && key.EntryName == "Accelerate")
                    {
                        imageOff = "{0}_replacedog.png";
                        imageOn = "{0}_replacedog_Accel.png";
                    }

                    if (usesreplacedogBrake && key.EntryName == "Brake")
                    {
                        imageOff = "{0}_replacedog.png";
                        imageOn = "{0}_replacedog_Brake.png";
                    }
                }

                return (
                    string.Format(imageOff, (int)Theme),
                    string.Format(imageOn, (int)Theme)
                );
            }

            foreach (var key in Keys)
            {
                var (imageOff, imageOn) = DetermineImages(key, key.IsSteerInput);

                if (!onlyAcceleration || !key.IsSteerInput)
                {
                    var track = CreateMediaTrack(key.TrackName);
                    trackDictionary[key] = track;

                    currentImageDictionary[key] = null;
                    pressedKeyDictionary[key] = false;

                    if (!ShowAfterInteraction)
                    {
                        var blockImage = CreateImageBlock(imageOff, eventStartTime, key.Position);

                        trackDictionary[key].Blocks.Add(blockImage);
                        currentImageDictionary[key] = blockImage;
                    }
                }
            }

            foreach (var entry in entries)
            {
                foreach (var key in Keys)
                {
                    var (imageOff, imageOn) = DetermineImages(key, key.IsSteerInput);

                    if (!onlyAcceleration || !key.IsSteerInput)
                    {
                        if (key.EntryNames.Contains(entry.Name))
                        {
                            if (entry.IsEnabled)
                            {
                                if (!pressedKeyDictionary[key])
                                {
                                    var time = entry.Time;

                                    if (currentImageDictionary[key] != null)
                                    {
                                        currentImageDictionary[key].Effect.Keys[1] = CreateSimiKey(time, key.Position);
                                    }

                                    var blockImage = CreateImageBlock(imageOn, time, key.Position);

                                    trackDictionary[key].Blocks.Add(blockImage);
                                    currentImageDictionary[key] = blockImage;
                                    pressedKeyDictionary[key] = true;
                                }
                            }
                            else
                            {
                                var prevTime = currentImageDictionary[key].Effect.Keys[0].Time;
                                var time = entry.Time;

                                if (AdjustToFPS)
                                {
                                    var blockLength = time.TotalSeconds - prevTime;

                                    if (blockLength < 1 / FPS)
                                        time = TimeSpan.FromSeconds(prevTime + 1 / FPS);
                                }

                                currentImageDictionary[key].Effect.Keys[1] = CreateSimiKey(time, key.Position);

                                var blockImage = CreateImageBlock(imageOff, time, key.Position);

                                trackDictionary[key].Blocks.Add(blockImage);
                                currentImageDictionary[key] = blockImage;
                                pressedKeyDictionary[key] = false;
                            }
                        }
                    }
                }
            }

            foreach (var key in Keys)
            {
                if (!onlyAcceleration || !key.IsSteerInput)
                {
                    currentImageDictionary[key].Effect.Keys[1] = CreateSimiKey(eventsDuration, key.Position);

                    tracks.Add(trackDictionary[key]);
                }
            }
        }

19 Source : TreeTableResult.cs
with MIT License
from bing-framework

protected virtual bool IsRoot(TNode dto)
        {
            if (_data.Any(t => t.ParentId.IsEmpty()))
                return dto.ParentId.IsEmpty();
            return dto.Level == _data.Min(t => t.Level);
        }

19 Source : ModuleResult.cs
with MIT License
from bing-framework

protected bool IsRoot(Module enreplacedy)
        {
            if (_data.Any(x => x.ParentId.IsEmpty()))
                return enreplacedy.ParentId.IsEmpty();
            return enreplacedy.Level == _data.Min(x => x.Level);
        }

19 Source : SelectMenuResult.cs
with MIT License
from bing-framework

protected bool IsRoot(Module dto)
        {
            if (_menuData.Any(t => t.ParentId.IsEmpty()))
                return dto.ParentId.IsEmpty();
            return dto.Level == _menuData.Min(t => t.Level);
        }

19 Source : MenuResult.cs
with MIT License
from bing-framework

protected bool IsRoot(MenuResponse dto)
        {
            if (_menuData.Any(t => t.ParentId.IsEmpty()))
                return dto.ParentId.IsEmpty();
            return dto.Level == _menuData.Min(t => t.Level);
        }

19 Source : KeyCombinationExtensions.cs
with MIT License
from Blacklock

public static void OnSequence(this IKeyboardEvents source, IEnumerable<KeyValuePair<Sequence, Action>> map)
        {
            var actBySeq = map.ToArray();
            var endsWith = new Func<Queue<Combination>, Sequence, bool>((chords, sequence) =>
            {
                var skipCount = chords.Count - sequence.Length;
                return skipCount >= 0 && chords.Skip(skipCount).SequenceEqual(sequence);
            });

            var max = actBySeq.Select(p => p.Key).Max(c => c.Length);
            var min = actBySeq.Select(p => p.Key).Min(c => c.Length);
            var buffer = new Queue<Combination>(max);

            var wrapMap = actBySeq.SelectMany(p => p.Key).Select(c => new KeyValuePair<Combination, Action>(c, () =>
            {
                buffer.Enqueue(c);
                if (buffer.Count > max) buffer.Dequeue();
                if (buffer.Count < min) return;
                //Invoke action corresponding to the longest matching sequence
                actBySeq
                    .Where(pair => endsWith(buffer, pair.Key))
                    .OrderBy(pair => pair.Key.Length)
                    .Select(pair => pair.Value)
                    .LastOrDefault()
                    ?.Invoke();
            }));

            OnCombination(source, wrapMap, buffer.Clear);
        }

19 Source : CalendarStack.cs
with MIT License
from BlazorComponent

public static List<CalendarStackNode> GetOverlappingRange(CalendarStackNode node, 
            List<CalendarStackNode> nodes, int indexMin, int indexMax, bool returnFirstColumn = false)
        { 
            var overlapping = new List<CalendarStackNode>();
            foreach (var other in nodes)
            {
                if(other.Index >= indexMin && other.Index <= indexMax &&
                    CalendarCommon.HasOverlap(node.Start, node.End, other.Start, other.End))
                    overlapping.Add(other);
            }
            if (returnFirstColumn && overlapping.Count > 0)
            {
                var first = overlapping.Min(x => x.Index);
                return overlapping.Where(x => x.Index == first).ToList();
            }

            return overlapping;
        }

19 Source : ResizeGroupData.cs
with MIT License
from BlazorFluentUI

public double LowestPriorityInItems()
        {
            if (Items.Count() > 0)
            {
                return Items.Min(item => item.Priority);
            }
            else
            {
                return double.MaxValue;
            }
        }

19 Source : PageArea.cs
with MIT License
from BobLd

public PageArea GetArea(PdfRectangle area)
        {
            List<TextElement> t = GetText(area);
            double min_char_width = 7;
            double min_char_height = 7;

            if (t.Count > 0)
            {
                min_char_width = t.Min(x => x.Width);
                min_char_height = t.Min(x => x.Height);
            }

            PageArea rv = new PageArea(area,
                                       Rotation,
                                       PageNumber,
                                       PdfPage,
                                       PdfDoreplacedent,
                                       t,
                                       Ruling.CropRulingsToArea(GetRulings(), area),
                                       min_char_width,
                                       min_char_height,
                                       spatial_index);

            rv.AddRuling(new Ruling(
                new PdfPoint(rv.Left, rv.Top),
                new PdfPoint(rv.Right, rv.Top)));

            rv.AddRuling(new Ruling(
                new PdfPoint(rv.Right, rv.Bottom),    // getTop
                new PdfPoint(rv.Right, rv.Top)));     // getBottom

            rv.AddRuling(new Ruling(
                new PdfPoint(rv.Right, rv.Bottom),
                new PdfPoint(rv.Left, rv.Bottom)));

            rv.AddRuling(new Ruling(
                new PdfPoint(rv.Left, rv.Bottom),
                new PdfPoint(rv.Left, rv.Top)));

            return rv;
        }

19 Source : Utils.cs
with MIT License
from BobLd

public static PdfRectangle Bounds(IEnumerable<PdfRectangle> shapes)
        {
            if (!shapes.Any())
            {
                throw new ArgumentException("shapes can't be empty");
            }

            var minX = shapes.Min(r => r.Left);
            var minY = shapes.Min(r => r.Bottom);
            var maxX = shapes.Max(r => r.Right);
            var maxY = shapes.Max(r => r.Top);
            return new PdfRectangle(minX, minY, maxX, maxY);
        }

19 Source : CombinatorBuilder.cs
with MIT License
from bonsai-rx

void UpdateArgumentRange()
        {
            if (combinator is ExpressionBuilder combinatorBuilder)
            {
                var range = combinatorBuilder.ArgumentRange;
                SetArgumentRange(range.LowerBound, range.UpperBound);
            }
            else
            {
                var combinatorType = combinator.GetType();
                resetCombinator = BuildResetCombinator(combinatorType);
                var processMethodParameters = GetProcessMethods(combinatorType).Select(m => m.GetParameters()).ToArray();
                var paramArray = processMethodParameters.Any(p =>
                    p.Length >= 1 &&
                    Attribute.IsDefined(p[p.Length - 1], typeof(ParamArrayAttribute)));

                if (paramArray) SetArgumentRange(1, maxArgumentCount = int.MaxValue);
                else if (processMethodParameters.Length == 0) SetArgumentRange(0, maxArgumentCount = int.MaxValue);
                else
                {
                    var min = processMethodParameters.Min(p => p.Length);
                    var max = processMethodParameters.Max(p => p.Length);
                    SetArgumentRange(min, maxArgumentCount = max);
                }
            }
        }

19 Source : LayeredGraphExtensions.cs
with MIT License
from bonsai-rx

static bool RemoveMergeGaps(GraphNodeGrouping[] layers)
        {
            // Forward preplaced
            var removed = false;
            var predecessorMap = new Dictionary<GraphNode, IEnumerable<GraphEdge>>();
            for (int i = layers.Length - 1; i >= 0; i--)
            {
                var layer = layers[i];
                if (i < layers.Length - 1)
                {
                    var sortedLayer = new GraphNodeGrouping(layer.Key);
                    foreach (var node in layer)
                    {
                        if (predecessorMap.TryGetValue(node, out IEnumerable<GraphEdge> nodePredecessors))
                        {
                            var minSuccessorLayer = nodePredecessors.Min(edge => edge.Node.LayerIndex);
                            while (sortedLayer.Count < minSuccessorLayer)
                            {
                                var dummyNode = new GraphNode(null, layer.Key, Enumerable.Empty<GraphEdge>());
                                sortedLayer.Add(dummyNode);
                                removed = true;
                            }
                        }

                        sortedLayer.Add(node);
                    }

                    layers[i] = sortedLayer;
                }

                predecessorMap.Clear();
                foreach (var group in (from node in layers[i]
                                       from successor in node.Successors
                                       group new GraphEdge(null, null, node) by successor.Node))
                {
                    predecessorMap.Add(group.Key, group);
                }
            }

            return removed;
        }

19 Source : AssertionResultSet.cs
with Apache License 2.0
from BoundfoxStudios

private KeyValuePair<object, string[]>[] GetBestResultSets()
        {
            int fewestFailures = set.Values.Min(r => r.Length);
            return set.Where(r => r.Value.Length == fewestFailures).ToArray();
        }

19 Source : LODSchedulerThread.cs
with MIT License
from breinsp

private float GetMinDistanceToRegion(Vector3 pos, Region region)
        {
            Vector3 planet_pos = region.planet.zoomed ? Vector3.zero : region.planet.position;
            float zoomFactor = region.planet.zoomed ? controller.planetScaleMultiplier : 1;
            return (new List<Vector3>(new Vector3[] { region.A_mod, region.B_mod, region.C_mod })).Min(V => ((planet_pos + V * zoomFactor) - pos).magnitude);
        }

19 Source : TagRepository.cs
with MIT License
from burki169

public IList<TopTagItem> GetTagCloud()
        {
            var popularTags = GetTopTags().OrderBy(c => Guid.NewGuid()).ToList();
            var maxTagRatio = popularTags.Max(t => t.Ratio).HasValue ? Convert.ToInt32(popularTags.Max(t => t.Ratio).Value) : -1;
            var minTagRatio = popularTags.Min(t => t.Ratio).HasValue ? Convert.ToInt32(popularTags.Min(t => t.Ratio).Value) : -1;
            var ratioDiff = maxTagRatio - minTagRatio;
            var minRatio = minTagRatio;
            foreach (var item in popularTags)
            {
                if (ratioDiff > 0)
                {
                    item.FontSize = 80 + Convert.ToInt32(Math.Truncate((double)(item.Ratio - minRatio) * (100 / ratioDiff)));
                }
                else
                {
                    item.FontSize = 80;
                }
            }

            return popularTags;
        }

19 Source : Utilities.cs
with MIT License
from cabarius

public static string[] TrimCommonPrefix(this string[] values) {
            var prefix = string.Empty;
            int? resultLength = null;

            if (values != null) {
                if (values.Length > 1) {
                    var min = values.Min(value => value.Length);
                    for (var charIndex = 0; charIndex < min; charIndex++) {
                        for (var valueIndex = 1; valueIndex < values.Length; valueIndex++) {
                            if (values[0][charIndex] != values[valueIndex][charIndex]) {
                                resultLength = charIndex;
                                break;
                            }
                        }
                        if (resultLength.HasValue) {
                            break;
                        }
                    }
                    if (resultLength.HasValue &&
                        resultLength.Value > 0) {
                        prefix = values[0].Substring(0, resultLength.Value);
                    }
                }
                else if (values.Length > 0) {
                    prefix = values[0];
                }
            }
            return prefix.Length > 0 ? values.Select(s => s.Replace(prefix, "")).ToArray() : values;
        }

19 Source : TrackViewModel.cs
with Apache License 2.0
from Capnode

internal static double CalculateScore(IList<Trade> trades)
        {
            if (trades == null || !trades.Any())
            {
                return 0;
            }

            // Calculate risk
            double worstTrade = (double)trades.Min(m => m.MAE);
//            double maxDrawdown = (double)MaxDrawdown(trades, out _);
            double linearError = -LinearDeviation(trades);
            double risk = Math.Sqrt(worstTrade * linearError);

            // Calculate period
            DateTime first = trades.Min(m => m.EntryTime);
            DateTime last = trades.Max(m => m.ExitTime);
            TimeSpan duration = last - first;
            double years = duration.Ticks / (_daysInYear * TimeSpan.TicksPerDay);

            // Calculate score
            double netProfit = (double)trades.Sum(m => m.ProfitLoss - m.TotalFees);
            if (risk == 0 || years == 0) return netProfit.CompareTo(0);
            double score = netProfit / risk / years;
            return Scale(score);
        }

19 Source : CompositeUniverseSelectionModel.cs
with Apache License 2.0
from Capnode

public override DateTime GetNextRefreshTimeUtc()
        {
            return _universeSelectionModels.Min(model => model.GetNextRefreshTimeUtc());
        }

19 Source : LeanData.cs
with Apache License 2.0
from Capnode

public static IEnumerable<QuoteBar> AggregateQuoteBars(IEnumerable<QuoteBar> bars, Symbol symbol, TimeSpan resolution)
        {
            return
                from b in bars
                    group b by b.Time.RoundDown(resolution)
                    into g
                    select new QuoteBar
                    {
                        Symbol = symbol,
                        Time = g.Key,
                        Bid = new Bar
                        {
                            Open = g.First().Bid.Open,
                            High = g.Max(b => b.Bid.High),
                            Low = g.Min(b => b.Bid.Low),
                            Close = g.Last().Bid.Close
                        },
                        Ask = new Bar
                        {
                            Open = g.First().Ask.Open,
                            High = g.Max(b => b.Ask.High),
                            Low = g.Min(b => b.Ask.Low),
                            Close = g.Last().Ask.Close
                        },
                        Period = resolution
                    };
        }

19 Source : LeanData.cs
with Apache License 2.0
from Capnode

public static IEnumerable<QuoteBar> AggregateTicks(IEnumerable<Tick> ticks, Symbol symbol, TimeSpan resolution)
         {
             return
                from t in ticks
                    group t by t.Time.RoundDown(resolution)
                    into g
                    select new QuoteBar
                    {
                        Symbol = symbol,
                        Time = g.Key,
                        Bid = new Bar
                        {
                            Open = g.First().BidPrice,
                            High = g.Max(b => b.BidPrice),
                            Low = g.Min(b => b.BidPrice),
                            Close = g.Last().BidPrice
                        },
                        Ask = new Bar
                        {
                            Open = g.First().AskPrice,
                            High = g.Max(b => b.AskPrice),
                            Low = g.Min(b => b.AskPrice),
                            Close = g.Last().AskPrice
                        },
                        Period = resolution
                    };
         }

19 Source : InsightCollection.cs
with Apache License 2.0
from Capnode

public DateTime? GetNextExpiryTime()
        {
            if (Count == 0)
            {
                return null;
            }

            if (_nextExpiryTime != null)
            {
                return _nextExpiryTime;
            }

            _nextExpiryTime = _insights.Min(x => x.Value.Min(i => i.CloseTimeUtc));
            return _nextExpiryTime;
        }

19 Source : FactorFileRow.cs
with Apache License 2.0
from Capnode

public static List<FactorFileRow> Parse(IEnumerable<string> lines, out DateTime? factorFileMinimumDate)
        {
            factorFileMinimumDate = null;

            var rows = new List<FactorFileRow>();

            // parse factor file lines
            foreach (var line in lines)
            {
                // Exponential notation is treated as inf is because of the loss of precision. In
                // all cases, the significant part has fewer decimals than the needed for a correct
                // representation, E.g., 1.6e+6 when the correct factor is 1562500.
                if (line.Contains("inf") || line.Contains("e+"))
                {
                    continue;
                }

                var row = Parse(line);

                // ignore zero factor rows
                if (row.PriceScaleFactor > 0)
                {
                    rows.Add(row);
                }
            }

            if (factorFileMinimumDate == null && rows.Count > 0)
            {
                factorFileMinimumDate = rows.Min(ffr => ffr.Date).AddDays(-1);
            }

            return rows;
        }

19 Source : LeanData.cs
with Apache License 2.0
from Capnode

public static IEnumerable<TradeBar> AggregateTradeBars(IEnumerable<TradeBar> bars, Symbol symbol, TimeSpan resolution)
        {
            return
                from b in bars
                group b by b.Time.RoundDown(resolution)
                into g
                select new TradeBar
                {
                    Symbol = symbol,
                    Time = g.Key,
                    Open = g.First().Open,
                    High = g.Max(b => b.High),
                    Low = g.Min(b => b.Low),
                    Close = g.Last().Close,
                    Value = g.Last().Close,
                    DataType = MarketDataType.TradeBar,
                    Period = resolution
                };
        }

19 Source : MappingProfile.cs
with MIT License
from capricornus-platform

private static long GetDuration(IEnumerable<Span> spans)
        {
            var timeSpan = spans.Max(x => x.FinishTimestamp) - spans.Min(x => x.StartTimestamp);
            return timeSpan.GetMicroseconds();
        }

19 Source : StatusSet.cs
with GNU General Public License v3.0
from chaincase-app

public void Set(IEnumerable<Status> statuses)
		{
			Status updateWith = null;
			lock (ActiveStatusesLock)
			{
				var updated = false;

				foreach (var status in statuses)
				{
					if (status.IsCompleted)
					{
						updated = ActiveStatuses.RemoveWhere(x => x.Type == status.Type) == 1 || updated;
					}
					else
					{
						var found = ActiveStatuses.FirstOrDefault(x => x.Type == status.Type);
						if (found is { Percentage: var perc })
						{
							if (perc != status.Percentage)
							{
								ActiveStatuses.Remove(found);
								updated = ActiveStatuses.Add(status) || updated;
							}
						}
						else
						{
							updated = ActiveStatuses.Add(status) || updated;
						}
					}
				}

				if (updated && ActiveStatuses.Any())
				{
					var priority = ActiveStatuses.Min(x => x.Type);
					updateWith = ActiveStatuses.First(x => x.Type == priority);
				}
			}

			if (updateWith is { })
			{
				//Avalonia.Dispatcher.UIThread.PostLogException(() => CurrentStatus = updateWith);
				CurrentStatus = updateWith;
			}
		}

19 Source : SmartCoinSelector.cs
with GNU General Public License v3.0
from chaincase-app

public IEnumerable<ICoin> Select(IEnumerable<ICoin> coins, IMoney target)
		{
			Money targetMoney = target as Money;

			long available = UnspentCoins.Sum(x => x.Amount);
			if (available < targetMoney)
			{
				throw new InsufficientBalanceException(targetMoney, available);
			}

			// Get unique clusters.
			IEnumerable<Cluster> uniqueClusters = UnspentCoins
				.Select(coin => coin.Clusters)
				.Distinct();

			// Build all the possible coin clusters, except when it's computationally too expensive.
			List<IEnumerable<SmartCoin>> coinClusters = uniqueClusters.Count() < 10
				? uniqueClusters
					.CombinationsWithoutRepereplacedion(ofLength: 1, upToLength: 6)
					.Select(clusterCombination => UnspentCoins.Where(coin => clusterCombination.Contains(coin.Clusters)))
					.ToList()
				: new List<IEnumerable<SmartCoin>>();

			coinClusters.Add(UnspentCoins);

			// This operation is doing super advanced grouping on the coin clusters and adding properties to each of them.
			var sayajinCoinClusters = coinClusters
				.Select(coins => (Coins: coins, Privacy: 1.0m / (1 + coins.Sum(x => x.Clusters.Labels.Count()))))
				.Select(group => new
				{
					group.Coins,
					Unconfirmed = group.Coins.Any(x => !x.Confirmed),    // If group has an unconfirmed, then the whole group is unconfirmed.
					AnonymitySet = group.Coins.Min(x => x.AnonymitySet), // The group is as anonymous as its weakest member.
					ClusterPrivacy = group.Privacy, // The number people/enreplacedies that know the cluster.
					Amount = group.Coins.Sum(x => x.Amount)
				});

			// Find the best coin cluster that we are going to use.
			IEnumerable<SmartCoin> bestCoinCluster = sayajinCoinClusters
				.Where(group => group.Amount >= targetMoney)
				.OrderBy(group => group.Unconfirmed)
				.ThenByDescending(group => group.AnonymitySet)     // Always try to spend/merge the largest anonset coins first.
				.ThenByDescending(group => group.ClusterPrivacy)   // Select lesser-known coins.
				.ThenByDescending(group => group.Amount)           // Then always try to spend by amount.
				.First()
				.Coins;

			var coinsInBestClusterByScript = bestCoinCluster
				.GroupBy(c => c.ScriptPubKey)
				.Select(group => new
				{
					Coins = group
				});

			List<SmartCoin> coinsToSpend = new List<SmartCoin>();

			foreach (IGrouping<Script, SmartCoin> coinsGroup in coinsInBestClusterByScript
				.Select(group => group.Coins))
			{
				coinsToSpend.AddRange(coinsGroup);

				if (coinsToSpend.Sum(x => x.Amount) >= targetMoney)
				{
					break;
				}
			}

			return coinsToSpend.Select(c => c.GetCoin());
		}

19 Source : TransactionProcessor.cs
with GNU General Public License v3.0
from chaincase-app

private ProcessedResult ProcessNoLock(SmartTransaction tx)
		{
			var result = new ProcessedResult(tx);

			// We do not care about non-witness transactions for other than mempool cleanup.
			if (tx.Transaction.PossiblyP2WPKHInvolved())
			{
				uint256 txId = tx.GetHash();

				// Performance ToDo: txids could be cached in a hashset here by the AllCoinsView and then the contains would be fast.
				if (!tx.Transaction.IsCoinBase && !Coins.AsAllCoinsView().CreatedBy(txId).Any()) // Transactions we already have and processed would be "double spends" but they shouldn't.
				{
					var doubleSpends = new List<SmartCoin>();
					foreach (var txin in tx.Transaction.Inputs)
					{
						if (Coins.TryGetSpenderSmartCoinsByOutPoint(txin.PrevOut, out var coins))
						{
							doubleSpends.AddRange(coins);
						}
					}

					if (doubleSpends.Any())
					{
						if (tx.Height == Height.Mempool)
						{
							// if the received transaction is spending at least one input already
							// spent by a previous unconfirmed transaction signaling RBF then it is not a double
							// spending transaction but a replacement transaction.
							var isReplacementTx = doubleSpends.Any(x => x.IsReplaceable && !x.Confirmed);
							if (isReplacementTx)
							{
								// Undo the replaced transaction by removing the coins it created (if other coin
								// spends it, remove that too and so on) and restoring those that it replaced.
								// After undoing the replaced transaction it will process the replacement transaction.
								var replacedTxId = doubleSpends.First().TransactionId;
								var (replaced, restored) = Coins.Undo(replacedTxId);

								result.ReplacedCoins.AddRange(replaced);
								result.RestoredCoins.AddRange(restored);

								foreach (var replacedTransactionId in replaced.Select(coin => coin.TransactionId))
								{
									TransactionStore.MempoolStore.TryRemove(replacedTransactionId, out _);
								}

								tx.SetReplacement();
							}
							else
							{
								return result;
							}
						}
						else // new confirmation always enjoys priority
						{
							// remove double spent coins recursively (if other coin spends it, remove that too and so on), will add later if they came to our keys
							foreach (SmartCoin doubleSpentCoin in doubleSpends)
							{
								Coins.Remove(doubleSpentCoin);
							}

							result.SuccessfullyDoubleSpentCoins.AddRange(doubleSpends);

							var unconfirmedDoubleSpentTxId = doubleSpends.First().TransactionId;
							TransactionStore.MempoolStore.TryRemove(unconfirmedDoubleSpentTxId, out _);
						}
					}
				}

				List<SmartCoin> spentOwnCoins = null;
				for (var i = 0U; i < tx.Transaction.Outputs.Count; i++)
				{
					// If transaction received to any of the wallet keys:
					var output = tx.Transaction.Outputs[i];
					HdPubKey foundKey = KeyManager.GetKeyForScriptPubKey(output.ScriptPubKey);
					if (foundKey != default)
					{
						foundKey.SetKeyState(KeyState.Used, KeyManager);
						if (output.Value <= DustThreshold)
						{
							result.ReceivedDusts.Add(output);
							continue;
						}

						spentOwnCoins ??= Coins.OutPoints(tx.Transaction.Inputs).ToList();

						// Get the anonymity set of i-th output in the transaction.
						var anonset = tx.Transaction.GetAnonymitySet(i);
						// If we provided inputs to the transaction.
						if (spentOwnCoins.Count != 0)
						{
							// Take the input that we provided with the the smallest anonset.
							// And add that to the base anonset from the tx.
							// Our smallest anonset input is the relevant here, because this way the common input ownership heuristic is considered.
							// Take minus 1, because we do not want to count own into the anonset, so...
							// If the anonset of our UTXO would be 1, and the smallest anonset of our inputs would be 1, too, then we don't make...
							// The new UTXO's anonset 2, but only 1.
							anonset += spentOwnCoins.Min(x => x.AnonymitySet) - 1;
						}

						SmartCoin newCoin = new SmartCoin(txId, i, output.ScriptPubKey, output.Value, tx.Transaction.Inputs.ToOutPoints().ToArray(), tx.Height, tx.IsRBF, anonset, foundKey.Label, spenderTransactionId: null, false, pubKey: foundKey); // Do not inherit locked status from key, that's different.

						result.ReceivedCoins.Add(newCoin);
						// If we did not have it.
						if (Coins.TryAdd(newCoin))
						{
							result.NewlyReceivedCoins.Add(newCoin);

							// Make sure there's always 21 clean keys generated and indexed.
							KeyManager.replacedertCleanKeysIndexed(isInternal: foundKey.IsInternal);

							if (foundKey.IsInternal)
							{
								// Make sure there's always 14 internal locked keys generated and indexed.
								KeyManager.replacedertLockedInternalKeysIndexed(14);
							}
						}
						else // If we had this coin already.
						{
							if (newCoin.Height != Height.Mempool) // Update the height of this old coin we already had.
							{
								SmartCoin oldCoin = Coins.AsAllCoinsView().GetByOutPoint(new OutPoint(txId, i));
								if (oldCoin is { }) // Just to be sure, it is a concurrent collection.
								{
									result.NewlyConfirmedReceivedCoins.Add(newCoin);
									oldCoin.Height = newCoin.Height;
								}
							}
						}

19 Source : StatusSet.cs
with GNU General Public License v3.0
from chaincase-app

public void Set(IEnumerable<Status> statuses)
		{
			Status updateWith = null;
			lock (ActiveStatusesLock)
			{
				var updated = false;

				foreach (var status in statuses)
				{
					if (status.IsCompleted)
					{
						updated = ActiveStatuses.RemoveWhere(x => x.Type == status.Type) == 1 || updated;
					}
					else
					{
						var found = ActiveStatuses.FirstOrDefault(x => x.Type == status.Type);
						if (found is { Percentage: var perc })
						{
							if (perc != status.Percentage)
							{
								ActiveStatuses.Remove(found);
								updated = ActiveStatuses.Add(status) || updated;
							}
						}
						else
						{
							updated = ActiveStatuses.Add(status) || updated;
						}
					}
				}

				if (updated && ActiveStatuses.Any())
				{
					var priority = ActiveStatuses.Min(x => x.Type);
					updateWith = ActiveStatuses.First(x => x.Type == priority);
				}
			}

			if (updateWith is { })
			{
				Dispatcher.UIThread.PostLogException(() => CurrentStatus = updateWith);
			}
		}

19 Source : ClientState.cs
with GNU General Public License v3.0
from chaincase-app

private IEnumerable<OutPoint> GetRegistrableCoinsNoLock(int maximumInputCountPerPeer, Money feePerInputs, Money amountNeededExceptInputFees, bool allowUnconfirmedZeroLink)
		{
			if (!WaitingList.Any()) // To avoid computations.
			{
				return Enumerable.Empty<OutPoint>();
			}

			Func<SmartCoin, bool> confirmationPredicate;
			if (allowUnconfirmedZeroLink)
			{
				confirmationPredicate = x => x.Confirmed || x.IsLikelyCoinJoinOutput is true;
			}
			else
			{
				confirmationPredicate = x => x.Confirmed;
			}

			var coins = WaitingList
				.Where(x => x.Value <= DateTimeOffset.UtcNow)
				.Select(x => x.Key) // Only if registering coins is already allowed.
				.Where(confirmationPredicate)
				.ToList(); // So to not redo it in every cycle.

			bool lazyMode = false;

			for (int i = 1; i <= maximumInputCountPerPeer; i++) // The smallest number of coins we can register the better it is.
			{
				List<IEnumerable<SmartCoin>> coinGroups;
				Money amountNeeded = amountNeededExceptInputFees + (feePerInputs * i); // If the sum reaches the minimum amount.

				if (lazyMode) // Do the largest valid combination.
				{
					IEnumerable<SmartCoin> highestValueEnumeration = coins.OrderByDescending(x => x.Amount).Take(i);
					coinGroups = highestValueEnumeration.Sum(x => x.Amount) >= amountNeeded
						? new List<IEnumerable<SmartCoin>> { highestValueEnumeration }
						: new List<IEnumerable<SmartCoin>>();
				}
				else
				{
					DateTimeOffset start = DateTimeOffset.UtcNow;

					coinGroups = coins.GetPermutations(i, amountNeeded).ToList();

					if (DateTimeOffset.UtcNow - start > TimeSpan.FromMilliseconds(10)) // If the permutations took long then then if there's a nextTime, calculating permutations would be too CPU intensive.
					{
						lazyMode = true;
					}
				}

				if (i == 1) // If only one coin is to be registered.
				{
					// Prefer the largest one, so more mixing volume is more likely.
					coinGroups = coinGroups.OrderByDescending(x => x.Sum(y => y.Amount)).ToList();

					// Try to register with the smallest anonymity set, so new unmixed coins come to the mix.
					coinGroups = coinGroups.OrderBy(x => x.Sum(y => y.AnonymitySet)).ToList();
				}
				else // Else coin merging will happen.
				{
					// Prefer the lowest amount sum, so perfect mix should be more likely.
					coinGroups = coinGroups.OrderBy(x => x.Sum(y => y.Amount)).ToList();

					// Try to register the largest anonymity set, so red and green coins input merging should be less likely.
					coinGroups = coinGroups.OrderByDescending(x => x.Sum(y => y.AnonymitySet)).ToList();
				}

				coinGroups = coinGroups.OrderBy(x => x.Count(y => y.Confirmed == false)).ToList(); // Where the lowest amount of unconfirmed coins there are.

				IEnumerable<SmartCoin> best = coinGroups.FirstOrDefault();

				if (best != default)
				{
					var bestSet = best.ToHashSet();

					// -- OPPORTUNISTIC CONSOLIDATION --
					// https://github.com/zkSNACKs/WalletWasabi/issues/1651
					if (bestSet.Count < maximumInputCountPerPeer) // Ensure limits.
					{
						// Generating toxic change leads to mreplaced merging so it's better to merge sooner in coinjoin than the user do it himself in a non-CJ.
						// The best selection's anonset should not be lowered by this merge.
						int bestMinAnonset = bestSet.Min(x => x.AnonymitySet);
						var bestSum = Money.Satoshis(bestSet.Sum(x => x.Amount));

						if (!bestSum.Almost(amountNeeded, Money.Coins(0.0001m)) // Otherwise it wouldn't generate change so consolidation would make no sense.
							&& bestMinAnonset > 1) // Red coins should never be merged.
						{
							IEnumerable<SmartCoin> coinsThatCanBeConsolidated = coins
								.Except(bestSet) // Get all the registrable coins, except the already chosen ones.
								.Where(x =>
									x.AnonymitySet >= bestMinAnonset // The anonset must be at least equal to the bestSet's anonset so we do not ruin the change's after mix anonset.
									&& x.AnonymitySet > 1 // Red coins should never be merged.
									&& x.Amount < amountNeeded // The amount needs to be smaller than the amountNeeded (so to make sure this is toxic change.)
									&& bestSum + x.Amount > amountNeeded) // Sanity check that the amount added do not ruin the registration.
								.OrderBy(x => x.Amount); // Choose the smallest ones.

							if (coinsThatCanBeConsolidated.Count() > 1) // Because the last one change should not be circulating, ruining privacy.
							{
								var bestCoinToAdd = coinsThatCanBeConsolidated.First();
								bestSet.Add(bestCoinToAdd);
							}
						}
					}

					return bestSet.Select(x => x.OutPoint).ToArray();
				}
			}

			return Enumerable.Empty<OutPoint>(); // Inputs are too small, max input to be registered is reached.
		}

19 Source : ClientState.cs
with GNU General Public License v3.0
from chaincase-app

public int GetSmallestRegistrationTimeout()
		{
			lock (StateLock)
			{
				if (Rounds.Count == 0)
				{
					return 0;
				}
				return Rounds.Min(x => x.State.RegistrationTimeout);
			}
		}

19 Source : CoordinatorRound.cs
with GNU General Public License v3.0
from chaincase-app

private Money CalculateNewDenomination()
		{
			var newDenomination = Alices.Min(x => x.InputSum - x.NetworkFeeToPayAfterBaseDenomination);
			var collision = MixingLevels.GetLevelsExceptBase().FirstOrDefault(x => x.Denomination == newDenomination);
			if (collision is { })
			{
				newDenomination -= Money.Satoshis(1);
				Logger.LogDebug($"This is impossibru. The new base denomination is exactly the same as the one of the mixing level. Adjusted the new denomination one satoshi less.");
			}

			return newDenomination;
		}

19 Source : Geometry.cs
with Apache License 2.0
from Chem4Word

public static Point? GetCentroid(T[] poly, Func<T, Point> getPosition)
        {
            double acreplacedulatedArea = 0.0f;
            double centerX = 0.0f;
            double centerY = 0.0f;
            if (poly.Any())
            {
                var minX = poly.Min(p => getPosition(p).X);
                var maxX = poly.Max(p => getPosition(p).X);
                var minY = poly.Min(p => getPosition(p).Y);
                var maxY = poly.Max(p => getPosition(p).Y);

                for (int i = 0, j = poly.Length - 1; i < poly.Length; j = i++)
                {
                    double temp = getPosition(poly[i]).X * getPosition(poly[j]).Y
                                  - getPosition(poly[j]).X * getPosition(poly[i]).Y;
                    acreplacedulatedArea += temp;
                    centerX += (getPosition(poly[i]).X + getPosition(poly[j]).X) * temp;
                    centerY += (getPosition(poly[i]).Y + getPosition(poly[j]).Y) * temp;
                }

                if (Math.Abs(acreplacedulatedArea) < 1E-7f)
                {
                    return null; // Avoid division by zero
                }

                acreplacedulatedArea *= 3f;
                var centroid = new Point(centerX / acreplacedulatedArea, centerY / acreplacedulatedArea);
                //Debug.replacedert(centroid.X >= minX & centroid.X <= maxX & centroid.Y >= minY & centroid.Y <= maxY);
                return centroid;
            }

            return null;
        }

19 Source : FLVFile.cs
with GNU General Public License v2.0
from CHKZL

public void PrintReport()
        {
            logger.Log(" -- Flags: {0}. Packets: {1}", Header.Flags, Packets.Count);
            long audioDataBytes = AudioDataBytes;
            long videoDataBytes = VideoDataBytes;
            TimeSpan start = Packets.Min(p => p.TimeStamp);
            TimeSpan end = Packets.Max(p => p.TimeStamp);

            logger.Log(" -- Audio: {0} bytes ({1:P1}) ({2} packets)", audioDataBytes, (float)audioDataBytes / Size, Packets.Count(p => p.PacketType == PacketType.AudioPayload));
            logger.Log(" -- Video: {0} bytes ({1:P1}) ({2} packets)", videoDataBytes, (float)videoDataBytes / Size, Packets.Count(p => p.PacketType == PacketType.VideoPayload));
            logger.Log(" -- Duration: {0} seconds (from {1} to {2})", (int)(end - start).TotalSeconds, (int)start.TotalSeconds, (int)end.TotalSeconds);
        }

19 Source : EditModeUtils.cs
with MIT License
from chstetco

public static void SetStart(IEnumerable<ITimelineItem> items, double time)
        {
            var offset = time - items.Min(c => c.start);

            foreach (var item in items)
                item.start += offset;
        }

19 Source : MenuItemActionBase.cs
with MIT License
from chstetco

public static void BuildMenu(GenericMenu menu, List<MenuActionItem> items)
        {
            // sorted the outer menu by priority, then sort the innermenu by priority
            var sortedItems =
                items.GroupBy(x => string.IsNullOrEmpty(x.category) ? x.entryName : x.category).
                    OrderBy(x => x.Min(y => y.priority)).
                    SelectMany(x => x.OrderBy(z => z.priority));

            int lastPriority = Int32.MinValue;
            string lastCategory = string.Empty;

            foreach (var s in sortedItems)
            {
                if (s.state == MenuActionDisplayState.Hidden)
                    continue;

                var priority = s.priority;
                if (lastPriority == Int32.MinValue)
                {
                    lastPriority = priority;
                }
                else if ((priority / MenuOrder.SeparatorAt) > (lastPriority / MenuOrder.SeparatorAt))
                {
                    string path = String.Empty;
                    if (lastCategory == s.category)
                        path = s.category;
                    menu.AddSeparator(path);
                }

                lastPriority = priority;
                lastCategory = s.category;

                string entry = s.category + s.entryName;
                if (!string.IsNullOrEmpty(s.shortCut))
                    entry += " " + s.shortCut;

                if (s.state == MenuActionDisplayState.Visible && s.isActiveInMode)
                    menu.AddItem(new GUIContent(entry), s.isChecked, s.callback);
                else
                    menu.AddDisabledItem(new GUIContent(entry));
            }
        }

19 Source : ItemsUtils.cs
with MIT License
from chstetco

public static void GereplacedemRange(this Trackreplacedet track, out double start, out double end)
        {
            start = 0;
            end = 0;
            var items = track.Gereplacedems().ToList();
            if (items.Any())
            {
                start = items.Min(p => p.start);
                end = items.Max(p => p.end);
            }
        }

19 Source : TimelineHelpers.cs
with MIT License
from chstetco

public static void FrameItems(WindowState state, IEnumerable<ITimelineItem> items)
        {
            if (items == null || !items.Any() || state == null)
                return;

            // if this is called before a repaint, the timeArea can be null
            var window = state.editorWindow as TimelineWindow;
            if (window == null || window.timeArea == null)
                return;

            var start = (float)items.Min(x => x.start);
            var end = (float)items.Max(x => x.end);
            var timeRange = state.timeAreaShownRange;

            // nothing to do
            if (timeRange.x <= start && timeRange.y >= end)
                return;

            var ds = start - timeRange.x;
            var de = end - timeRange.y;

            var padding = state.PixelDeltaToDeltaTime(15);
            var d = Math.Abs(ds) < Math.Abs(de) ? ds - padding : de + padding;

            state.SetTimeAreaShownRange(timeRange.x + d, timeRange.y + d);
        }

19 Source : StorageExcelHelper.cs
with MIT License
from cmdty

public static Func<Day, double> CreateLinearInterpolatedInterestRateFunc(object excelValues, string excelArgumentName)
        {
            if (excelValues is ExcelMissing || excelValues is ExcelEmpty)
                throw new ArgumentException(excelArgumentName + " hasn't been specified.");

            if (!(excelValues is object[,] excelValuesArray))
                throw new ArgumentException(excelArgumentName + " has been incorrectly entered. Argument value should be of a range with 2 columns, the first containing dates, the second containing numbers.");

            if (excelValuesArray.GetLength(1) != 2)
                throw new ArgumentException(excelArgumentName + " has been incorrectly entered. Argument value should be a range with 2 columns.");

            var interestRatePoints = new List<(Day Date, double InterestRate)>();

            for (int i = 0; i < excelValuesArray.GetLength(0); i++)
            {
                if (excelValuesArray[i, 0] is ExcelEmpty || excelValuesArray[i, 0] is ExcelError)
                    break;

                if (!(excelValuesArray[i, 1] is double doubleValue))
                    throw new ArgumentException($"Value in the second column of row {i} for argument {excelArgumentName} is not a number.");

                DateTime curvePointDateTime = ObjectToDateTime(excelValuesArray[i, 0], $"Cannot create DateTime from value in first row of argument {excelArgumentName}.");

                interestRatePoints.Add((Date: Day.FromDateTime(curvePointDateTime), InterestRate: doubleValue));
            }

            if (interestRatePoints.Count < 2)
                throw new ArgumentException(excelArgumentName + " must contain at least two points.");

            Day firstDate = interestRatePoints.Min(curvePoint => curvePoint.Date);
            IEnumerable<double> maturitiesToInterpolate =
                interestRatePoints.Select(curvePoint => curvePoint.Date.OffsetFrom(firstDate) / 365.0);

            LinearSpline linearSpline = LinearSpline.Interpolate(maturitiesToInterpolate, interestRatePoints.Select(curvePoint => curvePoint.InterestRate));

            Day lastDate = interestRatePoints.Max(curvePoint => curvePoint.Date);

            double InterpolatedCurve(Day cashFlowDate)
            {
                if (cashFlowDate < firstDate || cashFlowDate > lastDate)
                    throw new ArgumentException($"Interest rate for future cash flow {cashFlowDate} cannot be interpolated, as this date is outside of the bounds of the input rates curve.");
                double maturity = (cashFlowDate - firstDate) / 365.0;
                return linearSpline.Interpolate(maturity);
            }
            
            return InterpolatedCurve;
        }

19 Source : Bootstrapper.cs
with MIT License
from cmdty

private static BootstrapResults<T> Calculate([NotNull] List<Contract<T>> contracts, [NotNull] Func<T, double> weighting,
            [NotNull] List<Shaping<T>> shapings, bool allowRedundancy = false)
        {
            if (contracts == null) throw new ArgumentNullException(nameof(contracts));
            if (weighting == null) throw new ArgumentNullException(nameof(weighting));
            if (shapings == null) throw new ArgumentNullException(nameof(shapings));

            var contractsPlusShapingsCount = contracts.Count + shapings.Count;

            if (contractsPlusShapingsCount < 2)
                throw new ArgumentException("contracts and shapings combined must contain at least two elements", nameof(contracts));

            // TODO check if two contracts have the same Start and End?
            var minTimePeriod = contracts.Select(contract => contract.Start)
                .Concat(shapings.Select(shaping => shaping.Start1))
                .Concat(shapings.Select(shaping => shaping.Start2))
                .Min(timePeriod => timePeriod);

            var maxTimePeriod = contracts.Select(contract => contract.End)
                .Concat(shapings.Select(shaping => shaping.End1))
                .Concat(shapings.Select(shaping => shaping.End2))
                .Max(timePeriod => timePeriod);

            var numTimePeriods = maxTimePeriod.OffsetFrom(minTimePeriod) + 1;

            var matrix = Matrix<double>.Build.Dense(contractsPlusShapingsCount, numTimePeriods);
            var vector = Vector<double>.Build.Dense(contractsPlusShapingsCount);

            for (int i = 0; i < contracts.Count; i++)
            {
                var contract = contracts[i];
                double sumWeight = 0.0;
                var startOffset = contract.Start.OffsetFrom(minTimePeriod);
                var endOffset = contract.End.OffsetFrom(minTimePeriod);
                for (int j = startOffset; j <= endOffset; j++)
                {
                    var timePeriod = minTimePeriod.Offset(j);
                    var weight = weighting(timePeriod);
                    matrix[i, j] = weight;
                    sumWeight += weight;
                }
                if (sumWeight <= 0)
                {
                    throw new ArgumentException(
                        "sum of weighting evaluated to non-positive number for the following contract: " + contract);
                }
                vector[i] = contract.Price * sumWeight;
            }

            for (int i = 0; i < shapings.Count; i++)
            {
                var shaping = shapings[i];
                int rowIndex = i + contracts.Count;
                var startOffset1 = shaping.Start1.OffsetFrom(minTimePeriod);
                var endOffset1 = shaping.End1.OffsetFrom(minTimePeriod);

                var startOffset2 = shaping.Start2.OffsetFrom(minTimePeriod);
                var endOffset2 = shaping.End2.OffsetFrom(minTimePeriod);

                double sumWeighting1 = 0.0;
                for (int j = startOffset1; j <= endOffset1; j++)
                {
                    var timePeriod = minTimePeriod.Offset(j);
                    var weight = weighting(timePeriod);
                    matrix[rowIndex, j] = weight;
                    sumWeighting1 += weight;
                }

                for (int j = startOffset1; j <= endOffset1; j++)
                {
                    matrix[rowIndex, j] /= sumWeighting1;
                }

                double sumWeighting2 = shaping.Start2.EnumerateTo(shaping.End2).Sum(weighting);
                // TODO refactor to eliminate duplicate evaluation of weighting

                if (shaping.ShapingType == ShapingType.Spread)
                {
                    // TODO refactor out common code to shared methods
                    for (int j = startOffset2; j <= endOffset2; j++)
                    {
                        var timePeriod = minTimePeriod.Offset(j);
                        var weight = weighting(timePeriod);
                        matrix[rowIndex, j] -= weight / sumWeighting2;
                    }
                    vector[rowIndex] = shaping.Value;
                }
                else if (shaping.ShapingType == ShapingType.Ratio)
                {
                    // TODO refactor out common code to shared methods
                    for (int j = startOffset2; j <= endOffset2; j++)
                    {
                        var timePeriod = minTimePeriod.Offset(j);
                        var weight = weighting(timePeriod);
                        matrix[rowIndex, j] += -weight * shaping.Value / sumWeighting2;
                    }
                    vector[rowIndex] = 0.0; // Not necessary, but just being explicit
                }
                else
                {
                    throw new InvalidEnumArgumentException($"shapings[{i}].ShapingType", (int)shaping.ShapingType,
                                            typeof(ShapingType)); // TODO check the exception message and whether InvalidEnumArgumentException should be used in this context
                }
            }

            if (!allowRedundancy)
            {
                var matrixRank = matrix.Rank();
                if (matrixRank < matrix.RowCount)
                {
                    throw new ArgumentException("Redundant contracts and shapings are present");
                }
            }

            // Calculate least squares solution
            // TODO use alternative decomposition if full-rank http://www.imagingshop.com/linear-and-nonlinear-least-squares-with-math-net/
            // TODO does Math.Net offer a double tolerance parameter like NMath
            Vector<double> leastSquaresSolution = matrix.Svd(true).Solve(vector);

            var curvePeriods = new List<T>(leastSquaresSolution.Count);
            var curvePrices = new List<double>(leastSquaresSolution.Count);

            // TODO preplaced raw results into BootstrapResults and have the processed result lazy calculated on access

            var bootstrappedContracts = new List<Contract<T>>();

            // TODO check if only one element?
            var allOutputPeriods = minTimePeriod.EnumerateTo(maxTimePeriod.Offset(1)).Skip(1).ToList();
            T contractStart = minTimePeriod;

            for (var i = 0; i < allOutputPeriods.Count; i++)
            {
                var outputPeriod = allOutputPeriods[i];
                var inputStartsHere = contracts.Any(contract => contract.Start.Equals(outputPeriod)) ||
                        shapings.Any(shaping => shaping.Start1.Equals(outputPeriod) || shaping.Start2.Equals(outputPeriod));

                var inputEndsOneStepBefore = contracts.Any(contract => contract.End.Next().Equals(outputPeriod)) ||
                        shapings.Any(shaping => shaping.End1.Next().Equals(outputPeriod) || shaping.End2.Next().Equals(outputPeriod));

                // TODO refactor OR
                if (inputStartsHere || inputEndsOneStepBefore) // New output period
                {
                    var contractEnd = outputPeriod.Previous();

                    // Calculate weighted average price
                    // Add to bootstrappedContracts
                    double price = WeightedAveragePrice(contractStart, contractEnd, minTimePeriod, leastSquaresSolution, weighting);
                    bootstrappedContracts.Add(new Contract<T>(contractStart, contractEnd, price));

                    foreach (var period in contractStart.EnumerateTo(contractEnd))
                    {
                        curvePeriods.Add(period);
                        curvePrices.Add(price);
                    }

                    if (i < allOutputPeriods.Count - 1)
                    {
                        // Set contractStart unless last item of loop
                        if (!IsGapInContractsAndShapings(contracts, shapings, outputPeriod))
                        {
                            contractStart = outputPeriod;
                        }
                        else // outputPeriod is in a gap so need to increment i until not a gap
                        {
                            // TODO find more efficient way of doing this calculation
                            do
                            {
                                curvePeriods.Add(outputPeriod);
                                curvePrices.Add(price);
                                i++;
                                outputPeriod = outputPeriod.Next();
                            } while (IsGapInContractsAndShapings(contracts, shapings, outputPeriod));

                            contractStart = outputPeriod; // TODO remove top block of if as redundant?
                        }
                    }
                }
            }

            var curve = new DoubleCurve<T>(curvePeriods, curvePrices, weighting);
            return new BootstrapResults<T>(curve, bootstrappedContracts);
        }

19 Source : IntrinsicStorageValuationExtensions.cs
with MIT License
from cmdty

public static IIntrinsicAddInterpolator<T> WithFixedNumberOfPointsOnGlobalInventoryRange<T>(
                [NotNull] this IIntrinsicAddInventoryGridCalculation<T> intrinsicAddSpacing, int numGridPointsOverGlobalInventoryRange)
            where T : ITimePeriod<T>
        {
            if (intrinsicAddSpacing == null) throw new ArgumentNullException(nameof(intrinsicAddSpacing));
            if (numGridPointsOverGlobalInventoryRange < 3)
                throw new ArgumentException($"Parameter {nameof(numGridPointsOverGlobalInventoryRange)} value must be at least 3.", nameof(numGridPointsOverGlobalInventoryRange));
            
            IDoubleStateSpaceGridCalc GridCalcFactory(ICmdtyStorage<T> storage)
            {
                T[] storagePeriods = storage.StartPeriod.EnumerateTo(storage.EndPeriod).ToArray();

                double globalMaxInventory = storagePeriods.Max(storage.MaxInventory);
                double globalMinInventory = storagePeriods.Min(storage.MinInventory);
                double gridSpacing = (globalMaxInventory - globalMinInventory) /
                                     (numGridPointsOverGlobalInventoryRange - 1);
                return new FixedSpacingStateSpaceGridCalc(gridSpacing);
            }

            return intrinsicAddSpacing.WithStateSpaceGridCalculation(GridCalcFactory);
        }

19 Source : FixedSpacingStateSpaceGridCalc.cs
with MIT License
from cmdty

public static FixedSpacingStateSpaceGridCalc CreateForFixedNumberOfPointsOnGlobalInventoryRange<T>(
            [NotNull] ICmdtyStorage<T> storage,
            int numGridPointsOverGlobalInventoryRange)
            where T : ITimePeriod<T>
        {
            if (storage == null) throw new ArgumentNullException(nameof(storage));
            if (numGridPointsOverGlobalInventoryRange < 3)
                throw new ArgumentException($"Parameter {nameof(numGridPointsOverGlobalInventoryRange)} value must be at least 3.", nameof(numGridPointsOverGlobalInventoryRange));

            T[] storagePeriods = storage.StartPeriod.EnumerateTo(storage.EndPeriod).ToArray();

            double globalMaxInventory = storagePeriods.Max(storage.MaxInventory);
            double globalMinInventory = storagePeriods.Min(storage.MinInventory);
            double gridSpacing = (globalMaxInventory - globalMinInventory) /
                                 (numGridPointsOverGlobalInventoryRange - 1);
            return new FixedSpacingStateSpaceGridCalc(gridSpacing);
        }

19 Source : InventorySpaceGrid.cs
with MIT License
from cmdty

public static Func<ICmdtyStorage<T>, IDoubleStateSpaceGridCalc> FixedNumberOfPointsOnGlobalInventoryRangeFactory<T>(int numGridPointsOverGlobalInventoryRange)
            where T : ITimePeriod<T>
        {
            if (numGridPointsOverGlobalInventoryRange < 3)
                throw new ArgumentException($"Parameter {nameof(numGridPointsOverGlobalInventoryRange)} value must be at least 3.", nameof(numGridPointsOverGlobalInventoryRange));

            IDoubleStateSpaceGridCalc GridCalcFactory(ICmdtyStorage<T> storage)
            {
                T[] storagePeriods = storage.StartPeriod.EnumerateTo(storage.EndPeriod).ToArray();

                double globalMaxInventory = storagePeriods.Max(storage.MaxInventory);
                double globalMinInventory = storagePeriods.Min(storage.MinInventory);
                double gridSpacing = (globalMaxInventory - globalMinInventory) /
                                     (numGridPointsOverGlobalInventoryRange - 1);
                return new FixedSpacingStateSpaceGridCalc(gridSpacing);
            }

            return GridCalcFactory;
        }

19 Source : CmdtyStorageBuilderExtensions.cs
with MIT License
from cmdty

private static IAddInjectionCost<T> AddInjectWithdrawRanges<T>(
            IAddInjectWithdrawConstraints<T> builder,
            IEnumerable<InjectWithdrawRangeByInventoryAndPeriod<T>> injectWithdrawRanges, 
            Func<InjectWithdrawRangeByInventory[], IInjectWithdrawConstraint> constraintFactory) where T : ITimePeriod<T>
        {
            var injectWithdrawSortedList = new SortedList<T, IInjectWithdrawConstraint>();
            var inventoryRangeList = new List<InventoryRange>();

            foreach ((T period, IEnumerable<InjectWithdrawRangeByInventory> injectWithdrawRange) in injectWithdrawRanges)
            {
                if (period == null)
                    throw new ArgumentException("Null Period in collection.", nameof(injectWithdrawRanges));
                if (injectWithdrawRange == null)
                    throw new ArgumentException("Null InjectWithdrawRanges in collection.", nameof(injectWithdrawRange));
                
                InjectWithdrawRangeByInventory[] injectWithdrawRangeArray = injectWithdrawRange.ToArray();
                if (injectWithdrawRangeArray.Length < 2)
                    throw new ArgumentException($"Period {period} contains less than 2 inject/withdraw/inventory constraints.",
                        nameof(injectWithdrawRanges));

                IInjectWithdrawConstraint constraint;
                if (injectWithdrawRangeArray.Length == 2 &&
                    injectWithdrawRangeArray[0].InjectWithdrawRange.MinInjectWithdrawRate.AlmostEqual(
                        injectWithdrawRangeArray[1].InjectWithdrawRange.MinInjectWithdrawRate, double.Epsilon) &&
                    injectWithdrawRangeArray[0].InjectWithdrawRange.MaxInjectWithdrawRate.AlmostEqual(
                        injectWithdrawRangeArray[1].InjectWithdrawRange.MaxInjectWithdrawRate, double.Epsilon))
                {
                    // Two rows which represent constant inject/withdraw constraints over all inventories
                    constraint = new ConstantInjectWithdrawConstraint(injectWithdrawRangeArray[0].InjectWithdrawRange);
                }
                else
                {
                    constraint = constraintFactory(injectWithdrawRangeArray);
                }

                double minInventory = injectWithdrawRangeArray.Min(inventoryRange => inventoryRange.Inventory);
                double maxInventory = injectWithdrawRangeArray.Max(inventoryRange => inventoryRange.Inventory);

                try
                {
                    injectWithdrawSortedList.Add(period, constraint);
                    inventoryRangeList.Add(new InventoryRange(minInventory, maxInventory));
                }
                catch (ArgumentException) // TODO unit test
                {
                    throw new ArgumentException("Repeated periods found in inject/withdraw ranges.",
                        nameof(injectWithdrawRanges));
                }
            }

            if (injectWithdrawSortedList.Count == 0)
                throw new ArgumentException("No inject/withdraw constrains provided.", nameof(injectWithdrawRanges));

            // TODO create helper method (in Cmdty.TimeSeries) to create TimeSeries from piecewise data?
            T firstPeriod = injectWithdrawSortedList.Keys[0];
            T lastPeriod = injectWithdrawSortedList.Keys[injectWithdrawSortedList.Count - 1];
            int numPeriods = lastPeriod.OffsetFrom(firstPeriod) + 1;

            var timeSeriesInjectWithdrawValues = new IInjectWithdrawConstraint[numPeriods];
            var timeSeriesInventoryRangeValues = new InventoryRange[numPeriods];

            T periodLoop = firstPeriod;
            IInjectWithdrawConstraint constraintLoop = injectWithdrawSortedList.Values[0];
            InventoryRange inventoryRangeLoop = inventoryRangeList[0];

            int arrayCounter = 0;
            int sortedListCounter = 0;
            do
            {
                if (periodLoop.Equals(injectWithdrawSortedList.Keys[sortedListCounter]))
                {
                    constraintLoop = injectWithdrawSortedList.Values[sortedListCounter];
                    inventoryRangeLoop = inventoryRangeList[sortedListCounter];
                    sortedListCounter++;
                }

                timeSeriesInjectWithdrawValues[arrayCounter] = constraintLoop;
                timeSeriesInventoryRangeValues[arrayCounter] = inventoryRangeLoop;

                periodLoop = periodLoop.Offset(1);
                arrayCounter++;
            } while (periodLoop.CompareTo(lastPeriod) <= 0);

            var injectWithdrawTimeSeries =
                new TimeSeries<T, IInjectWithdrawConstraint>(firstPeriod, timeSeriesInjectWithdrawValues);
            var inventoryRangeTimeSeries = new TimeSeries<T, InventoryRange>(firstPeriod, timeSeriesInventoryRangeValues);

            IInjectWithdrawConstraint GetInjectWithdrawConstraint(T period)
            {
                if (period.CompareTo(injectWithdrawTimeSeries.End) > 0)
                    return injectWithdrawTimeSeries[injectWithdrawTimeSeries.End];
                return injectWithdrawTimeSeries[period];
            }

            IAddMinInventory<T>
                addMinInventory = builder.WithInjectWithdrawConstraint(GetInjectWithdrawConstraint);

            double GetMinInventory(T period)
            {
                if (period.CompareTo(inventoryRangeTimeSeries.End) > 0)
                    return inventoryRangeTimeSeries[inventoryRangeTimeSeries.End].MinInventory;
                return inventoryRangeTimeSeries[period].MinInventory;
            }

            IAddMaxInventory<T> addMaxInventory = addMinInventory.WithMinInventory(GetMinInventory);

            double GetMaxInventory(T period)
            {
                if (period.CompareTo(inventoryRangeTimeSeries.End) > 0)
                    return inventoryRangeTimeSeries[inventoryRangeTimeSeries.End].MaxInventory;
                return inventoryRangeTimeSeries[period].MaxInventory;
            }

            IAddInjectionCost<T> addInjectionCost = addMaxInventory.WithMaxInventory(GetMaxInventory);
            return addInjectionCost;
        }

19 Source : ShardingIQueryable.T.cs
with MIT License
from Coldairarrow

public TResult Min<TResult>(Expression<Func<T, TResult>> selector)
        {
            return GetStatisData(x => x.Min(selector)).Min(x => (TResult)x);
        }

19 Source : TextLayoutTests.cs
with MIT License
from CommitteeOfZero

[Theory]
        [InlineData("ruby base", "ruby text")]
        [InlineData("ru", "ruby text")]
        public void RubyText(string rb, string rt)
        {
            TextRun run = Ruby(rb, rt);
            TextLayout layout = Layout(new[] { run }, null, null, 45);

            GlyphRun rbRun = layout.GlyphRuns[0];
            GlyphRun rtRun = layout.GlyphRuns[1];

            replacedert.Equal(GlyphRunFlags.RubyBase, rbRun.Flags);
            replacedert.Equal(GlyphRunFlags.RubyText, rtRun.Flags);
            replacedert.True(rtRun.FontSize.Value.ToSingle() < rbRun.FontSize.Value.ToSingle());

            replacedertGlyphs(layout, rbRun.GlyphSpan, rb);
            replacedertGlyphs(layout, rtRun.GlyphSpan, rt);

            PositionedGlyph[] rubyBase = layout.Glyphs[rbRun.GlyphSpan].ToArray();
            PositionedGlyph[] rubyText = layout.Glyphs[rtRun.GlyphSpan].ToArray();
            float rbMinY = rubyBase.Min(x => x.Position.Y);
            float rtMaxY = rubyText.Max(x => x.Position.Y);
            replacedert.True(rbMinY > rtMaxY);
        }

19 Source : TreeNodesFactory.cs
with MIT License
from CompassSecurity

public async Task<ObservableCollection<TreeNode>> CreateTree()
        {
            var domains = await unitOfWork.ADDomainRepository.GetAllEnreplacedies();
            var tree = new ObservableCollection<TreeNode>();
            var root = new TreeNode();

            var rootDomain = domains.FirstOrDefault();
            var rsopPots = GetRsopPotsOfDomain(rootDomain);
            if (rootDomain != null)
            {
                rootDomain.DomainPercentage = rsopPots.Min(x => x.Rsops.Min(y => y.RsopPercentage));
                unitOfWork.ADDomainRepository.Update(rootDomain);

                root = NewDomainNode(rootDomain);
                foreach (var rsopPot in rsopPots)
                {
                    var rsopPotOfDomain = NewRsopPotNode(rsopPot);
                    root.ChildNodes.Add(rsopPotOfDomain);
                }

                BuildTree(root, rootDomain.SubADDomains);
            }

            await unitOfWork.SaveChangesAsync();
            tree.Add(root);
            return tree;
        }

19 Source : TreeNodesFactory.cs
with MIT License
from CompassSecurity

private void BuildTree(TreeNode root, List<ADDomain> domains)
        {
            if (domains != null)
            {
                foreach (var domain in domains)
                {
                    if (domain.IsAvailable)
                    {
                        var rsopPots = GetRsopPotsOfDomain(domain);
                        domain.DomainPercentage = rsopPots.Min(x => x.Rsops.Min(y => y.RsopPercentage));
                        unitOfWork.ADDomainRepository.Update(domain);

                        var child = NewDomainNode(domain);
                        foreach (var rsopPot in rsopPots)
                        {
                            var rsopPotOfDomain = NewRsopPotNode(rsopPot);
                            child.ChildNodes.Add(rsopPotOfDomain);
                        }

                        root.ChildNodes.Add(child);
                        BuildTree(child, domain.SubADDomains);
                    }
                }
            }
        }

See More Examples