System.TimeSpan.CompareTo(System.TimeSpan)

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

95 Examples 7

19 Source : ListViewItemComparer.cs
with GNU General Public License v3.0
from ahmed605

public int Compare(object x, object y)
        {
            if (x == null || y == null)
            {
                return 0;
            }

            try
            {
                if (_column > -1)
                {
                    int returnVal;
                    ListViewItem lvix = ((ListViewItem) x);
                    ListViewItem lviy = ((ListViewItem) y);

                    if (lvix.SubItems[_column].Tag is TimeSpan)
                    {
                        TimeSpan tx = (TimeSpan) lvix.SubItems[_column].Tag;
                        TimeSpan ty = (TimeSpan) lviy.SubItems[_column].Tag;
                        returnVal = tx.CompareTo(ty);
                    }
                    else if (lvix.SubItems[_column].Tag is int)
                    {
                        returnVal = ((int) lvix.SubItems[_column].Tag).CompareTo((int) lviy.SubItems[_column].Tag);
                    }
                    else
                    {
                        returnVal = String.Compare(lvix.SubItems[_column].Text, lviy.SubItems[_column].Text);
                    }

                    returnVal *= _descending ? -1 : 1;
                    return returnVal;
                }
                return 0;
            }
            catch
            {
                return 0;
            }
        }

19 Source : JValue.cs
with MIT License
from akaskela

internal static int Compare(JTokenType valueType, object objA, object objB)
        {
            if (objA == null && objB == null)
            {
                return 0;
            }
            if (objA != null && objB == null)
            {
                return 1;
            }
            if (objA == null && objB != null)
            {
                return -1;
            }

            switch (valueType)
            {
                case JTokenType.Integer:
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
                    if (objA is BigInteger)
                    {
                        return CompareBigInteger((BigInteger)objA, objB);
                    }
                    if (objB is BigInteger)
                    {
                        return -CompareBigInteger((BigInteger)objB, objA);
                    }
#endif
                    if (objA is ulong || objB is ulong || objA is decimal || objB is decimal)
                    {
                        return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture));
                    }
                    else if (objA is float || objB is float || objA is double || objB is double)
                    {
                        return CompareFloat(objA, objB);
                    }
                    else
                    {
                        return Convert.ToInt64(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToInt64(objB, CultureInfo.InvariantCulture));
                    }
                case JTokenType.Float:
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
                    if (objA is BigInteger)
                    {
                        return CompareBigInteger((BigInteger)objA, objB);
                    }
                    if (objB is BigInteger)
                    {
                        return -CompareBigInteger((BigInteger)objB, objA);
                    }
#endif
                    return CompareFloat(objA, objB);
                case JTokenType.Comment:
                case JTokenType.String:
                case JTokenType.Raw:
                    string s1 = Convert.ToString(objA, CultureInfo.InvariantCulture);
                    string s2 = Convert.ToString(objB, CultureInfo.InvariantCulture);

                    return string.CompareOrdinal(s1, s2);
                case JTokenType.Boolean:
                    bool b1 = Convert.ToBoolean(objA, CultureInfo.InvariantCulture);
                    bool b2 = Convert.ToBoolean(objB, CultureInfo.InvariantCulture);

                    return b1.CompareTo(b2);
                case JTokenType.Date:
#if !NET20
                    if (objA is DateTime)
                    {
#endif
                        DateTime date1 = (DateTime)objA;
                        DateTime date2;

#if !NET20
                        if (objB is DateTimeOffset)
                        {
                            date2 = ((DateTimeOffset)objB).DateTime;
                        }
                        else
#endif
                        {
                            date2 = Convert.ToDateTime(objB, CultureInfo.InvariantCulture);
                        }

                        return date1.CompareTo(date2);
#if !NET20
                    }
                    else
                    {
                        DateTimeOffset date1 = (DateTimeOffset)objA;
                        DateTimeOffset date2;

                        if (objB is DateTimeOffset)
                        {
                            date2 = (DateTimeOffset)objB;
                        }
                        else
                        {
                            date2 = new DateTimeOffset(Convert.ToDateTime(objB, CultureInfo.InvariantCulture));
                        }

                        return date1.CompareTo(date2);
                    }
#endif
                case JTokenType.Bytes:
                    if (!(objB is byte[]))
                    {
                        throw new ArgumentException("Object must be of type byte[].");
                    }

                    byte[] bytes1 = objA as byte[];
                    byte[] bytes2 = objB as byte[];
                    if (bytes1 == null)
                    {
                        return -1;
                    }
                    if (bytes2 == null)
                    {
                        return 1;
                    }

                    return MiscellaneousUtils.ByteArrayCompare(bytes1, bytes2);
                case JTokenType.Guid:
                    if (!(objB is Guid))
                    {
                        throw new ArgumentException("Object must be of type Guid.");
                    }

                    Guid guid1 = (Guid)objA;
                    Guid guid2 = (Guid)objB;

                    return guid1.CompareTo(guid2);
                case JTokenType.Uri:
                    if (!(objB is Uri))
                    {
                        throw new ArgumentException("Object must be of type Uri.");
                    }

                    Uri uri1 = (Uri)objA;
                    Uri uri2 = (Uri)objB;

                    return Comparer<string>.Default.Compare(uri1.ToString(), uri2.ToString());
                case JTokenType.TimeSpan:
                    if (!(objB is TimeSpan))
                    {
                        throw new ArgumentException("Object must be of type TimeSpan.");
                    }

                    TimeSpan ts1 = (TimeSpan)objA;
                    TimeSpan ts2 = (TimeSpan)objB;

                    return ts1.CompareTo(ts2);
                default:
                    throw MiscellaneousUtils.CreateArgumentOutOfRangeException("valueType", valueType, "Unexpected value type: {0}".FormatWith(CultureInfo.InvariantCulture, valueType));
            }
        }

19 Source : TimingPoint.cs
with MIT License
from AlFasGD

public static int AbsoluteComparison(TimingPoint left, TimingPoint right) => left.GetAbsoluteTimePosition().CompareTo(right.GetAbsoluteTimePosition());

19 Source : DanmakuMergerHandler.cs
with GNU General Public License v3.0
from Bililive

public async Task<CommandResponse<DanmakuMergerResponse>> Handle(DanmakuMergerRequest request, CancellationToken cancellationToken, ProgressCallback? progress)
        {
            var inputLength = request.Inputs.Length;

            if (inputLength < 2)
                return new CommandResponse<DanmakuMergerResponse>
                {
                    Status = ResponseStatus.Error,
                    ErrorMessage = "At least 2 input files required"
                };

            var files = new FileStream[inputLength];
            var readers = new XmlReader?[inputLength];

            FileStream? outputFile = null;
            XmlWriter? writer = null;
            XElement recordInfo;

            DateTimeOffset baseTime;
            TimeSpan[] timeDiff;

            try // finally
            {

                try
                {
                    // 打开输入文件
                    for (var i = 0; i < inputLength; i++)
                    {
                        var file = File.Open(request.Inputs[i], FileMode.Open, FileAccess.Read, FileShare.Read);
                        files[i] = file;
                        readers[i] = XmlReader.Create(file, null);
                    }

                    // 计算时间差
                    var startTimes = new (DateTimeOffset time, XElement element)[inputLength];
                    for (var i = 0; i < inputLength; i++)
                    {
                        var r = readers[i]!;
                        r.ReadStartElement("i");
                        while (r.Name != "i")
                        {
                            if (r.Name == "BililiveRecorderRecordInfo")
                            {
                                var el = (XNode.ReadFrom(r) as XElement)!;
                                var time = (DateTimeOffset)el.Attribute("start_time");
                                startTimes[i] = (time, el);
                                break;
                            }
                            else
                            {
                                r.Skip();
                            }
                        }
                    }

                    var b = startTimes.OrderBy(x => x.time).First();
                    recordInfo = b.element;
                    baseTime = b.time;
                    timeDiff = startTimes.Select(x => x.time - baseTime).ToArray();
                }
                catch (Exception ex)
                {
                    return new CommandResponse<DanmakuMergerResponse>
                    {
                        Status = ResponseStatus.InputIOError,
                        Exception = ex,
                        ErrorMessage = ex.Message
                    };
                }

                try
                {
                    // 打开输出文件
                    outputFile = File.Open(request.Output, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
                    writer = XmlWriter.Create(outputFile, new XmlWriterSettings
                    {
                        Indent = true,
                        IndentChars = "  ",
                        Encoding = Encoding.UTF8,
                        CloseOutput = true,
                        WriteEndDoreplacedentOnClose = true,
                    });

                    // 写入文件开头
                    writer.WriteStartDoreplacedent();
                    writer.WriteProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"#s\"");
                    writer.WriteStartElement("i");
                    writer.WriteComment("\nB站录播姬 " + GitVersionInformation.FullSemVer + " 使用工具箱合并\n本文件的弹幕信息兼容B站主站视频弹幕XML格式\n本XML自带样式可以在浏览器里打开(推荐使用Chrome)\n\nsc 为SuperChat\ngift为礼物\nguard为上船\n\nattribute \"raw\" 为原始数据\n");
                    writer.WriteElementString("chatserver", "chat.bilibili.com");
                    writer.WriteElementString("chatid", "0");
                    writer.WriteElementString("mission", "0");
                    writer.WriteElementString("maxlimit", "1000");
                    writer.WriteElementString("state", "0");
                    writer.WriteElementString("real_name", "0");
                    writer.WriteElementString("source", "0");

                    writer.WriteStartElement("BililiveRecorder");
                    writer.WriteAttributeString("version", GitVersionInformation.FullSemVer);
                    writer.WriteAttributeString("merged", "by toolbox");
                    writer.WriteEndElement();

                    // 写入直播间信息
                    recordInfo.WriteTo(writer);

                    // see BililiveRecorder.Core\Danmaku\BasicDanmakuWriter.cs
                    const string style = @"<z:stylesheet version=""1.0"" id=""s"" xml:id=""s"" xmlns:z=""http://www.w3.org/1999/XSL/Transform""><z:output method=""html""/><z:template match=""/""><html><meta name=""viewport"" content=""width=device-width""/><replacedle>B站录播姬弹幕文件 - <z:value-of select=""/i/BililiveRecorderRecordInfo/@name""/></replacedle><style>body{margin:0}h1,h2,p,table{margin-left:5px}table{border-spacing:0}td,th{border:1px solid grey;padding:1px}th{position:sticky;top:0;background:#4098de}tr:hover{background:#d9f4ff}div{overflow:auto;max-height:80vh;max-width:100vw;width:fit-content}</style><h1>B站录播姬弹幕XML文件</h1><p>本文件的弹幕信息兼容B站主站视频弹幕XML格式,可以使用现有的转换工具把文件中的弹幕转为replaced字幕文件</p><table><tr><td>录播姬版本</td><td><z:value-of select=""/i/BililiveRecorder/@version""/></td></tr><tr><td>房间号</td><td><z:value-of select=""/i/BililiveRecorderRecordInfo/@roomid""/></td></tr><tr><td>主播名</td><td><z:value-of select=""/i/BililiveRecorderRecordInfo/@name""/></td></tr><tr><td>录制开始时间</td><td><z:value-of select=""/i/BililiveRecorderRecordInfo/@start_time""/></td></tr><tr><td><a href=""#d"">弹幕</a></td><td>共 <z:value-of select=""count(/i/d)""/> 条记录</td></tr><tr><td><a href=""#guard"">上船</a></td><td>共 <z:value-of select=""count(/i/guard)""/> 条记录</td></tr><tr><td><a href=""#sc"">SC</a></td><td>共 <z:value-of select=""count(/i/sc)""/> 条记录</td></tr><tr><td><a href=""#gift"">礼物</a></td><td>共 <z:value-of select=""count(/i/gift)""/> 条记录</td></tr></table><h2 id=""d"">弹幕</h2><div><table><tr><th>用户名</th><th>弹幕</th><th>参数</th></tr><z:for-each select=""/i/d""><tr><td><z:value-of select=""@user""/></td><td><z:value-of select="".""/></td><td><z:value-of select=""@p""/></td></tr></z:for-each></table></div><h2 id=""guard"">舰长购买</h2><div><table><tr><th>用户名</th><th>舰长等级</th><th>购买数量</th><th>出现时间</th></tr><z:for-each select=""/i/guard""><tr><td><z:value-of select=""@user""/></td><td><z:value-of select=""@level""/></td><td><z:value-of select=""@count""/></td><td><z:value-of select=""@ts""/></td></tr></z:for-each></table></div><h2 id=""sc"">SuperChat 醒目留言</h2><div><table><tr><th>用户名</th><th>内容</th><th>显示时长</th><th>价格</th><th>出现时间</th></tr><z:for-each select=""/i/sc""><tr><td><z:value-of select=""@user""/></td><td><z:value-of select="".""/></td><td><z:value-of select=""@time""/></td><td><z:value-of select=""@price""/></td><td><z:value-of select=""@ts""/></td></tr></z:for-each></table></div><h2 id=""gift"">礼物</h2><div><table><tr><th>用户名</th><th>礼物名</th><th>礼物数量</th><th>出现时间</th></tr><z:for-each select=""/i/gift""><tr><td><z:value-of select=""@user""/></td><td><z:value-of select=""@giftname""/></td><td><z:value-of select=""@giftcount""/></td><td><z:value-of select=""@ts""/></td></tr></z:for-each></table></div></html></z:template></z:stylesheet>";

                    writer.WriteStartElement("BililiveRecorderXmlStyle");
                    writer.WriteRaw(style);
                    writer.WriteEndElement();
                }
                catch (Exception ex)
                {
                    return new CommandResponse<DanmakuMergerResponse>
                    {
                        Status = ResponseStatus.OutputIOError,
                        Exception = ex,
                        ErrorMessage = ex.Message
                    };
                }

                try
                {
                    var els = new List<(TimeSpan time, XElement el, int reader)>();

                    // 取出所有文件里第一条数据
                    for (var i = 0; i < inputLength; i++)
                    {
                        var r = readers[i]!;
                        var el = ReadDanmakuElement(r);
                        if (el is null)
                        {
                            readers[i] = null;
                            continue;
                        }
                        var time = UpdateTimestamp(el, timeDiff[i]);
                        els.Add((time, el, i));
                    }

                    // 排序
                    els.Sort((a, b) => a.time.CompareTo(b.time));

                    while (true)
                    {
                        // 写入时间最小的数据

                        // 所有数据写完就退出循环
                        if (els.Count == 0)
                            break;

                        (var time, var el, var readerIndex) = els[0];
                        el.WriteTo(writer);
                        els.RemoveAt(0);

                        // 读取一个新的数据

                        var reader = readers[readerIndex];
                        // 检查这个文件是否还有更多数据
                        if (reader is not null)
                        {
                        readNextElementFromSameReader:
                            var newEl = ReadDanmakuElement(reader);
                            if (newEl is null)
                            {
                                // 文件已结束
                                reader.Dispose();
                                readers[readerIndex] = null;
                                continue;
                            }
                            else
                            {
                                // 计算新的时间
                                var newTime = UpdateTimestamp(newEl, timeDiff[readerIndex]);
                                if (els.Count < 1 || newTime < els[0].time)
                                {
                                    // 如果这是最后一个文件,或当前数据的时间是所有数据里最小的
                                    // 直接写入输出文件
                                    newEl.WriteTo(writer);
                                    goto readNextElementFromSameReader;
                                }
                                else
                                {
                                    // 如果其他数据比本数据的时间更小
                                    // 添加到列表中,后面排序再来
                                    els.Add((newTime, newEl, readerIndex));
                                    els.Sort((a, b) => a.time.CompareTo(b.time));
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    return new CommandResponse<DanmakuMergerResponse>
                    {
                        Status = ResponseStatus.Error,
                        Exception = ex,
                        ErrorMessage = ex.Message
                    };
                }

                return new CommandResponse<DanmakuMergerResponse> { Status = ResponseStatus.OK, Data = new DanmakuMergerResponse() };
            }
            finally
            {
                try
                {
                    writer?.Dispose();
                    outputFile?.Dispose();
                }
                catch (Exception) { }

                for (var i = 0; i < inputLength; i++)
                {
                    try
                    {
                        readers[i]?.Dispose();
                        files[i]?.Dispose();
                    }
                    catch (Exception) { }
                }
            }
        }

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

public void BeLessOrEqualTo(TimeSpan maxDuration, string because = "", params object[] becauseArgs)
        {
            bool Condition(TimeSpan duration) => duration.CompareTo(maxDuration) <= 0;
            (bool isRunning, TimeSpan elapsed) = PollUntil(Condition, expectedResult: false, rate: maxDuration);

            Execute.replacedertion
                .ForCondition(Condition(elapsed))
                .BecauseOf(because, becauseArgs)
                .FailWith("Execution of " +
                          execution.ActionDescription + " should be less or equal to {0}{reason}, but it required " +
                          (isRunning ? "more than " : "exactly ") + "{1}.",
                    maxDuration,
                    elapsed);
        }

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

public void BeLessThan(TimeSpan maxDuration, string because = "", params object[] becauseArgs)
        {
            bool Condition(TimeSpan duration) => duration.CompareTo(maxDuration) < 0;
            (bool isRunning, TimeSpan elapsed) = PollUntil(Condition, expectedResult: false, rate: maxDuration);

            Execute.replacedertion
                .ForCondition(Condition(execution.ElapsedTime))
                .BecauseOf(because, becauseArgs)
                .FailWith("Execution of " +
                          execution.ActionDescription + " should be less than {0}{reason}, but it required " +
                          (isRunning ? "more than " : "exactly ") + "{1}.",
                    maxDuration,
                    elapsed);
        }

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

public void BeGreaterOrEqualTo(TimeSpan minDuration, string because = "", params object[] becauseArgs)
        {
            bool Condition(TimeSpan duration) => duration.CompareTo(minDuration) >= 0;
            (bool isRunning, TimeSpan elapsed) = PollUntil(Condition, expectedResult: true, rate: minDuration);

            Execute.replacedertion
                .ForCondition(Condition(elapsed))
                .BecauseOf(because, becauseArgs)
                .FailWith("Execution of " +
                          execution.ActionDescription + " should be greater or equal to {0}{reason}, but it required " +
                          (isRunning ? "more than " : "exactly ") + "{1}.",
                    minDuration,
                    elapsed);
        }

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

public void BeGreaterThan(TimeSpan minDuration, string because = "", params object[] becauseArgs)
        {
            bool Condition(TimeSpan duration) => duration.CompareTo(minDuration) > 0;
            (bool isRunning, TimeSpan elapsed) = PollUntil(Condition, expectedResult: true, rate: minDuration);

            Execute.replacedertion
                .ForCondition(Condition(elapsed))
                .BecauseOf(because, becauseArgs)
                .FailWith("Execution of " +
                          execution.ActionDescription + " should be greater than {0}{reason}, but it required " +
                          (isRunning ? "more than " : "exactly ") + "{1}.",
                    minDuration,
                    elapsed);
        }

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

public AndConstraint<SimpleTimeSpanreplacedertions> BePositive(string because = "", params object[] becauseArgs)
        {
            Execute.replacedertion
                .BecauseOf(because, becauseArgs)
                .WithExpectation("Expected {context:time} to be positive{reason}, ")
                .ForCondition(Subject.HasValue)
                .FailWith("but found <null>.")
                .Then
                .ForCondition(Subject.Value.CompareTo(TimeSpan.Zero) > 0)
                .FailWith("but found {0}.", Subject.Value)
                .Then
                .ClearExpectation();

            return new AndConstraint<SimpleTimeSpanreplacedertions>(this);
        }

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

public AndConstraint<SimpleTimeSpanreplacedertions> BeNegative(string because = "", params object[] becauseArgs)
        {
            Execute.replacedertion
                .BecauseOf(because, becauseArgs)
                .WithExpectation("Expected {context:time} to be negative{reason}, ")
                .ForCondition(Subject.HasValue)
                .FailWith("but found <null>.")
                .Then
                .ForCondition(Subject.Value.CompareTo(TimeSpan.Zero) < 0)
                .FailWith("but found {0}.", Subject.Value)
                .Then
                .ClearExpectation();

            return new AndConstraint<SimpleTimeSpanreplacedertions>(this);
        }

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

public AndConstraint<SimpleTimeSpanreplacedertions> Be(TimeSpan expected, string because = "", params object[] becauseArgs)
        {
            Execute.replacedertion
                .BecauseOf(because, becauseArgs)
                .WithExpectation("Expected {0}{reason}, ", expected)
                .ForCondition(Subject.HasValue)
                .FailWith("but found <null>.")
                .Then
                .ForCondition(Subject.Value.CompareTo(expected) == 0)
                .FailWith("but found {0}.", Subject.Value)
                .Then
                .ClearExpectation();

            return new AndConstraint<SimpleTimeSpanreplacedertions>(this);
        }

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

public AndConstraint<SimpleTimeSpanreplacedertions> NotBe(TimeSpan unexpected, string because = "", params object[] becauseArgs)
        {
            Execute.replacedertion
                .ForCondition(!Subject.HasValue || Subject.Value.CompareTo(unexpected) != 0)
                .BecauseOf(because, becauseArgs)
                .FailWith("Did not expect {0}{reason}.", unexpected);

            return new AndConstraint<SimpleTimeSpanreplacedertions>(this);
        }

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

public AndConstraint<SimpleTimeSpanreplacedertions> BeLessThan(TimeSpan expected, string because = "", params object[] becauseArgs)
        {
            Execute.replacedertion
                .BecauseOf(because, becauseArgs)
                .WithExpectation("Expected {context:time} to be less than {0}{reason}, ", expected)
                .ForCondition(Subject.HasValue)
                .FailWith("but found <null>.")
                .Then
                .ForCondition(Subject.Value.CompareTo(expected) < 0)
                .FailWith("but found {0}.", Subject.Value)
                .Then
                .ClearExpectation();

            return new AndConstraint<SimpleTimeSpanreplacedertions>(this);
        }

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

public AndConstraint<SimpleTimeSpanreplacedertions> BeLessOrEqualTo(TimeSpan expected, string because = "", params object[] becauseArgs)
        {
            Execute.replacedertion
                .BecauseOf(because, becauseArgs)
                .WithExpectation("Expected {context:time} to be less or equal to {0}{reason}, ", expected)
                .ForCondition(Subject.HasValue)
                .FailWith("but found <null>.")
                .Then
                .ForCondition(Subject.Value.CompareTo(expected) <= 0)
                .FailWith("but found {0}.", Subject.Value)
                .Then
                .ClearExpectation();

            return new AndConstraint<SimpleTimeSpanreplacedertions>(this);
        }

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

public AndConstraint<SimpleTimeSpanreplacedertions> BeGreaterThan(TimeSpan expected, string because = "", params object[] becauseArgs)
        {
            Execute.replacedertion
                .BecauseOf(because, becauseArgs)
                .WithExpectation("Expected {context:time} to be greater than {0}{reason}, ", expected)
                .ForCondition(Subject.HasValue)
                .FailWith("but found <null>.")
                .Then
                .ForCondition(Subject.Value.CompareTo(expected) > 0)
                .FailWith("but found {0}.", Subject.Value)
                .Then
                .ClearExpectation();

            return new AndConstraint<SimpleTimeSpanreplacedertions>(this);
        }

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

public AndConstraint<SimpleTimeSpanreplacedertions> BeGreaterOrEqualTo(TimeSpan expected, string because = "",
            params object[] becauseArgs)
        {
            Execute.replacedertion
                .BecauseOf(because, becauseArgs)
                .WithExpectation("Expected {context:time} to be greater or equal to {0}{reason}, ", expected)
                .ForCondition(Subject.HasValue)
                .FailWith("but found <null>.")
                .Then
                .ForCondition(Subject.Value.CompareTo(expected) >= 0)
                .FailWith("but found {0}.", Subject.Value)
                .Then
                .ClearExpectation();

            return new AndConstraint<SimpleTimeSpanreplacedertions>(this);
        }

19 Source : ScheduledItem.cs
with GNU General Public License v3.0
from BramDC3

public int CompareTo(ScheduledItem other)
        {
            // MSDN: By definition, any object compares greater than null, and two null references compare equal to each other. 
            if (object.ReferenceEquals(other, null))
                return 1;

            return DueTime.CompareTo(other.DueTime);
        }

19 Source : JValue.cs
with MIT License
from CragonGame

private static int Compare(JTokenType valueType, object objA, object objB)
    {
      if (objA == null && objB == null)
        return 0;
      if (objA != null && objB == null)
        return 1;
      if (objA == null && objB != null)
        return -1;

      switch (valueType)
      {
        case JTokenType.Integer:
          if (objA is ulong || objB is ulong || objA is decimal || objB is decimal)
            return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture));
          else if (objA is float || objB is float || objA is double || objB is double)
            return CompareFloat(objA, objB);
          else
            return Convert.ToInt64(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToInt64(objB, CultureInfo.InvariantCulture));
        case JTokenType.Float:
          return CompareFloat(objA, objB);
        case JTokenType.Comment:
        case JTokenType.String:
        case JTokenType.Raw:
          string s1 = Convert.ToString(objA, CultureInfo.InvariantCulture);
          string s2 = Convert.ToString(objB, CultureInfo.InvariantCulture);

          return s1.CompareTo(s2);
        case JTokenType.Boolean:
          bool b1 = Convert.ToBoolean(objA, CultureInfo.InvariantCulture);
          bool b2 = Convert.ToBoolean(objB, CultureInfo.InvariantCulture);

          return b1.CompareTo(b2);
        case JTokenType.Date:
          if (objA is DateTime)
          {
            DateTime date1 = Convert.ToDateTime(objA, CultureInfo.InvariantCulture);
            DateTime date2 = Convert.ToDateTime(objB, CultureInfo.InvariantCulture);

            return date1.CompareTo(date2);
          }
          else
          {
            if (!(objB is DateTimeOffset))
              throw new ArgumentException("Object must be of type DateTimeOffset.");

            DateTimeOffset date1 = (DateTimeOffset) objA;
            DateTimeOffset date2 = (DateTimeOffset) objB;

            return date1.CompareTo(date2);
          }
        case JTokenType.Bytes:
          if (!(objB is byte[]))
            throw new ArgumentException("Object must be of type byte[].");

          byte[] bytes1 = objA as byte[];
          byte[] bytes2 = objB as byte[];
          if (bytes1 == null)
            return -1;
          if (bytes2 == null)
            return 1;

          return MiscellaneousUtils.ByteArrayCompare(bytes1, bytes2);
        case JTokenType.Guid:
          if (!(objB is Guid))
            throw new ArgumentException("Object must be of type Guid.");

          Guid guid1 = (Guid) objA;
          Guid guid2 = (Guid) objB;

          return guid1.CompareTo(guid2);
        case JTokenType.Uri:
          if (!(objB is Uri))
            throw new ArgumentException("Object must be of type Uri.");

          Uri uri1 = (Uri)objA;
          Uri uri2 = (Uri)objB;

          return Comparer<string>.Default.Compare(uri1.ToString(), uri2.ToString());
        case JTokenType.TimeSpan:
          if (!(objB is TimeSpan))
            throw new ArgumentException("Object must be of type TimeSpan.");

          TimeSpan ts1 = (TimeSpan)objA;
          TimeSpan ts2 = (TimeSpan)objB;

          return ts1.CompareTo(ts2);
        default:
          throw MiscellaneousUtils.CreateArgumentOutOfRangeException("valueType", valueType, "Unexpected value type: {0}".FormatWith(CultureInfo.InvariantCulture, valueType));
      }
    }

19 Source : TimeSpan2.cs
with MIT License
from dahall

public int CompareTo(TimeSpan other) => core.CompareTo(other);

19 Source : TimeSpan2.cs
with MIT License
from dahall

public int CompareTo(TimeSpan2 other) => core.CompareTo(other.core);

19 Source : DerGeneralizedTime.cs
with MIT License
from dcomms

private string CalculateGmtOffset()
        {
            char sign = '+';
            DateTime time = ToDateTime();

#if SILVERLIGHT || PORTABLE
            long offset = time.Ticks - time.ToUniversalTime().Ticks;
            if (offset < 0)
            {
                sign = '-';
                offset = -offset;
            }
            int hours = (int)(offset / TimeSpan.TicksPerHour);
            int minutes = (int)(offset / TimeSpan.TicksPerMinute) % 60;
#else
            // Note: GetUtcOffset incorporates Daylight Savings offset
            TimeSpan offset =  TimeZone.CurrentTimeZone.GetUtcOffset(time);
            if (offset.CompareTo(TimeSpan.Zero) < 0)
            {
                sign = '-';
                offset = offset.Duration();
            }
            int hours = offset.Hours;
            int minutes = offset.Minutes;
#endif

            return "GMT" + sign + Convert(hours) + ":" + Convert(minutes);
        }

19 Source : JValue.cs
with Microsoft Public License
from demianrasko

internal static int Compare(JTokenType valueType, object objA, object objB)
        {
            if (objA == null && objB == null)
            {
                return 0;
            }
            if (objA != null && objB == null)
            {
                return 1;
            }
            if (objA == null && objB != null)
            {
                return -1;
            }

            switch (valueType)
            {
                case JTokenType.Integer:

                    if (objA is ulong || objB is ulong || objA is decimal || objB is decimal)
                    {
                        return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture));
                    }
                    else if (objA is float || objB is float || objA is double || objB is double)
                    {
                        return CompareFloat(objA, objB);
                    }
                    else
                    {
                        return Convert.ToInt64(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToInt64(objB, CultureInfo.InvariantCulture));
                    }
                case JTokenType.Float:

                    return CompareFloat(objA, objB);
                case JTokenType.Comment:
                case JTokenType.String:
                case JTokenType.Raw:
                    string s1 = Convert.ToString(objA, CultureInfo.InvariantCulture);
                    string s2 = Convert.ToString(objB, CultureInfo.InvariantCulture);

                    return string.CompareOrdinal(s1, s2);
                case JTokenType.Boolean:
                    bool b1 = Convert.ToBoolean(objA, CultureInfo.InvariantCulture);
                    bool b2 = Convert.ToBoolean(objB, CultureInfo.InvariantCulture);

                    return b1.CompareTo(b2);
                case JTokenType.Date:
#if !NET20
                    if (objA is DateTime)
                    {
#endif
                        DateTime date1 = (DateTime)objA;
                        DateTime date2;

#if !NET20
                        if (objB is DateTimeOffset)
                        {
                            date2 = ((DateTimeOffset)objB).DateTime;
                        }
                        else
#endif
                        {
                            date2 = Convert.ToDateTime(objB, CultureInfo.InvariantCulture);
                        }

                        return date1.CompareTo(date2);
#if !NET20
                    }
                    else
                    {
                        DateTimeOffset date1 = (DateTimeOffset)objA;
                        DateTimeOffset date2;

                        if (objB is DateTimeOffset)
                        {
                            date2 = (DateTimeOffset)objB;
                        }
                        else
                        {
                            date2 = new DateTimeOffset(Convert.ToDateTime(objB, CultureInfo.InvariantCulture));
                        }

                        return date1.CompareTo(date2);
                    }
#endif
                case JTokenType.Bytes:
                    if (!(objB is byte[]))
                    {
                        throw new ArgumentException("Object must be of type byte[].");
                    }

                    byte[] bytes1 = objA as byte[];
                    byte[] bytes2 = objB as byte[];
                    if (bytes1 == null)
                    {
                        return -1;
                    }
                    if (bytes2 == null)
                    {
                        return 1;
                    }

                    return MiscellaneousUtils.ByteArrayCompare(bytes1, bytes2);
                case JTokenType.Guid:
                    if (!(objB is Guid))
                    {
                        throw new ArgumentException("Object must be of type Guid.");
                    }

                    Guid guid1 = (Guid)objA;
                    Guid guid2 = (Guid)objB;

                    return guid1.CompareTo(guid2);
                case JTokenType.Uri:
                    if (!(objB is Uri))
                    {
                        throw new ArgumentException("Object must be of type Uri.");
                    }

                    Uri uri1 = (Uri)objA;
                    Uri uri2 = (Uri)objB;

                    return Comparer<string>.Default.Compare(uri1.ToString(), uri2.ToString());
                case JTokenType.TimeSpan:
                    if (!(objB is TimeSpan))
                    {
                        throw new ArgumentException("Object must be of type TimeSpan.");
                    }

                    TimeSpan ts1 = (TimeSpan)objA;
                    TimeSpan ts2 = (TimeSpan)objB;

                    return ts1.CompareTo(ts2);
                default:
                    throw MiscellaneousUtils.CreateArgumentOutOfRangeException("valueType", valueType, "Unexpected value type: {0}".FormatWith(CultureInfo.InvariantCulture, valueType));
            }
        }

19 Source : CalendarTimeScaleUnit.cs
with GNU Lesser General Public License v3.0
from derekantrican

internal bool CheckHighlighted()
        {
            for( int i = 0; i < Day.Calendar.HighlightRanges.Length; i++ )
            {
                CalendarHighlightRange range = Day.Calendar.HighlightRanges[i];

                if( range.DayOfWeek != Date.DayOfWeek )
                    continue;

                if( Date.TimeOfDay.CompareTo( range.StartTime ) >= 0
                    && Date.TimeOfDay.CompareTo( range.EndTime ) < 0 )
                {
                    return true;
                }

            }
            return false;
        }

19 Source : SqlDayToSecond.cs
with Apache License 2.0
from deveel

public int CompareTo(SqlDayToSecond other) {
			return value.CompareTo(other.value);
		}

19 Source : _TimeSpan.cs
with MIT License
from DevZest

protected override bool? EvalCore(TimeSpan? x, TimeSpan? y)
            {
                if (x == null || y == null)
                    return null;
                else
                    return x.GetValueOrDefault().CompareTo(y.GetValueOrDefault()) < 0;
            }

19 Source : _TimeSpan.cs
with MIT License
from DevZest

protected override bool? EvalCore(TimeSpan? x, TimeSpan? y)
            {
                if (x == null || y == null)
                    return null;
                else
                    return x.GetValueOrDefault().CompareTo(y.GetValueOrDefault()) <= 0;
            }

19 Source : _TimeSpan.cs
with MIT License
from DevZest

protected override bool? EvalCore(TimeSpan? x, TimeSpan? y)
            {
                if (x == null || y == null)
                    return null;
                else
                    return x.GetValueOrDefault().CompareTo(y.GetValueOrDefault()) >= 0;
            }

19 Source : _TimeSpan.cs
with MIT License
from DevZest

protected override bool? EvalCore(TimeSpan? x, TimeSpan? y)
            {
                if (x == null || y == null)
                    return null;
                else
                    return x.GetValueOrDefault().CompareTo(y.GetValueOrDefault()) > 0;
            }

19 Source : DerGeneralizedTime.cs
with GNU General Public License v3.0
from DSorlov

private string CalculateGmtOffset()
		{
			char sign = '+';
            DateTime time = ToDateTime();

#if SILVERLIGHT
			long offset = time.Ticks - time.ToUniversalTime().Ticks;
			if (offset < 0)
			{
				sign = '-';
				offset = -offset;
			}
			int hours = (int)(offset / TimeSpan.TicksPerHour);
			int minutes = (int)(offset / TimeSpan.TicksPerMinute) % 60;
#else
            // Note: GetUtcOffset incorporates Daylight Savings offset
			TimeSpan offset =  TimeZone.CurrentTimeZone.GetUtcOffset(time);
			if (offset.CompareTo(TimeSpan.Zero) < 0)
			{
				sign = '-';
				offset = offset.Duration();
			}
			int hours = offset.Hours;
			int minutes = offset.Minutes;
#endif

			return "GMT" + sign + Convert(hours) + ":" + Convert(minutes);
		}

19 Source : JValue.cs
with Apache License 2.0
from elastic

internal static int Compare(JTokenType valueType, object? objA, object? objB)
		{
			if (objA == objB) return 0;

			if (objB == null) return 1;

			if (objA == null) return -1;

			switch (valueType)
			{
				case JTokenType.Integer:
				{
#if HAVE_BIG_INTEGER
                    if (objA is BigInteger integerA)
                    {
                        return CompareBigInteger(integerA, objB);
                    }
                    if (objB is BigInteger integerB)
                    {
                            return -CompareBigInteger(integerB, objA);
                        }
#endif
					if (objA is ulong || objB is ulong || objA is decimal || objB is decimal)
						return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture));
					if (objA is float || objB is float || objA is double || objB is double)
						return CompareFloat(objA, objB);

					return Convert.ToInt64(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToInt64(objB, CultureInfo.InvariantCulture));
				}
				case JTokenType.Float:
				{
#if HAVE_BIG_INTEGER
                    if (objA is BigInteger integerA)
                    {
                        return CompareBigInteger(integerA, objB);
                    }
                    if (objB is BigInteger integerB)
                    {
                        return -CompareBigInteger(integerB, objA);
                    }
#endif
					if (objA is ulong || objB is ulong || objA is decimal || objB is decimal)
						return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture));

					return CompareFloat(objA, objB);
				}
				case JTokenType.Comment:
				case JTokenType.String:
				case JTokenType.Raw:
					var s1 = Convert.ToString(objA, CultureInfo.InvariantCulture);
					var s2 = Convert.ToString(objB, CultureInfo.InvariantCulture);

					return string.CompareOrdinal(s1, s2);
				case JTokenType.Boolean:
					var b1 = Convert.ToBoolean(objA, CultureInfo.InvariantCulture);
					var b2 = Convert.ToBoolean(objB, CultureInfo.InvariantCulture);

					return b1.CompareTo(b2);
				case JTokenType.Date:
#if HAVE_DATE_TIME_OFFSET
                    if (objA is DateTime dateA)
                    {
#else
					var dateA = (DateTime)objA;
#endif
					DateTime dateB;

#if HAVE_DATE_TIME_OFFSET
                        if (objB is DateTimeOffset offsetB)
                        {
                            dateB = offsetB.DateTime;
                        }
                        else
#endif
				{
					dateB = Convert.ToDateTime(objB, CultureInfo.InvariantCulture);
				}

					return dateA.CompareTo(dateB);
#if HAVE_DATE_TIME_OFFSET
                    }
                    else
                    {
                        DateTimeOffset offsetA = (DateTimeOffset)objA;
                        if (!(objB is DateTimeOffset offsetB))
                        {
                            offsetB = new DateTimeOffset(Convert.ToDateTime(objB, CultureInfo.InvariantCulture));
                        }

                        return offsetA.CompareTo(offsetB);
                    }
#endif
				case JTokenType.Bytes:
					if (!(objB is byte[] bytesB)) throw new ArgumentException("Object must be of type byte[].");

					var bytesA = objA as byte[];
					MiscellaneousUtils.replacedert(bytesA != null);

					return MiscellaneousUtils.ByteArrayCompare(bytesA!, bytesB);
				case JTokenType.Guid:
					if (!(objB is Guid)) throw new ArgumentException("Object must be of type Guid.");

					var guid1 = (Guid)objA;
					var guid2 = (Guid)objB;

					return guid1.CompareTo(guid2);
				case JTokenType.Uri:
					var uri2 = objB as Uri;
					if (uri2 == null) throw new ArgumentException("Object must be of type Uri.");

					var uri1 = (Uri)objA;

					return Comparer<string>.Default.Compare(uri1.ToString(), uri2.ToString());
				case JTokenType.TimeSpan:
					if (!(objB is TimeSpan)) throw new ArgumentException("Object must be of type TimeSpan.");

					var ts1 = (TimeSpan)objA;
					var ts2 = (TimeSpan)objB;

					return ts1.CompareTo(ts2);
				default:
					throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(valueType), valueType,
						"Unexpected value type: {0}".FormatWith(CultureInfo.InvariantCulture, valueType));
			}
		}

19 Source : TimeOfDay.cs
with MIT License
from erdomke

public int CompareTo(TimeOfDay other)
    {
      return this.timeSpan.CompareTo(other.timeSpan);
    }

19 Source : OracleTimeSpan.cs
with MIT License
from ericmend

public int CompareTo(object obj)
        {
            OracleTimeSpan o = (OracleTimeSpan)obj;
            if (obj == null)
                throw new NullReferenceException("Object reference not set to an instance of an object");
            else if (!(obj is OracleTimeSpan))
                throw new ArgumentException("Value is not a System.Data.OracleClient.OracleTimeSpan", obj.ToString());
            else if (o.IsNull && this.IsNull)
                return 0;
            else if (o.IsNull && !(this.IsNull))
                return 1;
            else
                return value.CompareTo(o.Value);
        }

19 Source : RealTouchScriptLoader.cs
with GNU General Public License v3.0
from FredTungsten

private static List<RealTouchCommand> FilterAndSortCommands(List<RealTouchCommand> commands, RealTouchAxis axis, TimeSpan minPeriodicDuration)
        {
            List<RealTouchCommand> result = new List<RealTouchCommand>();

            foreach (RealTouchCommand command in commands)
            {
                if (!CoversAxis(command.Axis, axis))
                    continue;
                if (command is RealTouchPeriodicMovementCommand periodic)
                    if (periodic.Period < minPeriodicDuration)
                        continue;

                result.Add(command);
            }

            result.Sort((a,b) => a.TimeStamp.CompareTo(b.TimeStamp));

            return result;
        }

19 Source : RabbitMQConsumerOptionsTests.cs
with MIT License
from GDATASoftwareAG

[Fact]
    public void BindConsumerOptions_ConfigWithDefaultValues_ContainDefaultValues()
    {
        var config = GetJsonConfig("consumer-default-values");
        var consumerOptions = new RabbitMQConsumerOptions<string>();

        config.Bind(consumerOptions);

        replacedert.Equal(5672, consumerOptions.Port);
        replacedert.Equal(0, TimeSpan.FromSeconds(60).CompareTo(consumerOptions.RequestedHeartbeat));
        replacedert.Equal("", consumerOptions.VirtualHost);
        replacedert.Equal(10, consumerOptions.PrefetchCount);
        replacedert.True(consumerOptions.Queue.Durable);
        replacedert.False(consumerOptions.Queue.AutoDelete);
        replacedert.Equal(1_000_000, consumerOptions.Queue.MaxLength);
        replacedert.Equal(255, consumerOptions.Queue.MaxPriority);
        replacedert.Equal(86_400_000, consumerOptions.Queue.MessageTtl);
    }

19 Source : Time.cs
with MIT License
from Giannoudis

public int CompareTo( Time other )
		{
			return duration.CompareTo( other.duration );
		}

19 Source : Time.cs
with MIT License
from Giannoudis

public int CompareTo( object obj )
		{
			return duration.CompareTo( ((Time)obj).duration );
		}

19 Source : AudioWindow.cs
with MIT License
from GTA-ASM

public void StartPlaying(AudioClip clip)
		{
			StopPlaying ();

			if (null == m_audioSource)
			{
				var go = new GameObject ("AudioWindowSound");
				go.hideFlags = HideFlags.HideInHierarchy;
				m_audioSource = go.AddComponent<AudioSource> ();
			}

			m_audioSource.clip = clip;

			if (m_playInterval)
			{
				System.TimeSpan timeSpanStart, timeSpanEnd;
				var fp = System.Globalization.CultureInfo.InvariantCulture;
				if (System.TimeSpan.TryParseExact (m_playIntervalStartStr, "mm\\:ss\\.fff", fp, out timeSpanStart)
					&& System.TimeSpan.TryParseExact (m_playIntervalEndStr, "mm\\:ss\\.fff", fp, out timeSpanEnd)
				    && timeSpanStart.CompareTo (timeSpanEnd) < 0)
				{
					m_audioSource.time = (float) timeSpanStart.TotalSeconds;
					m_audioSource.Play ();
					m_audioSource.SetScheduledEndTime (AudioSettings.dspTime + (timeSpanEnd.TotalSeconds - timeSpanStart.TotalSeconds));
				}

			}
			else
			{
				m_audioSource.time = 0f;
				m_audioSource.Play ();
			}

		}

19 Source : EncounterStatistics.cs
with MIT License
from gw2scratch

private GridView<EncounterStats> ConstructGridView()
		{
			var customSorts = new Dictionary<GridColumn, Comparison<EncounterStats>>();

			var gridView = new GridView<EncounterStats>();

			gridView.Columns.Add(new GridColumn
			{
				HeaderText = "Encounter name",
				DataCell = new TextBoxCell {Binding = new DelegateBinding<EncounterStats, string>(x => x.Name)}
			});

			gridView.Columns.Add(new GridColumn
			{
				HeaderText = "Logs",
				DataCell = new TextBoxCell {Binding = new DelegateBinding<EncounterStats, string>(x => $"{x.LogCount}")}
			});

			var totalTimeColumn = new GridColumn
			{
				HeaderText = "Total time",
				DataCell = new TextBoxCell
				{
					Binding = new DelegateBinding<EncounterStats, string>(x => FormatTimeSpan(x.GetTotalTimeSpent()))
				}
			};
			gridView.Columns.Add(totalTimeColumn);
			customSorts[totalTimeColumn] =
				(left, right) => left.GetTotalTimeSpent().CompareTo(right.GetTotalTimeSpent());

			var shownResults = new (EncounterResult Result, string CountHeaderText, string TimeHeaderText, string AverageHeaderText)[]
			{
				(EncounterResult.Success, "Successes", "Time in successes", "Average success time"),
				(EncounterResult.Failure, "Failures", "Time in failures", "Average failure time")
			};

			foreach ((var result, string countHeaderText, string timeHeaderText, string averageHeaderText) in shownResults)
			{
				gridView.Columns.Add(new GridColumn
				{
					HeaderText = countHeaderText,
					DataCell = new TextBoxCell
					{
						Binding = new DelegateBinding<EncounterStats, string>(x =>
							x.LogCountsByResult.TryGetValue(result, out int count) ? $"{count}" : "0")
					}
				});

				TimeSpan GetTime(EncounterStats x) =>
					x.TimeSpentByResult.TryGetValue(result, out TimeSpan time) ? time : TimeSpan.Zero;

				var timeColumn = new GridColumn
				{
					HeaderText = timeHeaderText,
					DataCell = new TextBoxCell
					{
						Binding = new DelegateBinding<EncounterStats, string>(x => FormatTimeSpan(GetTime(x)))
					}
				};
				gridView.Columns.Add(timeColumn);
				customSorts[timeColumn] = (left, right) => GetTime(left).CompareTo(GetTime(right));

				var averageTimeColumn = new GridColumn
				{
					HeaderText = averageHeaderText,
					DataCell = new TextBoxCell
					{
						Binding = new DelegateBinding<EncounterStats, string>(x => FormatTimeSpan(x.GetAverageTimeByResult(result)))
					}
				};
				gridView.Columns.Add(averageTimeColumn);
			}

			var successRateColumn = new GridColumn
			{
				HeaderText = "Success rate",
				DataCell = new TextBoxCell
				{
					Binding = new DelegateBinding<EncounterStats, string>(x => $"{x.GetSuccessRate() * 100:0.0}%")
				}
			};
			gridView.Columns.Add(successRateColumn);
			customSorts[successRateColumn] = (left, right) => left.GetSuccessRate().CompareTo(right.GetSuccessRate());

			sorter = new GridViewSorter<EncounterStats>(gridView, customSorts);
			sorter.EnableSorting();

			return gridView;
		}

19 Source : DerGeneralizedTime.cs
with MIT License
from hcq0618

private string CalculateGmtOffset()
        {
            char sign = '+';
            DateTime time = ToDateTime();

#if SILVERLIGHT || NETFX_CORE || UNITY_WP8
            long offset = time.Ticks - time.ToUniversalTime().Ticks;
            if (offset < 0)
            {
                sign = '-';
                offset = -offset;
            }
            int hours = (int)(offset / TimeSpan.TicksPerHour);
            int minutes = (int)(offset / TimeSpan.TicksPerMinute) % 60;
#else
            // Note: GetUtcOffset incorporates Daylight Savings offset
            TimeSpan offset =  TimeZone.CurrentTimeZone.GetUtcOffset(time);
            if (offset.CompareTo(TimeSpan.Zero) < 0)
            {
                sign = '-';
                offset = offset.Duration();
            }
            int hours = offset.Hours;
            int minutes = offset.Minutes;
#endif

            return "GMT" + sign + Convert(hours) + ":" + Convert(minutes);
        }

19 Source : Period.cs
with MIT License
from iAJTin

public int CompareTo(Period other) => Duration.CompareTo(other.Duration);

19 Source : TimeSpanF.cs
with MIT License
from ikorin24

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public int CompareTo(TimeSpanF other) => _ts.CompareTo(other._ts);

19 Source : TimeSpanF.cs
with MIT License
from ikorin24

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public int CompareTo(object? obj) => _ts.CompareTo(obj);

19 Source : CommonBluetoothInquiry.cs
with MIT License
from inthehand

public IAsyncResult BeginInquiry(int maxDevices, TimeSpan inquiryLength,
            AsyncCallback asyncCallback, Object state,
            BluetoothClient.LiveDiscoveryCallback liveDiscoHandler, object liveDiscoState,
            ThreadStart startInquiry,
            DiscoDevsParams args)
        {
            int fakeUseI = maxDevices;
            AR_Inquiry ar;
            AR_Inquiry sacAr = null;
            List_IBluetoothDeviceInfo sacResult = null;
            lock (_lockInquiry) {
                if (_inquiryAr != null) {
                    Debug.WriteLine("Merging concurrent DiscoverDevices call into the running one (will get same result list).");
                    // Just give any new request the same results as the outstanding Inquiry.
                    ar = new AR_Inquiry(asyncCallback, state, args);
                    if (_inquiryAr.IsCompleted) {
                        // This can never occur (is nulled before SAC'd), but leave in anyway...
                        sacAr = ar;
                        sacResult = _inquiryDevices;
                    } else {
                        if (_arInquiryFollowers == null)
                            _arInquiryFollowers = new List<AR_Inquiry>();
                        _arInquiryFollowers.Add(ar);
                    }
                } else { // New inquiry process.
                    ar = new AR_Inquiry(asyncCallback, state, args);
                    _inquiryAr = ar;
                    _arInquiryFollowers = null;
                    _inquiryDevices = new List_IBluetoothDeviceInfo();
                    _liveDiscoHandler = liveDiscoHandler;
                    _liveDiscoState = liveDiscoState;
                    bool siSuccess = false;
                    try {
                        startInquiry();
                        siSuccess = true;
                    } finally {
                        if (!siSuccess) { _inquiryAr = null; }
                    }
                    if (inquiryLength.CompareTo(TimeSpan.Zero) > 0) {
                        var tTmp = TimeSpan.FromMilliseconds(
                            checked(1.5 * inquiryLength.TotalMilliseconds));
                        System.Threading.ThreadPool.QueueUserWorkItem(InquiryTimeout_Runner,
                            new InquiryTimeoutParams(ar, tTmp));
                    }
                }
            }//lock
            if (sacAr != null) {
                sacAr.SetAsCompleted(sacResult, true);
            }
            return ar;
        }

19 Source : WidcommBluetoothClientInquiryTest.cs
with MIT License
from inthehand

static bool _WaitAll(WaitHandle[] events, int timeout)
        {
#if false && !NETCF
            return WaitHandle.WaitAll(events, timeout);
#else
            var final = DateTime.UtcNow.AddMilliseconds(timeout);
            foreach (var curE in events) {
                TimeSpan curTo = final.Subtract(DateTime.UtcNow);
                if (curTo.CompareTo(TimeSpan.Zero) <= 0) {
                    Debug.Fail("Should we expect to get here?  Normally exit at !signalled below...");
                    return false;
                }
                bool signalled = curE.WaitOne((int)curTo.TotalMilliseconds, false);
                if (!signalled) {
                    return false;
                }
            }//for
            return true;
#endif
        }

19 Source : VibrateController.cs
with MIT License
from inthehand

public void Start(System.TimeSpan duration)
        {
            if (duration.CompareTo(MaximumDuration) > 0)
            {
                throw new ArgumentOutOfRangeException("duration", Phone.Properties.Resources.vibratecontroller_DurationMax);
            }

            if (duration.Ticks < 0)
            {
                throw new ArgumentOutOfRangeException("duration", Phone.Properties.Resources.vibratecontroller_DurationMin);
            }

            if (InTheHand.WindowsCE.Forms.SystemSettingsInTheHand.Platform == WinCEPlatform.Smartphone)
            {
                int hresult = NativeMethods.Vibrate(0, IntPtr.Zero, true, (int)duration.TotalMilliseconds);
                if (hresult < 0)
                {
                    Marshal.ThrowExceptionForHR(hresult);
                }
            }
            else if (InTheHand.WindowsCE.Forms.SystemSettingsInTheHand.Platform == WinCEPlatform.PocketPC)
            {
                if (ledIndex > -1)
                {
                    NativeMethods.NLED_SETTINGS_INFO nsi = new NativeMethods.NLED_SETTINGS_INFO();
                    nsi.LedNum = ledIndex;
                    nsi.OffOnBlink = 1;
                    bool success = NativeMethods.NLedSetDevice(2, ref nsi);

                    // setup a thread to turn off after duration
                    System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(TurnOffLed), (int)duration.TotalMilliseconds);
                }
            }
        }

19 Source : JValue.cs
with Apache License 2.0
from intuit

private static int Compare(JTokenType valueType, object objA, object objB)
    {
      if (objA == null && objB == null)
        return 0;
      if (objA != null && objB == null)
        return 1;
      if (objA == null && objB != null)
        return -1;

      switch (valueType)
      {
        case JTokenType.Integer:
          if (objA is ulong || objB is ulong || objA is decimal || objB is decimal)
            return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture));
          else if (objA is float || objB is float || objA is double || objB is double)
            return CompareFloat(objA, objB);
          else
            return Convert.ToInt64(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToInt64(objB, CultureInfo.InvariantCulture));
        case JTokenType.Float:
          return CompareFloat(objA, objB);
        case JTokenType.Comment:
        case JTokenType.String:
        case JTokenType.Raw:
          string s1 = Convert.ToString(objA, CultureInfo.InvariantCulture);
          string s2 = Convert.ToString(objB, CultureInfo.InvariantCulture);

          return string.CompareOrdinal(s1, s2);
        case JTokenType.Boolean:
          bool b1 = Convert.ToBoolean(objA, CultureInfo.InvariantCulture);
          bool b2 = Convert.ToBoolean(objB, CultureInfo.InvariantCulture);

          return b1.CompareTo(b2);
        case JTokenType.Date:
#if !NET20
          if (objA is DateTime)
          {
#endif
            DateTime date1 = Convert.ToDateTime(objA, CultureInfo.InvariantCulture);
            DateTime date2 = Convert.ToDateTime(objB, CultureInfo.InvariantCulture);

            return date1.CompareTo(date2);
#if !NET20
          }
          else
          {
            if (!(objB is DateTimeOffset))
              throw new ArgumentException("Object must be of type DateTimeOffset.");

            DateTimeOffset date1 = (DateTimeOffset) objA;
            DateTimeOffset date2 = (DateTimeOffset) objB;

            return date1.CompareTo(date2);
          }
#endif
        case JTokenType.Bytes:
          if (!(objB is byte[]))
            throw new ArgumentException("Object must be of type byte[].");

          byte[] bytes1 = objA as byte[];
          byte[] bytes2 = objB as byte[];
          if (bytes1 == null)
            return -1;
          if (bytes2 == null)
            return 1;

          return MiscellaneousUtils.ByteArrayCompare(bytes1, bytes2);
        case JTokenType.Guid:
          if (!(objB is Guid))
            throw new ArgumentException("Object must be of type Guid.");

          Guid guid1 = (Guid) objA;
          Guid guid2 = (Guid) objB;

          return guid1.CompareTo(guid2);
        case JTokenType.Uri:
          if (!(objB is Uri))
            throw new ArgumentException("Object must be of type Uri.");

          Uri uri1 = (Uri)objA;
          Uri uri2 = (Uri)objB;

          return Comparer<string>.Default.Compare(uri1.ToString(), uri2.ToString());
        case JTokenType.TimeSpan:
          if (!(objB is TimeSpan))
            throw new ArgumentException("Object must be of type TimeSpan.");

          TimeSpan ts1 = (TimeSpan)objA;
          TimeSpan ts2 = (TimeSpan)objB;

          return ts1.CompareTo(ts2);
        default:
          throw MiscellaneousUtils.CreateArgumentOutOfRangeException("valueType", valueType, "Unexpected value type: {0}".FormatWith(CultureInfo.InvariantCulture, valueType));
      }
    }

19 Source : OpenTkControlBase.xaml.cs
with MIT License
from jayhf

protected TimeSpan Render()
        {
            try
            {
                RenderScreenshots(out int currentBufferWidth, out int currentBufferHeight);

                CalculateBufferSize(out int width, out int height);

                if ((_continuous && !IsVisible) || width == 0 || height == 0)
                    return TimeSpan.FromMilliseconds(20);


                if (_continuous && _frameRateLimit > 0 && _frameRateLimit < 1000)
                {
                    DateTime now = DateTime.Now;
                    TimeSpan delayTime = TimeSpan.FromSeconds(1 / _frameRateLimit) - (now - _lastFrameTime);
                    if (delayTime.CompareTo(TimeSpan.Zero) > 0)
                        return delayTime;

                    _lastFrameTime = now;
                }
                else
                {
                    _lastFrameTime = DateTime.MinValue;
                }

                if (!ReferenceEquals(GraphicsContext.CurrentContext, _context))
                    _context.MakeCurrent(_windowInfo);

                bool resized = false;
                Task resizeBitmapTask = null;
                //Need Abs(...) > 1 to handle an edge case where the resizing the bitmap causes the height to increase in an infinite loop
                if (_bitmap == null || Math.Abs(_bitmapWidth - width) > 1 || Math.Abs(_bitmapHeight - height) > 1)
                {
                    resized = true;
                    _bitmapWidth = width;
                    _bitmapHeight = height;
                    resizeBitmapTask = RunOnUiThread(() =>
                    {
                        _bitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Pbgra32, null);
                        _backBuffer = _bitmap.BackBuffer;
                    });
                }

                if (currentBufferWidth != _bitmapWidth || currentBufferHeight != _bitmapHeight)
                {
                    CreateOpenGlBuffers(_bitmapWidth, _bitmapHeight);
                }

                List<TaskCompletionSource<object>> repaintRequests = null;
                while (_repaintRequestQueue.TryDequeue(out var tcs))
                {
                    if (repaintRequests == null)
                    {
                        repaintRequests = new List<TaskCompletionSource<object>>();
                    }
                    repaintRequests.Add(tcs);
                }

                GlRenderEventArgs args = new GlRenderEventArgs(_bitmapWidth, _bitmapHeight, resized, false, CheckNewContext());
                try
                {
                    OnGlRender(args);
                }
                finally
                {
                    if (repaintRequests != null)
                    {
                        foreach (var taskCompletionSource in repaintRequests)
                        {
                            taskCompletionSource.SetResult(null);
                        }
                    }
                }

                Int32Rect dirtyArea = args.RepaintRect;

                if (dirtyArea.Width <= 0 || dirtyArea.Height <= 0)
                    return TimeSpan.Zero;

                try
                {
                    resizeBitmapTask?.Wait();
                    try
                    {
                        _previousUpdateImageTask?.Wait();
                    }
                    finally
                    {
                        _previousUpdateImageTask = null;
                    }
                }
                catch (TaskCanceledException)
                {
                    return TimeSpan.Zero;
                }

                if(_backBuffer != IntPtr.Zero)
                    GL.ReadPixels(0, 0, _bitmapWidth, _bitmapHeight, PixelFormat.Bgra, PixelType.UnsignedByte, _backBuffer);

                _previousUpdateImageTask = RunOnUiThread(() => UpdateImage(dirtyArea));
            }
            catch (Exception e)
            {
                ExceptionOccurred?.Invoke(this, new UnhandledExceptionEventArgs(e, false));
            }

            return TimeSpan.Zero;
        }

19 Source : ThreadOpenTkControl.cs
with MIT License
from jayhf

private void RenderThread(object boxedToken)
        {
#if DEBUG
            // Don't render in design mode to prevent errors from calling OpenGL API methods.
            if (Dispatcher.Invoke(() => IsDesignMode()))
                return;
#endif

            CancellationToken token = (CancellationToken) boxedToken;

            InitOpenGl();

            WaitHandle[] notContinousHandles = {token.WaitHandle, ManualRepaintEvent};
            WaitHandle[] notVisibleHandles   = {token.WaitHandle, _becameVisibleEvent};
            while (!token.IsCancellationRequested)
            {
                if (!_continuous)
                {
                    WaitHandle.WaitAny(notContinousHandles);
                }
                else if (!IsVisible)
                {
                    WaitHandle.WaitAny(notVisibleHandles);
                    _becameVisibleEvent.Reset();

                    if(!_continuous)
                        continue;
                }
                
                if (token.IsCancellationRequested)
                    break;

                ManualRepaintEvent.Reset();

                TimeSpan sleepTime = Render();
                if(sleepTime.CompareTo(TimeSpan.Zero) > 0)
                    Thread.Sleep(sleepTime);
            }

            DeInitOpenGl();
        }

19 Source : TimerQueue.cs
with MIT License
from jirenius

private void startTimer()
        {
            TimeSpan span = first.Time.Subtract(DateTime.Now);
            if (span.CompareTo(TimeSpan.Zero) < 0)
            {
                span = TimeSpan.Zero;
            }
            timer = new Timer(onTimeout, counter, (int)span.TotalMilliseconds, Timeout.Infinite);
        }

19 Source : RenderGraph.cs
with GNU Affero General Public License v3.0
from john-h-k

public int CompareTo([AllowNull] PreplacedHeuristics other) => AveragePreplacedRecordTime.CompareTo(other.AveragePreplacedRecordTime);

See More Examples