System.Func.Invoke(int)

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

969 Examples 7

19 View Source File : _.cs
License : MIT License
Project Creator : 0x0ade

public static List<T> GetList<T>(int count, Func<int, T> get) {
        if (count <= 0)
            return new List<T>();
        List<T> list = new List<T>(count);
        for (int i = 0; i < count; i++)
            list.Add(get(i));
        return list;
    }

19 View Source File : DictionaryExtension.cs
License : MIT License
Project Creator : a3geek

public static void SetCount<T1, T2>(this Dictionary<T1, T2> source, int count, Func<int, T1> defaultKey, Func<int, T2> defaultValue)
        {
            count = count < 0 ? 0 : count;

            if(source.Count < count)
            {
                for(var i = source.Count; i < count; i++)
                {
                    source.Add(defaultKey(i), defaultValue(i));
                }
            }
            else if(source.Count > count)
            {
                var maxCount = source.Count - count;

                for(var i = 0; i < maxCount; i++)
                {
                    source.Remove(source.Last().Key);
                }
            }
        }

19 View Source File : ListExtension.cs
License : MIT License
Project Creator : a3geek

public static void SetCount<T>(this List<T> list, int count, Func<int, T> defaultValue = null)
        {
            count = count < 0 ? 0 : count;
            defaultValue = defaultValue ?? (i => default(T));

            if(list.Count < count)
            {
                for(var i = list.Count; i < count; i++)
                {
                    list.Add(defaultValue(i));
                }
            }
            else if(list.Count > count)
            {
                list.RemoveRange(count, list.Count - count);
            }
        }

19 View Source File : SQLWriter.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

protected static void ValuesWriter(int count, Func<int, string> lineGenerator, StreamWriter writer)
        {
            for (int i = 0; i < count; i++)
            {
                string output;

                if (i == 0)
                    output = "VALUES (";
                else
                    output = "     , (";

                output += lineGenerator(i);

                if (i == count - 1)
                    output += ";";

                output = FixNullFields(output);

                writer.WriteLine(output);
            }
        }

19 View Source File : NodeComponentAutoCloner.cs
License : GNU General Public License v3.0
Project Creator : Adam-Wilkinson

private void CloneComponent()
        {
            if (_nameRule != null)
            {
                int index = 0;
                foreach (IVisualNodeComponent field in _originalClone.VisualComponentList)
                {
                    field.Name.Value = _nameRule(VisualComponentList.Count + index);
                    index++;
                }
            }

            ProtectedAdd(_originalClone.Clone());

            if (VisualComponentList.Count > 1)
            {
                this[^2].Opacity.Value = 1.0;
            }
        }

19 View Source File : NodeComponentAutoCloner.cs
License : GNU General Public License v3.0
Project Creator : Adam-Wilkinson

private void UpdateNames()
        {
            int index = 0;
            foreach (IVisualNodeComponent field in VisualComponentList)
            {
                field.Name.Value = _nameRule(index);
                index++;
            }
        }

19 View Source File : Command.cs
License : Apache License 2.0
Project Creator : adamralph

public static void Run(
            string name,
            string? args = null,
            string? workingDirectory = null,
            bool noEcho = false,
            string? windowsName = null,
            string? windowsArgs = null,
            string? echoPrefix = null,
            Action<IDictionary<string, string>>? configureEnvironment = null,
            bool createNoWindow = false,
            Func<int, bool>? handleExitCode = null,
            CancellationToken cancellationToken = default)
        {
            Validate(name);

            using var process = new Process();

            process.StartInfo = ProcessStartInfo.Create(
                RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? windowsName ?? name : name,
                (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? windowsArgs ?? args : args) ?? "",
                workingDirectory ?? "",
                false,
                configureEnvironment ?? defaultAction,
                createNoWindow);

            process.Run(noEcho, echoPrefix ?? defaultEchoPrefix, cancellationToken);

            if (!(handleExitCode?.Invoke(process.ExitCode) ?? false) && process.ExitCode != 0)
            {
                throw new ExitCodeException(process.ExitCode);
            }
        }

19 View Source File : Command.cs
License : Apache License 2.0
Project Creator : adamralph

public static async Task RunAsync(
            string name,
            string? args = null,
            string? workingDirectory = null,
            bool noEcho = false,
            string? windowsName = null,
            string? windowsArgs = null,
            string? echoPrefix = null,
            Action<IDictionary<string, string>>? configureEnvironment = null,
            bool createNoWindow = false,
            Func<int, bool>? handleExitCode = null,
            CancellationToken cancellationToken = default)
        {
            Validate(name);

            using var process = new Process();

            process.StartInfo = ProcessStartInfo.Create(
                RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? windowsName ?? name : name,
                (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? windowsArgs ?? args : args) ?? "",
                workingDirectory ?? "",
                false,
                configureEnvironment ?? defaultAction,
                createNoWindow);

            await process.RunAsync(noEcho, echoPrefix ?? defaultEchoPrefix, cancellationToken).ConfigureAwait(false);

            if (!(handleExitCode?.Invoke(process.ExitCode) ?? false) && process.ExitCode != 0)
            {
                throw new ExitCodeException(process.ExitCode);
            }
        }

19 View Source File : Command.cs
License : Apache License 2.0
Project Creator : adamralph

public static async Task<Result> ReadAsync(
            string name,
            string? args = null,
            string? workingDirectory = null,
            string? windowsName = null,
            string? windowsArgs = null,
            Action<IDictionary<string, string>>? configureEnvironment = null,
            Encoding? encoding = null,
            Func<int, bool>? handleExitCode = null,
            string? standardInput = null,
            CancellationToken cancellationToken = default)
        {
            Validate(name);

            using var process = new Process();

            process.StartInfo = ProcessStartInfo.Create(
                RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? windowsName ?? name : name,
                (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? windowsArgs ?? args : args) ?? "",
                workingDirectory ?? "",
                true,
                configureEnvironment ?? defaultAction,
                true,
                encoding);

            var runProcess = process.RunAsync(true, defaultEchoPrefix, cancellationToken);

            Task<string> readOutput;
            Task<string> readError;

            try
            {
                await process.StandardInput.WriteAsync(standardInput).ConfigureAwait(false);
                process.StandardInput.Close();

                readOutput = process.StandardOutput.ReadToEndAsync();
                readError = process.StandardError.ReadToEndAsync();
            }
            catch (Exception)
            {
                await runProcess.ConfigureAwait(false);
                throw;
            }

            await Task.WhenAll(runProcess, readOutput, readError).ConfigureAwait(false);

#pragma warning disable CA1849 // Call async methods when in an async method
            var output = readOutput.Result;
            var error = readError.Result;
#pragma warning restore CA1849 // Call async methods when in an async method

            return (handleExitCode?.Invoke(process.ExitCode) ?? false) || process.ExitCode == 0
                ? new Result(output, error)
                : throw new ExitCodeReadException(process.ExitCode, output, error);
        }

19 View Source File : POCatalog.cs
License : MIT License
Project Creator : adams85

public int GetPluralFormIndex(int n)
        {
            var count = _pluralFormCount;
            return
                --count > 0 ?
                Math.Max(Math.Min(count, _compiledPluralFormSelector(n)), 0) :
                count;
        }

19 View Source File : POCatalog.cs
License : MIT License
Project Creator : adams85

public string GetTranslation(POKey key, int n)
        {
            if (!TryGetValue(key, out IPOEntry entry))
                return null;

            var count = entry.Count;
            return
                count > 0 ?
                entry[--count > 0 ? Math.Max(Math.Min(count, _compiledPluralFormSelector(n)), 0) : 0] :
                null;
        }

19 View Source File : Deserializer.cs
License : MIT License
Project Creator : ADeltaX

public static T[] GetArray<T>(int length, int sizeOfPrimitiveType, Func<int, T> arr)
        {
            List<T> list = new List<T>();
            for (int i = 0; i < length; i += sizeOfPrimitiveType)
                list.Add(arr(i));

            return list.ToArray();
        }

19 View Source File : Deserializer.cs
License : MIT License
Project Creator : ADeltaX

public static T[] GetArray<T>(int index, int length, int sizeOfPrimitiveType, Func<int, T> arr)
        {
            List<T> list = new List<T>();
            for (int i = index; i < length + index; i += sizeOfPrimitiveType)
                list.Add(arr(i));

            return list.ToArray();
        }

19 View Source File : TopPaginator.cs
License : MIT License
Project Creator : Adoxio

private int Gereplacedems(int topLimit, int unfilteredItemOffset, int itemLimit, ICollection<T> items)
		{
			var top = _getTop(topLimit);

			if (unfilteredItemOffset >= top.TotalUnfilteredItems)
			{
				return top.TotalUnfilteredItems;
			}

			foreach (var item in top.Skip(unfilteredItemOffset))
			{
				unfilteredItemOffset++;

				if (!_selector(item))
				{
					continue;
				}

				items.Add(item);

				if (items.Count >= itemLimit)
				{
					return top.TotalUnfilteredItems;
				}
			}

			if (topLimit >= top.TotalUnfilteredItems)
			{
				return items.Count;
			}

			return Gereplacedems(topLimit * _extendedSearchLimitMultiple, unfilteredItemOffset, itemLimit, items);
		}

19 View Source File : ILASTBuilder.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private ILASTTree BuildAST(CILInstrList instrs, ILASTVariable[] beginStack)
        {
            var tree = new ILASTTree();
            var evalStack = new Stack<ILASTVariable>(beginStack);
            Func<int, IILASTNode[]> popArgs = numArgs =>
            {
                var args = new IILASTNode[numArgs];
                for(var i = numArgs - 1; i >= 0; i--)
                    args[i] = evalStack.Pop();
                return args;
            };

            var prefixes = new List<Instruction>();
            foreach(var instr in instrs)
            {
                if(instr.OpCode.OpCodeType == OpCodeType.Prefix)
                {
                    prefixes.Add(instr);
                    continue;
                }

                int pushes, pops;
                ILASTExpression expr;
                if(instr.OpCode.Code == Code.Dup)
                {
                    pushes = pops = 1;

                    var arg = evalStack.Peek();
                    expr = new ILASTExpression
                    {
                        ILCode = Code.Dup,
                        Operand = null,
                        Arguments = new IILASTNode[] {arg}
                    };
                }
                else
                {
                    instr.CalculateStackUsage(method.ReturnType.ElementType != ElementType.Void, out pushes, out pops);
                    Debug.replacedert(pushes == 0 || pushes == 1);

                    if(pops == -1)
                    {
                        evalStack.Clear();
                        pops = 0;
                    }

                    expr = new ILASTExpression
                    {
                        ILCode = instr.OpCode.Code,
                        Operand = instr.Operand,
                        Arguments = popArgs(pops)
                    };
                    if(expr.Operand is Instruction || expr.Operand is Instruction[])
                        instrReferences.Add(expr);
                }
                expr.CILInstr = instr;
                if(prefixes.Count > 0)
                {
                    expr.Prefixes = prefixes.ToArray();
                    prefixes.Clear();
                }

                if(pushes == 1)
                {
                    var variable = new ILASTVariable
                    {
                        Name = string.Format("s_{0:x4}", instr.Offset),
                        VariableType = ILASTVariableType.StackVar
                    };
                    evalStack.Push(variable);

                    tree.Add(new ILASTreplacedignment
                    {
                        Variable = variable,
                        Value = expr
                    });
                }
                else
                {
                    tree.Add(expr);
                }
            }
            tree.StackRemains = evalStack.Reverse().ToArray();
            return tree;
        }

19 View Source File : CalculateFunction.cs
License : MIT License
Project Creator : AElfProject

public long CalculateFee(int totalCount)
        {
            if (CalculateFeeCoefficients.PieceCoefficientsList.Count != _currentCalculateFunctions.Count)
            {
                throw new ArgumentOutOfRangeException(nameof(_currentCalculateFunctions),
                    "Coefficients count not match.");
            }

            var remainCount = totalCount;
            var result = 0L;
            var pieceStart = 0;
            for (var i = 0; i < _currentCalculateFunctions.Count; i++)
            {
                var function = _currentCalculateFunctions[i];
                var pieceCoefficient = CalculateFeeCoefficients.PieceCoefficientsList[i].Value;
                var pieceUpperBound = pieceCoefficient[0];
                var interval = pieceUpperBound - pieceStart;
                pieceStart = pieceUpperBound;
                var count = Math.Min(interval, remainCount);
                result += function(count);
                if (pieceUpperBound > totalCount)
                {
                    break;
                }

                remainCount -= interval;
            }

            return result;
        }

19 View Source File : ScrollView.cs
License : MIT License
Project Creator : aillieo

Vector2 GereplacedemSize(int index)
        {
            if(index >= 0 && index <= m_dataCount)
            {
                if (itemSizeFunc != null)
                {
                    return itemSizeFunc(index);
                }
            }
            return defaulreplacedemSize;
        }

19 View Source File : ScrollView.cs
License : MIT License
Project Creator : aillieo

private RectTransform GetNewItem(int index)
        {
            RectTransform item;
            if(itemGetFunc != null)
            {
                item = itemGetFunc(index);
            }
            else
            {
                item = itemPool.Get();
            }
            return item;
        }

19 View Source File : ScrollViewEx.cs
License : MIT License
Project Creator : aillieo

public override void SereplacedemSizeFunc(Func<int, Vector2> func)
        {
            if (func != null)
            {
                var f = func;
                func = (index) => {
                    return f(index + startOffset);
                };
            }
            base.SereplacedemSizeFunc(func);
        }

19 View Source File : RetryEngine.cs
License : MIT License
Project Creator : AiursoftWeb

public async Task<T> RunWithTry<T>(
            Func<int, Task<T>> taskFactory,
            int attempts = 3,
            Predicate<Exception> when = null)
        {
            for (var i = 1; i <= attempts; i++)
            {
                try
                {
                    this.logger.LogDebug($"Starting a job with retry. Attempt: {i}. (Starts from 1)");
                    var response = await taskFactory(i);
                    return response;
                }
                catch (Exception e)
                {
                    if (when != null)
                    {
                        var shouldRetry = when.Invoke(e);
                        if (!shouldRetry)
                        {
                            this.logger.LogWarning($"A task that was asked to retry failed. {e.Message} But from the given condition is false, we gave up retry.");
                            throw;
                        }
                        else
                        {
                            this.logger.LogInformation($"A task that was asked to retry failed. {e.Message} With given condition is true.");
                        }
                    }

                    if (i >= attempts)
                    {
                        this.logger.LogWarning($"A task that was asked to retry failed. {e.Message} Maximum attempts {attempts} already reached. We have to crash it.");
                        throw;
                    }

                    this.logger.LogCritical($"A task that was asked to retry failed. {e.Message} Current attempt is {i}. maximum attempts is {attempts}. Will retry soon...");

                    await Task.Delay(ExponentialBackoffTimeSlot(i) * 1000);
                }
            }

            throw new InvalidOperationException("Code shall not reach here.");
        }

19 View Source File : IDomainResultValueTests.cs
License : Apache License 2.0
Project Creator : AKlaus

[Fact]
		public void Implicitly_Convert_DomainResult_Test()
		{
			// If the code below gets complied, then implicit conversion works

			Func<int, DomainResult<int>> func = (i) => i;
			var res = func(10);
		}

19 View Source File : KafkaIntegrationTests.cs
License : Apache License 2.0
Project Creator : akkadotnet

protected async Task ProduceStrings<TKey>(Func<int, TopicParreplacedion> parreplacedionSelector, IEnumerable<int> range, ProducerSettings<TKey, string> producerSettings)
        {
            await Source
                .From(range)
                .Select(elem => new ProducerRecord<TKey, string>(parreplacedionSelector(elem), elem.ToString()))
                .RunWith(KafkaProducer.PlainSink(producerSettings), Materializer);
        }

19 View Source File : DynamicTree.cs
License : MIT License
Project Creator : Alan-FGR

public void Query(Func<int, bool> callback, ref AABB aabb)
        {
            _queryStack.Clear();
            _queryStack.Push(_root);

            while (_queryStack.Count > 0)
            {
                int nodeId = _queryStack.Pop();
                if (nodeId == NullNode)
                {
                    continue;
                }

                TreeNode<T> node = _nodes[nodeId];

                if (AABB.TestOverlap(ref node.AABB, ref aabb))
                {
                    if (node.IsLeaf())
                    {
                        bool proceed = callback(nodeId);
                        if (proceed == false)
                        {
                            return;
                        }
                    }
                    else
                    {
                        _queryStack.Push(node.Child1);
                        _queryStack.Push(node.Child2);
                    }
                }
            }
        }

19 View Source File : QueryResponseFactory.cs
License : MIT License
Project Creator : AllocZero

public static byte[] CreateResponse(Func<int, Doreplacedent> enreplacedyFactory, int itemsCount)
        {
            using var stream = new MemoryStream();
            using var writer = new Utf8JsonWriter(stream);
           
            writer.WriteStartObject();
            writer.WriteNumber("Count", itemsCount);
           
            writer.WritePropertyName("Items");
            writer.WriteStartArray();

            for (var i = 0; i < itemsCount; i++)
                writer.WriteAttributesDictionary(enreplacedyFactory(i));
            
            writer.WriteEndArray();

            writer.WriteNumber("ScannedCount", itemsCount);
            
            writer.WriteEndObject();
            writer.Flush();

            stream.Position = 0;
            return stream.ToArray();
        }

19 View Source File : CardinalPluralFormatProvider.cs
License : GNU General Public License v3.0
Project Creator : Amebis

public string Format(string format, object arg, IFormatProvider formatProvider)
        {
            string[] forms = format.Split('|');
            if (arg is int n)
            {
                if (CardinalPluralizers.TryGetValue(System.Threading.Thread.CurrentThread.CurrentUICulture.IetfLanguageTag, out var pluralizer) ||
                    CardinalPluralizers.TryGetValue(System.Threading.Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName, out pluralizer) ||
                    CardinalPluralizers.TryGetValue("", out pluralizer))
                {
                    int form = pluralizer(n >= 0 ? n : -n);
                    if (form >= forms.Length)
                        throw new ArgumentException(string.Format("Numeral {0} should use {1}. plural form, but \"{2}\" provides only {3} plural form(s).", n, form + 1, format, forms.Length));
                    return
                        CardinalSpacing.TryGetValue(System.Threading.Thread.CurrentThread.CurrentUICulture.IetfLanguageTag, out var spacing) ||
                        CardinalSpacing.TryGetValue(System.Threading.Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName, out spacing) ||
                        CardinalSpacing.TryGetValue("", out spacing) ? n.ToString() + spacing + forms[form] : n.ToString() + " " + forms[form];
                }
            }
            return arg.ToString();
        }

19 View Source File : HyndmanFanHelper.cs
License : MIT License
Project Creator : AndreyAkinshin

public static double Evaluate(HyndmanFanType type, int n, Probability p, Func<int, double> getValue)
        {
            double h = GetH(type, n, p);

            double LinearInterpolation()
            {
                int hFloor = (int)h;
                double fraction = h - hFloor;
                if (hFloor + 1 <= n)
                    return getValue(hFloor) * (1 - fraction) + getValue(hFloor + 1) * fraction;
                return getValue(hFloor);
            }

            return type switch
            {
                HyndmanFanType.Type1 => getValue((int)Math.Ceiling(h - 0.5)),
                HyndmanFanType.Type2 => (getValue((int)Math.Ceiling(h - 0.5)) + getValue((int)Math.Floor(h + 0.5))) / 2,
                HyndmanFanType.Type3 => getValue((int)Math.Round(h, MidpointRounding.ToEven)),
                _ => LinearInterpolation()
            };

19 View Source File : Rqq.cs
License : MIT License
Project Creator : AndreyAkinshin

public void DumpTreeAscii([NotNull] StreamWriter writer, bool details = false)
        {
            var valuesStr = values.Select(v => v.ToString(CultureInfo.InvariantCulture)).ToArray(); // TODO: precision

            // Calculate width for each node
            var width = new int[nodeCount];
            for (int node = 0; node < nodeCount; node++)
            {
                width[node] += rangeRight[node] - rangeLeft[node] + 2; // result += <widths of spaces>
                if (kinds[node] != NodeKind.Fake)
                    for (int i = rangeLeft[node]; i <= rangeRight[node]; i++)
                        width[node] += valuesStr[i].Length; // result += <widths of values>
                width[node] += 2; // result += <widths of borders>
            }

            // Calculate padding for each node and connector-with-child positions 
            var paddingLeft = new int[nodeCount];
            var paddingRight = new int[nodeCount];
            var connectorDownLeft = new int[nodeCount];
            var connectorDownRight = new int[nodeCount];
            var connectorUp = new int[nodeCount];
            for (int node = nodeCount - 1; node >= 0; node--)
            {
                if (kinds[node] == NodeKind.Parent)
                {
                    int child1 = node * 2 + 1;
                    int child2 = node * 2 + 2;
                    int totalWidth1 = paddingLeft[child1] + width[child1] + paddingRight[child1];
                    int totalWidth2 = paddingLeft[child2] + width[child2] + paddingRight[child2];
                    int childrenWidth = totalWidth1 + 1 + totalWidth2;

                    int padding = Math.Max(0, childrenWidth - width[node]);
                    paddingLeft[node] = paddingLeft[child1] + width[child1] +
                                        (paddingRight[child1] + 1 + paddingLeft[child2]) / 2 -
                                        width[node] / 2;
                    paddingRight[node] = padding - paddingLeft[node];

                    connectorDownLeft[node] = 1;
                    connectorDownRight[node] = width[node] - 2;
                    connectorUp[child1] = paddingLeft[node] + connectorDownLeft[node] - paddingLeft[child1];
                    connectorUp[child2] = paddingLeft[node] + connectorDownRight[node] -
                                          (totalWidth1 + 1) - paddingLeft[child2];
                }
            }

            int layer = -1;
            while (true)
            {
                layer++;
                int node2 = (1 << (layer + 1)) - 2;
                int node1 = node2 - (1 << layer) + 1;
                if (node1 >= nodeCount)
                    break;

                void DumpLine(char leftBorder, char separator, char rightBorder, Func<int, string> element,
                    char? down = null, char? up = null)
                {
                    for (int node = node1; node <= node2; node++)
                    {
                        if (kinds[node] == NodeKind.Fake)
                        {
                            if (node % 2 == 1) // It's a left child
                            {
                                int parentIndex = (node - 1) / 2;
                                int parentWidth = 1 + paddingLeft[parentIndex] + width[parentIndex] +
                                                  paddingRight[parentIndex];
                                for (int j = 0; j < parentWidth; j++)
                                    writer.Write(' ');
                            }

                            continue;
                        }

                        int position = -paddingLeft[node];

                        void PrintChar(char c)
                        {
                            if (kinds[node] == NodeKind.Parent && down.HasValue &&
                                (position == connectorDownLeft[node] ||
                                 position == connectorDownRight[node]))
                                writer.Write(down.Value);
                            else if (position == connectorUp[node] && node > 0 && up.HasValue)
                                writer.Write(up.Value);
                            else
                                writer.Write(c);
                            position++;
                        }

                        void PrintString(string s)
                        {
                            foreach (var c in s)
                                PrintChar(c);
                        }

                        for (int j = 0; j < paddingLeft[node]; j++)
                            PrintChar(' ');
                        PrintChar(leftBorder);
                        PrintChar(separator);

                        for (int i = rangeLeft[node]; i <= rangeRight[node]; i++)
                        {
                            string elementStr = element(i);
                            int elementPadding = Math.Max(0, valuesStr[i].Length - elementStr.Length);
                            for (int j = 0; j < elementPadding; j++)
                                PrintChar(separator);
                            PrintString(elementStr);
                            if (i != rangeRight[node])
                                PrintChar(separator);
                        }

                        PrintChar(separator);
                        PrintChar(rightBorder);
                        for (int j = 0; j < paddingRight[node]; j++)
                            PrintChar(' ');
                        if (node != node2)
                            PrintChar(' ');
                    }

                    writer.WriteLine();
                }

                DumpLine('┌', '─', '┐', i => "─", up: '┴');
                DumpLine('│', ' ', '│', i => valuesStr[i]);
                DumpLine('│', ' ', '│', i => b[i] == BinaryFlag.NotDefined ? " " : ((int) b[i]).ToString());
                DumpLine('└', '─', '┘', i => "─", down: '┬');
                DumpLine(' ', ' ', ' ', i => "", down: '│');
            }

            writer.WriteLine();

            if (details)
            {
                for (int node = 0; node < nodeCount; node++)
                {
                    writer.Write('#');
                    writer.Write(node.ToString());
                    writer.Write(": ");

                    switch (kinds[node])
                    {
                        case NodeKind.Parent:
                            writer.Write("NODE(");
                            for (int i = rangeLeft[node]; i <= rangeRight[node]; i++)
                            {
                                writer.Write(valuesStr[i]);
                                if (i != rangeRight[node])
                                    writer.Write(',');
                            }

                            writer.Write("); Children = { #");
                            writer.Write(node * 2 + 1);
                            writer.Write(", #");
                            writer.Write(node * 2 + 2);
                            writer.WriteLine(" }");
                            break;
                        case NodeKind.Leaf:
                            writer.Write("LEAF(");
                            writer.Write(valuesStr[rangeLeft[node]]);
                            writer.WriteLine(")");
                            break;
                        case NodeKind.Fake:
                            writer.WriteLine("FAKE");
                            break;
                        default:
                            throw new ArgumentOutOfRangeException();
                    }
                }

                writer.WriteLine();
                writer.WriteLine("Allocated values : " + values.Length);
                writer.WriteLine("Used values      : " + usedValues);
            }

            writer.Flush();
        }

19 View Source File : IMGUI.cs
License : MIT License
Project Creator : Apostolique

private void FindFocus(Func<int, IComponent> getNeighbor) {
            int initialFocus = Id;
            if (Focus != null) {
                initialFocus = Focus.Value;
            }
            int newFocus = initialFocus;
            do {
                var c = getNeighbor(newFocus);
                newFocus = c.Id;
                if (c.IsFocusable) {
                    GrabFocus(c);
                    return;
                }
            } while (initialFocus != newFocus);
        }

19 View Source File : ARSimpleFragmentPagerAdapter.cs
License : Apache License 2.0
Project Creator : AppRopio

public override Java.Lang.ICharSequence GetPagereplacedleFormatted(int position)
        {
            return new Java.Lang.String(GetreplacedleFunc?.Invoke(position) ?? string.Empty);
        }

19 View Source File : BinaryPatcher.cs
License : MIT License
Project Creator : arcusmaximus

public void PatchAddress(int originalOffset)
        {
            if (originalOffset < 0 || originalOffset + 4 > _inputStream.Length)
                throw new ArgumentOutOfRangeException(nameof(originalOffset));

            if (_inputStream.Position < originalOffset + 4)
                throw new InvalidOperationException();

            int inputPos = (int)_inputStream.Position;
            _inputStream.Position = originalOffset;
            int originalAddr = _reader.ReadInt32();
            _inputStream.Position = inputPos;

            int newOffset = MapOffset(originalOffset);
            int newAddr = _offsetToAddress(MapOffset(_addressToOffset(originalAddr)));

            _outputStream.Position = newOffset;
            _writer.Write(newAddr);
            _outputStream.Position = _outputStream.Length;
        }

19 View Source File : OutboxContextSql.cs
License : MIT License
Project Creator : ARKlab

public async Task<IEnumerable<OutboxMessage>> PeekLockMessagesAsync(int messageCount = 10, CancellationToken ctk = default)
        {
            var cmd = new CommandDefinition(_statements.PeekLock(messageCount), transaction: this.Transaction, cancellationToken: ctk);

            var res = await this.Connection.QueryAsync<(string Headers, byte[] Body)>(cmd).ConfigureAwait(false);

            return res.Select(x => new OutboxMessage
            {
                Body = x.Body,
                Headers = _headerSerializer.DeserializeFromString(x.Headers)
            }).ToList();
        }

19 View Source File : MapSelectionUI.cs
License : MIT License
Project Creator : ArnaudValensi

void LoadWorlds() {
		worldsManager = GameObject.Find("/Managers/WorldsManager").GetComponent<WorldsManager>();
		mapInfos = worldsManager.GetWorldList().ToArray();
		mapSelectionButtons = new MapSelectionButton[mapInfos.Length];

		foreach (Transform child in mapsHolder) {
			Destroy(child.gameObject);
		}

		int i = 0;
		foreach (var mapInfo in mapInfos) {
			GameObject newMap = Instantiate(mapPrefab, mapsHolder);
			MapSelectionButton mapSelectionButton = newMap.GetComponent<MapSelectionButton>();

			mapSelectionButtons[i] = mapSelectionButton;
			mapSelectionButton.Init(mapInfo.name, mapInfo.folderName, mapInfo.date);

			Func<int, Action> CreateClickAction = (index) => () => SelectMap(index);

			mapSelectionButton.OnClicked += CreateClickAction(i);

			i++;
		}
	}

19 View Source File : AMPlotter.cs
License : MIT License
Project Creator : asc-community

private void BuildData(Func<int, double> X, Func<int, double> Y)
        {
            for(int i = 0; i < pointCount; i++)
            {
                dataX[i] = X(i);
                dataY[i] = Y(i);
            }
        }

19 View Source File : GetMatrixFactoryTest.cs
License : MIT License
Project Creator : asc-community

[DataTestMethod]
        [DataRow(5)]
        [DataRow(3)]
        [DataRow(1)]
        [DataRow(2)]
        [DataRow(4)]
        public void TestMatrix(int diagLength)
        {
            replacedert.AreEqual(new TensorShape(diagLength, diagLength), GetMatrix(diagLength).Shape);
            replacedert.AreEqual(new TensorShape(diagLength, diagLength), GetMatrix(diagLength).Shape);
        }

19 View Source File : AppBuilderTests.cs
License : Apache License 2.0
Project Creator : aspnet

public Func<int, string> Invoke(Func<int, string> app)
            {
                return call => app(call) + _value;
            }

19 View Source File : AppBuilderTests.cs
License : Apache License 2.0
Project Creator : aspnet

public string Invoke(int call)
            {
                return _app(call) + _value;
            }

19 View Source File : BooleanDecisionTree.cs
License : MIT License
Project Creator : AutomataDotNet

private static bool[] Precompute(CharSetSolver solver, BDD domain, int precomputeLimit)
        {
            bool[] precomp = new bool[precomputeLimit + 1];
            Func<int, bool> F = i =>
            {
                var bdd = solver.MkCharConstraint((char)i);
                if (solver.IsSatisfiable(solver.MkAnd(bdd, domain)))
                    return true;
                else
                    return false;
            };
            for (int c = 0; c <= precomputeLimit; c++)
            {
                precomp[c] = F(c);
            }
            return precomp;
        }

19 View Source File : DecisionTree.cs
License : MIT License
Project Creator : AutomataDotNet

private static int[] Precompute(CharSetSolver solver, BDD[] parreplacedion, int precomputeLimit)
        {
            int[] precomp = new int[precomputeLimit + 1];
            Func<int, int> GetParreplacedionId = i =>
            {
                for (int j = 0; j < parreplacedion.Length; j++)
                {
                    var i_bdd = solver.MkCharConstraint((char)i);
                    if (solver.IsSatisfiable(solver.MkAnd(i_bdd, parreplacedion[j])))
                    {
                        return j;
                    }
                }
                return -1;
            };
            for (int c = 0; c <= precomputeLimit; c++)
            {
                int id = GetParreplacedionId(c);
                if (id < 0)
                    throw new AutomataException(AutomataExceptionKind.InternalError);
                precomp[c] = id;
            }
            return precomp;
        }

19 View Source File : BV64Algebra.cs
License : MIT License
Project Creator : AutomataDotNet

internal BV64Algebra ReplaceMintermsWithVisibleCharacters()
        {
            Func<int, int> f = x =>
            {
                int k;
                if (x <= 26)
                    k = ('A' + (x - 1));
                else if (x <= 52)
                    k = ('a' + (x - 27));
                else if (x <= 62)
                    k = ('0' + (x - 53));
                else
                    k = '=';
                return k;
            };
            var simplified_parreplacedion = new IntervalSet[this.parreplacedion.Length];
            int[] precomp = new int[256];
            for (int i=1; i < simplified_parreplacedion.Length; i++)
            {
                int k = f(i);
                simplified_parreplacedion[i] = new IntervalSet(new Tuple<uint, uint>((uint)k,(uint)k));
                precomp[k] = i;
            }
            var zeroIntervals = new List<Tuple<uint, uint>>();
            int lower = 0;
            int upper = 0;
            for (int i = 1; i <= 'z' + 1; i++)
            {
                if (precomp[i] == 0)
                {
                    if (upper == i - 1)
                        upper += 1;
                    else
                    {
                        zeroIntervals.Add(new Tuple<uint, uint>((uint)lower, (uint)upper));
                        lower = i;
                        upper = i;
                    }             
                }
            }
            zeroIntervals.Add(new Tuple<uint, uint>((uint)lower, 0xFFFF));
            simplified_parreplacedion[0] = new IntervalSet(zeroIntervals.ToArray());

            var simplified_dtree = new DecisionTree(precomp, new DecisionTree.BST(0, null, null));
            return new BV64Algebra(simplified_dtree, simplified_parreplacedion);
        }

19 View Source File : GraphicsAdapter.cs
License : MIT License
Project Creator : AvaloniaUI

private static int BinarySearch(Func<int, int> condition, int start, int end)
        {
            do
            {
                int ind = start + (end - start)/2;
                int res = condition(ind);
                if (res == 0)
                    return ind;
                else if (res > 0)
                {
                    if (start != ind)
                        start = ind;
                    else
                        start = ind + 1;
                }
                else
                    end = ind;

            } while (end > start);
            return -1;
        }

19 View Source File : PersonManager.cs
License : MIT License
Project Creator : Avanade

public async Task<int> DataSvcCustomAsync() => await ManagerInvoker.Current.InvokeAsync(this, async () =>
        {
            await (_dataSvcCustomOnPreValidateAsync?.Invoke() ?? Task.CompletedTask).ConfigureAwait(false);

            await MultiValidator.Create()
                .Additional((__mv) => _dataSvcCustomOnValidate?.Invoke(__mv))
                .RunAsync(throwOnError: true).ConfigureAwait(false);

            await (_dataSvcCustomOnBeforeAsync?.Invoke() ?? Task.CompletedTask).ConfigureAwait(false);
            var __result = await _dataService.DataSvcCustomAsync().ConfigureAwait(false);
            await (_dataSvcCustomOnAfterAsync?.Invoke(__result) ?? Task.CompletedTask).ConfigureAwait(false);
            return Cleaner.Clean(__result);
        }, BusinessInvokerArgs.Unspecified).ConfigureAwait(false);

19 View Source File : RandomExtension.cs
License : MIT License
Project Creator : Avatarchik

public static int Choose(this ref Random random, Func<int, float> getProbability, int startIndex, int count)
        {
            int lastIndex = startIndex + count - 1;
            float rest = (float)random.Next01();
            float current;

            for (; startIndex < lastIndex; startIndex++)
            {
                current = getProbability(startIndex);
                if (rest < current) return startIndex;
                else rest -= current;
            }

            return lastIndex;
        }

19 View Source File : AssertionHelper.cs
License : MIT License
Project Creator : awaescher

public static void Expect(
			this DefaultRepositoryMonitor monitor,
			Action act,
			Func<int, bool> changesreplacedertion,
			Func<int, bool> deletesreplacedertion)
		{
			ExpectInternal(monitor, act, out int actualChanges, out int actualDeletes);

			changesreplacedertion(actualChanges).Should().BeTrue();
			deletesreplacedertion(actualDeletes).Should().BeTrue();
		}

19 View Source File : NumberExtensions.cs
License : MIT License
Project Creator : ay2015

public static IEnumerable<T> Times<T>(this int num, Func<int, T> block)
        {
            for (int i = 0; i < num; i++)
            {
                yield return block(i);
            }
        }

19 View Source File : SerializerForm2.cs
License : MIT License
Project Creator : azist

private void brnDynreplaced_Click(object sender, EventArgs e)
          {
            prepare();


              var asmBuilder = AppDomain.CurrentDomain.DefineDynamicreplacedembly(
                    new replacedemblyName("ZmeyaTeztx"), replacedemblyBuilderAccess.Run);
              var modBuilder = asmBuilder.DefineDynamicModule("myModule");
              var tpBuilder = modBuilder.DefineType("myType_1", TypeAttributes.Public);
              var methodBuilder = tpBuilder.DefineMethod(
                           "myMethod_1", MethodAttributes.Public | MethodAttributes.Static);
              expression1.CompileToMethod(methodBuilder);
              var tp = tpBuilder.CreateType();
              var asmF1 = (Func<int, int>)Delegate.CreateDelegate( typeof(Func<int, int>), this, tp.GetMethod("myMethod_1"));

              Text = asmF1(5).ToString();

              tpBuilder = modBuilder.DefineType("myType_2", TypeAttributes.Public);
              methodBuilder = tpBuilder.DefineMethod(
                           "myMethod_2", MethodAttributes.Public | MethodAttributes.Static);

              expression2.CompileToMethod(methodBuilder);
              tp = tpBuilder.CreateType();
              var asmF2 = (Func<int, int>)Delegate.CreateDelegate( typeof(Func<int, int>), this, tp.GetMethod("myMethod_2"));

              Text += "    "+asmF2(5).ToString();

              test1(this, 2);
              test2(this, 3);
              test3(3);

              const int CNT = 500000000;
              for(var i=0; i<500000000; i++);

              var w = Stopwatch.StartNew();


              w.Restart();
              for(var i=0; i<CNT; i++)  asmF1(3);
              var ts1 = w.ElapsedMilliseconds;

              w.Restart();
              for(var i=0; i<CNT; i++)  asmF2(3);
              var ts2 = w.ElapsedMilliseconds;

              w.Restart();
              for(var i=0; i<CNT; i++)  test1(this, 3);
              var ts3 = w.ElapsedMilliseconds;

              w.Restart();
              for(var i=0; i<CNT; i++)  test2(this, 3);
              var ts4 = w.ElapsedMilliseconds;

              w.Restart();
              for(var i=0; i<CNT; i++)  test3(3);
              var ts5 = w.ElapsedMilliseconds;


              Text = "T1: {0:n2}/sec  T2: {1:n2}/sec  T3: {2:n2}/sec  T4: {3:n2}/sec T5: {4:n2}/sec".Args
                      (
                         CNT / (ts1 / 1000d),
                         CNT / (ts2 / 1000d),
                         CNT / (ts3 / 1000d),
                         CNT / (ts4 / 1000d),
                         CNT / (ts5 / 1000d)
                      );
          }

19 View Source File : IListExt.cs
License : MIT License
Project Creator : baba-s

public static void FillBy<T>( this IList<T> list, Func<int, T> func, int count )
		{
			int listcount = list.Count;
			for ( int i = 0; i < count; i++ )
			{
				if ( i < listcount )
				{
					list[ i ] = func( i );
				}
				else
				{
					list.Add( func( i ) );
				}
			}
		}

19 View Source File : CardHelper.cs
License : MIT License
Project Creator : banksystembg

public bool CheckLuhn(string creditCardNumber)
        {
            var checkSum = creditCardNumber
                .ToCharArray()
                .Where(c => !char.IsWhiteSpace(c))
                .ToArray()
                .Select(CharToInt)
                .Reverse()
                .Select((digit, index) => this.isEven(index + 1) ? this.doubleDigit(digit) : digit)
                .Sum();

            return checkSum % 10 == 0;
        }

19 View Source File : CardHelper.cs
License : MIT License
Project Creator : banksystembg

private string CreateCheckDigit(string number)
        {
            var digitsSum = number
                .ToCharArray()
                .Where(c => !char.IsWhiteSpace(c))
                .ToArray()
                .Reverse()
                .Select(CharToInt)
                .Select((digit, index) => this.isEven(index) ? this.doubleDigit(digit) : digit)
                .Sum();

            digitsSum *= 9;

            return digitsSum
                .ToString()
                .ToCharArray()
                .Last()
                .ToString();
        }

19 View Source File : NumbersTestData.cs
License : MIT License
Project Creator : bartoszlenar

public static IEnumerable<object[]> EqualTo_Signed<T>(Func<int, T> convert)
        {
            yield return new object[] { convert(0), convert(-1), false };
            yield return new object[] { convert(-2), convert(-5), false };
            yield return new object[] { convert(-1), convert(-1), true };
            yield return new object[] { convert(-2), convert(2), false };
        }

19 View Source File : NumbersTestData.cs
License : MIT License
Project Creator : bartoszlenar

public static IEnumerable<object[]> NotEqualTo_Unsigned<T>(Func<int, T> convert)
        {
            yield return new object[] { convert(0), convert(3), true };
            yield return new object[] { convert(2), convert(5), true };
            yield return new object[] { convert(1), convert(1), false };
        }

See More Examples