System.Collections.Generic.IEnumerable.Last()

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

4249 Examples 7

19 Source : Dumper.cs
with MIT License
from 13xforever

private List<string> EnumeratePhysicalDrivesLinux()
        {
            var cdInfo = "";
            try
            {
                cdInfo = File.ReadAllText("/proc/sys/dev/cdrom/info");
            }
            catch (Exception e)
            {
                Log.Debug(e, e.Message);
            }
            var lines = cdInfo.Split(MultilineSplit, StringSplitOptions.RemoveEmptyEntries);
            return lines.Where(s => s.StartsWith("drive name:")).Select(l => Path.Combine("/dev", l.Split(':').Last().Trim())).Where(File.Exists)
                    .Concat(IOEx.GetFilepaths("/dev", "sr*", SearchOption.TopDirectoryOnly))
                    .Distinct()
                    .ToList();

        }

19 Source : ExpressionActivator.cs
with Apache License 2.0
from 1448376744

private Expression CreateExpression(ParameterExpression parameter, string expression)
        {
            var expressions1 = Factorization(expression);
            var expressions2 = new Dictionary<string, Expression>();
            foreach (var item in expressions1)
            {
                var subexpr = item.Value.Trim('(', ')');
                var @opterator = ResovleOperator(item.Value);
                var opt = GetExpressionType(@opterator);
                if (opt == ExpressionType.Not)
                {
                    Expression exp;
                    var text = subexpr.Split(new string[] { @opterator }, StringSplitOptions.RemoveEmptyEntries)[0].Trim();
                    if (expressions2.ContainsKey(text))
                    {
                        exp = expressions2[text];
                    }
                    else if (parameter.Type.GetProperties().Any(a => a.Name == text))
                    {
                        var property = parameter.Type.GetProperty(text);
                        exp = Expression.MakeMemberAccess(parameter, property);
                    }
                    else
                    {
                        exp = Expression.Constant(Convert.ToBoolean(text));
                    }
                    expressions2.Add(item.Key, Expression.MakeUnary(opt, exp, null));
                }
                else
                {
                    var text1 = subexpr
                        .Split(new string[] { @opterator }, StringSplitOptions.RemoveEmptyEntries)[0]
                        .Trim();
                    var text2 = subexpr
                        .Split(new string[] { @opterator }, StringSplitOptions.RemoveEmptyEntries)[1]
                        .Trim();
                    string temp = null;
                    Expression exp1, exp2;
                    //永远将变量放在第一个操作数
                    if (parameter.Type.GetProperties().Any(a => a.Name == text2))
                    {
                        temp = text1;
                        text1 = text2;
                        text2 = temp;
                    }
                    //是否为上一次的分式
                    if (expressions2.ContainsKey(text1))
                    {
                        exp1 = expressions2[text1];
                    }
                    else if (parameter.Type.GetProperties().Any(a => a.Name == text1))
                    {
                        //是否为变量
                        var property = parameter.Type.GetProperty(text1);
                        exp1 = Expression.MakeMemberAccess(parameter, property);
                    }
                    else
                    {
                        exp1 = ResovleConstantExpression(text1);
                    }
                    //是否为上一次的分式
                    if (expressions2.ContainsKey(text2))
                    {
                        exp2 = expressions2[text2];
                    }
                    //如果第一个操作数是变量
                    else if (parameter.Type.GetProperties().Any(a => a.Name == text1))
                    {
                        var constantType = parameter.Type.GetProperty(text1).PropertyType;
                        exp2 = ResovleConstantExpression(text2, constantType);
                    }
                    else
                    {
                        exp2 = ResovleConstantExpression(text1, (exp1 as ConstantExpression)?.Type);
                    }
                    expressions2.Add(item.Key, Expression.MakeBinary(opt, exp1, exp2));
                }
            }
            return expressions2.Last().Value;
        }

19 Source : RedisClientPool.cs
with MIT License
from 2881099

internal void SetHost(string host)
        {
            if (string.IsNullOrEmpty(host?.Trim())) {
                _ip = "127.0.0.1";
                _port = 6379;
                return;
            }
            host = host.Trim();
            var ipv6 = Regex.Match(host, @"^\[([^\]]+)\]\s*(:\s*(\d+))?$");
            if (ipv6.Success) //ipv6+port 格式: [fe80::b164:55b3:4b4f:7ce6%15]:6379
            {
                _ip = ipv6.Groups[1].Value.Trim();
                _port = int.TryParse(ipv6.Groups[3].Value, out var tryint) && tryint > 0 ? tryint : 6379;
                return;
            }
            var spt = (host ?? "").Split(':');
            if (spt.Length == 1) //ipv4 or domain
            {
                _ip = string.IsNullOrEmpty(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1";
                _port = 6379;
                return;
            }
            if (spt.Length == 2) //ipv4:port or domain:port
            {
                if (int.TryParse(spt.Last().Trim(), out var testPort2))
                {
                    _ip = string.IsNullOrEmpty(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1";
                    _port = testPort2;
                    return;
                }
                _ip = host;
                _port = 6379;
                return;
            }
            if (IPAddress.TryParse(host, out var tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6) //test ipv6
            {
                _ip = host;
                _port = 6379;
                return;
            }
            if (int.TryParse(spt.Last().Trim(), out var testPort)) //test ipv6:port
            {
                var testHost = string.Join(":", spt.Where((a, b) => b < spt.Length - 1));
                if (IPAddress.TryParse(testHost, out tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    _ip = testHost;
                    _port = 6379;
                    return;
                }
            }
            _ip = host;
            _port = 6379;
        }

19 Source : DefaultRedisSocket.cs
with MIT License
from 2881099

public static KeyValuePair<string, int> SplitHost(string host)
        {
            if (string.IsNullOrWhiteSpace(host?.Trim()))
                return new KeyValuePair<string, int>("127.0.0.1", 6379);

            host = host.Trim();
            var ipv6 = Regex.Match(host, @"^\[([^\]]+)\]\s*(:\s*(\d+))?$");
            if (ipv6.Success) //ipv6+port 格式: [fe80::b164:55b3:4b4f:7ce6%15]:6379
                return new KeyValuePair<string, int>(ipv6.Groups[1].Value.Trim(), 
                    int.TryParse(ipv6.Groups[3].Value, out var tryint) && tryint > 0 ? tryint : 6379);

            var spt = (host ?? "").Split(':');
            if (spt.Length == 1) //ipv4 or domain
                return new KeyValuePair<string, int>(string.IsNullOrWhiteSpace(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1", 6379);

            if (spt.Length == 2) //ipv4:port or domain:port
            {
                if (int.TryParse(spt.Last().Trim(), out var testPort2))
                    return new KeyValuePair<string, int>(string.IsNullOrWhiteSpace(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1", testPort2);

                return new KeyValuePair<string, int>(host, 6379);
            }

            if (IPAddress.TryParse(host, out var tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6) //test ipv6
                return new KeyValuePair<string, int>(host, 6379);

            if (int.TryParse(spt.Last().Trim(), out var testPort)) //test ipv6:port
            {
                var testHost = string.Join(":", spt.Where((a, b) => b < spt.Length - 1));
                if (IPAddress.TryParse(testHost, out tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6)
                    return new KeyValuePair<string, int>(testHost, 6379);
            }

            return new KeyValuePair<string, int>(host, 6379);
        }

19 Source : Program.cs
with GNU Affero General Public License v3.0
from 3CORESec

public static void Main(string[] args)
        {

            int ruleCount = 0;
            int gradientMax = 0;
            Parser.Default.ParseArguments<Options>(args)
                .WithParsed(o =>
                {
                    LoadConfig(o);
                    if (!o.Suricata)
                    {
                        LoadMismatchSearchMatrix(o);
                        foreach (var ruleFilePath in Directory.EnumerateFiles(o.RulesDirectory, "*.yml", SearchOption.AllDirectories))
                        {
                            try
                            {
                                var dict = DeserializeYamlFile(ruleFilePath, o);
                                if (dict != null && dict.ContainsKey("tags"))
                                {
                                    ruleCount++;
                                    var tags = dict["tags"];
                                    var categories = new List<string>();
                                    string lastEntry = null;
                                    foreach (string tag in tags)
                                    {
                                        //If its the technique id entry, then this adds the file name to the techniques map
                                        if (tag.ToLower().StartsWith("attack.t"))
                                        {
                                            var techniqueId = tag.Replace("attack.", "").ToUpper();
                                            if (!techniques.ContainsKey(techniqueId))
                                                techniques[techniqueId] = new List<string>();
                                            techniques[techniqueId].Add(ruleFilePath.Split("\\").Last());
                                            if (techniques.Count > gradientMax)
                                                gradientMax = techniques.Count;
                                            //then if there are any categories so far, it checks for a mismatch for each one
                                            if (categories.Count > 0 && o.Warning)
                                            {
                                                foreach (string category in categories)
                                                    if (!(mismatchSearchMatrix.ContainsKey(techniqueId) && mismatchSearchMatrix[techniqueId].Contains(category)))
                                                        mismatchWarnings.Add($"MITRE ATT&CK technique ({techniqueId}) and tactic ({category}) mismatch in rule: {ruleFilePath.Split("\\").Last()}");
                                            }
                                        }
                                        else
                                        {
                                            //if its the start of a new technique block, then clean categories and adds first category
                                            if (lastEntry == null || lastEntry.StartsWith("attack.t"))
                                                categories = new List<string>();
                                            categories.Add(
                                                tag.Replace("attack.", "")
                                                .Replace("_", "-")
                                                .ToLower());
                                        }
                                        lastEntry = tag;
                                    }
                                }
                            }
                            catch (YamlException e)
                            {
                                Console.Error.WriteLine($"Ignoring rule {ruleFilePath} (parsing failed)");
                            }
                        }

                        WriteSigmaFileResult(o, gradientMax, ruleCount, techniques);
                        PrintWarnings();
                    }
                    else
                    {

                        List<Dictionary<string, List<string>>> res = new List<Dictionary<string, List<string>>>();

                        foreach (var ruleFilePath in Directory.EnumerateFiles(o.RulesDirectory, "*.rules", SearchOption.AllDirectories))
                        {
                            res.Add(ParseRuleFile(ruleFilePath));
                        }

                        WriteSuricataFileResult(o,
                            res
                                .SelectMany(dict => dict)
                                .ToLookup(pair => pair.Key, pair => pair.Value)
                                .ToDictionary(group => group.Key,
                                              group => group.SelectMany(list => list).ToList()));
                    }

                });
        }

19 Source : Program.cs
with GNU Affero General Public License v3.0
from 3CORESec

public static void WriteSigmaFileResult(Options o, int gradientMax, int ruleCount, Dictionary<string, List<string>> techniques)
        {
            try
            {
                var entries = techniques
                    .ToList()
                    .Select(entry => new
                    {
                        techniqueID = entry.Key,
                        score = entry.Value.Count,
                        comment = (o.NoComment) ? null : string.Join(Environment.NewLine, entry.Value.Select(x => x.Split("/").Last()))
                    });

                string filename = o.OutFile.EndsWith(".json") ? "sigma-coverage.json" : $"{o.OutFile}.json";
                File.WriteAllText(filename, JsonConvert.SerializeObject(new
                {
                    domain = "mitre-enterprise",
                    name = "Sigma signatures coverage",
                    gradient = new
                    {
                        colors = new[] { "#a0eab5", "#0f480f" },
                        maxValue = gradientMax,
                        minValue = 0
                    },
                    version = "4.2",
                    techniques = entries
                }, Formatting.Indented, new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                }));
                Console.WriteLine($"[*] Layer file written in {filename} ({ruleCount} rules)");
            }
            catch (Exception e)
            {
                Console.WriteLine("Problem writing to file: " + e.Message);
            }
        }

19 Source : Program.cs
with GNU Affero General Public License v3.0
from 3CORESec

public static void WriteSuricataFileResult(Options o, Dictionary<string, List<string>> techniques)
        {
            try
            {

                var entries = techniques
                    .ToList()
                    .Select(entry => new
                    {
                        techniqueID = entry.Key,
                        score = entry.Value.Count,
                        comment = (o.NoComment) ? null : string.Join(Environment.NewLine, entry.Value.Select(x => x.Split("/").Last()))
                    });

                string filename = o.OutFile.EndsWith(".json") ? "suricata-coverage.json" : $"{o.OutFile}.json";
                File.WriteAllText(filename, JsonConvert.SerializeObject(new
                {
                    domain = "mitre-enterprise",
                    name = "Suricata rules coverage",
                    gradient = new
                    {
                        colors = new[] { "#a0eab5", "#0f480f" },
                        maxValue = techniques
                            .Values
                            .Max(x => x.Count),
                        minValue = 0
                    },
                    version = "4.2",
                    techniques = entries
                }, Formatting.Indented, new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                }));
                Console.WriteLine($"[*] Layer file written in {filename} ({entries.Count()} techniques covered)");
            }
            catch (Exception e)
            {
                Console.WriteLine("Problem writing to file: " + e.Message);
            }
        }

19 Source : PlyHeader.cs
with MIT License
from 3DBear

private void SetVertexProperties(IList<string> properties)
        {
            for (int i = 0; i < properties.Count; i++)
            {
                var split = properties[i].Split(' ');
                var propertyType = split.Last();
                switch (propertyType)
                {
                    case "x":
                        XIndex = i;
                        break;
                    case "y":
                        YIndex = i;
                        break;
                    case "z":
                        ZIndex = i;
                        break;
                    case "red":
                        RedIndex = i;
                        break;
                    case "green":
                        GreenIndex = i;
                        break;
                    case "blue":
                        BlueIndex = i;
                        break;
                    case "alpha":
                        AlphaIndex = i;
                        break;
                }
            }
        }

19 Source : Seat.cs
with Apache License 2.0
from 42skillz

public bool IsAdjacentWith(List<Seat> seats)
        {
            var orderedSeats = seats.OrderBy(s => s.Number).ToList();

            var seat = orderedSeats.First();

            if (Number + 1 == seat.Number || Number - 1 == seat.Number)
            {
                return true;
            }

            seat = seats.Last();

            return Number + 1 == seat.Number || Number - 1 == seat.Number;
        }

19 Source : QueryExpression.Parser.cs
with MIT License
from 71

protected override Expression VisitMethodCall(MethodCallExpression node)
        {
            if (node == null)
                return null;

            Expression result = base.VisitMethodCall(node);

            node = result as MethodCallExpression;

            if (node == null)
                return result;

            LambdaExpression GetLambda()
                => node.Arguments.Last() as LambdaExpression ?? throw InvalidBody();

            switch (node.Method.Name)
            {
                case nameof(Enumerable.Select):
                    _clauses.Add(VisitSelect(node, GetLambda()));
                    break;
                case nameof(Enumerable.SelectMany):
                    _clauses.Add(VisitSelectMany(node, (LambdaExpression)node.Arguments[1], (LambdaExpression)node.Arguments.Last()));
                    break;
                case nameof(Enumerable.Where):
                    _clauses.Add(VisitWhere(node, GetLambda()));
                    break;
                case nameof(Enumerable.GroupJoin):
                    _clauses.Add(VisitGroupJoin(node));
                    break;
                case nameof(Enumerable.GroupBy):
                    _clauses.Add(VisitGroupBy(node));
                    break;
                case nameof(Enumerable.Join):
                    _clauses.Add(VisitJoin(node));
                    break;
                case nameof(Enumerable.OrderBy):
                    _clauses.Add(VisitOrderBy(node, GetLambda(), false));
                    break;
                case nameof(Enumerable.OrderByDescending):
                    _clauses.Add(VisitOrderBy(node, GetLambda(), true));
                    break;
            }

            return result;
        }

19 Source : Geometry.cs
with GNU Lesser General Public License v3.0
from 9and3

public static T IndexOrLast<T>(List<T> list, int index) {
            if (list.Count - 1 < index) {
                return list.Last();
            }
            return list[index];
        }

19 Source : ByteBuffer.cs
with MIT License
from a1q123456

public void WriteToBuffer(byte data)
        {
            if (Length > _maxiumBufferSize && _maxiumBufferSize >= 0)
            {
                throw new InvalidOperationException("buffer length exceeded");
            }
            lock (_sync)
            {
                int available = BufferBytesAvailable();
                byte[] buffer = null;
                if (available == 0)
                {
                    AddNewBufferSegment();
                    buffer = _buffers.Last();
                }
                else
                {
                    buffer = _buffers.Last();
                }
                buffer[_bufferEnd] = data;
                _bufferEnd += 1;
            }
        }

19 Source : ByteBuffer.cs
with MIT License
from a1q123456

private void WriteToBufferNoCheck(ReadOnlySpan<byte> bytes)
        {
            lock (_sync)
            {
                var requiredLength = bytes.Length;
                int available = BufferBytesAvailable();
                if (available < requiredLength)
                {
                    var bytesIndex = 0;
                    do
                    {
                        var buffer = _buffers.Last();
                        var seq = bytes.Slice(bytesIndex, Math.Min(available, requiredLength));
                        seq.CopyTo(buffer.replacedpan(_bufferEnd));
                        _bufferEnd += seq.Length;
                        requiredLength -= seq.Length;
                        available -= seq.Length;
                        bytesIndex += seq.Length;

                        if (available == 0)
                        {
                            AddNewBufferSegment();
                            available = BufferBytesAvailable();
                        }
                    }
                    while (requiredLength != 0);
                }
                else
                {
                    var buffer = _buffers.Last();
                    bytes.CopyTo(buffer.replacedpan(_bufferEnd));
                    _bufferEnd += bytes.Length;
                }
            }
            _dataWritten?.Invoke();
        }

19 Source : ByteBuffer.cs
with MIT License
from a1q123456

private void TakeOutMemoryNoCheck(Span<byte> buffer)
        {
            lock (_sync)
            {
                var discardBuffers = new List<byte[]>();
                bool prevDiscarded = false;
                if (Length < buffer.Length && _maxiumBufferSize >= 0)
                {
                    throw new InvalidProgramException();
                }
                foreach (var b in _buffers)
                {
                    if (buffer.Length == 0)
                    {
                        break;
                    }
                    var start = 0;
                    var end = BufferSegmentSize;
                    var isFirst = b == _buffers.First() || prevDiscarded;
                    var isLast = b == _buffers.Last();
                    if (isFirst)
                    {
                        start = _bufferStart;
                    }
                    if (isLast)
                    {
                        end = _bufferEnd;
                    }
                    var length = end - start;
                    var needToCopy = Math.Min(buffer.Length, length);

                    b.replacedpan(start, needToCopy).CopyTo(buffer);

                    start += needToCopy;
                    if (isFirst)
                    {
                        _bufferStart += needToCopy;
                    }

                    if (end - start == 0)
                    {
                        if (isFirst)
                        {
                            _bufferStart = 0;
                        }
                        if (isLast)
                        {
                            _bufferEnd = 0;
                        }
                        discardBuffers.Add(b);
                        prevDiscarded = true;
                    }
                    else
                    {
                        prevDiscarded = false;
                    }

                    buffer = buffer.Slice(needToCopy);
                }
                //Console.WriteLine(Length);
                Debug.replacedert(buffer.Length == 0 || _maxiumBufferSize < 0);
                while (discardBuffers.Any())
                {
                    var b = discardBuffers.First();
                    _arrayPool.Return(b);
                    discardBuffers.Remove(b);
                    _buffers.Remove(b);
                }
                if (!_buffers.Any())
                {
                    AddNewBufferSegment();
                }
            }
            if (Length <= _maxiumBufferSize && _maxiumBufferSize >= 0)
            {
                _memoryUnderLimit?.Invoke();
            }
        }

19 Source : Amf3Writer.cs
with MIT License
from a1q123456

private void WrapDictionary(object value, SerializationContext context)
        {
            var valueType = value.GetType();
            var contractRet = valueType.IsGenericType;
            Contract.replacedert(contractRet);
            var defination = valueType.GetGenericTypeDefinition();
            Contract.replacedert(defination == typeof(Amf3Dictionary<,>));
            var tKey = valueType.GetGenericArguments().First();
            var tValue = valueType.GetGenericArguments().Last();

            _writeDictionaryTMethod.MakeGenericMethod(tKey, tValue).Invoke(this, new object[] { value, context });
        }

19 Source : RtmpSession.cs
with MIT License
from a1q123456

internal uint MakeUniqueChunkStreamId()
        {
            // TBD make csid unique
            lock (_allocCsidLocker)
            {
                var next = _allocatedCsid.Any() ? _allocatedCsid.Last().Key : 2;
                if (uint.MaxValue == next)
                {
                    for (uint i = 0; i < uint.MaxValue; i++)
                    {
                        if (!_allocatedCsid.ContainsKey(i))
                        {
                            _allocatedCsid.Add(i, i);
                            return i;
                        }
                    }
                    throw new InvalidOperationException("too many chunk stream");
                }
                next += 1;
                _allocatedCsid.Add(next, next);
                return next;
            }
            
        }

19 Source : DictionaryExtension.cs
with MIT License
from 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 Source : WorkbookEditor.cs
with Apache License 2.0
from aaaddress1

public WorkbookStream SetMacroSheetContent_NoLoader(List<string> macroStrings, int rwStart = 0, int colStart = 0)
        {
            WorkbookStream macroStream = GetMacroStream();
            Formula replaceMeFormula = macroStream.GetAllRecordsByType<Formula>().First();

            //ixfe default cell value is 15
            List<BiffRecord> formulasToAdd = new List<BiffRecord>();
            int curRow = rwStart, curCol = colStart;
            int dstCurRow = 0, dstCurCol = 0;

            foreach (string str in macroStrings) {
                var formulas = FormulaHelper.ConvertStringToFormulas(str, curRow, curCol, dstCurRow, dstCurCol, 15, SheetPackingMethod.ObfuscatedCharFuncAlt);
                curRow += formulas.Count;
                dstCurRow += 1;
                formulasToAdd.AddRange(formulas);
            }
            
            int lastGotoCol = formulasToAdd.Last().AsRecordType<Formula>().col;
            int lastGotoRow = formulasToAdd.Last().AsRecordType<Formula>().rw + 1;

            WorkbookStream modifiedStream = WbStream;
            modifiedStream = modifiedStream.InsertRecords(formulasToAdd, replaceMeFormula);
            // we replacedert decrypted macros should at R1C1, so place a GOTO(R1C1) here.
            modifiedStream = modifiedStream.ReplaceRecord(replaceMeFormula, FormulaHelper.GetGotoFormulaForCell(lastGotoRow, lastGotoCol, 0, 0));
            WbStream = modifiedStream;
            return WbStream;
        }

19 Source : WorkbookEditor.cs
with Apache License 2.0
from aaaddress1

public WorkbookStream SetMacroSheetContent(List<string> macroStrings, int rwStart = 0, int colStart = 0, 
            int dstRwStart = 0, int dstColStart = 0, SheetPackingMethod packingMethod = SheetPackingMethod.ObfuscatedCharFunc)
        {
            WorkbookStream macroStream = GetMacroStream();

            //The macro sheet template contains a single formula record to replace
            Formula replaceMeFormula = macroStream.GetAllRecordsByType<Formula>().First();

            //ixfe default cell value is 15
            List<BiffRecord> formulasToAdd = FormulaHelper.ConvertStringsToRecords(macroStrings, rwStart, colStart, dstRwStart, dstColStart, 15, packingMethod);

            int lastGotoCol = formulasToAdd.Last().AsRecordType<Formula>().col;
            int lastGotoRow = formulasToAdd.Last().AsRecordType<Formula>().rw + 1;
            
            Formula gotoFormula = FormulaHelper.GetGotoFormulaForCell(lastGotoRow, lastGotoCol, dstRwStart, dstColStart);
            WorkbookStream modifiedStream = WbStream.ReplaceRecord(replaceMeFormula, gotoFormula);
            modifiedStream = modifiedStream.InsertRecords(formulasToAdd, gotoFormula);

            WbStream = modifiedStream;
            return WbStream;
        }

19 Source : WorkbookEditor.cs
with Apache License 2.0
from aaaddress1

public WorkbookStream AddExistingLabel(Lbl existingLbl, ushort iTab = 0)
        {
            List<Lbl> existingLbls = WbStream.GetAllRecordsByType<Lbl>();
            ExternSheet lastExternSheet = WbStream.GetAllRecordsByType<ExternSheet>().LastOrDefault();

            existingLbl.itab = iTab;
            if (existingLbls.Count > 0)
            {
                WbStream = WbStream.InsertRecord(existingLbl, existingLbls.Last());
            }
            else
            {
                if (lastExternSheet == null)
                {
                    throw new NotImplementedException("AddExistingLabel replacedumes an ExternSheet exists");
                }
                WbStream = WbStream.InsertRecord(existingLbl, lastExternSheet);
            }

            WbStream = WbStream.FixBoundSheetOffsets();
            return WbStream;
        }

19 Source : WorkbookEditor.cs
with Apache License 2.0
from aaaddress1

public WorkbookStream AddLabel(string label, Stack<AbstractPtg> rgce, bool isHidden = false, bool isUnicode = false, bool isMacroStack = false)
        {
            /*
             * Labels require a reference to an XTI index which is used to say which
             * BoundSheet8 record maps to the appropriate tab. In order to make this
             * record we need a SupBook record, and ExternSheet record to specify
             * which BoundSheet8 record to use.
             */

            List<SupBook> supBooksExisting = WbStream.GetAllRecordsByType<SupBook>();
            List<ExternSheet> externSheetsExisting = WbStream.GetAllRecordsByType<ExternSheet>();
            List<Lbl> existingLbls = WbStream.GetAllRecordsByType<Lbl>();

            ExternSheet lastExternSheet;

            if (supBooksExisting.Count > 0 || externSheetsExisting.Count > 0)
            {
                lastExternSheet = externSheetsExisting.Last();
            }
            else
            {
                InitializeGlobalStreamLabels();
                lastExternSheet = WbStream.GetAllRecordsByType<ExternSheet>().Last(); ;
            }

            // For now we replacedume that any labels being added belong to the last BoundSheet8 we added
            Lbl newLbl = new Lbl(label, (ushort) (WbStream.GetAllRecordsByType<BoundSheet8>().Count));

            if (isUnicode)
            {
                newLbl.SetName(new XLUnicodeStringNoCch(label, true));
            }

            if (isMacroStack)
            {
                newLbl.fProc = true;
                newLbl.fFunc = true;
            }

            if (isHidden) newLbl.fHidden = true;

            if (rgce != null)
            {
                newLbl.SetRgce(rgce);
            }
            else
            {
                newLbl.cce = 0;
            }

            if (existingLbls.Count > 0)
            {
                WbStream = WbStream.InsertRecord(newLbl, existingLbls.Last());
            }
            else
            {
                WbStream = WbStream.InsertRecord(newLbl, lastExternSheet);
            }

            WbStream = WbStream.FixBoundSheetOffsets();
            return WbStream;
        }

19 Source : WorkbookStream.cs
with Apache License 2.0
from aaaddress1

public WorkbookStream AddSheet(BoundSheet8 sheetHeader, byte[] sheetBytes)
        {
            WorkbookStream newStream = new WorkbookStream(Records);
            List<BoundSheet8> existingBoundSheets = newStream.GetAllRecordsByType<BoundSheet8>();
            BoundSheet8 lastSheet8 = existingBoundSheets.Last();

            newStream = newStream.InsertRecord(sheetHeader, lastSheet8);

            List<BiffRecord> sheetRecords = RecordHelper.ParseBiffStreamBytes(sheetBytes);
            newStream = newStream.InsertRecords(sheetRecords);

            newStream = newStream.FixBoundSheetOffsets();

            return newStream;
        }

19 Source : WorkbookEditor.cs
with Apache License 2.0
from aaaddress1

public WorkbookStream AddLabel(string label, Stack<AbstractPtg> rgce, bool isHidden = false, bool isUnicode = false, bool isMacroStack = false)
        {
            /*
             * Labels require a reference to an XTI index which is used to say which
             * BoundSheet8 record maps to the appropriate tab. In order to make this
             * record we need a SupBook record, and ExternSheet record to specify
             * which BoundSheet8 record to use.
             */

                List<SupBook> supBooksExisting = WbStream.GetAllRecordsByType<SupBook>();
            List<ExternSheet> externSheetsExisting = WbStream.GetAllRecordsByType<ExternSheet>();
            List<Lbl> existingLbls = WbStream.GetAllRecordsByType<Lbl>();

            ExternSheet lastExternSheet;

            if (supBooksExisting.Count > 0 || externSheetsExisting.Count > 0)
            {
                lastExternSheet = externSheetsExisting.Last();
            }
            else
            {
                InitializeGlobalStreamLabels();
                lastExternSheet = WbStream.GetAllRecordsByType<ExternSheet>().Last(); ;
            }

            // For now we replacedume that any labels being added belong to the last BoundSheet8 we added
            Lbl newLbl = new Lbl(label, (ushort) (WbStream.GetAllRecordsByType<BoundSheet8>().Count));

            if (isUnicode)
            {
                newLbl.SetName(new XLUnicodeStringNoCch(label, true));
            }

            if (isMacroStack)
            {
                newLbl.fProc = true;
                newLbl.fFunc = true;
            }

            if (isHidden) newLbl.fHidden = true;

            if (rgce != null)
            {
                newLbl.SetRgce(rgce);
            }
            else
            {
                newLbl.cce = 0;
            }

            if (existingLbls.Count > 0)
            {
                WbStream = WbStream.InsertRecord(newLbl, existingLbls.Last());
            }
            else
            {
                WbStream = WbStream.InsertRecord(newLbl, lastExternSheet);
            }

            WbStream = WbStream.FixBoundSheetOffsets();
            return WbStream;
        }

19 Source : MacroPatterns.cs
with Apache License 2.0
from aaaddress1

public static string ReplaceSelectActiveCellFormula(string cellFormula, string variableName = DefaultVariableName)
        {
            if (cellFormula.Contains("ACTIVE.CELL()"))
            {
                cellFormula = cellFormula.Replace("ACTIVE.CELL()", variableName);
            }

            string selectRegex = @"=SELECT\(.*?\)";
            string selectRelativeRegex = @"=SELECT\(.*(R(\[\d+\]){0,1}C(\[\d+\]){0,1}).*?\)";

            Regex sRegex = new Regex(selectRegex);
            Regex srRegex = new Regex(selectRelativeRegex);
            Match sRegexMatch = sRegex.Match(cellFormula);
            if (sRegexMatch.Success)
            {
                Match srRegexMatch = srRegex.Match(cellFormula);
                string selectStringMatch = sRegexMatch.Value;
                //We have a line like =SELECT(,"R[1]C")
                if (srRegexMatch.Success)
                {
                    string relAddress = srRegexMatch.Groups[1].Value;
                    string relReplace = cellFormula.Replace(selectStringMatch,
                        string.Format("{0}=ABSREF(\"{1}\",{0})", variableName, relAddress));
                    return relReplace;
                }
                //We have a line like =SELECT(B1:B111,B1)
                else
                {
                    string targetCell = selectStringMatch.Split(",").Last().Split(')').First();
                    string varreplacedign = cellFormula.Replace(selectStringMatch,
                        string.Format("{0}={1}", variableName, targetCell));
                    return varreplacedign;
                }
            }

            return cellFormula;
        }

19 Source : WorkbookEditor.cs
with Apache License 2.0
from aaaddress1

public WorkbookStream SetMacroSheetContent_NoLoader(List<string> macroStrings, int rwStart = 0, int colStart = 0)
        {
            WorkbookStream macroStream = GetMacroStream();
            Formula replaceMeFormula = macroStream.GetAllRecordsByType<Formula>().First();

            //ixfe default cell value is 15
            List<BiffRecord> formulasToAdd = new List<BiffRecord>();
            int curRow = rwStart, curCol = colStart;
            int dstCurRow = 0, dstCurCol = 0;

            foreach (string str in macroStrings) {
                List<Formula> charFormulas = FormulaHelper.GetCharFormulasForString(str, curRow, curCol, SheetPackingMethod.ObfuscatedCharFuncAlt);
                curRow += charFormulas.Count;
                var createdCells = charFormulas.Select(formula => new Cell(formula.rw, formula.col, 15)).ToList();
                var formulaInvocationRecords = FormulaHelper.BuildFORMULAFunctionCall(createdCells, curRow, curCol, dstCurRow, dstCurCol, SheetPackingMethod.ObfuscatedCharFuncAlt, false);
                curRow += formulaInvocationRecords.Count;
                dstCurRow++;
                formulasToAdd.AddRange(charFormulas);
                formulasToAdd.AddRange(formulaInvocationRecords);
            }

            int lastGotoCol = formulasToAdd.Last().AsRecordType<Formula>().col;
            int lastGotoRow = formulasToAdd.Last().AsRecordType<Formula>().rw + 1;

            WorkbookStream modifiedStream = WbStream;
            modifiedStream = modifiedStream.InsertRecords(formulasToAdd, replaceMeFormula);
            // we replacedert decrypted macros should at R1C1, so place a GOTO(R1C1) here.
            modifiedStream = modifiedStream.ReplaceRecord(replaceMeFormula, FormulaHelper.GetGotoFormulaForCell(lastGotoRow, lastGotoCol, 0, 0));
            WbStream = modifiedStream;
            return WbStream;
        }

19 Source : RichTextModel.cs
with MIT License
from Abdesol

internal void Append(int offset, int[] newOffsets, HighlightingColor[] newColors)
		{
			Debug.replacedert(newOffsets.Length == newColors.Length);
			Debug.replacedert(newOffsets[0] == 0);
			// remove everything not before offset:
			while (stateChangeOffsets.Count > 0 && stateChangeOffsets.Last() >= offset) {
				stateChangeOffsets.RemoveAt(stateChangeOffsets.Count - 1);
				stateChanges.RemoveAt(stateChanges.Count - 1);
			}
			// Append the new segments
			for (int i = 0; i < newOffsets.Length; i++) {
				stateChangeOffsets.Add(offset + newOffsets[i]);
				stateChanges.Add(newColors[i]);
			}
		}

19 Source : RectangleSelection.cs
with MIT License
from Abdesol

TextViewPosition GetStart()
		{
			SelectionSegment segment = (startLine < endLine ? segments.First() : segments.Last());
			if (startXPos < endXPos) {
				return new TextViewPosition(doreplacedent.GetLocation(segment.StartOffset), segment.StartVisualColumn);
			} else {
				return new TextViewPosition(doreplacedent.GetLocation(segment.EndOffset), segment.EndVisualColumn);
			}
		}

19 Source : RectangleSelection.cs
with MIT License
from Abdesol

TextViewPosition GetEnd()
		{
			SelectionSegment segment = (startLine < endLine ? segments.Last() : segments.First());
			if (startXPos < endXPos) {
				return new TextViewPosition(doreplacedent.GetLocation(segment.EndOffset), segment.EndVisualColumn);
			} else {
				return new TextViewPosition(doreplacedent.GetLocation(segment.StartOffset), segment.StartVisualColumn);
			}
		}

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

private static List<Type> GenerateObjectTrace(IEnumerable<IEnumerator> enumerators)
            {
                var objTrace = new List<Type>();

                foreach (var enumerator in enumerators)
                {
                    // NOTE: This only works with scripting engine 4.6
                    // And could easily stop working with unity updates
                    var field = enumerator.GetType().GetField("$this", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

                    if (field == null)
                    {
                        continue;
                    }

                    var obj = field.GetValue(enumerator);

                    if (obj == null)
                    {
                        continue;
                    }

                    var objType = obj.GetType();

                    if (!objTrace.Any() || objType != objTrace.Last())
                    {
                        objTrace.Add(objType);
                    }
                }

                objTrace.Reverse();
                return objTrace;
            }

19 Source : CustomSeriesValueMarkersViewModel.cs
with MIT License
from ABTSoftware

private void UpdateLineAnnotations(ISciChartSurface surface)
        {
            if (surface.XAxis.GetCurrentCoordinateCalculator() is ICategoryCoordinateCalculator categoryCalc)
            {
                var lineOpen = (LineAnnotationViewModel) Annotations.First();
                var lineClose = (LineAnnotationViewModel) Annotations.Last();

                IComparable x1Value;
                IComparable x2Value = categoryCalc.TransformIndexToData(XVisibleRange.Max);

                if (XVisibleRange.Max >= _dataSeries.Count)
                {
                    x1Value = _dataSeries.XValues.Last();

                    lineOpen.Y1 = _dataSeries.OpenValues.Last();
                    lineClose.Y1 = _dataSeries.CloseValues.Last();
                }
                else
                {
                    x1Value = _dataSeries.XValues[XVisibleRange.Max];

                    lineOpen.Y1 = _dataSeries.OpenValues[XVisibleRange.Max];
                    lineClose.Y1 = _dataSeries.CloseValues[XVisibleRange.Max];
                }

                lineOpen.X1 = x1Value;
                lineClose.X1 = x1Value;

                lineOpen.X2 = x2Value;
                lineClose.X2 = x2Value;

                var candleSeries = (CandlestickRenderableSeriesViewModel) Series.First();

                if (lineOpen.Y1.CompareTo(lineClose.Y1) <= 0)
                {
                    lineOpen.Stroke = candleSeries.StrokeUp;
                    lineClose.Stroke = candleSeries.StrokeUp;
                }
                else
                {
                    lineOpen.Stroke = candleSeries.StrokeDown;
                    lineClose.Stroke = candleSeries.StrokeDown;
                }
            }
        }

19 Source : VitalSignsBatch.cs
with MIT License
from ABTSoftware

public void UpdateData(IList<VitalSignsData> dataList)
        {
            XValues.Clear();

            ECGHeartRateValuesA.Clear();
            BloodPressureValuesA.Clear();
            BloodVolumeValuesA.Clear();
            BloodOxygenationValuesA.Clear();

            ECGHeartRateValuesB.Clear();
            BloodPressureValuesB.Clear();
            BloodVolumeValuesB.Clear();
            BloodOxygenationValuesB.Clear();

            foreach (VitalSignsData data in dataList)
            {
                XValues.Add(data.XValue);

                if (data.IsATrace)
                {
                    ECGHeartRateValuesA.Add(data.ECGHeartRate);
                    BloodPressureValuesA.Add(data.BloodPressure);
                    BloodVolumeValuesA.Add(data.BloodVolume);
                    BloodOxygenationValuesA.Add(data.BloodOxygenation);

                    ECGHeartRateValuesB.Add(double.NaN);
                    BloodPressureValuesB.Add(double.NaN);
                    BloodVolumeValuesB.Add(double.NaN);
                    BloodOxygenationValuesB.Add(double.NaN);
                }
                else
                {
                    ECGHeartRateValuesB.Add(data.ECGHeartRate);
                    BloodPressureValuesB.Add(data.BloodPressure);
                    BloodVolumeValuesB.Add(data.BloodVolume);
                    BloodOxygenationValuesB.Add(data.BloodOxygenation);

                    ECGHeartRateValuesA.Add(double.NaN);
                    BloodPressureValuesA.Add(double.NaN);
                    BloodVolumeValuesA.Add(double.NaN);
                    BloodOxygenationValuesA.Add(double.NaN);
                }
            }

            LastVitalSignsData = dataList.Last();
        }

19 Source : ConsultaExtensions.cs
with MIT License
from ACBrNet

internal static string SendPost(this HttpWebRequest request, Dictionary<string, string> postData, Encoding enconde)
        {
            request.Method = "POST";

            var post = new StringBuilder();
            var lastKey = postData.Last().Key;
            foreach (var postValue in postData)
            {
                post.Append($"{postValue.Key}={postValue.Value}");
                if (postValue.Key != lastKey) post.Append("&");
            }

            var byteArray = enconde.GetBytes(post.ToString());
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;

            var dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            var response = request.GetResponse();
            var responseStream = response.GetResponseStream();
            Guard.Against<ACBrException>(responseStream == null, "Erro ao acessar o site.");

            string retorno;
            using (var stHtml = new StreamReader(responseStream, enconde))
                retorno = stHtml.ReadToEnd();

            return retorno;
        }

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

public void InterpolateTo(Position position, bool keepHeading)
        {
            if (PhysicsObj == null)
                return;

            var dest = PositionQueue.Count > 0 && PositionQueue.Last().Type == InterpolationNodeType.PositionType ?
                PositionQueue.Last().Position : PhysicsObj.Position;

            var dist = dest.Distance(position);

            if (PhysicsObj.GetAutonomyBlipDistance() >= dist)
            {
                if (PhysicsObj.Position.Distance(position) > 0.05f)
                {
                    while (PositionQueue.Count > 0)
                    {
                        var lastNode = PositionQueue.Last();
                        if (lastNode.Type != InterpolationNodeType.PositionType || lastNode.Position.Distance(position) >= 0.05f)
                            break;

                        PositionQueue.DequeueLast();
                    }
                    while (PositionQueue.Count >= 20)
                        PositionQueue.Dequeue();

                    var interpolationNode = new InterpolationNode(InterpolationNodeType.PositionType, position);
                    if (keepHeading)
                        interpolationNode.Position.Frame.set_heading(PhysicsObj.get_heading());

                    PositionQueue.Enqueue(interpolationNode);
                }
                else
                {
                    if (!keepHeading)
                        PhysicsObj.set_heading(position.Frame.get_heading(), true);

                    StopInterpolating();
                }
            }
            else
            {
                var interpolationNode = new InterpolationNode(InterpolationNodeType.PositionType, position);
                if (keepHeading)
                    interpolationNode.Position.Frame.set_heading(PhysicsObj.get_heading());

                PositionQueue.Enqueue(interpolationNode);
                NodeFailCounter = 4;
            }
        }

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

public void UseTime()
        {
            if (PhysicsObj == null)
                return;

            if (NodeFailCounter > 3 || PositionQueue.Count == 0)
            {
                if (NodeFailCounter <= 0) return;

                var last = PositionQueue.Last();
                if (last.Type != InterpolationNodeType.JumpType && last.Type != InterpolationNodeType.VelocityType)
                {
                    if (PhysicsObj.SetPositionSimple(last.Position, true) != SetPositionError.OK)
                        return;

                    StopInterpolating();
                    return;
                }

                if (PositionQueue.Count > 1)
                {
                    for (var i = PositionQueue.Count; i >= 0; --i)
                    {
                        var node = PositionQueue.ElementAt(i);
                        if (node.Type == InterpolationNodeType.PositionType)
                        {
                            if (PhysicsObj.SetPositionSimple(node.Position, true) != SetPositionError.OK)
                                return;

                            PhysicsObj.set_velocity(last.Velocity, true);
                            StopInterpolating();
                            return;
                        }
                    }
                }

                if (PhysicsObj.SetPositionSimple(BlipToPosition, true) != SetPositionError.OK)
                    return;

                StopInterpolating();
                return;
            }

            var first = PositionQueue.FirstOrDefault();
            switch (first.Type)
            {
                case InterpolationNodeType.JumpType:
                    NodeCompleted(true);
                    break;

                case InterpolationNodeType.VelocityType:
                    PhysicsObj.set_velocity(first.Velocity, true);
                    NodeCompleted(true);
                    break;
            }
        }

19 Source : SolarAnalysisColourSchemes.cs
with GNU Lesser General Public License v3.0
from acnicholas

public static ElementId CreatereplacedysisScheme(List<replacedysisDisplayColorEntry> colours, Doreplacedent doc, string name, bool showLegend)
        {
            var result = ElementId.InvalidElementId;

            var colouredSurfaceSettings = new replacedysisDisplayColoredSurfaceSettings();
            colouredSurfaceSettings.ShowContourLines = true;
            colouredSurfaceSettings.ShowGridLines = false;

            var colourSettings = new replacedysisDisplayColorSettings();
            colourSettings.MaxColor = colours.Last().Color;
            colourSettings.MinColor = colours.First().Color;
            colourSettings.SetIntermediateColors(colours);
            colourSettings.ColorSettingsType = replacedysisDisplayStyleColorSettingsType.GradientColor;

            if (replacedysisDisplayStyle.IsNameUnique(doc, name, null)) {
                var ads = replacedysisDisplayStyle.CreatereplacedysisDisplayStyle(
                    doc,
                    name,
                    colouredSurfaceSettings,
                    colourSettings,
                    new replacedysisDisplayLegendSettings());
                if (!showLegend) {
                    ads.GetLegendSettings().ShowLegend = false;
                }
                result = ads.Id;
            } else {
                result = replacedysisDisplayStyle.FindByName(doc, name);
            }

            return result;
        }

19 Source : SelectionHistory.cs
with MIT License
from acoppes

public void UpdateSelection(Object selection)
        {
            if (selection == null)
                return;

            var lastSelectedObject = _history.Count > 0 ? _history.Last() : null;

            var isLastSelected = lastSelectedObject != null && lastSelectedObject.reference == selection;
            var isCurrentSelection = currentSelection != null && currentSelection.reference == selection;
            
            if (!isLastSelected && !isCurrentSelection)
            {
                _history.Add(new Entry(selection));
                currentSelectionIndex = _history.Count - 1;
                
                OnNewEntryAdded?.Invoke(this);
            }

            if (_history.Count > historySize)
            {
                _history.RemoveRange(0, _history.Count - historySize);
                //			_history.RemoveAt(0);
            }
        }

19 Source : SheetFilter.cs
with GNU Lesser General Public License v3.0
from acnicholas

private static string FirstDigitOfLastNumberInString(string s)
        {
            var onlyNumbers = Regex.Replace(s, "[^0-9]", @" ");
            string[] numberParts = onlyNumbers.Split(new[] { @" " }, StringSplitOptions.RemoveEmptyEntries);
            var n = numberParts.Where(v => v.Length > 1);
            if (n.Count() > 0) {
                return n.Last().Substring(0, 1);
            }
            return null;
        }

19 Source : CustomShellService.cs
with MIT License
from Actipro

public override IShellObject CreateObjectForParsingName(string parsingName) {
			// Does the parsing name refer to a custom folder?
			if (IsCloudStorageParsingName(parsingName)) {
				var relativeParsingNames = SplitCloudStorageParsingName(parsingName);
				if (relativeParsingNames.Count == 1) {
					// Create root cloud storage folder.
					// A relative parsing name is provided since the name of the folder, "Custom Cloud Storage", differs from the name used in the path, "cloud:".
					// A specific editing name is used so that the root folder displays as "cloud:\" in a path text box instead of "cloud:"
					string editingName = CloudStorageParsingNameRoot + CloudStorageParsingNameSeparator;
					return this.CreateCloudStorageFolder("Custom Cloud Storage (" + CloudStorageParsingNameRoot + ")", parsingName, relativeParsingNames[0], editingName);
				}
				else if (relativeParsingNames.Count > 1) {
					// Create nested cloud storage folder
					string name = relativeParsingNames.Last();
					return this.CreateCloudStorageFolder(name, parsingName);
				}

				// Invalid parsing name
				return null;
			}

			return base.CreateObjectForParsingName(parsingName);
		}

19 Source : ControlDataRepository.cs
with MIT License
from Actipro

private static ControlData CreateControlData(Type controlType) {
			// Use the last part of the namespace as the category
			string category = controlType.Namespace.Split('.').Last();
			return new ControlData(controlType.FullName, category);
		}

19 Source : ControlTreeNodeModel.cs
with MIT License
from Actipro

private static string GetControlNameOnly(string fullName) {
			// Full name includes the namespace, so the last part of the full name is the control
			return fullName.Split('.').Last();
		}

19 Source : RasterCache.cs
with MIT License
from adamped

public RasterCacheResult Get(SKPicture picture, SKMatrix ctm)
        {
            var cache_key = new RasterCacheKey<UniqueEntry>(new UniqueEntry(picture.UniqueId), ctm);
            var it = picture_cache_.First(x => x.Equals(cache_key));
            return it == picture_cache_.Last() ? new RasterCacheResult() : new RasterCacheResult(); // This aint right;
        }

19 Source : Repository.cs
with Apache License 2.0
from adamralph

public Version GetVersion(string tagPrefix, VersionPart autoIncrement, string defaultPreReleasePhase, ILogger log)
        {
            var commit = this.head;

            if (commit == null)
            {
                var version = new Version(defaultPreReleasePhase);

                log.Info($"No commits found. Using default version {version}.");

                return version;
            }

            var tagsAndVersions = this.tags
                .Select(tag => (tag, Version.ParseOrDefault(tag.Name, tagPrefix)))
                .OrderBy(tagAndVersion => tagAndVersion.Item2)
                .ThenBy(tagsAndVersion => tagsAndVersion.tag.Name)
                .ToList();

            var commitsChecked = new HashSet<string>();
            var count = 0;
            var height = 0;
            var candidates = new List<Candidate>();
            var commitsToCheck = new Stack<(Commit, int, Commit)>();
            Commit previousCommit = null;

            if (log.IsTraceEnabled)
            {
                log.Trace($"Starting at commit {commit.ShortSha} (height {height})...");
            }

            while (true)
            {
                var parentCount = 0;

                if (commitsChecked.Add(commit.Sha))
                {
                    ++count;

                    var commitTagsAndVersions = tagsAndVersions.Where(tagAndVersion => tagAndVersion.tag.Sha == commit.Sha).ToList();
                    var foundVersion = false;

                    foreach (var (tag, commitVersion) in commitTagsAndVersions)
                    {
                        var candidate = new Candidate { Commit = commit, Height = height, Tag = tag.Name, Version = commitVersion, Index = candidates.Count };

                        foundVersion = foundVersion || candidate.Version != null;

                        if (log.IsTraceEnabled)
                        {
                            log.Trace($"Found {(candidate.Version == null ? "non-" : null)}version tag {candidate}.");
                        }

                        candidates.Add(candidate);
                    }

                    if (!foundVersion)
                    {
                        if (log.IsTraceEnabled)
                        {
                            var parentIndex = 0;
                            Commit firstParent = null;

                            foreach (var parent in commit.Parents)
                            {
                                switch (parentIndex)
                                {
                                    case 0:
                                        firstParent = parent;
                                        break;
                                    case 1:
                                        log.Trace($"History diverges from {commit.ShortSha} (height {height}) to:");
                                        log.Trace($"- {firstParent.ShortSha} (height {height + 1})");
                                        goto default;
                                    default:
                                        log.Trace($"- {parent.ShortSha} (height {height + 1})");
                                        break;
                                }

                                ++parentIndex;
                                parentCount = parentIndex;
                            }
                        }

                        foreach (var parent in ((IEnumerable<Commit>)commit.Parents).Reverse())
                        {
                            commitsToCheck.Push((parent, height + 1, commit));
                        }

                        if (commitsToCheck.Count == 0 || commitsToCheck.Peek().Item2 <= height)
                        {
                            var candidate = new Candidate { Commit = commit, Height = height, Tag = null, Version = new Version(defaultPreReleasePhase), Index = candidates.Count };

                            if (log.IsTraceEnabled)
                            {
                                log.Trace($"Found root commit {candidate}.");
                            }

                            candidates.Add(candidate);
                        }
                    }
                }
                else
                {
                    if (log.IsTraceEnabled)
                    {
                        log.Trace($"History converges from {previousCommit.ShortSha} (height {height - 1}) back to previously seen commit {commit.ShortSha} (height {height}). Abandoning path.");
                    }
                }

                if (commitsToCheck.Count == 0)
                {
                    break;
                }

                if (log.IsTraceEnabled)
                {
                    previousCommit = commit;
                }

                var oldHeight = height;
                Commit child;
                (commit, height, child) = commitsToCheck.Pop();

                if (log.IsTraceEnabled)
                {
                    if (parentCount > 1)
                    {
                        log.Trace($"Following path from {child.ShortSha} (height {height - 1}) through first parent {commit.ShortSha} (height {height})...");
                    }
                    else if (height <= oldHeight)
                    {
                        if (commitsToCheck.Any() && commitsToCheck.Peek().Item2 == height)
                        {
                            log.Trace($"Backtracking to {child.ShortSha} (height {height - 1}) and following path through next parent {commit.ShortSha} (height {height})...");
                        }
                        else
                        {
                            log.Trace($"Backtracking to {child.ShortSha} (height {height - 1}) and following path through last parent {commit.ShortSha} (height {height})...");
                        }
                    }
                }
            }

            log.Debug($"{count:N0} commits checked.");

            var orderedCandidates = candidates.OrderBy(candidate => candidate.Version).ThenByDescending(candidate => candidate.Index).ToList();

            var tagWidth = log.IsDebugEnabled ? orderedCandidates.Max(candidate => candidate.Tag?.Length ?? 2) : 0;
            var versionWidth = log.IsDebugEnabled ? orderedCandidates.Max(candidate => candidate.Version?.ToString().Length ?? 4) : 0;
            var heightWidth = log.IsDebugEnabled ? orderedCandidates.Max(candidate => candidate.Height).ToString(CultureInfo.CurrentCulture).Length : 0;

            if (log.IsDebugEnabled)
            {
                foreach (var candidate in orderedCandidates.Take(orderedCandidates.Count - 1))
                {
                    log.Debug($"Ignoring {candidate.ToString(tagWidth, versionWidth, heightWidth)}.");
                }
            }

            var selectedCandidate = orderedCandidates.Last();

            if (selectedCandidate.Tag == null)
            {
                log.Info($"No commit found with a valid SemVer 2.0 version{(tagPrefix == null ? null : $" prefixed with '{tagPrefix}'")}. Using default version {selectedCandidate.Version}.");
            }

            log.Info($"Using{(log.IsDebugEnabled && orderedCandidates.Count > 1 ? "    " : " ")}{selectedCandidate.ToString(tagWidth, versionWidth, heightWidth)}.");

            return selectedCandidate.Version.WithHeight(selectedCandidate.Height, autoIncrement, defaultPreReleasePhase);
        }

19 Source : PrimeFactory.cs
with GNU General Public License v3.0
from AdamWhiteHat

private static void SetPrimes()
		{
			primes = Eratosthenes.Sieve((Int32)MaxValue).ToList();
			primesCount = primes.Count;
			primesLast = primes.Last();
		}

19 Source : OutputTests.cs
with Apache License 2.0
from adamralph

private static async Task Write(Output output, bool dryRun)
        {
            var badInput = new Target("badInput", "", Enumerable.Empty<string>());
            var badInputDuration = dryRun ? (TimeSpan?)null : TimeSpan.FromMilliseconds(1.234);
            var badInputEx = new InvalidOperationException("badInputEx");
            var badInputId = Guid.ParseExact("AA123".PadRight(32, '0'), "N");

            var badInputsTarget = new Target("badInputsTarget", "", Enumerable.Empty<string>());

            var badTarget = new Target("badTarget", "", Enumerable.Empty<string>());
            var badTargetDuration = dryRun ? (TimeSpan?)null : TimeSpan.FromMilliseconds(3.456);
            var badTargetEx = new InvalidOperationException("badTargetEx");

            var emptyTargets = Enumerable.Empty<Target>();

            var goodInput1 = new Target("goodInput1", "", Enumerable.Empty<string>());
            var goodInput2 = new Target("goodInput2", "", Enumerable.Empty<string>());
            var goodInputDuration1 = dryRun ? (TimeSpan?)null : TimeSpan.FromSeconds(1.234);
            var goodInputDuration2 = dryRun ? (TimeSpan?)null : TimeSpan.FromSeconds(2.345);
            var goodInputId1 = Guid.ParseExact("BB123".PadRight(32, '0'), "N");
            var goodInputId2 = Guid.ParseExact("BB234".PadRight(32, '0'), "N");

            var goodInputsTarget = new Target("goodInputsTarget", "", Enumerable.Empty<string>());

            var goodTarget1 = new Target("goodTarget1", "", Enumerable.Empty<string>());
            var goodTarget2 = new Target("goodTarget2", "", Enumerable.Empty<string>());
            var goodTargetDuration1 = (TimeSpan?)null;
            var goodTargetDuration2 = dryRun ? (TimeSpan?)null : TimeSpan.FromMinutes(1.234);

            var looseInput = new Target("looseInput", "", Enumerable.Empty<string>());
            var looseInputDuration = (TimeSpan?)null;
            var looseInputId = Guid.ParseExact("CC123".PadRight(32, '0'), "N");

            var looseTarget = new Target("looseTarget", "", Enumerable.Empty<string>());

            var looseTargets = new List<Target> { new Target("looseTarget", "", Enumerable.Empty<string>()) };

            var noInputsTarget = new Target("noInputsTarget", "", Enumerable.Empty<string>());

            var targets = new List<Target>
            {
                new Target("target1", "", Enumerable.Empty<string>()),
                new Target("target2", "", Enumerable.Empty<string>()),
                new Target("target3", "", Enumerable.Empty<string>()),
            };

            var verboseTargets = new Queue<Target>(
                new[]
                {
                    new Target("verboseTarget1", "", Enumerable.Empty<string>()),
                    new Target("verboseTarget2", "", Enumerable.Empty<string>()),
                    new Target("verboseTarget3", "", Enumerable.Empty<string>()),
                });

            var version = "version";

            await output.Header(() => version);

            await output.Awaiting(verboseTargets.Last(), verboseTargets);
            await output.WalkingDependencies(verboseTargets.Last(), verboseTargets);

            await output.Succeeded(emptyTargets);

            await output.Succeeded(looseTarget, looseInput, looseInputDuration, looseInputId, verboseTargets);
            await output.Succeeded(looseTargets);

            await output.Starting(targets);
            {
                await output.NoInputs(noInputsTarget, verboseTargets);

                await output.Succeeded(goodTarget1, verboseTargets, goodTargetDuration1);

                await output.Starting(goodTarget2, verboseTargets);
                await output.Succeeded(goodTarget2, verboseTargets, goodTargetDuration2);

                await output.Starting(badTarget, verboseTargets);
                {
                    await output.Error(badTarget, badTargetEx);
                }
                await output.Failed(badTarget, badTargetEx, badTargetDuration, verboseTargets);

                await output.Starting(goodInputsTarget, verboseTargets);
                {
                    await output.Starting(goodInputsTarget, goodInput1, goodInputId1, verboseTargets);
                    await output.Succeeded(goodInputsTarget, goodInput1, goodInputDuration1, goodInputId1, verboseTargets);

                    await output.Starting(goodInputsTarget, goodInput2, goodInputId2, verboseTargets);
                    await output.Succeeded(goodInputsTarget, goodInput2, goodInputDuration2, goodInputId2, verboseTargets);
                }
                await output.Succeeded(goodInputsTarget, verboseTargets);

                await output.Starting(badInputsTarget, verboseTargets);
                {
                    await output.Starting(badInputsTarget, goodInput1, goodInputId1, verboseTargets);
                    await output.Succeeded(badInputsTarget, goodInput1, goodInputDuration1, goodInputId1, verboseTargets);

                    await output.Starting(badInputsTarget, badInput, badInputId, verboseTargets);
                    {
                        await output.Error(badInputsTarget, badInput, badInputEx);
                    }
                    await output.Failed(badInputsTarget, badInput, badInputEx, badInputDuration, badInputId, verboseTargets);
                }
                await output.Failed(badInputsTarget, verboseTargets);
            }
            await output.Succeeded(targets);
            await output.Failed(targets);
        }

19 Source : BigDecimal.cs
with MIT License
from AdamWhiteHat

private static String ToString(BigInteger mantissa, int exponent, IFormatProvider provider)
		{
			if (provider == null) throw new ArgumentNullException();
			if (mantissa == null || BigDecimalNumberFormatInfo == null) { return NullString; }

			NumberFormatInfo formatProvider = NumberFormatInfo.GetInstance(provider);

			bool negativeValue = (mantissa.Sign == -1);
			bool negativeExponent = (Math.Sign(exponent) == -1);

			string result = BigInteger.Abs(mantissa).ToString();
			int absExp = Math.Abs(exponent);

			if (negativeExponent)
			{
				if (absExp > result.Length)
				{
					int zerosToAdd = Math.Abs(absExp - result.Length);
					string zeroString = string.Join(string.Empty, Enumerable.Repeat(formatProvider.NativeDigits[0], zerosToAdd));
					result = zeroString + result;
					result = result.Insert(0, formatProvider.NumberDecimalSeparator);
					result = result.Insert(0, formatProvider.NativeDigits[0]);
				}
				else
				{
					int indexOfRadixPoint = Math.Abs(absExp - result.Length);
					result = result.Insert(indexOfRadixPoint, formatProvider.NumberDecimalSeparator);
					if (indexOfRadixPoint == 0)
					{
						result = result.Insert(0, formatProvider.NativeDigits[0]);
					}
				}

				result = result.TrimEnd(new char[] { '0' });
				if (result.Last().ToString() == formatProvider.NumberDecimalSeparator)
				{
					result = result.Substring(0, result.Length - 1);
				}
			}
			else
			{
				string zeroString = string.Join(string.Empty, Enumerable.Repeat(formatProvider.NativeDigits[0], absExp));
				result += zeroString;
			}

			if (negativeExponent) // Prefix "0."
			{

			}
			if (negativeValue) // Prefix "-"
			{
				result = result.Insert(0, formatProvider.NegativeSign);
			}

			return result;


		}

19 Source : SqliteSyncProvider.cs
with MIT License
from adospace

public async Task<SyncChangeSet> GetChangesAsync(Guid otherStoreId, SyncFilterParameter[] syncFilterParameters, SyncDirection syncDirection, CancellationToken cancellationToken = default)
        {
            syncFilterParameters = syncFilterParameters ?? new SyncFilterParameter[] { };

            var fromAnchor = (await GetLastLocalAnchorForStoreAsync(otherStoreId, cancellationToken));

            //if fromVersion is 0 means that client needs actually to initialize its local datastore

            //await InitializeStoreAsync();

            var now = DateTime.Now;

            _logger?.Info($"[{_storeId}] Begin GetChanges(from={otherStoreId}, syncDirection={syncDirection}, fromVersion={fromAnchor})");

            using (var c = new SqliteConnection(Configuration.ConnectionString))
            {
                await c.OpenAsync(cancellationToken);

                using (var cmd = new SqliteCommand())
                {
                    var items = new List<SqliteSyncItem>();

                    using (var tr = c.BeginTransaction())
                    {
                        cmd.Connection = c;
                        cmd.Transaction = tr;

                        try
                        {
                            cmd.CommandText = "SELECT MAX(ID) FROM  __CORE_SYNC_CT";
                            cmd.Parameters.Clear();
                            var version = await cmd.ExecuteLongScalarAsync(cancellationToken);

                            cmd.CommandText = "SELECT MIN(ID) FROM  __CORE_SYNC_CT";
                            cmd.Parameters.Clear();
                            var minVersion = await cmd.ExecuteLongScalarAsync(cancellationToken);

                            if (!fromAnchor.IsNull() && fromAnchor.Version < minVersion - 1)
                                throw new InvalidOperationException($"Unable to get changes, version of data requested ({fromAnchor}) is too old (min valid version {minVersion})");

                            foreach (var table in Configuration.Tables.Cast<SqliteSyncTable>().Where(_ => _.Columns.Any()))
                            {
                                if (table.SyncDirection != SyncDirection.UploadAndDownload &&
                                    table.SyncDirection != syncDirection)
                                    continue;

                                //var snapshoreplacedems = new HashSet<object>();

                                if (fromAnchor.IsNull() && !table.SkipInitialSnapshot)
                                {
                                    cmd.CommandText = table.InitialSnapshotQuery;
                                    cmd.Parameters.Clear();
                                    foreach (var syncFilterParameter in syncFilterParameters)
                                    {
                                        cmd.Parameters.AddWithValue(syncFilterParameter.Name, syncFilterParameter.Value);
                                    }

                                    using (var r = await cmd.ExecuteReaderAsync(cancellationToken))
                                    {
                                        while (await r.ReadAsync(cancellationToken))
                                        {
                                            var values = Enumerable.Range(0, r.FieldCount).ToDictionary(_ => r.GetName(_), _ => GetValueFromRecord(table, r.GetName(_), _, r));
                                            items.Add(new SqliteSyncItem(table, ChangeType.Insert, values));
                                            //snapshoreplacedems.Add(values[table.PrimaryColumnName]);
                                            _logger?.Trace($"[{_storeId}] Initial snapshot {items.Last()}");
                                        }
                                    }
                                }

                                if (!fromAnchor.IsNull())
                                {
                                    cmd.CommandText = table.IncrementalAddOrUpdatesQuery;
                                    cmd.Parameters.Clear();
                                    cmd.Parameters.AddWithValue("@version", fromAnchor.Version);
                                    cmd.Parameters.AddWithValue("@sourceId", otherStoreId.ToString());
                                    foreach (var syncFilterParameter in syncFilterParameters)
                                    {
                                        cmd.Parameters.AddWithValue(syncFilterParameter.Name, syncFilterParameter.Value);
                                    }

                                    using (var r = await cmd.ExecuteReaderAsync(cancellationToken))
                                    {
                                        while (await r.ReadAsync(cancellationToken))
                                        {
                                            var values = Enumerable.Range(0, r.FieldCount).ToDictionary(_ => r.GetName(_), _ => GetValueFromRecord(table, r.GetName(_), _, r));
                                            //if (snapshoreplacedems.Contains(values[table.PrimaryColumnName]))
                                            //    continue;

                                            items.Add(new SqliteSyncItem(table, DetectChangeType(values),
                                                values.Where(_ => _.Key != "__OP").ToDictionary(_ => _.Key, _ => _.Value == DBNull.Value ? null : _.Value)));
                                            _logger?.Trace($"[{_storeId}] Incremental add or update {items.Last()}");
                                        }
                                    }

                                    cmd.CommandText = table.IncrementalDeletesQuery;
                                    cmd.Parameters.Clear();
                                    cmd.Parameters.AddWithValue("@version", fromAnchor.Version);
                                    cmd.Parameters.AddWithValue("@sourceId", otherStoreId.ToString());
                                    using (var r = await cmd.ExecuteReaderAsync(cancellationToken))
                                    {
                                        while (await r.ReadAsync(cancellationToken))
                                        {
                                            var values = Enumerable.Range(0, r.FieldCount).ToDictionary(_ => r.GetName(_), _ => GetValueFromRecord(table, r.GetName(_), _, r));
                                            items.Add(new SqliteSyncItem(table, ChangeType.Delete, values));
                                            _logger?.Trace($"[{_storeId}] Incremental delete {items.Last()}");
                                        }
                                    }
                                }
                            }

                            tr.Commit();

                            var resChangeSet = new SyncChangeSet(new SyncAnchor(_storeId, version), await GetLastRemoteAnchorForStoreAsync(otherStoreId, cancellationToken), items);

                            _logger?.Info($"[{_storeId}] Completed GetChanges(to={version}, {items.Count} items) in {(DateTime.Now - now).TotalMilliseconds}ms");

                            return resChangeSet;

                        }
                        catch (Exception)
                        {
                            tr.Rollback();
                            throw;
                        }
                    }
                }
            }

        }

19 Source : OrganizationServiceExtensions.cs
with MIT License
from Adoxio

private static EnreplacedyCollection JoinPages(ICollection<EnreplacedyCollection> pages)
		{
			if (pages.Count < 2)
			{
				return pages.FirstOrDefault();
			}

			var last = pages.Last();
			var joinedPages = pages.SelectMany(page => page.Enreplacedies).ToList();

			var enreplacedies = new EnreplacedyCollection(joinedPages)
			{
				EnreplacedyName = last.EnreplacedyName,
				ExtensionData = last.ExtensionData,
				MinActiveRowVersion = last.MinActiveRowVersion,
				MoreRecords = last.MoreRecords,
				PagingCookie = last.PagingCookie,
				TotalRecordCount = last.TotalRecordCount,
				TotalRecordCountLimitExceeded = last.TotalRecordCountLimitExceeded
			};

			return enreplacedies;
		}

19 Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio

public static int FetchCount(this OrganizationServiceContext serviceContext, string enreplacedyLogicalName, string countAttributeLogicalName, Action<Action<string, string, string>> addFilterConditions, Action<Action<string, string, string>> addOrFilterConditions = null)
		{
			var fetchXml = XDoreplacedent.Parse(@"
				<fetch mapping=""logical"" aggregate=""true"">
					<enreplacedy>
						<attribute aggregate=""countcolumn"" distinct=""true"" alias=""count"" />
						<filter type=""and"" />
						<filter type=""or"" />
					</enreplacedy>
				</fetch>");

			var enreplacedy = fetchXml.Descendants("enreplacedy").First();
			enreplacedy.SetAttributeValue("name", enreplacedyLogicalName);

			enreplacedy.Descendants("attribute").First().SetAttributeValue("name", countAttributeLogicalName);

			var andFilter = enreplacedy.Descendants("filter").First();

			addFilterConditions(andFilter.AddFetchXmlFilterCondition);

			if (addOrFilterConditions != null)
			{
				var orFilter = enreplacedy.Descendants("filter").Last();

				addOrFilterConditions(orFilter.AddFetchXmlFilterCondition);
			}

			var response = (RetrieveMultipleResponse)serviceContext.Execute(new RetrieveMultipleRequest
			{
				Query = new FetchExpression(fetchXml.ToString())
			});

			return response.EnreplacedyCollection.Enreplacedies.First().GetAttributeAliasedValue<int>("count");
		}

19 Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio

public static int FetchCount(
			this OrganizationServiceContext serviceContext,
			string enreplacedyLogicalName,
			string countAttributeLogicalName,
			Action<Action<string, string, string>> addFilterConditions,
			Action<Action<string, string, string>> addOrFilterConditions = null,
			Action<Action<string, string>> addBinaryFilterConditions = null)
		{
			var fetchXml = XDoreplacedent.Parse(@"
				<fetch mapping=""logical"" aggregate=""true"">
					<enreplacedy>
						<attribute aggregate=""countcolumn"" distinct=""true"" alias=""count"" />
						<filter type=""and"" />
						<filter type=""or"" />
					</enreplacedy>
				</fetch>");

			var enreplacedy = fetchXml.Descendants("enreplacedy").First();
			enreplacedy.SetAttributeValue("name", enreplacedyLogicalName);

			enreplacedy.Descendants("attribute").First().SetAttributeValue("name", countAttributeLogicalName);

			var andFilter = enreplacedy.Descendants("filter").First();

			addFilterConditions(andFilter.AddFetchXmlFilterCondition);
			if (addBinaryFilterConditions != null)
			{
				addBinaryFilterConditions(andFilter.AddFetchXmlFilterCondition);
			}

			if (addOrFilterConditions != null)
			{
				var orFilter = enreplacedy.Descendants("filter").Last();

				addOrFilterConditions(orFilter.AddFetchXmlFilterCondition);
			}

			var response = serviceContext.RetrieveSingle(Fetch.Parse(fetchXml.ToString()), false, false, RequestFlag.AllowStaleData);

			return response.GetAttributeAliasedValue<int>("count");
		}

19 Source : PortalViewContext.cs
with MIT License
from Adoxio

public bool IsAncestorSiteMapNode(string url, bool excludeRootNodes = false)
		{
			if (string.IsNullOrWhiteSpace(url) || !(VirtualPathUtility.IsAbsolute(url) || VirtualPathUtility.IsAppRelative(url)))
			{
				return false;
			}

			var currentNodeAncestors = CurrentSiteMapNodeAncestors;

			if (currentNodeAncestors.Length < 1)
			{
				return false;
			}

			var node = FindSiteMapNode(url);

			if (node == null)
			{
				return false;
			}

			var root = currentNodeAncestors.Last();

			foreach (var ancestor in currentNodeAncestors)
			{
				if (ancestor.Equals(node))
				{
					return !(excludeRootNodes && ancestor.Equals(root));
				}
			}

			return false;
		}

See More Examples