System.Collections.Generic.IEnumerable.Sum()

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

905 Examples 7

19 Source : SimulatedHandUtils.cs
with Apache License 2.0
from abist-co-ltd

public static void CalculateJointRotations(Handedness handedness, Vector3[] jointPositions, Quaternion[] jointOrientationsOut)
        {
            const int numFingers = 5;
            int[] jointsPerFinger = { 4, 5, 5, 5, 5 }; // thumb, index, middle, right, pinky

            for (int fingerIndex = 0; fingerIndex < numFingers; fingerIndex++)
            {
                int jointsCurrentFinger = jointsPerFinger[fingerIndex];
                int lowIndex = (int)TrackedHandJoint.ThumbMetacarpalJoint + jointsPerFinger.Take(fingerIndex).Sum();
                int highIndex = lowIndex + jointsCurrentFinger - 1;

                for (int jointStartidx = lowIndex; jointStartidx <= highIndex; jointStartidx++)
                {
                    // If we are at the lowIndex (metacarpals) use the wrist as the previous joint.
                    int jointEndidx = jointStartidx == lowIndex ? (int)TrackedHandJoint.Wrist : jointStartidx - 1;
                    Vector3 boneForward = jointPositions[jointStartidx] - jointPositions[jointEndidx];
                    Vector3 boneUp = Vector3.Cross(boneForward, GetPalmRightVector(handedness, jointPositions));
                    if (boneForward.magnitude > float.Epsilon && boneUp.magnitude > float.Epsilon)
                    {
                        Quaternion jointRotation = Quaternion.LookRotation(boneForward, boneUp);
                        // If we are the thumb, set the up vector to be from pinky to index (right hand) or index to pinky (left hand).
                        if (fingerIndex == 0)
                        {
                            // Rotate the thumb by 90 degrees (-90 if left hand) about thumb forward vector.
                            Quaternion rotateThumb90 = Quaternion.AngleAxis(handedness == Handedness.Left ? -90 : 90, boneForward);
                            jointRotation = rotateThumb90 * jointRotation;
                        }
                        jointOrientationsOut[jointStartidx] = jointRotation;
                    }
                    else
                    {
                        jointOrientationsOut[jointStartidx] = Quaternion.idenreplacedy;
                    }
                }
            }
            jointOrientationsOut[(int)TrackedHandJoint.Palm] = Quaternion.LookRotation(GetPalmForwardVector(jointPositions), GetPalmUpVector(handedness, jointPositions));
        }

19 Source : ExampleSearchProvider.cs
with MIT License
from ABTSoftware

private double DotProduct(double[] vector1, double[] vector2)
        {
            double result = vector1.Length != vector2.Length ? 0 : vector1.Zip(vector2, (x, y) => x * y).Sum();
            return result;
        }

19 Source : ManaStone.cs
with GNU Affero General Public License v3.0
from ACEmulator

public override void HandleActionUseOnTarget(Player player, WorldObject target)
        {
            WorldObject invTarget;

            var useResult = WeenieError.None;

            if (player.IsOlthoiPlayer)
            {
                player.SendUseDoneEvent(WeenieError.OlthoiCannotInteractWithThat);
                return;
            }

            if (player != target)
            {
                invTarget = player.FindObject(target.Guid.Full, Player.SearchLocations.MyInventory | Player.SearchLocations.MyEquippedItems);
                if (invTarget == null)
                {
                    // Haven't looked to see if an error was sent for this case; however, this one fits
                    player.Session.Network.EnqueueSend(new GameEventUseDone(player.Session, WeenieError.YouDoNotOwnThareplacedem));
                    return;
                }

                target = invTarget;
            }

            if (!ItemCurMana.HasValue)
            {
                if (target == player)
                    useResult = WeenieError.ActionCancelled;
                else if (target.ItemCurMana.HasValue && target.ItemCurMana.Value > 0 && target.ItemMaxMana.HasValue && target.ItemMaxMana.Value > 0)
                {
                    // absorb mana from the item
                    if (target.Retained)
                        useResult = WeenieError.ActionCancelled;
                    else
                    {
                        if (!player.TryConsumeFromInventoryWithNetworking(target, 1) && !player.TryDequipObjectWithNetworking(target.Guid, out _, Player.DequipObjectAction.ConsumeItem))
                        {
                            log.Error($"Failed to remove {target.Name} from player inventory.");
                            player.Session.Network.EnqueueSend(new GameEventUseDone(player.Session, WeenieError.ActionCancelled));
                            return;
                        }

                        //The Mana Stone drains 5,253 points of mana from the Wand.
                        //The Wand is destroyed.

                        //The Mana Stone drains 4,482 points of mana from the Pantaloons.
                        //The Pantaloons is destroyed.

                        var manaDrained = (int)Math.Round(Efficiency.Value * target.ItemCurMana.Value);
                        ItemCurMana = manaDrained;
                        player.Session.Network.EnqueueSend(new GameMessageSystemChat($"The Mana Stone drains {ItemCurMana:N0} points of mana from the {target.Name}.\nThe {target.Name} is destroyed.", ChatMessageType.Broadcast));
                        SetUiEffect(player, ACE.Enreplacedy.Enum.UiEffects.Magical);
                    }
                }
                else
                {
                    useResult = WeenieError.ItemDoesntHaveEnoughMana;
                }
            }
            else if (ItemCurMana.Value > 0)
            {
                if (target == player)
                {
                    // dump mana into equipped items
                    var origItemsNeedingMana = player.EquippedObjects.Values.Where(k => k.ItemCurMana.HasValue && k.ItemMaxMana.HasValue && k.ItemCurMana < k.ItemMaxMana).ToList();
                    var itemsGivenMana = new Dictionary<WorldObject, int>();

                    while (ItemCurMana > 0)
                    {
                        var itemsNeedingMana = origItemsNeedingMana.Where(k => k.ItemCurMana < k.ItemMaxMana).ToList();
                        if (itemsNeedingMana.Count < 1)
                            break;

                        var ration = Math.Max(ItemCurMana.Value / itemsNeedingMana.Count, 1);

                        foreach (var item in itemsNeedingMana)
                        {
                            var manaNeededForTopoff = (int)(item.ItemMaxMana - item.ItemCurMana);
                            var adjustedRation = Math.Min(ration, manaNeededForTopoff);

                            ItemCurMana -= adjustedRation;

                            if (player.LumAugItemManaGain != 0)
                            {
                                adjustedRation = (int)Math.Round(adjustedRation * Creature.GetPositiveRatingMod(player.LumAugItemManaGain * 5));
                                if (adjustedRation > manaNeededForTopoff)
                                {
                                    var diff = adjustedRation - manaNeededForTopoff;
                                    adjustedRation = manaNeededForTopoff;
                                    ItemCurMana += diff;
                                }
                            }

                            item.ItemCurMana += adjustedRation;
                            if (!itemsGivenMana.ContainsKey(item))
                                itemsGivenMana[item] = adjustedRation;
                            else
                                itemsGivenMana[item] += adjustedRation;

                            if (ItemCurMana <= 0)
                                break;
                        }
                    }

                    if (itemsGivenMana.Count < 1)
                    {
                        player.Session.Network.EnqueueSend(new GameMessageSystemChat("You have no items equipped that need mana.", ChatMessageType.Broadcast));
                        useResult = WeenieError.ActionCancelled;
                    }
                    else
                    {
                        //The Mana Stone gives 4,496 points of mana to the following items: Fire Compound Crossbow, Qafiya, Celdon Sleeves, Amuli Leggings, Messenger's Collar, Heavy Bracelet, Scalemail Bracers, Olthoi Alduressa Gauntlets, Studded Leather Girth, Shoes, Chainmail Greaves, Loose Pants, Mechanical Scarab, Ring, Ring, Heavy Bracelet
                        //Your items are fully charged.

                        //The Mana Stone gives 1,921 points of mana to the following items: Haebrean Girth, Chiran Helm, Ring, Baggy Breeches, Scalemail Greaves, Alduressa Boots, Heavy Bracelet, Heavy Bracelet, Lorica Breastplate, Pocket Watch, Heavy Necklace
                        //You need 2,232 more mana to fully charge your items.

                        var additionalManaNeeded = origItemsNeedingMana.Sum(k => k.ItemMaxMana.Value - k.ItemCurMana.Value);
                        var additionalManaText = (additionalManaNeeded > 0) ? $"\nYou need {additionalManaNeeded:N0} more mana to fully charge your items." : "\nYour items are fully charged.";
                        var msg = $"The Mana Stone gives {itemsGivenMana.Values.Sum():N0} points of mana to the following items: {itemsGivenMana.Select(c => c.Key.Name).Aggregate((a, b) => a + ", " + b)}.{additionalManaText}";
                        player.Session.Network.EnqueueSend(new GameMessageSystemChat(msg, ChatMessageType.Broadcast));

                        if (!DoDestroyDiceRoll(player) && !UnlimitedUse)
                        {
                            ItemCurMana = null;
                            SetUiEffect(player, ACE.Enreplacedy.Enum.UiEffects.Undef);
                        }

                        if (UnlimitedUse && ItemMaxMana.HasValue)
                            ItemCurMana = ItemMaxMana;
                    }
                }
                else if (target.ItemMaxMana.HasValue && target.ItemMaxMana.Value > 0)
                {
                    var targereplacedemCurMana = target.ItemCurMana ?? 0;

                    if (targereplacedemCurMana >= target.ItemMaxMana)
                    {
                        player.Session.Network.EnqueueSend(new GameMessageSystemChat($"The {target.Name} is already full of mana.", ChatMessageType.Broadcast));
                    }
                    else
                    {
                        // The Mana Stone gives 3,502 points of mana to the Focusing Stone.

                        // The Mana Stone gives 3,267 points of mana to the Protective Drudge Charm.

                        var targetManaNeeded = target.ItemMaxMana.Value - targereplacedemCurMana;
                        var manaToPour = Math.Min(targetManaNeeded, ItemCurMana.Value);

                        if (player.LumAugItemManaGain != 0)
                        {
                            manaToPour = (int)Math.Round(manaToPour * Creature.GetPositiveRatingMod(player.LumAugItemManaGain * 5));
                            manaToPour = Math.Min(targetManaNeeded, manaToPour);
                        }

                        target.ItemCurMana = targereplacedemCurMana + manaToPour;
                        var msg = $"The Mana Stone gives {manaToPour:N0} points of mana to the {target.Name}.";
                        player.Session.Network.EnqueueSend(new GameMessageSystemChat(msg, ChatMessageType.Broadcast));

                        if (!DoDestroyDiceRoll(player) && !UnlimitedUse)
                        {
                            ItemCurMana = null;
                            SetUiEffect(player, ACE.Enreplacedy.Enum.UiEffects.Undef);
                        }
                    }
                }
                else
                {
                    useResult = WeenieError.ActionCancelled;
                }
            }

            player.Session.Network.EnqueueSend(new GameEventUseDone(player.Session, useResult));
        }

19 Source : Buffer.cs
with GNU General Public License v3.0
from ACEmulator

public void DebugBuffer_Textures(Dictionary<uint, InstanceBatch> objects)
        {
            var textures = QueryTextureInfo(objects);

            Console.WriteLine($"Texture refs: {textures.Values.Sum()}");
            Console.WriteLine($"Texture uniques: {textures.Count}");

            var t2s_index = TextureToSetup(objects);

            Console.WriteLine($"Texture -> Setup ({t2s_index.Count}):");
            foreach (var entry in t2s_index)
            {
                var textureID = entry.Key;
                var setupIDs = entry.Value;
                Console.WriteLine($"{textureID:X8} ({setupIDs.Count}): {String.Join(",", setupIDs.Select(i => i.ToString("X8")))}");
            }

            var s2t_index = SetupToTexture(objects);

            Console.WriteLine($"\nSetup -> Texture ({s2t_index.Count}):");
            foreach (var entry in s2t_index)
            {
                var setupID = entry.Key;
                var textureIDs = entry.Value;
                Console.WriteLine($"{setupID:X8} ({textureIDs.Count}): {String.Join(",", textureIDs.Select(i => i.ToString("X8")))}");
            }
        }

19 Source : Buffer.cs
with GNU General Public License v3.0
from ACEmulator

public void DebugBuffer_GfxObj(Dictionary<uint, InstanceBatch> objects)
        {
            var gfxObjs = QueryGfxObjInfo(objects);

            Console.WriteLine($"GfxObj refs: {gfxObjs.Values.Sum()}");
            Console.WriteLine($"GfxObj uniques: {gfxObjs.Count}");

            var g2s_index = GfxObjToSetup(objects);

            Console.WriteLine($"GfxObj -> Setup ({g2s_index.Count}):");
            foreach (var entry in g2s_index)
            {
                var gfxObjID = entry.Key;
                var setupIDs = entry.Value;
                Console.WriteLine($"{gfxObjID:X8} ({setupIDs.Count}): {String.Join(",", setupIDs.Select(i => i.ToString("X8")))}");
            }

            var s2g_index = SetupToGfxObj(objects);

            Console.WriteLine($"\nSetup -> GfxObjs ({s2g_index.Count}):");
            foreach (var entry in s2g_index)
            {
                var setupID = entry.Key;
                var gfxObjIDs = entry.Value;
                Console.WriteLine($"{setupID:X8} ({gfxObjIDs.Count}): {String.Join(",", gfxObjIDs.Select(i => i.ToString("X8")))}");
            }
        }

19 Source : Array.cs
with MIT License
from Adsito

public static float[,,] NormaliseMulti(float[,,] array, int texturesAmount)
        {
            int length = (int)Math.Sqrt(array.Length / texturesAmount);
            int arrayLength = array.GetLength(0);
            int channelLength = array.GetLength(2);
            Parallel.For(0, arrayLength, i =>
            {
                float[] splatWeights = new float[channelLength];
                for (int j = 0; j < arrayLength; j++)
                {
                    for (int k = 0; k < channelLength; k++)
                        splatWeights[k] = array[i, j, k];
                    float normalisedWeights = splatWeights.Sum();

                    for (int k = 0; k < channelLength; k++)
                    {
                        splatWeights[k] /= normalisedWeights;
                        array[i, j, k] = splatWeights[k];
                    }
                }
            });
            return array;
        }

19 Source : Array.cs
with MIT License
from Adsito

public static float[,,] SetRangeBlend(float[,,] array, float[,] range, int channel, float rangeLow, float rangeHigh, float rangeBlendLow, float rangeBlendHigh, Area dmns = null)
        {
            if (dmns == null)
                dmns = AreaManager.ActiveArea;

            int channelLength = array.GetLength(2);
            for (int i = dmns.x0; i < dmns.x1; i++)
            {
                Parallel.For(dmns.z0, dmns.z1, j =>
                {
                    float[] normalised = new float[channelLength];
                    if (range[i, j] >= rangeLow && range[i, j] <= rangeHigh)
                    {
                        for (int k = 0; k < channelLength; k++)
                            array[i, j, k] = 0;

                        array[i, j, channel] = 1;
                    }
                    else if (range[i, j] >= rangeBlendLow && range[i, j] < rangeLow)
                    {
                        float normalisedRange = range[i, j] - rangeBlendLow;
                        float newRange = rangeLow - rangeBlendLow;
                        float rangeBlend = normalisedRange / newRange; // Holds data about the texture weight between the blend ranges.
                        for (int k = 0; k < channelLength; k++) // Gets the weights of the textures in the pos. 
                        {
                            if (k == channel)
                                array[i, j, channel] = rangeBlend;
                            else
                                array[i, j, k] = array[i, j, k] * Mathf.Clamp01(1f - rangeBlend);

                            normalised[k] = array[i, j, k];
                        }
                        float normalisedWeights = normalised.Sum();
                        for (int k = 0; k < channelLength; k++)
                        {
                            normalised[k] /= normalisedWeights;
                            array[i, j, k] = normalised[k];
                        }
                    }
                    else if (range[i, j] > rangeHigh && range[i, j] <= rangeBlendHigh)
                    {
                        float normalisedRange = range[i, j] - rangeHigh;
                        float newRange = rangeBlendHigh - rangeHigh;
                        float rangeBlend = normalisedRange / newRange; // Holds data about the texture weight between the blend ranges.
                        float rangeBlendInverted = 1 - rangeBlend;
                        for (int k = 0; k < channelLength; k++) // Gets the weights of the textures in the pos. 
                        {
                            if (k == channel)
                                array[i, j, channel] = rangeBlendInverted;
                            else
                                array[i, j, k] = array[i, j, k] * Mathf.Clamp01(1f - rangeBlendInverted);

                            normalised[k] = array[i, j, k];
                        }
                        float normalisedWeights = normalised.Sum();
                        for (int k = 0; k < channelLength; k++)
                        {
                            normalised[k] /= normalisedWeights;
                            array[i, j, k] = normalised[k];
                        }
                    }
                });
            }
            return array;
        }

19 Source : TreasuryContract.cs
with MIT License
from AElfProject

private long CalculateAverage(List<long> list)
        {
            var sum = list.Sum();
            return sum.Div(list.Count);
        }

19 Source : TreasuryCollectionTests.cs
with MIT License
from AElfProject

[IgnoreOnCIFact]
        public async Task TreasuryCollection_ThirdTerm_Test()
        {
            var distributedAmountOfFirstTerm = await TreasuryDistribution_FirstTerm_Test();
            var distributionInformationOfSecondTerm = await TreasuryDistribution_SecondTerm_Test();
            var distributionInformationOfThirdTerm = await TreasuryDistribution_ThirdTerm_Test();

            var subsidyInformationOfSecondTerm = distributionInformationOfSecondTerm[SchemeType.BackupSubsidy];
            var subsidyInformationOfThirdTerm = distributionInformationOfThirdTerm[SchemeType.BackupSubsidy];

            // First 7 core data centers can profit from backup subsidy of term 1, term 2 and term 3.
            var firstSevenCoreDataCenters = MissionedECKeyPairs.CoreDataCenterKeyPairs.Take(7).ToList();
            {
                var balancesBefore = firstSevenCoreDataCenters.ToDictionary(k => k, k =>
                    AsyncHelper.RunSync(() => TokenStub.GetBalance.CallAsync(new GetBalanceInput
                    {
                        Owner = Address.FromPublicKey(k.PublicKey),
                        Symbol = EconomicTestConstants.TokenSymbol
                    })).Balance);
                await ClaimProfits(firstSevenCoreDataCenters, _schemes[SchemeType.BackupSubsidy].SchemeId);
                var subsidyInFirstTerm = distributedAmountOfFirstTerm / 20 / 7;
                var subsidyInSecondTerm =
                    subsidyInformationOfSecondTerm.Amount / subsidyInformationOfSecondTerm.TotalShares;
                var subsidyInThirdTerm =
                    subsidyInformationOfThirdTerm.Amount / subsidyInformationOfThirdTerm.TotalShares;
                await CheckBalancesAsync(firstSevenCoreDataCenters,
                    subsidyInFirstTerm + subsidyInSecondTerm + subsidyInThirdTerm -
                    EconomicTestConstants.TransactionFeeOfClaimProfit,
                    balancesBefore);
            }

            // Last 12 core data centers can profit from backup subsidy of term 2 and term 3.
            var lastTwelveCoreDataCenters = MissionedECKeyPairs.CoreDataCenterKeyPairs.Skip(7).Take(12).ToList();

            {
                var balancesBefore = lastTwelveCoreDataCenters.ToDictionary(k => k, k =>
                    AsyncHelper.RunSync(() => TokenStub.GetBalance.CallAsync(new GetBalanceInput
                    {
                        Owner = Address.FromPublicKey(k.PublicKey),
                        Symbol = EconomicTestConstants.TokenSymbol
                    })).Balance);
                await ClaimProfits(lastTwelveCoreDataCenters, _schemes[SchemeType.BackupSubsidy].SchemeId);
                var subsidyInSecondTerm =
                    subsidyInformationOfSecondTerm.Amount / subsidyInformationOfSecondTerm.TotalShares;
                var subsidyInThirdTerm =
                    subsidyInformationOfThirdTerm.Amount / subsidyInformationOfThirdTerm.TotalShares;
                await CheckBalancesAsync(lastTwelveCoreDataCenters,
                    subsidyInSecondTerm + subsidyInThirdTerm -
                    EconomicTestConstants.TransactionFeeOfClaimProfit,
                    balancesBefore);
            }

            // First 7 core data centers can profit from miner basic reward of term 2 and term 3.
            {
                var balancesBefore = firstSevenCoreDataCenters.ToDictionary(k => k, k =>
                    AsyncHelper.RunSync(() => TokenStub.GetBalance.CallAsync(new GetBalanceInput
                    {
                        Owner = Address.FromPublicKey(k.PublicKey),
                        Symbol = EconomicTestConstants.TokenSymbol
                    })).Balance);
                await ClaimProfits(firstSevenCoreDataCenters, _schemes[SchemeType.MinerBasicReward].SchemeId);

                // Term 2.
                var secondTermInformation = ConsensusStub.GetPreviousTermInformation
                    .CallAsync(new Int64Value { Value = 2 })
                    .Result;
                var producedBlocksOfSecondTerm = secondTermInformation.RealTimeMinersInformation.Values
                    .Select(i => i.ProducedBlocks).ToList();
                var totalProducedBlocksOfSecondTerm = producedBlocksOfSecondTerm.Sum();
                var averageOfSecondTerm = totalProducedBlocksOfSecondTerm.Div(producedBlocksOfSecondTerm.Count);
                var sharesDictOfSecondTerm = new Dictionary<string, long>();
                foreach (var pubkey in secondTermInformation.RealTimeMinersInformation.Keys)
                {
                    var producedBlocks = secondTermInformation.RealTimeMinersInformation[pubkey].ProducedBlocks;
                    sharesDictOfSecondTerm.Add(pubkey, CalculateShares(producedBlocks, averageOfSecondTerm));
                }
                var totalSharesOfSecondTerm = sharesDictOfSecondTerm.Values.Sum();

                // Term 3.
                var thirdTermInformation = ConsensusStub.GetPreviousTermInformation
                    .CallAsync(new Int64Value { Value = 3 })
                    .Result;
                var producedBlocksOfThirdTerm = thirdTermInformation.RealTimeMinersInformation.Values
                    .Select(i => i.ProducedBlocks).ToList();
                var totalProducedBlocksOfThirdTerm = producedBlocksOfThirdTerm.Sum();
                var averageOfThirdTerm = totalProducedBlocksOfThirdTerm.Div(producedBlocksOfThirdTerm.Count);
                var sharesDictOfThirdTerm = new Dictionary<string, long>();
                foreach (var pubkey in thirdTermInformation.RealTimeMinersInformation.Keys)
                {
                    var producedBlocks = thirdTermInformation.RealTimeMinersInformation[pubkey].ProducedBlocks;
                    sharesDictOfThirdTerm.Add(pubkey, CalculateShares(producedBlocks, averageOfThirdTerm));
                }
                var totalSharesOfThirdTerm = sharesDictOfThirdTerm.Values.Sum();
                foreach (var keyPair in firstSevenCoreDataCenters)
                {
                    var shouldIncreaseForSecondTerm =
                        distributionInformationOfSecondTerm[SchemeType.MinerBasicReward].Amount *
                        sharesDictOfSecondTerm[keyPair.PublicKey.ToHex()] / totalSharesOfSecondTerm;
                    var shouldIncreaseForThirdTerm =
                        distributionInformationOfThirdTerm[SchemeType.MinerBasicReward].Amount *
                        sharesDictOfThirdTerm[keyPair.PublicKey.ToHex()] / totalSharesOfThirdTerm;
                    var amount = await GetBalanceAsync(Address.FromPublicKey(keyPair.PublicKey));
                    amount.ShouldBe(shouldIncreaseForSecondTerm + shouldIncreaseForThirdTerm + balancesBefore[keyPair]);
                }
            }

            // Last 12 core data centers can profit from miner basic reward of term 3.
            {
                var balancesBefore = lastTwelveCoreDataCenters.ToDictionary(k => k, k =>
                    AsyncHelper.RunSync(() => TokenStub.GetBalance.CallAsync(new GetBalanceInput
                    {
                        Owner = Address.FromPublicKey(k.PublicKey),
                        Symbol = EconomicTestConstants.TokenSymbol
                    })).Balance);
                await ClaimProfits(lastTwelveCoreDataCenters, _schemes[SchemeType.MinerBasicReward].SchemeId);
                var thirdTermInformation = ConsensusStub.GetPreviousTermInformation.CallAsync(new Int64Value {Value = 3})
                    .Result;
                var producedBlocksOfThirdTerm = thirdTermInformation.RealTimeMinersInformation.Values
                    .Select(i => i.ProducedBlocks).ToList();
                var totalProducedBlocksOfThirdTerm = producedBlocksOfThirdTerm.Sum();
                var averageOfThirdTerm = totalProducedBlocksOfThirdTerm.Div(producedBlocksOfThirdTerm.Count);
                var sharesDictOfThirdTerm = new Dictionary<string, long>();
                foreach (var pubkey in thirdTermInformation.RealTimeMinersInformation.Keys)
                {
                    var producedBlocks = thirdTermInformation.RealTimeMinersInformation[pubkey].ProducedBlocks;
                    sharesDictOfThirdTerm.Add(pubkey, CalculateShares(producedBlocks, averageOfThirdTerm));
                }
                var totalSharesOfThirdTerm = sharesDictOfThirdTerm.Values.Sum();
                foreach (var keyPair in lastTwelveCoreDataCenters)
                {
                    var shouldIncrease = distributionInformationOfThirdTerm[SchemeType.MinerBasicReward].Amount *
                                         CalculateShares(sharesDictOfThirdTerm[keyPair.PublicKey.ToHex()],
                                             averageOfThirdTerm) / totalSharesOfThirdTerm -
                                         EconomicTestConstants.TransactionFeeOfClaimProfit;
                    var amount = await GetBalanceAsync(Address.FromPublicKey(keyPair.PublicKey));
                    amount.ShouldBe(shouldIncrease + balancesBefore[keyPair]);
                }
            }

            // Last 2 core data centers can profit from welcome reward (of only term 3)
            {
                var lastTwoCoreDataCenters = MissionedECKeyPairs.CoreDataCenterKeyPairs.Skip(22).Take(2).ToList();
                var balancesBefore = lastTwoCoreDataCenters.ToDictionary(k => k, k =>
                    AsyncHelper.RunSync(() => TokenStub.GetBalance.CallAsync(new GetBalanceInput
                    {
                        Owner = Address.FromPublicKey(k.PublicKey),
                        Symbol = EconomicTestConstants.TokenSymbol
                    })).Balance);
                await ClaimProfits(lastTwoCoreDataCenters, _schemes[SchemeType.WelcomeReward].SchemeId);
                var welcomeRewardInThirdTerm =
                    distributionInformationOfThirdTerm[SchemeType.WelcomeReward].Amount / 10;
                await CheckBalancesAsync(lastTwoCoreDataCenters,
                    welcomeRewardInThirdTerm - EconomicTestConstants.TransactionFeeOfClaimProfit,
                    balancesBefore);
            }

            // First 10 voters can profit from citizen welfare.
            var firstTenVoters = MissionedECKeyPairs.CitizenKeyPairs.Take(10).ToList();
            {
                var balancesBefore = firstTenVoters.ToDictionary(k => k, k =>
                    AsyncHelper.RunSync(() => TokenStub.GetBalance.CallAsync(new GetBalanceInput
                    {
                        Owner = Address.FromPublicKey(k.PublicKey),
                        Symbol = EconomicTestConstants.TokenSymbol
                    })).Balance);
                // We limited profiting, thus ClaimProfits need to be called 4 times to profit all.
                await ClaimProfits(firstTenVoters, _schemes[SchemeType.CitizenWelfare].SchemeId);
                await ClaimProfits(firstTenVoters, _schemes[SchemeType.CitizenWelfare].SchemeId);
                await ClaimProfits(firstTenVoters, _schemes[SchemeType.CitizenWelfare].SchemeId);
                await ClaimProfits(firstTenVoters, _schemes[SchemeType.CitizenWelfare].SchemeId);
                var citizenWelfareInSecondTerm =
                    distributionInformationOfSecondTerm[SchemeType.CitizenWelfare].Amount / 10;
                var citizenWelfareInThirdTerm =
                    distributionInformationOfThirdTerm[SchemeType.CitizenWelfare].Amount / 10;
                await CheckBalancesAsync(firstTenVoters,
                    citizenWelfareInSecondTerm + citizenWelfareInThirdTerm -
                    EconomicTestConstants.TransactionFeeOfClaimProfit * 4,
                    balancesBefore);
            }
        }

19 Source : CreditCardNumberValidator.cs
with MIT License
from afucher

private bool IsValidLuhnAlgorithm(string cleanCreditCardNumber)
        {
            // Store the last digit (check digit)
            var checkDigit = cleanCreditCardNumber[cleanCreditCardNumber.Length - 1];

            // Remove the last digit (check digit)
            cleanCreditCardNumber = cleanCreditCardNumber.Remove(cleanCreditCardNumber.Length - 1);

            // Reverse all digits
            cleanCreditCardNumber = new string(cleanCreditCardNumber.Reverse().ToArray());

            // Convert the clean credit card number into a int list
            var creditCardNumArr = cleanCreditCardNumber.ToCharArray().Select(x => (int)char.GetNumericValue(x)).ToList();

            // Multiply odd position digits by 2
            var creditCardNumArrTemp = new List<int>();
            for (int i = 0; i < creditCardNumArr.Count; i++)
            {
                if ((i + 1) % 2 != 0)
                {
                    creditCardNumArrTemp.Add(creditCardNumArr[i] * 2);
                }
                else
                {
                    creditCardNumArrTemp.Add(creditCardNumArr[i]);
                }
            }
            creditCardNumArr = creditCardNumArrTemp;

            // Subtract 9 to all numbers above 9
            creditCardNumArr = creditCardNumArr.Select(x =>
            {
                if (x > 9)
                {
                    return x - 9;
                }
                return x;
            }).ToList();

            // Get numbers total
            var ccNumbersTotal = creditCardNumArr.Sum();

            // Get modulo of total
            var moduloOfNumbersTotal = (10 - (ccNumbersTotal % 10)) % 10;

            // If modulo of total is equal to the check digit
            return moduloOfNumbersTotal == (int)char.GetNumericValue(checkDigit);
        }

19 Source : LinqSample.cs
with The Unlicense
from ahotko

private void SumAgeSimple()
        {
            int sumAge = _sampleList.Select(x => x.Age).Sum();
            Console.WriteLine($"Sum with Select = {sumAge}");
            //...or...
            sumAge = _sampleList.Sum(x => x.Age);
            Console.WriteLine($"Sum without Select = {sumAge}");
        }

19 Source : CsvAsyncInputTestBase.cs
with MIT License
from airbreather

protected async Task RunTestAsync(Func<CsvAsyncInputBase> sutCreator, string filePath, bool ignoreUTF8ByteOrderMark)
        {
            (byte[] fileData, int originalLength) = GetExpectedCsvData(filePath, ignoreUTF8ByteOrderMark);
            var expected = TokenizeCsvFileUsingCursively(fileData, fileData.Length, (byte)',');

            // run without progress
            {
                var sut = sutCreator();
                var inputVisitor = new StringBufferingVisitor();

                await sut.ProcessAsync(inputVisitor).ConfigureAwait(false);

                replacedert.Equal(expected, inputVisitor.Records);

                await replacedert.ThrowsAsync<InvalidOperationException>(() => sut.ProcessAsync(null).AsTask());
            }

            // run with progress
            {
                var sut = sutCreator();
                var inputVisitor = new StringBufferingVisitor();

                var readSoFar = new List<int>();
                var progress = new ImmediateProgress<int>(readSoFar.Add);

                await sut.ProcessAsync(inputVisitor, progress).ConfigureAwait(false);

                replacedert.Equal(expected, inputVisitor.Records);

                replacedert.Equal(originalLength, readSoFar.Sum());
                replacedert.Equal(0, readSoFar.Last());

                await replacedert.ThrowsAsync<InvalidOperationException>(() => sut.ProcessAsync(null).AsTask());
            }
        }

19 Source : Coordinates.cs
with GNU General Public License v3.0
from akaAgar

internal static Coordinates Sum(IEnumerable<Coordinates> coordinates)
        {
            return new Coordinates(
                (from coordinate in coordinates select coordinate.X).Sum(),
                (from coordinate in coordinates select coordinate.Y).Sum());
        }

19 Source : ConsumerSpec.cs
with Apache License 2.0
from akkadotnet

private async Task CheckMessagesReceiving(List<List<CommittableMessage<K, V>>> msgss)
        {
            var mock = new MockConsumer<K, V>();
            var (control, probe) = CreateCommitableSource(mock)
                .ToMaterialized(this.SinkProbe<CommittableMessage<K, V>>(), Keep.Both)
                .Run(Sys.Materializer());

            probe.Request(msgss.Select(t => t.Count).Sum());
            foreach (var chunk in msgss)
            {
                mock.Enqueue(chunk.Select(l => l.Record).ToList());
            }

            var messages = msgss.SelectMany(m => m).Select(m => m);
            foreach (var message in messages)
            {
                var received = probe.ExpectNext();
                received.Record.Message.Key.Should().Be(message.Record.Message.Key);
                received.Record.Message.Value.Should().Be(message.Record.Message.Value);
            }
            await control.Shutdown().WithTimeout(RemainingOrDefault);
        }

19 Source : MapboxUnitTests_SQLiteCache.cs
with MIT License
from alen-smajic

private void logTime(string label, List<long> elapsed)
		{
			double overall = elapsed.Sum() / 1000.0;
			double min = elapsed.Min() / 1000.0;
			double max = elapsed.Max() / 1000.0;
			double avg = elapsed.Average() / 1000.0;

			double sum = elapsed.Sum(d => Math.Pow(d - avg, 2));
			double stdDev = (Math.Sqrt((sum) / (elapsed.Count - 1))) / 1000.0;

			ued.Log(string.Format(
				CultureInfo.InvariantCulture
				, "[{0}] {1} items, overall time:{2,6:0.000}s avg:{3,6:0.000}s min:{4,6:0.000}s max:{5,6:0.000}s stdDev:{6,6:0.000}s"
				, label
				, elapsed.Count
				, overall
				, avg
				, min
				, max
				, stdDev
			));
		}

19 Source : Program.cs
with MIT License
from alexshtf

static void RunBenchmark(TextWriter resultWriter, TextWriter logWriter)
        {
            var fac = new CsvHelper.CsvFactory();
            using (var csvWriter = fac.CreateWriter(resultWriter))
            {
                csvWriter.WriteHeader<BenchmarkResult>();

                int[] sizes = { 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000 };
                foreach (int sz in sizes)
                {
                    var row = new BenchmarkResult();

                    var termsCount = sz; row.NumberOfTerms = termsCount;
                    var varsCount = sz; row.NumberOfVars = varsCount;
                    var grad = new double[sz];


                    logWriter.WriteLine("Benchmark for {0} terms and {1} variables", termsCount, varsCount);

                    logWriter.Write("\tConstructing coefficients ...");
                    var coefficients = GenerateCoefficients(termsCount, varsCount);
                    logWriter.WriteLine(" done");

                    // generate variables
                    var vars = new Variable[varsCount];
                    for (var j = 0; j < sz; ++j)
                        vars[j] = new Variable();


                    logWriter.Write("\tGenerating input data ...");
                    var inputData = new double[1000][];
                    for (var j = 0; j < inputData.Length; ++j)
                        inputData[j] = RandomDoubles(varsCount);
                    logWriter.WriteLine(" done");
                    GC.Collect(GC.MaxGeneration, GCCollectionMode.Default, true);


                    ICompiledTerm compiledTerm = null;
                    row.CompileMilliseconds = MeasureMsec("Constructing compiled term", logWriter, 
                        () => compiledTerm = ConstructTerm(coefficients, vars));

                    row.MillisecondsPerManualEval = MeasureMsecPerOp("manual evaluation", 
                        logWriter, inputData.Length, () => inputData.Sum(array => NativeEvaluate(coefficients, array)));

                    row.MillisecondsPerCompiledEval = MeasureMsecPerOp("AutoDiff compiled evaluation",
                        logWriter, inputData.Length, () => inputData.Sum(array => compiledTerm.Evaluate(array)));

                    row.MillisecondsPerCompiledDiff = MeasureMsecPerOp("compiled differentiation",
                        logWriter, inputData.Length, () =>
                        {
                            var sum = 0.0;
                            foreach (var array in inputData)
                            {
                                var val = compiledTerm.Differentiate(array, grad);
                                sum += val + grad.Sum();
                            }
                            return sum;
                        });

                    csvWriter.WriteRecord(row);
                }
            }
        }

19 Source : Program.cs
with MIT License
from alexshtf

static void Main(string[] args)
        {
            Console.SetWindowSize(120, 30);

            int[] sizes = { 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000 };
            for (int i = 0; i < sizes.Length; ++i)
            {
                var termsCount = sizes[i];
                var varsCount = sizes[i];

                Console.WriteLine("Benchmark for {0} terms and {1} variables", termsCount, varsCount);

                Console.Write("\tConstructing coefficients ...");
                var coefficients = GenerateCoefficients(termsCount, varsCount);
                Console.WriteLine(" done");

                // generate variables
                var vars = new Variable[varsCount];
                for(int j = 0; j < sizes[i]; ++j)
                    vars[j] = new Variable();


                Console.Write("\tGenerating input data ...");
                double[][] inputData = new double[1000][];
                for (int j = 0; j < inputData.Length; ++j)
                    inputData[j] = RandomDoubles(varsCount);
                Console.WriteLine(" done");

                GC.Collect();
                Thread.Sleep(4000);

                Console.Write("\tConstructing compiled term ...");
                var stopWatch = Stopwatch.StartNew();
                var compiledTerm = ConstructTerm(coefficients, vars);
                stopWatch.Stop();
                Console.WriteLine(" done in {0} milliseconds", stopWatch.ElapsedMilliseconds);

                GC.Collect();
                Thread.Sleep(4000);

                Console.Write("\tBenchmarking manual evaluation ...");
                stopWatch = Stopwatch.StartNew();
                double sum = 0;
                for (int j = 0; j < inputData.Length; ++j)
                    sum += NativeEvaluate(coefficients, inputData[j]);
                stopWatch.Stop();
                Console.WriteLine(" sum is {0}, speed is {1} msec/op", sum, stopWatch.ElapsedMilliseconds / (double)inputData.Length);

                GC.Collect();
                Thread.Sleep(4000);

                Console.Write("\tBenchmarking gradient approximation ...");
                stopWatch = Stopwatch.StartNew();
                sum = 0;
                for (int j = 0; j < inputData.Length / 10; ++j)
                {
                    var gradient = ApproxGradient(coefficients, inputData[j]);
                    sum += gradient.Sum();
                }
                stopWatch.Stop();
                Console.WriteLine(" sum is {0}, speed is {1} msec/op", sum, 10 * stopWatch.ElapsedMilliseconds / (double)inputData.Length);

                GC.Collect();
                Thread.Sleep(4000);

                Console.Write("\tBenchmarking AutoDiff compiled evaluation ...");
                stopWatch = Stopwatch.StartNew();
                sum = 0;
                for (int j = 0; j < inputData.Length; ++j)
                    sum += compiledTerm.Evaluate(inputData[j]);
                stopWatch.Stop();
                Console.WriteLine(" sum is {0}, speed is {1} msec/op", sum, stopWatch.ElapsedMilliseconds / (double)inputData.Length);

                GC.Collect();
                Thread.Sleep(4000);

                Console.Write("\tBenchmarking compiled differentiation ...");
                stopWatch = Stopwatch.StartNew();
                sum = 0; 
                for(int j = 0; j < inputData.Length; ++j)
                {
                    var diffResult = compiledTerm.Differentiate(inputData[j]);
                    sum += diffResult.Item2 + diffResult.Item1.Sum();
                }
                Console.WriteLine(" sum is {0}, speed is {1} msec/op", sum, stopWatch.ElapsedMilliseconds / (double)inputData.Length);

            }
        }

19 Source : ConvexHullAlgorithm.Initialize.cs
with Apache License 2.0
from allenai

private List<int> FindInitialPoints()
        {
            var bigNumber = maxima.Sum() * NumOfDimensions * NumberOfVertices;
            // the first two points are taken from the dimension that had the fewest extremes
            // well, in most cases there will only be 2 in all dimensions: one min and one max
            // but a lot of engineering part shapes are nice and square and can have hundreds of 
            // parallel vertices at the extremes
            var vertex1 = boundingBoxPoints[indexOfDimensionWithLeastExtremes].First(); // these are min and max vertices along
            var vertex2 = boundingBoxPoints[indexOfDimensionWithLeastExtremes].Last(); // the dimension that had the fewest points
            boundingBoxPoints[indexOfDimensionWithLeastExtremes].RemoveAt(0);
            boundingBoxPoints[indexOfDimensionWithLeastExtremes].RemoveAt(boundingBoxPoints[indexOfDimensionWithLeastExtremes].Count - 1);
            var initialPoints = new List<int> { vertex1, vertex2 };
            VertexVisited[vertex1] = VertexVisited[vertex2] = true;
            CurrentVertex = vertex1; UpdateCenter();
            CurrentVertex = vertex2; UpdateCenter();
            var edgeVectors = new double[NumOfDimensions][];
            edgeVectors[0] = mathHelper.VectorBetweenVertices(vertex2, vertex1);
            // now the remaining vertices are just combined in one big list
            var extremes = boundingBoxPoints.SelectMany(x => x).ToList();
            // otherwise find the remaining points by maximizing the initial simplex volume
            var index = 1;
            while (index < NumOfDimensions && extremes.Any())
            {
                var bestVertex = -1;
                var bestEdgeVector = new double[] { };
                var maxVolume = Constants.DefaultPlaneDistanceTolerance;
                for (var i = extremes.Count - 1; i >= 0; i--)
                {
                    // count backwards in order to remove potential duplicates
                    var vIndex = extremes[i];
                    if (initialPoints.Contains(vIndex)) extremes.RemoveAt(i);
                    else
                    {
                        edgeVectors[index] = mathHelper.VectorBetweenVertices(vIndex, vertex1);
                        var volume = mathHelper.GetSimplexVolume(edgeVectors, index, bigNumber);
                        if (maxVolume < volume)
                        {
                            maxVolume = volume;
                            bestVertex = vIndex;
                            bestEdgeVector = edgeVectors[index];
                        }
                    }
                }
                extremes.Remove(bestVertex);
                if (bestVertex == -1) break;
                initialPoints.Add(bestVertex);
                edgeVectors[index++] = bestEdgeVector;
                CurrentVertex = bestVertex; UpdateCenter();
            }
            // hmm, there are not enough points on the bounding box to make a simplex. It is rare but entirely possibly.
            // As an extreme, the bounding box can be made in n dimensions from only 2 unique points. When we can't find
            // enough unique points, we start again with ALL the vertices. The following is a near replica of the code 
            // above, but instead of extremes, we consider "allVertices".
            if (initialPoints.Count <= NumOfDimensions && !IsLifted)
            {
                var allVertices = Enumerable.Range(0, NumberOfVertices).ToList();
                while (index < NumOfDimensions && allVertices.Any())
                {
                    var bestVertex = -1;
                    var bestEdgeVector = new double[] { };
                    var maxVolume = 0.0;
                    for (var i = allVertices.Count - 1; i >= 0; i--)
                    {
                        // count backwards in order to remove potential duplicates
                        var vIndex = allVertices[i];
                        if (initialPoints.Contains(vIndex)) allVertices.RemoveAt(i);
                        else
                        {
                            edgeVectors[index] = mathHelper.VectorBetweenVertices(vIndex, vertex1);
                            var volume = mathHelper.GetSimplexVolume(edgeVectors, index, bigNumber);
                            if (maxVolume < volume)
                            {
                                maxVolume = volume;
                                bestVertex = vIndex;
                                bestEdgeVector = edgeVectors[index];
                            }
                        }
                    }
                    allVertices.Remove(bestVertex);
                    if (bestVertex == -1) break;
                    initialPoints.Add(bestVertex);
                    edgeVectors[index++] = bestEdgeVector;
                    CurrentVertex = bestVertex; UpdateCenter();
                }
            }
            if (initialPoints.Count <= NumOfDimensions && IsLifted)
            {
                var allVertices = Enumerable.Range(0, NumberOfVertices).ToList();
                while (index < NumOfDimensions && allVertices.Any())
                {
                    var bestVertex = -1;
                    var bestEdgeVector = new double[] { };
                    var maxVolume = 0.0;
                    for (var i = allVertices.Count - 1; i >= 0; i--)
                    {
                        // count backwards in order to remove potential duplicates
                        var vIndex = allVertices[i];
                        if (initialPoints.Contains(vIndex)) allVertices.RemoveAt(i);
                        else
                        {
                            mathHelper.RandomOffsetToLift(vIndex, maxima.Last() - minima.Last());
                            edgeVectors[index] = mathHelper.VectorBetweenVertices(vIndex, vertex1);
                            var volume = mathHelper.GetSimplexVolume(edgeVectors, index, bigNumber);
                            if (maxVolume < volume)
                            {
                                maxVolume = volume;
                                bestVertex = vIndex;
                                bestEdgeVector = edgeVectors[index];
                            }
                        }
                    }
                    allVertices.Remove(bestVertex);
                    if (bestVertex == -1) break;
                    initialPoints.Add(bestVertex);
                    edgeVectors[index++] = bestEdgeVector;
                    CurrentVertex = bestVertex; UpdateCenter();
                }
            }
            if (initialPoints.Count <= NumOfDimensions && IsLifted)
                throw new ConvexHullGenerationException(ConvexHullCreationResultOutcome.DegenerateData, "The input data is degenerate. It appears to exist in " + NumOfDimensions +
                    " dimensions, but it is a " + (NumOfDimensions - 1) + " dimensional set (i.e. the point of collinear,"
                    + " coplanar, or co-hyperplanar.)");
            return initialPoints;
        }

19 Source : SequenceExtensions.cs
with MIT License
from AndreyAkinshin

public static double[] GenerateArray([NotNull] this ISequence sequence, int count, bool normalize = false)
        {
            var values = sequence.GenerateEnumerable().Take(count).ToArray();
            if (normalize)
            {
                double sum = values.Sum();
                for (int i = 0; i < values.Length; i++)
                    values[i] /= sum;
            }

            return values;
        }

19 Source : RqqPeltSimulation.cs
with MIT License
from AndreyAkinshin

public void Run(string[] args)
        {
            var stopwatch = Stopwatch.StartNew();

            var fullDataSet = CpdReferenceDataSet.Generate(new Random(42), 2);
            string dataSetArg = args.Length > 0 ? args[0] : "*";
            bool printReports = args.Contains("--reports");
            int limit = int.MaxValue;
            int limitArgIndex = Array.IndexOf(args, "--limit");
            if (limitArgIndex >= 0 && limitArgIndex < args.Length - 1)
                if (int.TryParse(args[limitArgIndex + 1], out int actualLimit))
                    limit = actualLimit;

            var dataSet = dataSetArg == "*" ? fullDataSet : fullDataSet.Where(data => data.Name.Contains(dataSetArg)).ToList();
            if (limit < dataSet.Count)
            {
                new Shuffler(42).Shuffle(dataSet);
                dataSet.RemoveRange(limit, dataSet.Count - limit);
            }

            if (dataSet.Count == 0)
            {
                PrintLine("DataSet is empty");
                return;
            }

            dataSet.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.Ordinal));

            if (args.Contains("--tune"))
            {
                var heterogeneityFactors = new ArithmeticProgressionSequence(1.1, 0.05).GenerateArray(7);
                var sensitivities = new ArithmeticProgressionSequence(0.4, 0.02).GenerateArray(8);
                var quantileSets = new List<QuantileSet>
                {
                    QuantileSet.Clreplacedic,
                    QuantileSet.ArithmeticProgression(12, 0),
                    QuantileSet.SteadyPlusArithmeticProgression(12, 7, -0.01),
                    QuantileSet.ArithmeticProgressionWithRepereplacedions(12, 4, -0.1)
                };
                int quantileSetMaxLength = quantileSets.Max(s => s.Name.Length);

                var results =
                    new List<(double HeterogeneityFactor, double Sensitivity, string QuantileSet, double MaxPenalty, double SumPenalty)>();
                foreach (double heterogeneityFactor in heterogeneityFactors)
                foreach (double sensitivity in sensitivities)
                foreach (var quantileSet in quantileSets)
                {
                    double replacedgeneityFactor = heterogeneityFactor - 1;
                    PrintLine(Separator('@'));
                    PrintLine(
                        $"@ HeterogeneityFactor = {heterogeneityFactor:0.0}, Sensitivity = {sensitivity:0.00}, QuantileSet = {quantileSet.Name}");
                    var detector = new RqqPeltChangePointDetector(
                        quantileSet.Probabilities,
                        quantileSet.Factors,
                        sensitivity: sensitivity,
                        heterogeneityFactor: heterogeneityFactor,
                        replacedgeneityFactor: replacedgeneityFactor);
                    var penalties = RunSingle(detector, dataSet, printReports);
                    results.Add((heterogeneityFactor, sensitivity, quantileSet.Name, penalties.Max(), penalties.Sum()));
                }

                PrintLine(Separator('*'));
                PrintLine(Separator('*'));
                PrintLine(Separator('*'));
                results.Sort((a, b) =>
                    Math.Sign(b.MaxPenalty.CompareTo(a.MaxPenalty)) * 10 + Math.Sign(b.SumPenalty.CompareTo(a.SumPenalty)));
                foreach ((double heterogeneityFactor, double sensitivity, string quantileSet, double maxPenalty,
                    double sumPenalty) in results)
                    PrintLine(
                        $"{heterogeneityFactor:0.00} {sensitivity:0.00} {quantileSet.PadRight(quantileSetMaxLength)} : {maxPenalty} / {sumPenalty}");
            }
            else
                RunSingle(RqqPeltChangePointDetector.Instance, dataSet, printReports);

            stopwatch.Stop();
            PrintLine();
            PrintLine($"TotalTime = {stopwatch.Elapsed.TotalSeconds:0.0} sec");
        }

19 Source : RqqPeltSimulation.cs
with MIT License
from AndreyAkinshin

private List<double> RunSingle(RqqPeltChangePointDetector detector, IReadOnlyList<CpdTestData> dataSet, bool printReports)
        {
            int maxNameLength = dataSet.Select(data => data.Name.Length).Max();

            var penalties = new List<double>();

            Parallel.ForEach(dataSet, testData =>
            {
                var changePointIndexes = detector.GetChangePointIndexes(testData.Values.ToArray());
                var verification = CpdTestDataVerification.Verify(testData, changePointIndexes);
                lock (detector)
                {
                    penalties.Add(verification.Penalty);
                    PrintLine($"{testData.Name.PadRight(maxNameLength)} : {verification.Penalty}");
                    if (printReports)
                        PrintLine(verification.Report);
                }
            });

            PrintLine("  Sum  = " + penalties.Sum());
            PrintLine("  Max  = " + penalties.Max());
            foreach (double p in new[] {0.5, 0.90, 0.99})
            {
                string metric = $"P{p * 100}".PadRight(4);
                double estimate = HarrellDavisQuantileEstimator.Instance.GetQuantile(penalties, p);
                PrintLine($"  {metric} = {estimate:0.##}");
            }

            return penalties;
        }

19 Source : BinomialDistributionTests.cs
with MIT License
from AndreyAkinshin

[Theory]
        [MemberData(nameof(TestDataKeys))]
        public void Test(string testDataKey)
        {
            var testData = TestDataList.First(it => it.Key == testDataKey);
            int n = testData.N;
            var p = testData.P;
            var distribution = new BinomialDistribution(n, p);
            var comparer = new AbsoluteEqualityComparer(1e-7);
            for (int k = 0; k < n; k++)
            {
                double actualPmf = distribution.Pmf(k);
                double expectedPmf = testData.ExpectedPmf[k];
                output.WriteLine($"PMF({k}) = {actualPmf} (Expected: {expectedPmf})");

                double actualCdf = distribution.Cdf(k);
                double expectedCdf = testData.ExpectedPmf.Take(k + 1).Sum();
                output.WriteLine($"CDF({k}) = {actualCdf} (Expected: {expectedCdf})");

                int actualQuantile = distribution.Quantile(expectedCdf);
                int expectedQuantile = k;
                output.WriteLine($"Quantile({expectedCdf}) = {actualQuantile} (Expected: {expectedQuantile})");
                
                replacedert.Equal(expectedPmf, actualPmf, comparer);
                replacedert.Equal(expectedCdf, actualCdf, comparer);
                replacedert.Equal(expectedQuantile, actualQuantile, comparer);
            }
        }

19 Source : PositivePointController.cs
with Apache License 2.0
from anjoy8

[HttpGet]
        public async Task<MessageModel<List<PositivePointTotal>>> Get(int GradeId, string AcademicYearSchoolTerm, string ExamName, int CourseId, int ClazzId, int page = 1)
        {
            int intPageSize = 100;
            if (!(GradeId > 0 && CourseId > 0 && !string.IsNullOrEmpty(AcademicYearSchoolTerm) && !string.IsNullOrEmpty(ExamName)))
            {
                return new MessageModel<List<PositivePointTotal>>();
            }

            var exScoreList = await _iExScoreRepository.Query(d => d.IsDeleted == false);

            var gradeList = await _iGradeRepository.Query(d => d.IsDeleted == false && d.Id == GradeId);
            var clazzList = await _iClazzRepository.Query(d => d.IsDeleted == false && d.GradeId == GradeId);
            var courseList = await _iCourseRepository.Query(d => d.IsDeleted == false);
            var examList = await _iExamRepository.Query(d => d.IsDeleted == false && d.gradeid == GradeId);
            var studentsList = await _iStudentsRepository.Query(d => d.IsDeleted == false && d.gradeid == GradeId);
            var cctList = await _iCCTRepository.Query(d => d.IsDeleted == false && d.gradeid == GradeId);
            var teachersList = await _iTeacherRepository.Query(d => d.IsDeleted == false && d.gradeId == GradeId);


            foreach (var item in examList)
            {
                item.grade = gradeList.Where(d => d.Id == item.gradeid).FirstOrDefault();
                item.course = courseList.Where(d => d.Id == item.courseid).FirstOrDefault();
            }

            foreach (var exscore in exScoreList)
            {
                try
                {
                    exscore.exam = examList.Where(d => d.Id == exscore.examid).FirstOrDefault();
                    var teacherid = cctList.Where(d => d.clazzid == exscore.clazzid && d.gradeid == exscore.exam.gradeid && d.courseid == exscore.exam.courseid).FirstOrDefault()?.teacherid;
                    exscore.Teacher = teachersList.Where(d => d.Id == teacherid.ObjToInt()).FirstOrDefault()?.Name;


                    exscore.clazz = clazzList.Where(d => d.Id == exscore.clazzid).FirstOrDefault();
                    exscore.student = studentsList.Where(d => d.Id == exscore.studentid).FirstOrDefault();
                }
                catch (Exception ex)
                {

                }
            }


            exScoreList = exScoreList.Where(d => (d.exam != null && d.exam.grade != null && d.exam.grade.Id == GID || (GID == -9999 && true))).ToList();

            // 统计 全年级的 某次考试 全部科目的 全部成绩
            var examSortAllCourse = exScoreList.Where(d => AcademicYearSchoolTerm == (d.exam?.AcademicYear + d.exam?.SchoolTerm) && d.exam?.ExamName == ExamName && d.exam?.gradeid == GradeId).ToList();


            // 统计 全年级的 某次考试 某门科目中 的全部成绩
            var exscoreGrade = examSortAllCourse.Where(d => d.courseid == CourseId).ToList();


            List<PositivePoint> totalGradePositivePoints = new List<PositivePoint>();


            foreach (var item in exscoreGrade)
            {

                PositivePoint PositivePoint = new PositivePoint()
                {
                    StudentNo = item.student.StudentNo,
                    StudentName = item.student.Name,
                    BaseSort = item.BaseSort.ObjToInt(),
                    Score = item.score.ObjToDecimal(),
                    Clazz = item.clazz.ClreplacedNo,
                    Teacher = item.Teacher,
                    Clazzid = item.clazz.Id,

                };
                totalGradePositivePoints.Add(PositivePoint);
            }

            // 基础名次排序 —— 求出来 基础名次ok,序号,本次基础
            totalGradePositivePoints = totalGradePositivePoints.OrderBy(d => d.BaseSort).ToList();

            List<int> baseSortArr = new List<int>();
            var j = 1;
            var clazzCount = clazzList.Count;
            var totalStudentCount = studentsList.Count;
            var examStudentCount = totalGradePositivePoints.Count;

            for (int i = 1; i <= totalGradePositivePoints.Count; i++)
            {
                var item = totalGradePositivePoints[i - 1];
                item.Xuhao = i;

                if (!baseSortArr.Contains(item.BaseSort))
                {
                    j = i;
                    baseSortArr.Add(item.BaseSort);
                }

                item.BaseSortOK = j;
                item.ThisBase = (examStudentCount - (i - 1))*0.01 * clazzCount * 100 / (0.01 * ((examStudentCount + 1)/ 2)* examStudentCount);
            }

            // 基础名次OK排名 —— 求出来 本次基础ok
            totalGradePositivePoints = totalGradePositivePoints.OrderBy(d => d.BaseSortOK).ToList();
            for (int i = 1; i <= totalGradePositivePoints.Count; i++)
            {
                var item = totalGradePositivePoints[i - 1];
                var avgList = totalGradePositivePoints.Where(d => d.BaseSortOK == item.BaseSortOK).Select(d => d.ThisBase).ToList();
                item.ThisBaseOk = avgList.Sum() / avgList.Count;
            }

            // 根据分数排序 —— 得到年级排序ok,序号,本次考试
            totalGradePositivePoints = totalGradePositivePoints.OrderByDescending(d => d.Score).ToList();

            List<decimal> scoreArr = new List<decimal>();
            for (int i = 1; i <= totalGradePositivePoints.Count; i++)
            {
                var item = totalGradePositivePoints[i - 1];
                item.Xuhao = i;

                if (!scoreArr.Contains(item.Score))
                {
                    j = i;
                    scoreArr.Add(item.Score);
                }

                item.GradeSortOk = j;
                item.ThisExam = (examStudentCount - (i - 1)) * 0.01 * clazzCount * 100 / (0.01 * ((examStudentCount + 1) / 2) * examStudentCount);
            }



            // 年级重排OK排名 —— 求出来 本次考试ok
            totalGradePositivePoints = totalGradePositivePoints.OrderBy(d => d.GradeSortOk).ToList();
            for (int i = 1; i <= totalGradePositivePoints.Count; i++)
            {
                var item = totalGradePositivePoints[i - 1];
                var avgList = totalGradePositivePoints.Where(d => d.GradeSortOk == item.GradeSortOk).Select(d => d.ThisExam).ToList();
                item.ThisExamOk = avgList.Sum() / avgList.Count;
            }



            var clazzids = clazzList.Where(d => d.GradeId == GradeId).GroupBy(x => new { x.Id }).Select(s => s.First()).ToList();



            // ↑↑↑↑每个考生正负分完成↑↑↑↑↑↑



            List<PositivePointTotal>  positivePointTotals = new List<PositivePointTotal>();

            foreach (var item in clazzids)
            {
                var totalGradePositivePointsClazz = totalGradePositivePoints.Where(d => d.Clazzid == item.Id).ToList();

                PositivePointTotal positivePointTotal = new PositivePointTotal() {
                    Clazz = item.ClreplacedNo,
                    Teacher = totalGradePositivePointsClazz.FirstOrDefault()?.Teacher,
                    TotalStudentCount = studentsList.Where(d => d.clazzid == item.Id).Count(),
                    ExamStudentCount= totalGradePositivePointsClazz.Count,
                    ThisBaseOk= totalGradePositivePointsClazz.Select(d=>d.ThisBaseOk).Sum(),
                    ThisExamOk= totalGradePositivePointsClazz.Select(d=>d.ThisExamOk).Sum(),
                };

                positivePointTotal.NoExamStudentCount = positivePointTotal.TotalStudentCount- positivePointTotal.ExamStudentCount;
                positivePointTotal.RankBase = positivePointTotal.ThisExamOk - positivePointTotal.ThisBaseOk;


                positivePointTotal.ThisBaseOk= Math.Round(positivePointTotal.ThisBaseOk, 2, MidpointRounding.AwayFromZero);
                positivePointTotal.ThisExamOk = Math.Round(positivePointTotal.ThisExamOk, 2, MidpointRounding.AwayFromZero);
                positivePointTotal.ThisOk = positivePointTotal.ThisExamOk;
                positivePointTotal.RankBase = Math.Round(positivePointTotal.RankBase, 2, MidpointRounding.AwayFromZero);


                positivePointTotals.Add(positivePointTotal);
            }




            return new MessageModel<List<PositivePointTotal>>()
            {
                msg = "获取成功",
                success = positivePointTotals.Count >= 0,
                response = positivePointTotals
            };

        }

19 Source : RoadSearchHelperTests.cs
with MIT License
from AnnoDesigner

[Fact]
        public void BreadthFirstSearch_FindBuildingInfluenceRange()
        {
            // Arrange
            var placedObjects = defaultObjectList.Objects;
            var startObjects = placedObjects.Where(o => o.Label == "Start").ToList();
            foreach (var startObject in startObjects)
            {
                var expectedCount = 4 * Enumerable.Range(1, (int)startObject.InfluenceRange).Sum() + 1;

                // Act
                var visitedCells = RoadSearchHelper.BreadthFirstSearch(placedObjects, new[] { startObject }, o => (int)o.InfluenceRange);

                // replacedert
                replacedert.Equal(expectedCount, visitedCells.Sum(c => c.Count(visited => visited)));
            }
        }

19 Source : RepairUtility.cs
with GNU Lesser General Public License v3.0
from ApexGameTools

internal ResolutionStatus GetStatus()
        {
            if (_typeResolution.Length > 0 || _membersResolution.Length > 0 || _mismatchedMembers.Length > 0)
            {
                _status = new ResolutionStatus
                {
                    unresolvedTypesCount = _typeResolution.Length,
                    resolvedTypesCount = _typeResolution.Count(t => t.resolvedTypeName != null),
                    unresolvedMembersCount = _membersResolution.Select(mr => mr.unresolvedMembers.Count).Sum(),
                    resolvedMembersCount = _membersResolution.Select(mr => mr.unresolvedMembers.Count(m => m.resolvedName != null)).Sum(),
                    unresolvedMismatchesCount = _mismatchedMembers.Length,
                    resolvableMismatchesCount = _mismatchedMembers.Count(mm => mm.isCorrectable),
                    resolvedMismatchesCount = _mismatchedMembers.Count(mm => mm.resolvedTypeName != null || mm.resolvedValue != null)
                };
            }
            else
            {
                _status = new ResolutionStatus();
            }

            return _status;
        }

19 Source : Spectral.cs
with MIT License
from ar1st0crat

public static float Entropy(float[] spectrum)
        {
            var entropy = 0.0;

            var sum = spectrum.Sum();

            if (sum < 1e-8)
            {
                return 0;
            }

            for (var i = 1; i < spectrum.Length; i++)
            {
                var p = spectrum[i] / sum;

                if (p > 1e-8)
                {
                    entropy += p * Math.Log(p, 2);
                }
            }

            return (float)(-entropy / Math.Log(spectrum.Length, 2));
        }

19 Source : Stft.cs
with MIT License
from ar1st0crat

public float[] ReconstructMagnitudePhase(MagnitudePhaseList spectrogram, bool perfectReconstruction = true)
        {
            var spectraCount = spectrogram.Magnitudes.Count;
            var output = new float[spectraCount * _hopSize + _windowSize];

            var mag = spectrogram.Magnitudes;
            var phase = spectrogram.Phases;

            var buf = new float[_fftSize];
            var re = new float[_fftSize / 2 + 1];
            var im = new float[_fftSize / 2 + 1];

            float gain;
            
            if (perfectReconstruction)
            {
                Guard.AgainstExceedance(_hopSize, _windowSize, "Hop size for perfect reconstruction", "window size");

                gain = 1f / _windowSize;
            }
            // simpler reconstruction of the signal
            // (with insignificant discrepancies in the beginning and in the end)
            else
            {
                gain = 1 / (_fftSize * _windowSamples.Select(w => w * w).Sum() / _hopSize);
            }

            var pos = 0;

            for (var i = 0; i < spectraCount; i++)
            {
                for (var j = 0; j <= _fftSize / 2; j++)
                {
                    re[j] = (float)(mag[i][j] * Math.Cos(phase[i][j]));
                    im[j] = (float)(mag[i][j] * Math.Sin(phase[i][j]));
                }

                _fft.Inverse(re, im, buf);

                // windowing and reconstruction

                for (var j = 0; j < _windowSize; j++)
                {
                    output[pos + j] += buf[j] * _windowSamples[j];
                }

                for (var j = 0; j < _hopSize; j++)
                {
                    output[pos + j] *= gain;
                }

                pos += _hopSize;
            }

            for (var j = 0; j < _windowSize; j++)
            {
                output[pos + j] *= gain;
            }


            if (perfectReconstruction)      // additional normalization
            {
                float[] windowSummed = ComputeWindowSummed();

                var offset = _windowSize - _hopSize;

                for (int j = 0, k = output.Length - _hopSize - 1; j < offset; j++, k--)
                {
                    if (Math.Abs(windowSummed[j]) > 1e-30)
                    {
                        output[j] /= windowSummed[j];   // leftmost part of the signal
                        output[k] /= windowSummed[j];   // rightmost part of the signal
                    }
                }

                // main central part of the signal

                for (int j = offset, k = offset; j < output.Length - _windowSize; j++, k++)
                {
                    if (k == _windowSize) k = offset;

                    output[j] /= windowSummed[k];
                }
            }

            return output;
        }

19 Source : Stft.cs
with MIT License
from ar1st0crat

public float[] Inverse(List<(float[], float[])> stft, bool perfectReconstruction = true)
        {
            var spectraCount = stft.Count;
            var output = new float[spectraCount * _hopSize + _fftSize];

            var buf = new float[_fftSize];

            float gain;

            if (perfectReconstruction)
            {
                Guard.AgainstExceedance(_hopSize, _windowSize, "Hop size for perfect reconstruction", "window size");

                gain = 1f / _windowSize;
            }
            // simpler reconstruction of the signal
            // (with insignificant discrepancies in the beginning and in the end)
            else
            {
                gain = 1 / (_fftSize * _windowSamples.Select(w => w * w).Sum() / _hopSize);
            }


            var pos = 0;

            for (var i = 0; i < spectraCount; i++)
            {
                var (re, im) = stft[i];

                _fft.Inverse(re, im, buf);

                // windowing and reconstruction

                for (var j = 0; j < _windowSize; j++)
                {
                    output[pos + j] += buf[j] * _windowSamples[j];
                }

                for (var j = 0; j < _hopSize; j++)
                {
                    output[pos + j] *= gain;
                }

                pos += _hopSize;
            }

            for (var j = 0; j < _windowSize; j++)
            {
                output[pos + j] *= gain;
            }


            if (perfectReconstruction)      // additional normalization
            {
                float[] windowSummed = ComputeWindowSummed();

                var offset = _windowSize - _hopSize;

                for (int j = 0, k = output.Length - _hopSize - 1; j < offset; j++, k--)
                {
                    if (Math.Abs(windowSummed[j]) > 1e-30)
                    {
                        output[j] /= windowSummed[j];   // leftmost part of the signal
                        output[k] /= windowSummed[j];   // rightmost part of the signal
                    }
                }

                // main central part of the signal

                for (int j = offset, k = offset; j < output.Length - _windowSize; j++, k++)
                {
                    if (k == _windowSize) k = offset;

                    output[j] /= windowSummed[k];
                }
            }

            return output;
        }

19 Source : ResultsPlotting.cs
with GNU General Public License v3.0
from architecture-building-systems

public double EmbodiedEnergyBuildingsYearly(bool normalized) => EmbodiedEnergyBuildingsMonthly(normalized).Sum();

19 Source : ResultsPlotting.cs
with GNU General Public License v3.0
from architecture-building-systems

public double EmbodiedEnergyBuildings(bool normalized) => EmbodiedEnergyBuildingsMonthly(normalized).Sum();

19 Source : ResultsPlotting.cs
with GNU General Public License v3.0
from architecture-building-systems

public double EmbodiedEnergySystemsYearly(bool normalized) => EmbodiedEnergySystemsMonthly(normalized).Sum();

19 Source : ResultsPlotting.cs
with GNU General Public License v3.0
from architecture-building-systems

public double OperationEnergyBuildingsYearly(bool normalized) => OperationEnergyBuildingsMonthly(normalized).Sum();

19 Source : ResultsPlotting.cs
with GNU General Public License v3.0
from architecture-building-systems

public double OperationEnergySystemsYearly(bool normalized) => OperationEnergySystemsMonthly(normalized).Sum();

19 Source : EnergyBalancePlot.cs
with GNU General Public License v3.0
from architecture-building-systems

public void Render(ResultsPlotting results, Dictionary<string, string> plotParameters, Graphics graphics,
            RectangleF bounds)
        {
            _bounds = bounds;
            var houseBounds =
                bounds.CloneInflate(-bounds.Width / 3, 0); // place it in the middle, one third of the width
            houseBounds.Height = bounds.Height - LegendHeight; // leave room for the legend
            var innerHousePolygon = RenderHouse(graphics, houseBounds);

            // throw new Exception("Losses and Gains need to be positive values.");
            // FIXME: remove this when chris has fixed the bug
            // FIXME: in case of corrupted / not valid data, avoid trying to draw NaN gains or losses.
            float CleanUpNegativeOrNan(float val) => val < 0.0f || float.IsNaN(val) ? 0.0f : val; 

            var gains = new float[]
            {
                results.SolarGains(Normalized),
                results.InternalGains(Normalized),
                results.PrimaryEnergy(Normalized),
                results.RenewableEnergy(Normalized),
                results.VentilationGains(Normalized),
                results.EnvelopeGains(Normalized),
                results.WindowsGains(Normalized)
            };
            var losses = new float[]
            {
                results.Electricity(Normalized),
                results.VentilationLosses(Normalized),
                results.EnvelopeLosses(Normalized),
                results.WindowsLosses(Normalized),
                results.SystemLosses(Normalized),
                results.ActiveCooling(Normalized),
                results.SurplusElectricity(Normalized),
                results.SurplusHeating(Normalized)
            };

            gains = gains.Select(v => CleanUpNegativeOrNan(v)).ToArray();
            losses = losses.Select(v => CleanUpNegativeOrNan(v)).ToArray();

            var maxTotal = Math.Max(gains.Sum(), losses.Sum());

            RenderGainsArrows(graphics, innerHousePolygon, houseBounds, bounds, gains, maxTotal);
            RenderLossesArrows(graphics, innerHousePolygon, houseBounds, bounds, losses, maxTotal);

            var legendBounds =
                new RectangleF(bounds.X, houseBounds.Bottom, bounds.Width, bounds.Height - houseBounds.Height)
                    .CloneInflate(-LegendPadding, -LegendPadding);
            RenderLegend(graphics, gains, losses, legendBounds);
        }

19 Source : EnergyBalancePlot.cs
with GNU General Public License v3.0
from architecture-building-systems

private void RenderLegend(Graphics graphics, float[] gains, float[] losses, RectangleF legendBounds)
        {
            var units = Normalized ? "kWh/m²" : "kWh";

            var leftreplacedle = "ENERGY IN";
            var totalGains = gains.Sum() == 0.0 ? 1.0 : gains.Sum(); // to prevent divide by zero errors
            var energyInStrings = gains.Zip(EnergyInStrings,
                    (gain, s) => $"{s}: {gain:0} {units} ({gain / totalGains * 100:0}%)"
                ).ToList();
            var leftLegendWidth =
                energyInStrings.Concat(new[] {leftreplacedle}).Select(
                    // NOTE: the "xxx" in the string template is used for a bit of padding
                    s => GH_FontServer.MeasureString($"{s}xxx", GH_FontServer.Standard).Width).Max() + IconWidth +
                IconPadding;

            var leftLegendBounds = new RectangleF(legendBounds.X, legendBounds.Y, leftLegendWidth, legendBounds.Height);
            RenderLegendColumn(graphics, leftreplacedle, leftLegendBounds, energyInStrings, GainsColors);

            var rightreplacedle = "ENERGY OUT";
            var totalLosses = losses.Sum() == 0.0 ? 1.0 : losses.Sum(); // to prevent divide by zero errors
            var energyOutStrings = losses.Zip(EnergyOutStrings,
                (loss, s) => $"{s}: {loss:0} {units} ({loss / totalLosses * 100:0}%)").ToList();
            var rightLegendWidth
                = energyOutStrings.Concat(new[] {rightreplacedle}).Select(
                      s => GH_FontServer.MeasureString($"{s}xxx", GH_FontServer.Standard).Width).Max() + IconWidth +
                  IconPadding;
            var rightLegendBounds = new RectangleF(legendBounds.Right - rightLegendWidth, legendBounds.Y,
                rightLegendWidth, legendBounds.Height);
            RenderLegendColumn(graphics, rightreplacedle, rightLegendBounds, energyOutStrings, LossesColors);
        }

19 Source : EnergyBalancePlot.cs
with GNU General Public License v3.0
from architecture-building-systems

private void RenderGainsArrows(Graphics graphics, PointF[] innerHousePolygon, RectangleF houseBounds,
            RectangleF bounds, float[] gains, float max)
        {
            if (max.IsClose(0.0f))
                // no data computed yet
                return;

            // inner axis, centered inside the house, left is end point of gains, right is starting point of losses
            var innerHouseBounds = HousePolygonToInnerRectangleF(innerHousePolygon);
            var houseCenterBounds = innerHouseBounds.CloneInflate(-innerHouseBounds.Width / 4f, -10);

            var inflectionPointRight = innerHouseBounds.X + 10f;
            var rightBounds = new RectangleF(
                inflectionPointRight, houseCenterBounds.Y,
                houseCenterBounds.Left - inflectionPointRight, houseCenterBounds.Height);

            var gainsArrowLeft = (bounds.Left + houseBounds.Left) / 2f;
            var innerHouseTop = innerHousePolygon[2].Y;
            var leftBounds = new RectangleF(gainsArrowLeft, innerHouseTop, rightBounds.Width,
                houseBounds.Bottom - innerHouseTop);

            var totalGains = gains.Sum();
            var newMax = rightBounds.Height - ArrowPadding * gains.GetUpperBound(0);
            var leftArrowPadding = (leftBounds.Height - newMax) / gains.GetUpperBound(0);
            var rightY = rightBounds.Y;
            var leftY = leftBounds.Y;
            var blackPen = new Pen(Color.Black);
            var blackBrush = new SolidBrush(Color.Black);
            var format = StringFormat.GenericTypographic;
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;
            using (var color = GainsColors.Select(c => c).GetEnumerator())
            {
                color.MoveNext();
                foreach (var gain in gains)
                {
                    var arrowHeight = gain.Scale(max, newMax);
                    var rightArrowBounds = new RectangleF(rightBounds.Left, rightY, rightBounds.Width, arrowHeight);
                    var leftArrowBounds = new RectangleF(leftBounds.Left, leftY, leftBounds.Width, arrowHeight);

                    var arrowPolygon = CreateGainsArrowPolygon(leftArrowBounds, rightArrowBounds);
                    graphics.FillPolygon(new SolidBrush(color.Current), arrowPolygon);
                    graphics.DrawPolygon(blackPen, arrowPolygon);

                    // write the percentages
                    var gainPercent = gain / totalGains * 100;
                    graphics.DrawString($"{gainPercent:F0}%", GH_FontServer.Standard, blackBrush, rightArrowBounds,
                        format);

                    rightY += rightArrowBounds.Height + ArrowPadding;
                    leftY += rightArrowBounds.Height + leftArrowPadding;
                    color.MoveNext();
                }
            }
        }

19 Source : EnergyBalancePlot.cs
with GNU General Public License v3.0
from architecture-building-systems

private void RenderLossesArrows(Graphics graphics, PointF[] innerHousePolygon, RectangleF houseBounds,
            RectangleF bounds, float[] losses, float max)
        {
            if (max.IsClose(0.0f))
                // no data computed yet
                return;

            // inner axis, centered inside the house, left is end point of gains, right is starting point of losses
            var innerHouseBounds = HousePolygonToInnerRectangleF(innerHousePolygon);

            var houseCenterBounds = innerHouseBounds.CloneInflate(-innerHouseBounds.Width / 4f, -10);

            var inflectionPointLeft = innerHouseBounds.Right - 10f;
            var leftBounds = new RectangleF(
                houseCenterBounds.Right, houseCenterBounds.Y,
                inflectionPointLeft - houseCenterBounds.Right, houseCenterBounds.Height);

            var lossesArrowRight = (bounds.Right + houseBounds.Right) / 2f;
            var innerHouseTop = innerHousePolygon[2].Y;
            var rightBounds = new RectangleF(lossesArrowRight - leftBounds.Width, innerHouseTop, leftBounds.Width,
                houseBounds.Bottom - innerHouseTop);

            var totalLosses = losses.Sum();
            var newMax = leftBounds.Height - ArrowPadding * losses.GetUpperBound(0);
            var rightArrowPadding = (rightBounds.Height - newMax) / losses.GetUpperBound(0);
            var leftY = leftBounds.Y;
            var rightY = rightBounds.Y;
            var blackPen = new Pen(Color.Black);
            var blackBrush = new SolidBrush(Color.Black);
            var format = StringFormat.GenericTypographic;
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;
            using (var color = LossesColors.Select(c => c).GetEnumerator())
            {
                color.MoveNext();
                foreach (var loss in losses)
                {
                    var arrowHeight = loss.Scale(max, newMax);
                    var leftArrowBounds = new RectangleF(leftBounds.Left, leftY, leftBounds.Width, arrowHeight);
                    var rightArrowBounds = new RectangleF(rightBounds.Left, rightY, rightBounds.Width, arrowHeight);

                    var arrowPolygon = CreateLossesArrowPolygon(leftArrowBounds, rightArrowBounds);
                    graphics.FillPolygon(new SolidBrush(color.Current), arrowPolygon);
                    graphics.DrawPolygon(blackPen, arrowPolygon);

                    // write the percentages
                    var lossPercent = loss / totalLosses * 100;
                    graphics.DrawString($"{lossPercent:F0}%", GH_FontServer.Standard, blackBrush, leftArrowBounds,
                        format);

                    leftY += leftArrowBounds.Height + ArrowPadding;
                    rightY += rightArrowBounds.Height + rightArrowPadding;
                    color.MoveNext();
                }
            }
        }

19 Source : Misc.cs
with GNU General Public License v3.0
from architecture-building-systems

public static double ComputeLevelisedValues(double[] valuesNonLevelised, double interestRate, double projectLifetime)
        {
            // From (with real discount rate) https://www.homerenergy.com/products/pro/docs/latest/capital_recovery_factor.html
            double CapitalRecoveryFactor(double i, double N) => i != 0 ? i * Math.Pow(1 + i, N) / (Math.Pow(1 + i, N) - 1) : 1;

            double NetPresentCost(double[] values, double i)
            {
                double[] netPresentValues = new double[values.Length];
                for (int t = 0; t < values.Length; t++)
                {
                    netPresentValues[t] = DiscountFactor(i, t) * values[t];
                }
                return netPresentValues.Sum();
            }

            double DiscountFactor(double i, double N) => 1 / Math.Pow(1 + i, N);

            double costLevelised = CapitalRecoveryFactor(interestRate, projectLifetime) * NetPresentCost(valuesNonLevelised, interestRate);

            return costLevelised;
        }

19 Source : Matrix3.cs
with MIT License
from arcplus

private double ComputeFrobeniusNorm()
        {
            return Math.Sqrt(_arr.Select(c => c * c).Sum());
        }

19 Source : MahjongLogic.cs
with MIT License
from ArcturusZhang

private static void replacedyze13Orphans(int[] hand, HashSet<List<Meld>> result)
        {
            if (hand.Sum() != MahjongConstants.FullHandTilesCount) return;
            var sub = new List<Meld>();
            int kinds = 0;
            for (int index = 0; index < hand.Length; index++)
            {
                var tile = Tile.GetTile(index);
                if (!tile.IsYaojiu && hand[index] != 0) return;
                if (tile.IsYaojiu && (hand[index] == 0 || hand[index] > 2)) return;
                if (tile.IsYaojiu) // 1 or 2
                {
                    kinds++;
                    if (hand[index] == 1) sub.Add(new Meld(false, tile));
                    if (hand[index] == 2) sub.Add(new Meld(false, tile, tile));
                }
            }
            replacedert.AreEqual(kinds, 13, "Something wrong happened");
            sub.Sort();
            result.Add(sub);
        }

19 Source : MahjongLogic.cs
with MIT License
from ArcturusZhang

private static void replacedyze7Pairs(int[] hand, HashSet<List<Meld>> result)
        {
            if (hand.Sum() != MahjongConstants.FullHandTilesCount) return;
            var sub = new List<Meld>();
            for (int index = 0; index < hand.Length; index++)
            {
                if (hand[index] != 0 && hand[index] != 2) return;
                if (hand[index] == 2)
                {
                    var tile = Tile.GetTile(index);
                    sub.Add(new Meld(false, tile, tile));
                }
            }
            sub.Sort();
            result.Add(sub);
        }

19 Source : Set_up_stochastic_mapping.cs
with GNU Affero General Public License v3.0
from arklumpus

public static void Transform(ref TreeNode tree, Dictionary<string, object> parameterValues, Action<double> progressAction)
        {
            TreeCollection trees = (TreeCollection)parameterValues["Trees"];
            InstanceStateData stateData = (InstanceStateData)parameterValues["StateData"];

            bool isClockLike = (bool)parameterValues["Treat trees as clock-like"];

            double resolution = (double)parameterValues["Resolution:"];
            int resolutionType = (int)parameterValues["Resolution unit:"];

            double actualResolution = resolution;

            switch (resolutionType)
            {
                case 0:
                    break;
                case 1:
                    actualResolution = resolution * tree.LongestDownstreamLength();
                    break;
                case 2:
                    break;
            }

            Dictionary<string, TreeNode> nodeCorresps = new Dictionary<string, TreeNode>();

            foreach (TreeNode node in tree.GetChildrenRecursiveLazy())
            {
                nodeCorresps[node.GetLeafNames().OrderBy(a => a).Aggregate((a, b) => a + "," + b)] = node;
            }

            Dictionary<string, List<(double left, double right, SimmapBranchState[] states)>> branchStates = new Dictionary<string, List<(double, double, SimmapBranchState[])>>(nodeCorresps.Count);

            foreach (KeyValuePair<string, TreeNode> kvp in nodeCorresps)
            {
                branchStates.Add(kvp.Value.Id, new List<(double start, double end, SimmapBranchState[] states)>());
            }

            HashSet<string>[] states = null;

            int sampleIndex = 0;

            foreach (TreeNode sample in trees)
            {
                foreach (TreeNode node in sample.GetChildrenRecursiveLazy())
                {
                    SimmapBranchState[] nodeStates = null;

                    if (node.Attributes.TryGetValue("States", out object statesObj) && statesObj is string statesString)
                    {
                        try
                        {
                            nodeStates = System.Text.Json.JsonSerializer.Deserialize<SimmapBranchState[]>(statesString);
                        }
                        catch { }
                    }

                    if (nodeStates != null)
                    {
                        string leafString = node.GetLeafNames().OrderBy(a => a).Aggregate((a, b) => a + "," + b);

                        if (nodeCorresps.TryGetValue(leafString, out TreeNode corresp))
                        {
                            if (states == null)
                            {
                                states = new HashSet<string>[nodeStates[0].States.Length];
                                for (int i = 0; i < states.Length; i++)
                                {
                                    states[i] = new HashSet<string>();
                                }
                            }

                            for (int i = 0; i < nodeStates.Length; i++)
                            {
                                for (int j = 0; j < nodeStates[i].States.Length; j++)
                                {
                                    states[j].Add(nodeStates[i].States[j]);
                                }
                            }

                            double left;
                            double right;

                            if (!isClockLike)
                            {
                                right = node.UpstreamLength();
                                left = right - node.Length;
                            }
                            else
                            {
                                right = node.LongestDownstreamLength();
                                left = right + node.Length;
                            }

                            branchStates[corresp.Id].Add((left, right, nodeStates));
                        }
                    }
                }

                sampleIndex++;
                progressAction((double)sampleIndex / trees.Count * 0.5);
            }

            List<List<string>> allPossibleStates = GetAllPossibleStates(states);

            Dictionary<string, (double samplePosPerc, double[] stateProbs)[]> preparedStates = new Dictionary<string, (double, double[])[]>();

            Dictionary<string, double[]> conditionedPosteriors = new Dictionary<string, double[]>();
            Dictionary<string, double[]> meanPosteriors = new Dictionary<string, double[]>();

            int nodeIndex = 0;

            List<(string, List<int>)> NaNSamples = new List<(string, List<int>)>();
            List<string> missingConditionedPosteriors = new List<string>();

            foreach (TreeNode node in tree.GetChildrenRecursiveLazy())
            {
                if (!double.IsNaN(node.Length) && node.Length > 0)
                {
                    double left;
                    double right;

                    if (!isClockLike)
                    {
                        right = node.UpstreamLength();
                        left = right - node.Length;
                    }
                    else
                    {
                        right = node.LongestDownstreamLength();
                        left = right + node.Length;
                    }

                    if (resolutionType == 2)
                    {
                        actualResolution = resolution * node.Length;
                    }

                    List<(double left, double right, SimmapBranchState[] states)> observedStates = branchStates[node.Id];

                    double[] meanPosterior = new double[allPossibleStates.Count];

                    for (int i = 0; i < observedStates.Count; i++)
                    {
                        for (int j = 0; j < allPossibleStates.Count; j++)
                        {
                            if (allPossibleStates[j].SequenceEqual(observedStates[i].states[0].States))
                            {
                                meanPosterior[j]++;
                                break;
                            }
                        }
                    }

                    if (observedStates.Count > 0)
                    {
                        for (int i = 0; i < meanPosterior.Length; i++)
                        {
                            meanPosterior[i] /= observedStates.Count;
                        }
                    }

                    {
                        string state = "{";

                        for (int j = 0; j < allPossibleStates.Count; j++)
                        {
                            state += allPossibleStates[j].Aggregate((a, b) => a + "|" + b) + ":" + meanPosterior[j].ToString(System.Globalization.CultureInfo.InvariantCulture);

                            if (j < allPossibleStates.Count - 1)
                            {
                                state += ",";
                            }
                        }

                        state += "}";

                        meanPosteriors[node.Id] = meanPosterior;
                        node.Attributes["MeanPosteriors"] = state;
                    }


                    List<(double samplePosPerc, double[] stateProbs)> preparedBranchStates = new List<(double samplePosPerc, double[] stateProbs)>();
                    List<int> NaNs = new List<int>();

                    for (int i = 0; i < Math.Ceiling(Math.Abs(right - left) / actualResolution) + 1; i++)
                    {
                        double samplingTime;
                        if (!isClockLike)
                        {
                            samplingTime = Math.Min(left + actualResolution * i, right);
                        }
                        else
                        {
                            samplingTime = Math.Max(left - actualResolution * i, right);
                        }

                        double perc = (samplingTime - left) / (right - left);



                        int[] counts = new int[allPossibleStates.Count];

                        for (int j = 0; j < observedStates.Count; j++)
                        {
                            string[] sample = SampleBranch(samplingTime, observedStates[j].left, observedStates[j].right, observedStates[j].states);

                            if (sample != null)
                            {
                                for (int k = 0; k < allPossibleStates.Count; k++)
                                {
                                    if (sample.SequenceEqual(allPossibleStates[k]))
                                    {
                                        counts[k]++;
                                        break;
                                    }
                                }
                            }
                        }

                        double total = counts.Sum();

                        double[] probs = new double[counts.Length];

                        if (total > 0)
                        {
                            for (int j = 0; j < probs.Length; j++)
                            {
                                probs[j] = counts[j] / total;
                            }
                        }
                        else
                        {
                            NaNs.Add(i);
                        }

                        preparedBranchStates.Add((perc, probs));

                        if (samplingTime == right)
                        {
                            if (total > 0)
                            {
                                string state = "{";

                                for (int j = 0; j < allPossibleStates.Count; j++)
                                {
                                    state += allPossibleStates[j].Aggregate((a, b) => a + "|" + b) + ":" + probs[j].ToString(System.Globalization.CultureInfo.InvariantCulture);

                                    if (j < allPossibleStates.Count - 1)
                                    {
                                        state += ",";
                                    }
                                }

                                state += "}";

                                node.Attributes["ConditionedPosteriors"] = state;
                                conditionedPosteriors[node.Id] = probs;
                            }
                            else
                            {
                                missingConditionedPosteriors.Add(node.Id);
                            }

                            break;
                        }
                    }

                    if (NaNs.Count > 0)
                    {
                        NaNs.Sort();
                        NaNSamples.Add((node.Id, NaNs));
                    }

                    preparedStates[node.Id] = preparedBranchStates.ToArray();
                }
                else if (node.Parent == null && node.Children.Count > 0)
                {
                    List<(double left, double right, SimmapBranchState[] states)> observedStates = branchStates[node.Children[0].Id];

                    double[] meanPosterior = new double[allPossibleStates.Count];

                    for (int i = 0; i < observedStates.Count; i++)
                    {
                        for (int j = 0; j < allPossibleStates.Count; j++)
                        {
                            if (allPossibleStates[j].SequenceEqual(observedStates[i].states[observedStates[i].states.Length - 1].States))
                            {
                                meanPosterior[j]++;
                                break;
                            }
                        }
                    }

                    if (observedStates.Count > 0)
                    {
                        for (int i = 0; i < meanPosterior.Length; i++)
                        {
                            meanPosterior[i] /= observedStates.Count;
                        }
                    }

                    {
                        string state = "{";

                        for (int j = 0; j < allPossibleStates.Count; j++)
                        {
                            state += allPossibleStates[j].Aggregate((a, b) => a + "|" + b) + ":" + meanPosterior[j].ToString(System.Globalization.CultureInfo.InvariantCulture);

                            if (j < allPossibleStates.Count - 1)
                            {
                                state += ",";
                            }
                        }

                        state += "}";

                        node.Attributes["MeanPosteriors"] = state;
                        node.Attributes["ConditionedPosteriors"] = state;

                        conditionedPosteriors[node.Id] = meanPosterior;
                    }
                }

                nodeIndex++;
                progressAction(0.5 + (double)nodeIndex / nodeCorresps.Count * 0.5);
            }

            for (int i = 0; i < NaNSamples.Count; i++)
            {
                (double samplePosPerc, double[] stateProbs)[] samples = preparedStates[NaNSamples[i].Item1];
                TreeNode node = tree.GetNodeFromId(NaNSamples[i].Item1);

                if (NaNSamples[i].Item2.Count == samples.Length)
                {
                    if (missingConditionedPosteriors.Contains(node.Id))
                    {
                        conditionedPosteriors[node.Id] = meanPosteriors[node.Id];
                    }

                    for (int j = 0; j < samples.Length; j++)
                    {
                        samples[j] = (samples[j].samplePosPerc, conditionedPosteriors[node.Id]);
                    }
                }
                else
                {
                    List<int> missingSamplesStart = new List<int>();
                    List<int> missingSamplesEnd = new List<int>();

                    for (int j = 0; j < NaNSamples[i].Item2.Count; j++)
                    {
                        if (NaNSamples[i].Item2[j] == j)
                        {
                            missingSamplesStart.Add(NaNSamples[i].Item2[j]);
                        }

                        if (NaNSamples[i].Item2[NaNSamples[i].Item2.Count - 1 - j] == samples.Length - 1 - j)
                        {
                            missingSamplesEnd.Add(NaNSamples[i].Item2[NaNSamples[i].Item2.Count - 1 - j]);
                        }
                    }

                    if (missingSamplesStart.Count > 0)
                    {
                        double[] left = null;
                        double[] right = null;

                        // Parent
                        if (!missingConditionedPosteriors.Contains(node.Parent.Id))
                        {
                            left = conditionedPosteriors[node.Parent.Id];
                        }
                        else
                        {
                            (double samplePosPerc, double[] stateProbs)[] parentSamples = preparedStates[node.Parent.Id];

                            for (int j = parentSamples.Length - 1; j >= 0; j--)
                            {
                                if (parentSamples[j].stateProbs.Sum() > 0)
                                {
                                    left = parentSamples[j].stateProbs;
                                    break;
                                }
                            }
                        }

                        // First sample
                        for (int j = 0; j < samples.Length; j++)
                        {
                            if (samples[j].stateProbs.Sum() > 0)
                            {
                                right = samples[j].stateProbs;
                                break;
                            }
                        }

                        if (left != null && right != null)
                        {
                            for (int j = 0; j < missingSamplesStart.Count; j++)
                            {
                                double[] average = new double[left.Length];

                                for (int k = 0; k < left.Length; k++)
                                {
                                    average[k] = left[k] * (1 - (double)(j + 1) / (missingSamplesStart.Count + 1)) + right[k] * (double)(j + 1) / (missingSamplesStart.Count + 1);
                                }

                                samples[missingSamplesStart[j]] = (samples[missingSamplesStart[j]].samplePosPerc, average);
                            }
                        }
                        else if (right != null)
                        {
                            for (int j = 0; j < missingSamplesStart.Count; j++)
                            {
                                samples[missingSamplesStart[j]] = (samples[missingSamplesStart[j]].samplePosPerc, right);
                            }
                        }
                        else if (left != null)
                        {
                            for (int j = 0; j < missingSamplesStart.Count; j++)
                            {
                                samples[missingSamplesStart[j]] = (samples[missingSamplesStart[j]].samplePosPerc, left);
                            }
                        }
                    }


                    if (missingSamplesEnd.Count > 0)
                    {
                        double[] left = null;
                        List<double[]> right = new List<double[]>();

                        // Children
                        for (int k = 0; k < node.Children.Count; k++)
                        {
                            if (!missingConditionedPosteriors.Contains(node.Children[k].Id))
                            {
                                right.Add(conditionedPosteriors[node.Children[k].Id]);
                            }
                            else
                            {
                                (double samplePosPerc, double[] stateProbs)[] childSamples = preparedStates[node.Children[k].Id];

                                for (int j = 0; j < childSamples.Length; j++)
                                {
                                    if (childSamples[j].stateProbs.Sum() > 0)
                                    {
                                        right.Add(childSamples[j].stateProbs);
                                        break;
                                    }
                                }
                            }
                        }

                        // Last sample
                        for (int j = samples.Length - 1; j >= 0; j--)
                        {
                            if (samples[j].stateProbs.Sum() > 0)
                            {
                                left = samples[j].stateProbs;
                                break;
                            }
                        }

                        if (left != null && right.Count > 0)
                        {
                            double[] rightAverage = new double[right[0].Length];

                            for (int j = 0; j < right.Count; j++)
                            {
                                for (int k = 0; k < rightAverage.Length; k++)
                                {
                                    rightAverage[k] += right[j][k];
                                }
                            }

                            for (int k = 0; k < rightAverage.Length; k++)
                            {
                                rightAverage[k] /= right.Count;
                            }

                            for (int j = 0; j < missingSamplesEnd.Count; j++)
                            {
                                double[] average = new double[left.Length];

                                for (int k = 0; k < left.Length; k++)
                                {
                                    average[k] = rightAverage[k] * (1 - (double)(j + 1) / (missingSamplesEnd.Count + 1)) + left[k] * (double)(j + 1) / (missingSamplesEnd.Count + 1);
                                }

                                samples[missingSamplesEnd[j]] = (samples[missingSamplesEnd[j]].samplePosPerc, average);
                            }
                        }
                        else if (right.Count > 0)
                        {
                            double[] rightAverage = new double[right[0].Length];

                            for (int j = 0; j < right.Count; j++)
                            {
                                for (int k = 0; k < rightAverage.Length; k++)
                                {
                                    rightAverage[k] += right[j][k];
                                }
                            }

                            for (int k = 0; k < rightAverage.Length; k++)
                            {
                                rightAverage[k] /= right.Count;
                            }

                            for (int j = 0; j < missingSamplesEnd.Count; j++)
                            {
                                samples[missingSamplesEnd[j]] = (samples[missingSamplesEnd[j]].samplePosPerc, rightAverage);
                            }
                        }
                        else if (left != null)
                        {
                            for (int j = 0; j < missingSamplesEnd.Count; j++)
                            {
                                samples[missingSamplesEnd[j]] = (samples[missingSamplesEnd[j]].samplePosPerc, left);
                            }
                        }
                    }
                }
            }

            for (int i = 0; i < missingConditionedPosteriors.Count; i++)
            {
                double[] probs = preparedStates[missingConditionedPosteriors[i]].Last().stateProbs;

                string state = "{";

                for (int j = 0; j < allPossibleStates.Count; j++)
                {
                    state += allPossibleStates[j].Aggregate((a, b) => a + "|" + b) + ":" + probs[j].ToString(System.Globalization.CultureInfo.InvariantCulture);

                    if (j < allPossibleStates.Count - 1)
                    {
                        state += ",";
                    }
                }

                state += "}";

                tree.GetNodeFromId(missingConditionedPosteriors[i]).Attributes["ConditionedPosteriors"] = state;
                conditionedPosteriors[missingConditionedPosteriors[i]] = probs;
            }

            stateData.Tags["32858c9d-0247-497f-aeee-03f7bfe24158"] = preparedStates;
            stateData.Tags["32858c9d-0247-497f-aeee-03f7bfe24158/states"] = (from el in states select el.ToArray()).ToArray();
            tree.Attributes["32858c9d-0247-497f-aeee-03f7bfe24158"] = "Stochastic map";
        }

19 Source : Set_up_stochastic_mapping_attachment.cs
with GNU Affero General Public License v3.0
from arklumpus

public static void Transform(ref TreeNode tree, Dictionary<string, object> parameterValues, Action<double> progressAction)
        {
            Attachment attachment = (Attachment)parameterValues["Attachment:"];

            if (attachment == null)
            {
                return;
            }

            attachment.Stream.Seek(attachment.StreamStart, SeekOrigin.Begin);

            TreeCollection trees = new TreeCollection(OpenFile(attachment.Stream, progressAction));

            InstanceStateData stateData = (InstanceStateData)parameterValues["StateData"];

            bool isClockLike = (bool)parameterValues["Treat trees as clock-like"];

            double resolution = (double)parameterValues["Resolution:"];
            int resolutionType = (int)parameterValues["Resolution unit:"];

            double actualResolution = resolution;

            switch (resolutionType)
            {
                case 0:
                    break;
                case 1:
                    actualResolution = resolution * tree.LongestDownstreamLength();
                    break;
                case 2:
                    break;
            }

            Dictionary<string, TreeNode> nodeCorresps = new Dictionary<string, TreeNode>();

            foreach (TreeNode node in tree.GetChildrenRecursiveLazy())
            {
                nodeCorresps[node.GetLeafNames().OrderBy(a => a).Aggregate((a, b) => a + "," + b)] = node;
            }

            Dictionary<string, List<(double left, double right, SimmapBranchState[] states)>> branchStates = new Dictionary<string, List<(double, double, SimmapBranchState[])>>(nodeCorresps.Count);

            foreach (KeyValuePair<string, TreeNode> kvp in nodeCorresps)
            {
                branchStates.Add(kvp.Value.Id, new List<(double start, double end, SimmapBranchState[] states)>());
            }

            HashSet<string>[] states = null;

            int sampleIndex = 0;

            foreach (TreeNode sample in trees)
            {
                foreach (TreeNode node in sample.GetChildrenRecursiveLazy())
                {
                    SimmapBranchState[] nodeStates = null;

                    if (node.Attributes.TryGetValue("States", out object statesObj) && statesObj is string statesString)
                    {
                        try
                        {
                            nodeStates = System.Text.Json.JsonSerializer.Deserialize<SimmapBranchState[]>(statesString);
                        }
                        catch { }
                    }

                    if (nodeStates != null)
                    {
                        string leafString = node.GetLeafNames().OrderBy(a => a).Aggregate((a, b) => a + "," + b);

                        if (nodeCorresps.TryGetValue(leafString, out TreeNode corresp))
                        {
                            if (states == null)
                            {
                                states = new HashSet<string>[nodeStates[0].States.Length];
                                for (int i = 0; i < states.Length; i++)
                                {
                                    states[i] = new HashSet<string>();
                                }
                            }

                            for (int i = 0; i < nodeStates.Length; i++)
                            {
                                for (int j = 0; j < nodeStates[i].States.Length; j++)
                                {
                                    states[j].Add(nodeStates[i].States[j]);
                                }
                            }

                            double left;
                            double right;

                            if (!isClockLike)
                            {
                                right = node.UpstreamLength();
                                left = right - node.Length;
                            }
                            else
                            {
                                right = node.LongestDownstreamLength();
                                left = right + node.Length;
                            }

                            branchStates[corresp.Id].Add((left, right, nodeStates));
                        }
                    }
                }

                sampleIndex++;

                progressAction(0.5 + (double)sampleIndex / trees.Count * 0.25);
            }

            List<List<string>> allPossibleStates = GetAllPossibleStates(states);

            Dictionary<string, (double samplePosPerc, double[] stateProbs)[]> preparedStates = new Dictionary<string, (double, double[])[]>();

            Dictionary<string, double[]> conditionedPosteriors = new Dictionary<string, double[]>();
            Dictionary<string, double[]> meanPosteriors = new Dictionary<string, double[]>();

            int nodeIndex = 0;

            List<(string, List<int>)> NaNSamples = new List<(string, List<int>)>();
            List<string> missingConditionedPosteriors = new List<string>();

            foreach (TreeNode node in tree.GetChildrenRecursiveLazy())
            {
                if (!double.IsNaN(node.Length) && node.Length > 0)
                {
                    double left;
                    double right;

                    if (!isClockLike)
                    {
                        right = node.UpstreamLength();
                        left = right - node.Length;
                    }
                    else
                    {
                        right = node.LongestDownstreamLength();
                        left = right + node.Length;
                    }

                    if (resolutionType == 2)
                    {
                        actualResolution = resolution * node.Length;
                    }

                    List<(double left, double right, SimmapBranchState[] states)> observedStates = branchStates[node.Id];

                    double[] meanPosterior = new double[allPossibleStates.Count];

                    for (int i = 0; i < observedStates.Count; i++)
                    {
                        for (int j = 0; j < allPossibleStates.Count; j++)
                        {
                            if (allPossibleStates[j].SequenceEqual(observedStates[i].states[0].States))
                            {
                                meanPosterior[j]++;
                                break;
                            }
                        }
                    }

                    if (observedStates.Count > 0)
                    {
                        for (int i = 0; i < meanPosterior.Length; i++)
                        {
                            meanPosterior[i] /= observedStates.Count;
                        }
                    }

                    {
                        string state = "{";

                        for (int j = 0; j < allPossibleStates.Count; j++)
                        {
                            state += allPossibleStates[j].Aggregate((a, b) => a + "|" + b) + ":" + meanPosterior[j].ToString(System.Globalization.CultureInfo.InvariantCulture);

                            if (j < allPossibleStates.Count - 1)
                            {
                                state += ",";
                            }
                        }

                        state += "}";

                        meanPosteriors[node.Id] = meanPosterior;
                        node.Attributes["MeanPosteriors"] = state;
                    }


                    List<(double samplePosPerc, double[] stateProbs)> preparedBranchStates = new List<(double samplePosPerc, double[] stateProbs)>();
                    List<int> NaNs = new List<int>();

                    for (int i = 0; i < Math.Ceiling(Math.Abs(right - left) / actualResolution) + 1; i++)
                    {
                        double samplingTime;
                        if (!isClockLike)
                        {
                            samplingTime = Math.Min(left + actualResolution * i, right);
                        }
                        else
                        {
                            samplingTime = Math.Max(left - actualResolution * i, right);
                        }

                        double perc = (samplingTime - left) / (right - left);



                        int[] counts = new int[allPossibleStates.Count];

                        for (int j = 0; j < observedStates.Count; j++)
                        {
                            string[] sample = SampleBranch(samplingTime, observedStates[j].left, observedStates[j].right, observedStates[j].states);

                            if (sample != null)
                            {
                                for (int k = 0; k < allPossibleStates.Count; k++)
                                {
                                    if (sample.SequenceEqual(allPossibleStates[k]))
                                    {
                                        counts[k]++;
                                        break;
                                    }
                                }
                            }
                        }

                        double total = counts.Sum();

                        double[] probs = new double[counts.Length];


                        if (total > 0)
                        {
                            for (int j = 0; j < probs.Length; j++)
                            {
                                probs[j] = counts[j] / total;
                            }
                        }
                        else
                        {
                            NaNs.Add(i);
                        }

                        preparedBranchStates.Add((perc, probs));

                        if (samplingTime == right)
                        {
                            if (total > 0)
                            {
                                string state = "{";

                                for (int j = 0; j < allPossibleStates.Count; j++)
                                {
                                    state += allPossibleStates[j].Aggregate((a, b) => a + "|" + b) + ":" + probs[j].ToString(System.Globalization.CultureInfo.InvariantCulture);

                                    if (j < allPossibleStates.Count - 1)
                                    {
                                        state += ",";
                                    }
                                }

                                state += "}";

                                node.Attributes["ConditionedPosteriors"] = state;
                                conditionedPosteriors[node.Id] = probs;
                            }
                            else
                            {
                                missingConditionedPosteriors.Add(node.Id);
                            }

                            break;
                        }
                    }

                    if (NaNs.Count > 0)
                    {
                        NaNs.Sort();
                        NaNSamples.Add((node.Id, NaNs));
                    }

                    preparedStates[node.Id] = preparedBranchStates.ToArray();
                }
                else if (node.Parent == null && node.Children.Count > 0)
                {
                    List<(double left, double right, SimmapBranchState[] states)> observedStates = branchStates[node.Children[0].Id];

                    double[] meanPosterior = new double[allPossibleStates.Count];

                    for (int i = 0; i < observedStates.Count; i++)
                    {
                        for (int j = 0; j < allPossibleStates.Count; j++)
                        {
                            if (allPossibleStates[j].SequenceEqual(observedStates[i].states[observedStates[i].states.Length - 1].States))
                            {
                                meanPosterior[j]++;
                                break;
                            }
                        }
                    }

                    if (observedStates.Count > 0)
                    {
                        for (int i = 0; i < meanPosterior.Length; i++)
                        {
                            meanPosterior[i] /= observedStates.Count;
                        }
                    }

                    {
                        string state = "{";

                        for (int j = 0; j < allPossibleStates.Count; j++)
                        {
                            state += allPossibleStates[j].Aggregate((a, b) => a + "|" + b) + ":" + meanPosterior[j].ToString(System.Globalization.CultureInfo.InvariantCulture);

                            if (j < allPossibleStates.Count - 1)
                            {
                                state += ",";
                            }
                        }

                        state += "}";

                        node.Attributes["MeanPosteriors"] = state;
                        node.Attributes["ConditionedPosteriors"] = state;

                        conditionedPosteriors[node.Id] = meanPosterior;
                    }
                }

                nodeIndex++;
                progressAction(0.75 + (double)nodeIndex / nodeCorresps.Count * 0.25);
            }

            for (int i = 0; i < NaNSamples.Count; i++)
            {
                (double samplePosPerc, double[] stateProbs)[] samples = preparedStates[NaNSamples[i].Item1];
                TreeNode node = tree.GetNodeFromId(NaNSamples[i].Item1);

                if (NaNSamples[i].Item2.Count == samples.Length)
                {
                    if (missingConditionedPosteriors.Contains(node.Id))
                    {
                        conditionedPosteriors[node.Id] = meanPosteriors[node.Id];
                    }

                    for (int j = 0; j < samples.Length; j++)
                    {
                        samples[j] = (samples[j].samplePosPerc, conditionedPosteriors[node.Id]);
                    }
                }
                else
                {
                    List<int> missingSamplesStart = new List<int>();
                    List<int> missingSamplesEnd = new List<int>();

                    for (int j = 0; j < NaNSamples[i].Item2.Count; j++)
                    {
                        if (NaNSamples[i].Item2[j] == j)
                        {
                            missingSamplesStart.Add(NaNSamples[i].Item2[j]);
                        }

                        if (NaNSamples[i].Item2[NaNSamples[i].Item2.Count - 1 - j] == samples.Length - 1 - j)
                        {
                            missingSamplesEnd.Add(NaNSamples[i].Item2[NaNSamples[i].Item2.Count - 1 - j]);
                        }
                    }

                    if (missingSamplesStart.Count > 0)
                    {
                        double[] left = null;
                        double[] right = null;

                        // Parent
                        if (!missingConditionedPosteriors.Contains(node.Parent.Id))
                        {
                            left = conditionedPosteriors[node.Parent.Id];
                        }
                        else
                        {
                            (double samplePosPerc, double[] stateProbs)[] parentSamples = preparedStates[node.Parent.Id];

                            for (int j = parentSamples.Length - 1; j >= 0; j--)
                            {
                                if (parentSamples[j].stateProbs.Sum() > 0)
                                {
                                    left = parentSamples[j].stateProbs;
                                    break;
                                }
                            }
                        }

                        // First sample
                        for (int j = 0; j < samples.Length; j++)
                        {
                            if (samples[j].stateProbs.Sum() > 0)
                            {
                                right = samples[j].stateProbs;
                                break;
                            }
                        }

                        if (left != null && right != null)
                        {
                            for (int j = 0; j < missingSamplesStart.Count; j++)
                            {
                                double[] average = new double[left.Length];

                                for (int k = 0; k < left.Length; k++)
                                {
                                    average[k] = left[k] * (1 - (double)(j + 1) / (missingSamplesStart.Count + 1)) + right[k] * (double)(j + 1) / (missingSamplesStart.Count + 1);
                                }

                                samples[missingSamplesStart[j]] = (samples[missingSamplesStart[j]].samplePosPerc, average);
                            }
                        }
                        else if (right != null)
                        {
                            for (int j = 0; j < missingSamplesStart.Count; j++)
                            {
                                samples[missingSamplesStart[j]] = (samples[missingSamplesStart[j]].samplePosPerc, right);
                            }
                        }
                        else if (left != null)
                        {
                            for (int j = 0; j < missingSamplesStart.Count; j++)
                            {
                                samples[missingSamplesStart[j]] = (samples[missingSamplesStart[j]].samplePosPerc, left);
                            }
                        }
                    }


                    if (missingSamplesEnd.Count > 0)
                    {
                        double[] left = null;
                        List<double[]> right = new List<double[]>();

                        // Children
                        for (int k = 0; k < node.Children.Count; k++)
                        {
                            if (!missingConditionedPosteriors.Contains(node.Children[k].Id))
                            {
                                right.Add(conditionedPosteriors[node.Children[k].Id]);
                            }
                            else
                            {
                                (double samplePosPerc, double[] stateProbs)[] childSamples = preparedStates[node.Children[k].Id];

                                for (int j = 0; j < childSamples.Length; j++)
                                {
                                    if (childSamples[j].stateProbs.Sum() > 0)
                                    {
                                        right.Add(childSamples[j].stateProbs);
                                        break;
                                    }
                                }
                            }
                        }

                        // Last sample
                        for (int j = samples.Length - 1; j >= 0; j--)
                        {
                            if (samples[j].stateProbs.Sum() > 0)
                            {
                                left = samples[j].stateProbs;
                                break;
                            }
                        }

                        if (left != null && right.Count > 0)
                        {
                            double[] rightAverage = new double[right[0].Length];

                            for (int j = 0; j < right.Count; j++)
                            {
                                for (int k = 0; k < rightAverage.Length; k++)
                                {
                                    rightAverage[k] += right[j][k];
                                }
                            }

                            for (int k = 0; k < rightAverage.Length; k++)
                            {
                                rightAverage[k] /= right.Count;
                            }

                            for (int j = 0; j < missingSamplesEnd.Count; j++)
                            {
                                double[] average = new double[left.Length];

                                for (int k = 0; k < left.Length; k++)
                                {
                                    average[k] = rightAverage[k] * (1 - (double)(j + 1) / (missingSamplesEnd.Count + 1)) + left[k] * (double)(j + 1) / (missingSamplesEnd.Count + 1);
                                }

                                samples[missingSamplesEnd[j]] = (samples[missingSamplesEnd[j]].samplePosPerc, average);
                            }
                        }
                        else if (right.Count > 0)
                        {
                            double[] rightAverage = new double[right[0].Length];

                            for (int j = 0; j < right.Count; j++)
                            {
                                for (int k = 0; k < rightAverage.Length; k++)
                                {
                                    rightAverage[k] += right[j][k];
                                }
                            }

                            for (int k = 0; k < rightAverage.Length; k++)
                            {
                                rightAverage[k] /= right.Count;
                            }

                            for (int j = 0; j < missingSamplesEnd.Count; j++)
                            {
                                samples[missingSamplesEnd[j]] = (samples[missingSamplesEnd[j]].samplePosPerc, rightAverage);
                            }
                        }
                        else if (left != null)
                        {
                            for (int j = 0; j < missingSamplesEnd.Count; j++)
                            {
                                samples[missingSamplesEnd[j]] = (samples[missingSamplesEnd[j]].samplePosPerc, left);
                            }
                        }
                    }
                }
            }

            for (int i = 0; i < missingConditionedPosteriors.Count; i++)
            {
                double[] probs = preparedStates[missingConditionedPosteriors[i]].Last().stateProbs;

                string state = "{";

                for (int j = 0; j < allPossibleStates.Count; j++)
                {
                    state += allPossibleStates[j].Aggregate((a, b) => a + "|" + b) + ":" + probs[j].ToString(System.Globalization.CultureInfo.InvariantCulture);

                    if (j < allPossibleStates.Count - 1)
                    {
                        state += ",";
                    }
                }

                state += "}";

                tree.GetNodeFromId(missingConditionedPosteriors[i]).Attributes["ConditionedPosteriors"] = state;
                conditionedPosteriors[missingConditionedPosteriors[i]] = probs;
            }

            stateData.Tags["32858c9d-0247-497f-aeee-03f7bfe24158"] = preparedStates;
            stateData.Tags["32858c9d-0247-497f-aeee-03f7bfe24158/states"] = (from el in states select el.ToArray()).ToArray();
            tree.Attributes["32858c9d-0247-497f-aeee-03f7bfe24158"] = "Stochastic map";
        }

19 Source : Set_up_stochastic_mapping_attachment.cs
with GNU Affero General Public License v3.0
from arklumpus

private static List<TreeNode> OpenFile(Stream fileStream, Action<double> progressAction)
        {
            Action<double> nwkaProgressAction = (prog) => { progressAction(prog * 0.25); };

            List<TreeNode> trees = NWKA.ParseTrees(fileStream, progressAction: nwkaProgressAction, keepOpen: true).ToList();

            HashSet<string>[] characters = null;

            int treeIndex = 0;

            foreach (TreeNode tree in trees)
            {
                foreach (TreeNode node in tree.GetChildrenRecursiveLazy())
                {
                    string attributeToRemove = null;

                    foreach (KeyValuePair<string, object> attribute in node.Attributes)
                    {
                        if (attribute.Key.StartsWith("Unknown") && attribute.Value is string attributeValue && attributeValue.StartsWith("{") && attributeValue.EndsWith("}"))
                        {
                            SimmapBranchState[] states = SimmapBranchState.Parse(attributeValue).ToArray();

                            if (states.Length > 0)
                            {
                                if (characters == null)
                                {
                                    characters = new HashSet<string>[states[0].States.Length];

                                    for (int i = 0; i < characters.Length; i++)
                                    {
                                        characters[i] = new HashSet<string>();
                                    }
                                }

                                node.Attributes.Add("States", System.Text.Json.JsonSerializer.Serialize(states, Modules.DefaultSerializationOptions));
                                node.Length = (from el in states select el.Length).Sum();

                                foreach (SimmapBranchState state in states)
                                {
                                    for (int i = 0; i < state.States.Length; i++)
                                    {
                                        characters[i].Add(state.States[i]);
                                    }
                                }

                                attributeToRemove = attribute.Key;

                                break;
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(attributeToRemove))
                    {
                        node.Attributes.Remove(attributeToRemove);
                    }
                }

                tree.Attributes.Add("Characters", System.Text.Json.JsonSerializer.Serialize(characters, Modules.DefaultSerializationOptions));

                treeIndex++;
                progressAction(0.25 + (double)treeIndex / trees.Count * 0.25);
            }

            return trees;
        }

19 Source : Stochastic_map_filetype.cs
with GNU Affero General Public License v3.0
from arklumpus

public static IEnumerable<TreeNode> OpenFile(string fileName, List<(string, Dictionary<string, object>)> moduleSuggestions, Action<double> progressAction, Func<RSAParameters?, bool> askForCodePermission)
        {
            bool escaping = false;
            bool escaped;
            bool openQuotes = false;
            bool openApostrophe = false;
            bool eof = false;

            if (GlobalSettings.Settings.DrawTreeWhenOpened)
            {
                moduleSuggestions.Add(("32858c9d-0247-497f-aeee-03f7bfe24158", new Dictionary<string, object>()));

                moduleSuggestions.Add(("7c767b07-71be-48b2-8753-b27f3e973570", new Dictionary<string, object>()));
                moduleSuggestions.Add(("f7a20f2f-94b2-4331-8bbf-4e0087da6fba", new Dictionary<string, object>()));
                moduleSuggestions.Add(("ac496677-2650-4d92-8646-0812918bab03", new Dictionary<string, object>() { { "Position:", new VectSharp.Point(10, 0) } }));

                NumberFormatterOptions widthFO = new NumberFormatterOptions(Modules.DefaultAttributeConvertersToDouble[1]) { AttributeName = "StateWidth", AttributeType = "Number", DefaultValue = 10.0, Parameters = new object[] { Modules.DefaultAttributeConvertersToDouble[1], 0, double.PositiveInfinity, true } };
                NumberFormatterOptions heightFO = new NumberFormatterOptions(Modules.DefaultAttributeConvertersToDouble[1]) { AttributeName = "StateHeight", AttributeType = "Number", DefaultValue = 10.0, Parameters = new object[] { Modules.DefaultAttributeConvertersToDouble[1], 0, double.PositiveInfinity, true } };

                moduleSuggestions.Add(("0512b822-044d-4c13-b3bb-bca494c51daa", new Dictionary<string, object>()
                {
                    { "Show on:",  2 },
                    { "Stroke thickness:", 1.0 },
                    { "Width:", widthFO },
                    { "Height:", heightFO },
                    { "Attribute:", "ConditionedPosteriors" }
                }));
            }

            using (StreamReader sr = new StreamReader(fileName))
            {
                double length = sr.BaseStream.Length;

                while (!eof)
                {
                    StringBuilder sb = new StringBuilder();

                    char c = sr.NextToken(ref escaping, out escaped, ref openQuotes, ref openApostrophe, out eof);

                    while (!eof && !(c == ';' && !escaped && !openQuotes && !openApostrophe))
                    {
                        sb.Append((char)c);
                        c = sr.NextToken(ref escaping, out escaping, ref openQuotes, ref openApostrophe, out eof);
                    }

                    if (sb.Length > 0)
                    {
                        TreeNode tree = NWKA.ParseTree(sb.ToString());

                        HashSet<string>[] characters = null;

                        foreach (TreeNode node in tree.GetChildrenRecursiveLazy())
                        {
                            string attributeToRemove = null;

                            foreach (KeyValuePair<string, object> attribute in node.Attributes)
                            {
                                if (attribute.Key.StartsWith("Unknown") && attribute.Value is string attributeValue && attributeValue.StartsWith("{") && attributeValue.EndsWith("}"))
                                {
                                    SimmapBranchState[] states = SimmapBranchState.Parse(attributeValue).ToArray();

                                    if (states.Length > 0)
                                    {
                                        if (characters == null)
                                        {
                                            characters = new HashSet<string>[states[0].States.Length];

                                            for (int i = 0; i < characters.Length; i++)
                                            {
                                                characters[i] = new HashSet<string>();
                                            }
                                        }

                                        node.Attributes.Add("States", System.Text.Json.JsonSerializer.Serialize(states, Modules.DefaultSerializationOptions));
                                        node.Length = (from el in states select el.Length).Sum();

                                        foreach (SimmapBranchState state in states)
                                        {
                                            for (int i = 0; i < state.States.Length; i++)
                                            {
                                                characters[i].Add(state.States[i]);
                                            }
                                        }

                                        attributeToRemove = attribute.Key;

                                        break;
                                    }
                                }
                            }

                            if (!string.IsNullOrEmpty(attributeToRemove))
                            {
                                node.Attributes.Remove(attributeToRemove);
                            }
                        }

                        tree.Attributes.Add("Characters", System.Text.Json.JsonSerializer.Serialize(characters, Modules.DefaultSerializationOptions));

                        yield return tree;
                        double progress = Math.Max(0, Math.Min(1, sr.BaseStream.Position / length));
                        progressAction?.Invoke(progress);
                    }
                }
            }
        }

19 Source : ManagerViewModel.cs
with GNU General Public License v3.0
from Artentus

private async Task UpdateModsAsync()
        {
            try
            {
                string replacedle = (string)App.Current.Locales.GetResource("ModUpdateSearch_replacedle");
                string message = (string)App.Current.Locales.GetResource("ModUpdateSearch_Message");

                var progress = new Progress<double>();
                var cancellationSource = new CancellationTokenSource();
                var searchTask = SearchModUpdatesAsync(progress, cancellationSource.Token);
                await ProgressDialog.Show(replacedle, message, searchTask, progress, 0.0, 1.0, cancellationSource, App.Current.MainWindow);

                var updates = searchTask.Result;
                int updateCount = updates.Values.Select(l => l.Count()).Sum();
                if (updateCount > 0)
                {
                    // Some updates are available

                    var vm = new ModUpdateWindowViewModel(updates);
                    var window = View.CreateAndAttach(vm);
                    await window.ShowDialog(App.Current.MainWindow);

                    if (vm.DialogResult == DialogResult.Ok)
                    {
                        var (success, username, token) = await App.Current.Credentials.TryLogInAsync();
                        if (success.IsTrue())
                        {
                            foreach (var update in updates.Values.Flatten())
                            {
                                if (update.Selected)
                                {
                                    var job = new UpdateModJob(update, vm.ReplaceUpdates, vm.RemoveOldMods, username, token);
                                    _downloadQueue.AddJob(job);
                                }
                            }
                        }
                    }
                }
                else
                {
                    // No updates available
                    await Messages.NoModUpdates.Show();
                }
            }
            catch (ApiException ex)
            {
                await MessageHelper.ShowMessageForApiException(ex);
            }
        }

19 Source : AsposePdfRedaction.cs
with MIT License
from aspose-pdf

public Response Redact(DoreplacedentInfo[] docs, string sourceFolder, string searchQuery, string replaceText,
		  bool caseSensitive, bool text, bool comments, bool metadata)
		{
			
			if (docs == null)
				return BadDoreplacedentResponse;
			if (docs.Length == 0 || docs.Length > MaximumUploadFiles)
				return MaximumFileLimitsResponse;

			SetDefaultOptions(docs, "");
			Opts.AppName = "Redaction";
			Opts.MethodName = "Redact";
			Opts.ZipFileName = "Redacted doreplacedents";
			Opts.FolderName = sourceFolder;
			Opts.OutputType = ".pdf";

			if (replaceText == null)
				replaceText = "";

			var statusValue = "OK";
			var statusCodeValue = 200;
			var fileProcessingErrorCode = FileProcessingErrorCode.OK;
			var lck = new object();
			var catchedException = false;

			if (IsValidRegex(searchQuery))
			{
				var regex = new Regex(searchQuery, caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase);
				var matchesFound = new int[docs.Length];
				var tasks = Enumerable.Range(0, docs.Length).Select(i => Task.Factory.StartNew(() =>
				{
					try
					{
						var doreplacedent = docs[i].PdfDoreplacedent;
						if (text)
						{
							var tfa = new Aspose.Pdf.Text.TextFragmentAbsorber(searchQuery, new TextSearchOptions(true));
							tfa.Visit(doreplacedent);
							foreach (var textFragment in tfa.TextFragments)
							{
								textFragment.Text = replaceText;
								matchesFound[i] += 1;
							}
						}

						if (comments)
						{
							foreach (var page in doreplacedent.Pages)
							{
								foreach (var item in page.Annotations)
								{
									if (item is TextMarkupAnnotation)
									{
										item.Contents = Regex.Replace(item.Contents, searchQuery, replaceText);
										matchesFound[i] += 1;
									}
								}
							}
						}

						if (metadata)
						{
							Pdf.DoreplacedentInfo docInfo = new Pdf.DoreplacedentInfo(doreplacedent);
							docInfo.replacedle = System.Text.RegularExpressions.Regex.Replace(docInfo.replacedle, searchQuery, replaceText);
							docInfo.Keywords = System.Text.RegularExpressions.Regex.Replace(docInfo.Keywords, searchQuery, replaceText);
							matchesFound[i] += 2;
						}




						//if (text || comments)
						//{
						//	var findings = new RedactionCallback(text, comments);
						//	var options = new FindReplaceOptions()
						//	{
						//		ReplacingCallback = findings,
						//		Direction = FindReplaceDirection.Forward,
						//		MatchCase = caseSensitive
						//	};
						//	docs[i].Range.Replace(regex, replaceText, options);
						//	matchesFound[i] += findings.MatchesFound;
						//}

						//if (metadata)
						//	matchesFound[i] += ProcessMetadata(docs[i].PdfDoreplacedent, regex, replaceText);
					}
					catch (Exception ex)
					{
						Console.WriteLine(ex.Message);
						lock (lck)
							catchedException = true;
						
					}
				})).ToArray();
				Task.WaitAll(tasks);

				if (!catchedException)
				{
					if (matchesFound.Sum() > 0)
						return  Process((inFilePath, outPath, zipOutFolder) =>
						{
							foreach (var doc in docs)
								SaveDoreplacedent(doc, outPath, zipOutFolder, new SaveFormatType() { SaveOptions = new PdfSaveOptions(), SaveType = SaveType.pdf });
						});

					fileProcessingErrorCode = FileProcessingErrorCode.NoSearchResults;
				}
				else
				{
					statusCodeValue = 500;
					statusValue = "500 Exception during processing";
				}
			}
			else
				fileProcessingErrorCode = FileProcessingErrorCode.WrongRegExp;

			return new Response
			{
				Status = statusValue,
				StatusCode = statusCodeValue,
				FileProcessingErrorCode = fileProcessingErrorCode
			};
		}

19 Source : Entry.cs
with GNU General Public License v3.0
from atomex-me

public decimal Qty()
        {
            return QtyProfile?.Sum() ?? 0;
        }

19 Source : Exemplo8.8.cs
with MIT License
from atrigo

static void Main(string[] args)
        {
            int[] v = new int[] { 3, 7, 4, 9, 2, 6, 7, 8, 9, 2 };

            Console.WriteLine("Soma dos valores: {0}", v.Sum());
            Console.WriteLine("Media dos valores: {0}", v.Average());
            Console.WriteLine("Valor minimo: {0}", v.Min());
            Console.WriteLine("Valor maximo: {0}", v.Max());
            if (v.Contains(5))
                Console.WriteLine("O vetor contem o numero 5.");
        }

19 Source : Book.Progress.cs
with GNU General Public License v3.0
from audiamus

public int TotalPhaseWeights () => _weightedPhases.Select (wp => wp.wght).Sum () * _numParts;

See More Examples