System.TimeSpan.FromTicks(long)

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

797 Examples 7

19 View Source File : RedisDate.cs
License : MIT License
Project Creator : 2881099

public static TimeSpan FromMicroseconds(long microseconds)
            {
                return TimeSpan.FromTicks(microseconds * (TimeSpan.TicksPerMillisecond / 1000));
            }

19 View Source File : BclHelpers.cs
License : MIT License
Project Creator : 404Lcc

public static TimeSpan ReadTimeSpan(ProtoReader source)
        {
            DateTimeKind kind;
            long ticks = ReadTimeSpanTicks(source, out kind);
            if (ticks == long.MinValue) return TimeSpan.MinValue;
            if (ticks == long.MaxValue) return TimeSpan.MaxValue;
            return TimeSpan.FromTicks(ticks);
        }

19 View Source File : BclHelpers.cs
License : MIT License
Project Creator : 404Lcc

static TimeSpan FromDurationSeconds(long seconds, int nanos)
        {
            
            long ticks = checked((seconds * TimeSpan.TicksPerSecond)
                + (nanos * TimeSpan.TicksPerMillisecond) / 1000000);
            return TimeSpan.FromTicks(ticks);
        }

19 View Source File : FileTransferProgressBar.cs
License : MIT License
Project Creator : a-luna

void TimerHandler(object state)
		{
			lock (Timer)
			{
				if (Disposed) return;
				var elapsedTicks = DateTime.Now.Ticks - _lastReportTicks;
				var elapsed = TimeSpan.FromTicks(elapsedTicks);

				UpdateText(GetProgressBarText(CurrentProgress));
				ResetTimer();

				if (elapsed < TimeSpanFileStalled) return;

				FileTransferStalled?.Invoke(this,
				new ProgressEventArgs
				{
			LastDataReceived = new DateTime(_lastReportTicks),
			TimeOutTriggered = DateTime.Now
			});
			}
		}

19 View Source File : FdbConverters.cs
License : MIT License
Project Creator : abdullin

private static void RegisterDefaultConverters()
		{
			//TODO: there is too much generic type combinations! need to refactor this ...

			RegisterUnsafe<bool, Slice>((value) => Slice.FromByte(value ? (byte)1 : default(byte)));
			RegisterUnsafe<bool, byte[]>((value) => Slice.FromByte(value ? (byte)1 : default(byte)).GetBytes());
			RegisterUnsafe<bool, string>((value) => value ? "true" : "false");
			RegisterUnsafe<bool, sbyte>((value) => value ? (sbyte)1 : default(sbyte));
			RegisterUnsafe<bool, byte>((value) => value ? (byte)1 : default(byte));
			RegisterUnsafe<bool, short>((value) => value ? (short)1 : default(short));
			RegisterUnsafe<bool, ushort>((value) => value ? (ushort)1 : default(ushort));
			RegisterUnsafe<bool, int>((value) => value ? 1 : default(int));
			RegisterUnsafe<bool, uint>((value) => value ? 1U : default(uint));
			RegisterUnsafe<bool, long>((value) => value ? 1L : default(long));
			RegisterUnsafe<bool, ulong>((value) => value ? 1UL : default(ulong));
			RegisterUnsafe<bool, double>((value) => value ? 0.0d : 1.0d);
			RegisterUnsafe<bool, float>((value) => value ? 0.0f : 1.0f);

			RegisterUnsafe<int, Slice>((value) => Slice.FromInt32(value));
			RegisterUnsafe<int, byte[]>((value) => Slice.FromInt32(value).GetBytes());
			RegisterUnsafe<int, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<int, bool>((value) => value != 0);
			RegisterUnsafe<int, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<int, byte>((value) => checked((byte)value));
			RegisterUnsafe<int, short>((value) => checked((short)value));
			RegisterUnsafe<int, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<int, uint>((value) => (uint)value);
			RegisterUnsafe<int, long>((value) => value);
			RegisterUnsafe<int, ulong>((value) => (ulong)value);
			RegisterUnsafe<int, double>((value) => value);
			RegisterUnsafe<int, float>((value) => checked((float)value));
			RegisterUnsafe<int, FdbTupleAlias>((value) => (FdbTupleAlias)value);

			RegisterUnsafe<uint, Slice>((value) => Slice.FromUInt64(value));
			RegisterUnsafe<uint, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
			RegisterUnsafe<uint, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<uint, bool>((value) => value != 0);
			RegisterUnsafe<uint, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<uint, byte>((value) => checked((byte)value));
			RegisterUnsafe<uint, short>((value) => checked((short)value));
			RegisterUnsafe<uint, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<uint, int>((value) => (int)value);
			RegisterUnsafe<uint, long>((value) => value);
			RegisterUnsafe<uint, ulong>((value) => value);
			RegisterUnsafe<uint, double>((value) => value);
			RegisterUnsafe<uint, float>((value) => checked((float)value));

			RegisterUnsafe<long, Slice>((value) => Slice.FromInt64(value));
			RegisterUnsafe<long, byte[]>((value) => Slice.FromInt64(value).GetBytes());
			RegisterUnsafe<long, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<long, bool>((value) => value != 0);
			RegisterUnsafe<long, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<long, byte>((value) => checked((byte)value));
			RegisterUnsafe<long, short>((value) => checked((short)value));
			RegisterUnsafe<long, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<long, int>((value) => checked((int)value));
			RegisterUnsafe<long, uint>((value) => (uint)value);
			RegisterUnsafe<long, ulong>((value) => (ulong)value);
			RegisterUnsafe<long, double>((value) => checked((double)value));
			RegisterUnsafe<long, float>((value) => checked((float)value));
			RegisterUnsafe<long, TimeSpan>((value) => TimeSpan.FromTicks(value));
			RegisterUnsafe<long, Uuid64>((value) => new Uuid64(value));
			RegisterUnsafe<long, System.Net.IPAddress>((value) => new System.Net.IPAddress(value));

			RegisterUnsafe<ulong, Slice>((value) => Slice.FromUInt64(value));
			RegisterUnsafe<ulong, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
			RegisterUnsafe<ulong, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<ulong, bool>((value) => value != 0);
			RegisterUnsafe<ulong, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<ulong, byte>((value) => checked((byte)value));
			RegisterUnsafe<ulong, short>((value) => checked((short)value));
			RegisterUnsafe<ulong, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<ulong, int>((value) => checked((int)value));
			RegisterUnsafe<ulong, uint>((value) => checked((uint)value));
			RegisterUnsafe<ulong, long>((value) => checked((long)value));
			RegisterUnsafe<ulong, double>((value) => checked((double)value));
			RegisterUnsafe<ulong, float>((value) => checked((float)value));
			RegisterUnsafe<ulong, Uuid64>((value) => new Uuid64(value));
			RegisterUnsafe<ulong, TimeSpan>((value) => TimeSpan.FromTicks(checked((long)value)));

			RegisterUnsafe<short, Slice>((value) => Slice.FromInt32(value));
			RegisterUnsafe<short, byte[]>((value) => Slice.FromInt32(value).GetBytes());
			RegisterUnsafe<short, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<short, bool>((value) => value != 0);
			RegisterUnsafe<short, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<short, byte>((value) => checked((byte)value));
			RegisterUnsafe<short, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<short, int>((value) => value);
			RegisterUnsafe<short, uint>((value) => checked((uint)value));
			RegisterUnsafe<short, long>((value) => value);
			RegisterUnsafe<short, ulong>((value) => checked((ulong)value));
			RegisterUnsafe<short, double>((value) => value);
			RegisterUnsafe<short, float>((value) => value);
			RegisterUnsafe<short, FdbTupleAlias>((value) => (FdbTupleAlias)value);

			RegisterUnsafe<ushort, Slice>((value) => Slice.FromUInt64(value));
			RegisterUnsafe<ushort, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
			RegisterUnsafe<ushort, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<ushort, bool>((value) => value != 0);
			RegisterUnsafe<ushort, byte>((value) => checked((byte)value));
			RegisterUnsafe<ushort, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<ushort, short>((value) => checked((short)value));
			RegisterUnsafe<ushort, int>((value) => value);
			RegisterUnsafe<ushort, uint>((value) => value);
			RegisterUnsafe<ushort, long>((value) => value);
			RegisterUnsafe<ushort, ulong>((value) => value);
			RegisterUnsafe<ushort, double>((value) => value);
			RegisterUnsafe<ushort, float>((value) => value);

			RegisterUnsafe<byte, Slice>((value) => Slice.FromInt32(value));
			RegisterUnsafe<byte, byte[]>((value) => Slice.FromInt32(value).GetBytes());
			RegisterUnsafe<byte, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<byte, bool>((value) => value != 0);
			RegisterUnsafe<byte, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<byte, short>((value) => value);
			RegisterUnsafe<byte, ushort>((value) => value);
			RegisterUnsafe<byte, int>((value) => value);
			RegisterUnsafe<byte, uint>((value) => value);
			RegisterUnsafe<byte, long>((value) => value);
			RegisterUnsafe<byte, ulong>((value) => value);
			RegisterUnsafe<byte, double>((value) => value);
			RegisterUnsafe<byte, float>((value) => value);
			RegisterUnsafe<byte, FdbTupleAlias>((value) => (FdbTupleAlias)value);

			RegisterUnsafe<sbyte, Slice>((value) => Slice.FromInt64(value));
			RegisterUnsafe<sbyte, byte[]>((value) => Slice.FromInt64(value).GetBytes());
			RegisterUnsafe<sbyte, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<sbyte, bool>((value) => value != 0);
			RegisterUnsafe<sbyte, byte>((value) => checked((byte)value));
			RegisterUnsafe<sbyte, short>((value) => value);
			RegisterUnsafe<sbyte, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<sbyte, int>((value) => value);
			RegisterUnsafe<sbyte, uint>((value) => checked((uint)value));
			RegisterUnsafe<sbyte, long>((value) => value);
			RegisterUnsafe<sbyte, ulong>((value) => checked((ulong)value));
			RegisterUnsafe<sbyte, double>((value) => value);
			RegisterUnsafe<sbyte, float>((value) => value);

			RegisterUnsafe<float, Slice>((value) => Slice.FromSingle(value));
			RegisterUnsafe<float, byte[]>((value) => Slice.FromSingle(value).GetBytes());
			RegisterUnsafe<float, string>((value) => value.ToString("R", CultureInfo.InvariantCulture));
			RegisterUnsafe<float, bool>((value) => !(value == 0f || float.IsNaN(value)));
			RegisterUnsafe<float, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<float, byte>((value) => checked((byte)value));
			RegisterUnsafe<float, short>((value) => checked((short)value));
			RegisterUnsafe<float, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<float, int>((value) => checked((int)value));
			RegisterUnsafe<float, uint>((value) => (uint)value);
			RegisterUnsafe<float, long>((value) => checked((long)value));
			RegisterUnsafe<float, ulong>((value) => (ulong)value);
			RegisterUnsafe<float, double>((value) => value);

			RegisterUnsafe<double, Slice>((value) => Slice.FromDouble(value));
			RegisterUnsafe<double, byte[]>((value) => Slice.FromDouble(value).GetBytes());
			RegisterUnsafe<double, string>((value) => value.ToString("R", CultureInfo.InvariantCulture));
			RegisterUnsafe<double, bool>((value) => !(value == 0d || double.IsNaN(value)));
			RegisterUnsafe<double, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<double, byte>((value) => checked((byte)value));
			RegisterUnsafe<double, short>((value) => checked((short)value));
			RegisterUnsafe<double, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<double, int>((value) => checked((int)value));
			RegisterUnsafe<double, uint>((value) => (uint)value);
			RegisterUnsafe<double, long>((value) => checked((long)value));
			RegisterUnsafe<double, ulong>((value) => (ulong)value);
			RegisterUnsafe<double, float>((value) => checked((float)value));

			RegisterUnsafe<string, Slice>((value) => Slice.FromString(value));
			RegisterUnsafe<string, byte[]>((value) => Slice.FromString(value).GetBytes());
			RegisterUnsafe<string, bool>((value) => !string.IsNullOrEmpty(value));
			RegisterUnsafe<string, sbyte>((value) => string.IsNullOrEmpty(value) ? default(sbyte) : SByte.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, byte>((value) => string.IsNullOrEmpty(value) ? default(byte) : Byte.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, short>((value) => string.IsNullOrEmpty(value) ? default(short) : Int16.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, ushort>((value) => string.IsNullOrEmpty(value) ? default(ushort) : UInt16.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, int>((value) => string.IsNullOrEmpty(value) ? default(int) : Int32.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, uint>((value) => string.IsNullOrEmpty(value) ? default(uint) : UInt32.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, long>((value) => string.IsNullOrEmpty(value) ? default(long) : Int64.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, ulong>((value) => string.IsNullOrEmpty(value) ? default(ulong) : UInt64.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, float>((value) => string.IsNullOrEmpty(value) ? default(float) : Single.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, double>((value) => string.IsNullOrEmpty(value) ? default(double) : Double.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, Guid>((value) => string.IsNullOrEmpty(value) ? default(Guid) : Guid.Parse(value));
			RegisterUnsafe<string, Uuid128>((value) => string.IsNullOrEmpty(value) ? default(Uuid128) : Uuid128.Parse(value));
			RegisterUnsafe<string, Uuid64>((value) => string.IsNullOrEmpty(value) ? default(Uuid64) : Uuid64.Parse(value));
			RegisterUnsafe<string, System.Net.IPAddress>((value) => string.IsNullOrEmpty(value) ? default(System.Net.IPAddress) : System.Net.IPAddress.Parse(value));

			RegisterUnsafe<byte[], Slice>((value) => Slice.Create(value));
			RegisterUnsafe<byte[], string>((value) => value == null ? default(string) : value.Length == 0 ? String.Empty : System.Convert.ToBase64String(value));
			RegisterUnsafe<byte[], bool>((value) => value != null && value.Length > 0);
			RegisterUnsafe<byte[], sbyte>((value) => value == null ? default(sbyte) : Slice.Create(value).ToSByte());
			RegisterUnsafe<byte[], byte>((value) => value == null ? default(byte) : Slice.Create(value).ToByte());
			RegisterUnsafe<byte[], short>((value) => value == null ? default(short) : Slice.Create(value).ToInt16());
			RegisterUnsafe<byte[], ushort>((value) => value == null ? default(ushort) : Slice.Create(value).ToUInt16());
			RegisterUnsafe<byte[], int>((value) => value == null ? 0 : Slice.Create(value).ToInt32());
			RegisterUnsafe<byte[], uint>((value) => value == null ? 0U : Slice.Create(value).ToUInt32());
			RegisterUnsafe<byte[], long>((value) => value == null ? 0L : Slice.Create(value).ToInt64());
			RegisterUnsafe<byte[], ulong>((value) => value == null ? 0UL : Slice.Create(value).ToUInt64());
			RegisterUnsafe<byte[], Guid>((value) => value == null || value.Length == 0 ? default(Guid) : new Uuid128(value).ToGuid());
			RegisterUnsafe<byte[], Uuid128>((value) => value == null || value.Length == 0 ? default(Uuid128) : new Uuid128(value));
			RegisterUnsafe<byte[], Uuid64>((value) => value == null || value.Length == 0 ? default(Uuid64) : new Uuid64(value));
			RegisterUnsafe<byte[], TimeSpan>((value) => value == null ? TimeSpan.Zero : TimeSpan.FromTicks(Slice.Create(value).ToInt64()));
			RegisterUnsafe<byte[], System.Net.IPAddress>((value) => value == null || value.Length == 0 ? default(System.Net.IPAddress) : new System.Net.IPAddress(value));

			RegisterUnsafe<Guid, Slice>((value) => Slice.FromGuid(value));
			RegisterUnsafe<Guid, byte[]>((value) => Slice.FromGuid(value).GetBytes());
			RegisterUnsafe<Guid, string>((value) => value.ToString("D", null));
			RegisterUnsafe<Guid, Uuid128>((value) => new Uuid128(value));
			RegisterUnsafe<Guid, bool>((value) => value != Guid.Empty);
			RegisterUnsafe<Guid, System.Net.IPAddress>((value) => new System.Net.IPAddress(new Uuid128(value).ToByteArray()));

			RegisterUnsafe<Uuid128, Slice>((value) => value.ToSlice());
			RegisterUnsafe<Uuid128, byte[]>((value) => value.ToByteArray());
			RegisterUnsafe<Uuid128, string>((value) => value.ToString("D", null));
			RegisterUnsafe<Uuid128, Guid>((value) => value.ToGuid());
			RegisterUnsafe<Uuid128, bool>((value) => value != Uuid128.Empty);
			RegisterUnsafe<Guid, System.Net.IPAddress>((value) => new System.Net.IPAddress(value.ToByteArray()));

			RegisterUnsafe<Uuid64, Slice>((value) => value.ToSlice());
			RegisterUnsafe<Uuid64, byte[]>((value) => value.ToByteArray());
			RegisterUnsafe<Uuid64, string>((value) => value.ToString("D", null));
			RegisterUnsafe<Uuid64, long>((value) => value.ToInt64());
			RegisterUnsafe<Uuid64, ulong>((value) => value.ToUInt64());
			RegisterUnsafe<Uuid64, bool>((value) => value.ToInt64() != 0L);

			RegisterUnsafe<TimeSpan, Slice>((value) => Slice.FromInt64(value.Ticks));
			RegisterUnsafe<TimeSpan, byte[]>((value) => Slice.FromInt64(value.Ticks).GetBytes());
			RegisterUnsafe<TimeSpan, long>((value) => value.Ticks);
			RegisterUnsafe<TimeSpan, ulong>((value) => checked((ulong)value.Ticks));
			RegisterUnsafe<TimeSpan, double>((value) => value.TotalSeconds);
			RegisterUnsafe<TimeSpan, bool>((value) => value == TimeSpan.Zero);

			RegisterUnsafe<System.Net.IPAddress, Slice>((value) => value != null ? Slice.Create(value.GetAddressBytes()) : Slice.Nil);
			RegisterUnsafe<System.Net.IPAddress, byte[]>((value) => value != null ? value.GetAddressBytes() : null);
			RegisterUnsafe<System.Net.IPAddress, string>((value) => value != null ? value.ToString() : null);

			RegisterUnsafe<FdbTupleAlias, byte>((value) => (byte)value);
			RegisterUnsafe<FdbTupleAlias, int>((value) => (int)value);
			RegisterUnsafe<FdbTupleAlias, Slice>((value) => Slice.FromByte((byte)value));

			//REVIEW: this should go in the Tuples layer !
			RegisterUnsafe<Slice, byte[]>((value) => value.GetBytes());
			RegisterUnsafe<Slice, string>((value) => value.ToUnicode());
			RegisterUnsafe<Slice, bool>((value) => value.ToBool());
			RegisterUnsafe<Slice, sbyte>((value) => value.ToSByte());
			RegisterUnsafe<Slice, byte>((value) => value.ToByte());
			RegisterUnsafe<Slice, short>((value) => value.ToInt16());
			RegisterUnsafe<Slice, ushort>((value) => value.ToUInt16());
			RegisterUnsafe<Slice, int>((value) => value.ToInt32());
			RegisterUnsafe<Slice, uint>((value) => value.ToUInt32());
			RegisterUnsafe<Slice, long>((value) => value.ToInt64());
			RegisterUnsafe<Slice, ulong>((value) => value.ToUInt64());
			RegisterUnsafe<Slice, Guid>((value) => value.ToGuid());
			RegisterUnsafe<Slice, Uuid128>((value) => value.ToUuid128());
			RegisterUnsafe<Slice, Uuid64>((value) => value.ToUuid64());
			RegisterUnsafe<Slice, TimeSpan>((value) => TimeSpan.FromTicks(value.ToInt64()));
			RegisterUnsafe<Slice, FdbTupleAlias>((value) => (FdbTupleAlias)value.ToByte());
			RegisterUnsafe<Slice, System.Net.IPAddress>((value) => !value.IsNullOrEmpty ? new System.Net.IPAddress(value.GetBytes()) : null);
		}

19 View Source File : FdbConverters.cs
License : MIT License
Project Creator : abdullin

private static void RegisterDefaultConverters()
		{
			//TODO: there is too much generic type combinations! need to refactor this ...

			RegisterUnsafe<bool, Slice>((value) => Slice.FromByte(value ? (byte)1 : default(byte)));
			RegisterUnsafe<bool, byte[]>((value) => Slice.FromByte(value ? (byte)1 : default(byte)).GetBytes());
			RegisterUnsafe<bool, string>((value) => value ? "true" : "false");
			RegisterUnsafe<bool, sbyte>((value) => value ? (sbyte)1 : default(sbyte));
			RegisterUnsafe<bool, byte>((value) => value ? (byte)1 : default(byte));
			RegisterUnsafe<bool, short>((value) => value ? (short)1 : default(short));
			RegisterUnsafe<bool, ushort>((value) => value ? (ushort)1 : default(ushort));
			RegisterUnsafe<bool, int>((value) => value ? 1 : default(int));
			RegisterUnsafe<bool, uint>((value) => value ? 1U : default(uint));
			RegisterUnsafe<bool, long>((value) => value ? 1L : default(long));
			RegisterUnsafe<bool, ulong>((value) => value ? 1UL : default(ulong));
			RegisterUnsafe<bool, double>((value) => value ? 0.0d : 1.0d);
			RegisterUnsafe<bool, float>((value) => value ? 0.0f : 1.0f);

			RegisterUnsafe<int, Slice>((value) => Slice.FromInt32(value));
			RegisterUnsafe<int, byte[]>((value) => Slice.FromInt32(value).GetBytes());
			RegisterUnsafe<int, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<int, bool>((value) => value != 0);
			RegisterUnsafe<int, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<int, byte>((value) => checked((byte)value));
			RegisterUnsafe<int, short>((value) => checked((short)value));
			RegisterUnsafe<int, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<int, uint>((value) => (uint)value);
			RegisterUnsafe<int, long>((value) => value);
			RegisterUnsafe<int, ulong>((value) => (ulong)value);
			RegisterUnsafe<int, double>((value) => value);
			RegisterUnsafe<int, float>((value) => checked((float)value));
			RegisterUnsafe<int, FdbTupleAlias>((value) => (FdbTupleAlias)value);

			RegisterUnsafe<uint, Slice>((value) => Slice.FromUInt64(value));
			RegisterUnsafe<uint, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
			RegisterUnsafe<uint, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<uint, bool>((value) => value != 0);
			RegisterUnsafe<uint, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<uint, byte>((value) => checked((byte)value));
			RegisterUnsafe<uint, short>((value) => checked((short)value));
			RegisterUnsafe<uint, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<uint, int>((value) => (int)value);
			RegisterUnsafe<uint, long>((value) => value);
			RegisterUnsafe<uint, ulong>((value) => value);
			RegisterUnsafe<uint, double>((value) => value);
			RegisterUnsafe<uint, float>((value) => checked((float)value));

			RegisterUnsafe<long, Slice>((value) => Slice.FromInt64(value));
			RegisterUnsafe<long, byte[]>((value) => Slice.FromInt64(value).GetBytes());
			RegisterUnsafe<long, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<long, bool>((value) => value != 0);
			RegisterUnsafe<long, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<long, byte>((value) => checked((byte)value));
			RegisterUnsafe<long, short>((value) => checked((short)value));
			RegisterUnsafe<long, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<long, int>((value) => checked((int)value));
			RegisterUnsafe<long, uint>((value) => (uint)value);
			RegisterUnsafe<long, ulong>((value) => (ulong)value);
			RegisterUnsafe<long, double>((value) => checked((double)value));
			RegisterUnsafe<long, float>((value) => checked((float)value));
			RegisterUnsafe<long, TimeSpan>((value) => TimeSpan.FromTicks(value));
			RegisterUnsafe<long, Uuid64>((value) => new Uuid64(value));
			RegisterUnsafe<long, System.Net.IPAddress>((value) => new System.Net.IPAddress(value));

			RegisterUnsafe<ulong, Slice>((value) => Slice.FromUInt64(value));
			RegisterUnsafe<ulong, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
			RegisterUnsafe<ulong, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<ulong, bool>((value) => value != 0);
			RegisterUnsafe<ulong, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<ulong, byte>((value) => checked((byte)value));
			RegisterUnsafe<ulong, short>((value) => checked((short)value));
			RegisterUnsafe<ulong, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<ulong, int>((value) => checked((int)value));
			RegisterUnsafe<ulong, uint>((value) => checked((uint)value));
			RegisterUnsafe<ulong, long>((value) => checked((long)value));
			RegisterUnsafe<ulong, double>((value) => checked((double)value));
			RegisterUnsafe<ulong, float>((value) => checked((float)value));
			RegisterUnsafe<ulong, Uuid64>((value) => new Uuid64(value));
			RegisterUnsafe<ulong, TimeSpan>((value) => TimeSpan.FromTicks(checked((long)value)));

			RegisterUnsafe<short, Slice>((value) => Slice.FromInt32(value));
			RegisterUnsafe<short, byte[]>((value) => Slice.FromInt32(value).GetBytes());
			RegisterUnsafe<short, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<short, bool>((value) => value != 0);
			RegisterUnsafe<short, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<short, byte>((value) => checked((byte)value));
			RegisterUnsafe<short, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<short, int>((value) => value);
			RegisterUnsafe<short, uint>((value) => checked((uint)value));
			RegisterUnsafe<short, long>((value) => value);
			RegisterUnsafe<short, ulong>((value) => checked((ulong)value));
			RegisterUnsafe<short, double>((value) => value);
			RegisterUnsafe<short, float>((value) => value);
			RegisterUnsafe<short, FdbTupleAlias>((value) => (FdbTupleAlias)value);

			RegisterUnsafe<ushort, Slice>((value) => Slice.FromUInt64(value));
			RegisterUnsafe<ushort, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
			RegisterUnsafe<ushort, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<ushort, bool>((value) => value != 0);
			RegisterUnsafe<ushort, byte>((value) => checked((byte)value));
			RegisterUnsafe<ushort, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<ushort, short>((value) => checked((short)value));
			RegisterUnsafe<ushort, int>((value) => value);
			RegisterUnsafe<ushort, uint>((value) => value);
			RegisterUnsafe<ushort, long>((value) => value);
			RegisterUnsafe<ushort, ulong>((value) => value);
			RegisterUnsafe<ushort, double>((value) => value);
			RegisterUnsafe<ushort, float>((value) => value);

			RegisterUnsafe<byte, Slice>((value) => Slice.FromInt32(value));
			RegisterUnsafe<byte, byte[]>((value) => Slice.FromInt32(value).GetBytes());
			RegisterUnsafe<byte, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<byte, bool>((value) => value != 0);
			RegisterUnsafe<byte, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<byte, short>((value) => value);
			RegisterUnsafe<byte, ushort>((value) => value);
			RegisterUnsafe<byte, int>((value) => value);
			RegisterUnsafe<byte, uint>((value) => value);
			RegisterUnsafe<byte, long>((value) => value);
			RegisterUnsafe<byte, ulong>((value) => value);
			RegisterUnsafe<byte, double>((value) => value);
			RegisterUnsafe<byte, float>((value) => value);
			RegisterUnsafe<byte, FdbTupleAlias>((value) => (FdbTupleAlias)value);

			RegisterUnsafe<sbyte, Slice>((value) => Slice.FromInt64(value));
			RegisterUnsafe<sbyte, byte[]>((value) => Slice.FromInt64(value).GetBytes());
			RegisterUnsafe<sbyte, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<sbyte, bool>((value) => value != 0);
			RegisterUnsafe<sbyte, byte>((value) => checked((byte)value));
			RegisterUnsafe<sbyte, short>((value) => value);
			RegisterUnsafe<sbyte, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<sbyte, int>((value) => value);
			RegisterUnsafe<sbyte, uint>((value) => checked((uint)value));
			RegisterUnsafe<sbyte, long>((value) => value);
			RegisterUnsafe<sbyte, ulong>((value) => checked((ulong)value));
			RegisterUnsafe<sbyte, double>((value) => value);
			RegisterUnsafe<sbyte, float>((value) => value);

			RegisterUnsafe<float, Slice>((value) => Slice.FromSingle(value));
			RegisterUnsafe<float, byte[]>((value) => Slice.FromSingle(value).GetBytes());
			RegisterUnsafe<float, string>((value) => value.ToString("R", CultureInfo.InvariantCulture));
			RegisterUnsafe<float, bool>((value) => !(value == 0f || float.IsNaN(value)));
			RegisterUnsafe<float, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<float, byte>((value) => checked((byte)value));
			RegisterUnsafe<float, short>((value) => checked((short)value));
			RegisterUnsafe<float, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<float, int>((value) => checked((int)value));
			RegisterUnsafe<float, uint>((value) => (uint)value);
			RegisterUnsafe<float, long>((value) => checked((long)value));
			RegisterUnsafe<float, ulong>((value) => (ulong)value);
			RegisterUnsafe<float, double>((value) => value);

			RegisterUnsafe<double, Slice>((value) => Slice.FromDouble(value));
			RegisterUnsafe<double, byte[]>((value) => Slice.FromDouble(value).GetBytes());
			RegisterUnsafe<double, string>((value) => value.ToString("R", CultureInfo.InvariantCulture));
			RegisterUnsafe<double, bool>((value) => !(value == 0d || double.IsNaN(value)));
			RegisterUnsafe<double, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<double, byte>((value) => checked((byte)value));
			RegisterUnsafe<double, short>((value) => checked((short)value));
			RegisterUnsafe<double, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<double, int>((value) => checked((int)value));
			RegisterUnsafe<double, uint>((value) => (uint)value);
			RegisterUnsafe<double, long>((value) => checked((long)value));
			RegisterUnsafe<double, ulong>((value) => (ulong)value);
			RegisterUnsafe<double, float>((value) => checked((float)value));

			RegisterUnsafe<string, Slice>((value) => Slice.FromString(value));
			RegisterUnsafe<string, byte[]>((value) => Slice.FromString(value).GetBytes());
			RegisterUnsafe<string, bool>((value) => !string.IsNullOrEmpty(value));
			RegisterUnsafe<string, sbyte>((value) => string.IsNullOrEmpty(value) ? default(sbyte) : SByte.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, byte>((value) => string.IsNullOrEmpty(value) ? default(byte) : Byte.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, short>((value) => string.IsNullOrEmpty(value) ? default(short) : Int16.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, ushort>((value) => string.IsNullOrEmpty(value) ? default(ushort) : UInt16.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, int>((value) => string.IsNullOrEmpty(value) ? default(int) : Int32.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, uint>((value) => string.IsNullOrEmpty(value) ? default(uint) : UInt32.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, long>((value) => string.IsNullOrEmpty(value) ? default(long) : Int64.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, ulong>((value) => string.IsNullOrEmpty(value) ? default(ulong) : UInt64.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, float>((value) => string.IsNullOrEmpty(value) ? default(float) : Single.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, double>((value) => string.IsNullOrEmpty(value) ? default(double) : Double.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, Guid>((value) => string.IsNullOrEmpty(value) ? default(Guid) : Guid.Parse(value));
			RegisterUnsafe<string, Uuid128>((value) => string.IsNullOrEmpty(value) ? default(Uuid128) : Uuid128.Parse(value));
			RegisterUnsafe<string, Uuid64>((value) => string.IsNullOrEmpty(value) ? default(Uuid64) : Uuid64.Parse(value));
			RegisterUnsafe<string, System.Net.IPAddress>((value) => string.IsNullOrEmpty(value) ? default(System.Net.IPAddress) : System.Net.IPAddress.Parse(value));

			RegisterUnsafe<byte[], Slice>((value) => Slice.Create(value));
			RegisterUnsafe<byte[], string>((value) => value == null ? default(string) : value.Length == 0 ? String.Empty : System.Convert.ToBase64String(value));
			RegisterUnsafe<byte[], bool>((value) => value != null && value.Length > 0);
			RegisterUnsafe<byte[], sbyte>((value) => value == null ? default(sbyte) : Slice.Create(value).ToSByte());
			RegisterUnsafe<byte[], byte>((value) => value == null ? default(byte) : Slice.Create(value).ToByte());
			RegisterUnsafe<byte[], short>((value) => value == null ? default(short) : Slice.Create(value).ToInt16());
			RegisterUnsafe<byte[], ushort>((value) => value == null ? default(ushort) : Slice.Create(value).ToUInt16());
			RegisterUnsafe<byte[], int>((value) => value == null ? 0 : Slice.Create(value).ToInt32());
			RegisterUnsafe<byte[], uint>((value) => value == null ? 0U : Slice.Create(value).ToUInt32());
			RegisterUnsafe<byte[], long>((value) => value == null ? 0L : Slice.Create(value).ToInt64());
			RegisterUnsafe<byte[], ulong>((value) => value == null ? 0UL : Slice.Create(value).ToUInt64());
			RegisterUnsafe<byte[], Guid>((value) => value == null || value.Length == 0 ? default(Guid) : new Uuid128(value).ToGuid());
			RegisterUnsafe<byte[], Uuid128>((value) => value == null || value.Length == 0 ? default(Uuid128) : new Uuid128(value));
			RegisterUnsafe<byte[], Uuid64>((value) => value == null || value.Length == 0 ? default(Uuid64) : new Uuid64(value));
			RegisterUnsafe<byte[], TimeSpan>((value) => value == null ? TimeSpan.Zero : TimeSpan.FromTicks(Slice.Create(value).ToInt64()));
			RegisterUnsafe<byte[], System.Net.IPAddress>((value) => value == null || value.Length == 0 ? default(System.Net.IPAddress) : new System.Net.IPAddress(value));

			RegisterUnsafe<Guid, Slice>((value) => Slice.FromGuid(value));
			RegisterUnsafe<Guid, byte[]>((value) => Slice.FromGuid(value).GetBytes());
			RegisterUnsafe<Guid, string>((value) => value.ToString("D", null));
			RegisterUnsafe<Guid, Uuid128>((value) => new Uuid128(value));
			RegisterUnsafe<Guid, bool>((value) => value != Guid.Empty);
			RegisterUnsafe<Guid, System.Net.IPAddress>((value) => new System.Net.IPAddress(new Uuid128(value).ToByteArray()));

			RegisterUnsafe<Uuid128, Slice>((value) => value.ToSlice());
			RegisterUnsafe<Uuid128, byte[]>((value) => value.ToByteArray());
			RegisterUnsafe<Uuid128, string>((value) => value.ToString("D", null));
			RegisterUnsafe<Uuid128, Guid>((value) => value.ToGuid());
			RegisterUnsafe<Uuid128, bool>((value) => value != Uuid128.Empty);
			RegisterUnsafe<Guid, System.Net.IPAddress>((value) => new System.Net.IPAddress(value.ToByteArray()));

			RegisterUnsafe<Uuid64, Slice>((value) => value.ToSlice());
			RegisterUnsafe<Uuid64, byte[]>((value) => value.ToByteArray());
			RegisterUnsafe<Uuid64, string>((value) => value.ToString("D", null));
			RegisterUnsafe<Uuid64, long>((value) => value.ToInt64());
			RegisterUnsafe<Uuid64, ulong>((value) => value.ToUInt64());
			RegisterUnsafe<Uuid64, bool>((value) => value.ToInt64() != 0L);

			RegisterUnsafe<TimeSpan, Slice>((value) => Slice.FromInt64(value.Ticks));
			RegisterUnsafe<TimeSpan, byte[]>((value) => Slice.FromInt64(value.Ticks).GetBytes());
			RegisterUnsafe<TimeSpan, long>((value) => value.Ticks);
			RegisterUnsafe<TimeSpan, ulong>((value) => checked((ulong)value.Ticks));
			RegisterUnsafe<TimeSpan, double>((value) => value.TotalSeconds);
			RegisterUnsafe<TimeSpan, bool>((value) => value == TimeSpan.Zero);

			RegisterUnsafe<System.Net.IPAddress, Slice>((value) => value != null ? Slice.Create(value.GetAddressBytes()) : Slice.Nil);
			RegisterUnsafe<System.Net.IPAddress, byte[]>((value) => value != null ? value.GetAddressBytes() : null);
			RegisterUnsafe<System.Net.IPAddress, string>((value) => value != null ? value.ToString() : null);

			RegisterUnsafe<FdbTupleAlias, byte>((value) => (byte)value);
			RegisterUnsafe<FdbTupleAlias, int>((value) => (int)value);
			RegisterUnsafe<FdbTupleAlias, Slice>((value) => Slice.FromByte((byte)value));

			//REVIEW: this should go in the Tuples layer !
			RegisterUnsafe<Slice, byte[]>((value) => value.GetBytes());
			RegisterUnsafe<Slice, string>((value) => value.ToUnicode());
			RegisterUnsafe<Slice, bool>((value) => value.ToBool());
			RegisterUnsafe<Slice, sbyte>((value) => value.ToSByte());
			RegisterUnsafe<Slice, byte>((value) => value.ToByte());
			RegisterUnsafe<Slice, short>((value) => value.ToInt16());
			RegisterUnsafe<Slice, ushort>((value) => value.ToUInt16());
			RegisterUnsafe<Slice, int>((value) => value.ToInt32());
			RegisterUnsafe<Slice, uint>((value) => value.ToUInt32());
			RegisterUnsafe<Slice, long>((value) => value.ToInt64());
			RegisterUnsafe<Slice, ulong>((value) => value.ToUInt64());
			RegisterUnsafe<Slice, Guid>((value) => value.ToGuid());
			RegisterUnsafe<Slice, Uuid128>((value) => value.ToUuid128());
			RegisterUnsafe<Slice, Uuid64>((value) => value.ToUuid64());
			RegisterUnsafe<Slice, TimeSpan>((value) => TimeSpan.FromTicks(value.ToInt64()));
			RegisterUnsafe<Slice, FdbTupleAlias>((value) => (FdbTupleAlias)value.ToByte());
			RegisterUnsafe<Slice, System.Net.IPAddress>((value) => !value.IsNullOrEmpty ? new System.Net.IPAddress(value.GetBytes()) : null);
		}

19 View Source File : SimRuntime.cs
License : MIT License
Project Creator : abdullin

public void Debug(LogType type, string message) {
            _lastActivity = _time;


            var diff = _time - _lastDebug;
            _lastDebug = _time;

            string consoleColor;

            switch (type) {
                case LogType.RuntimeInfo:
                    consoleColor = Cli.DarkBlue;
                    break;
                case LogType.Fault:
                    consoleColor = Cli.Red;
                    break;
                case LogType.Error:
                    consoleColor = Cli.Red;
                    break;
                case LogType.Info:
                    consoleColor = Cli.Default;
                    break;
                case LogType.Warning:
                    consoleColor = Cli.DarkYellow;
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(type), type, null);
            }

            Console.WriteLine(
                $"{Cli.Gray}+ {TimeSpan.FromTicks(diff).TotalMilliseconds:0000} ms{Cli.Default} {consoleColor}{message}{Cli.Default}");

        }

19 View Source File : SimRuntime.cs
License : MIT License
Project Creator : abdullin

public void Run(Func<SimControl, Task> plan) {
            _haltError = null;

            var watch = Stopwatch.StartNew();
            var reason = "none";
            
            Debug(LogType.RuntimeInfo,  $"{"start".ToUpper()}");
            Rand.Reinitialize(0);

            using (var cluster = new SimCluster(Def, this)) {
                
                Schedule(_scheduler,TimeSpan.Zero, _factory.StartNew(async () => {
                    var control = new SimControl(cluster, this);
                    try {
                        await plan(control);
                    } catch (Exception ex) {
                        Halt("Plan failed", ex);
                    }
                }));


                try {
                    var step = 0;
                    while (true) {
                        step++;

                        var hasFuture = FutureQueue.TryGetFuture(out var o);
                        if (!hasFuture) {
                            reason = "died";
                            break;
                        }

                        if (o.Time > _time) {
                            _time = o.Time;
                        }

                        switch (o.Item) {
                            case Task t:
                                o.Scheduler.Execute(t);
                                break;
                            default:
                                throw new InvalidOperationException();
                        }

                        if (_haltError != null || _haltMessage != null) {
                            reason = "halt";
                            break;
                        }

                        if ((_time - _lastActivity) >= _maxInactiveTicks) {
                            reason = "no activity " + Moment.Print(TimeSpan.FromTicks(_maxInactiveTicks));
                            break;
                        }

                        if (_steps >= MaxSteps) {
                            reason = MaxSteps + " steps reached";
                            break;
                        }

                        if (_time >= MaxTicks) {
                            reason = "max time";
                            break;
                        }
                    }
                } catch (Exception ex) {
                    reason = "fatal";
                    _haltError = ex;
                    Console.WriteLine("Fatal: " + ex);
                } finally {
                    if (_folder != null) {
                        Directory.Delete(_folder, true);
                    }
                }

                watch.Stop();

                var softTime = TimeSpan.FromTicks(_time);
                var factor = softTime.TotalHours / watch.Elapsed.TotalHours;

                if (_haltMessage != null) {
                    reason = _haltMessage.ToUpper();
                }

                Debug(LogType.RuntimeInfo,  $"{reason.ToUpper()} at {softTime}");

                if (_haltError != null) {
                    var demystify = _haltError.Demystify();
                    Console.WriteLine(demystify.GetType().Name + ": " + demystify.Message);
                    Console.WriteLine(demystify.StackTrace);
                }

                Console.WriteLine($"Simulated {Moment.Print(softTime)} in {_steps} steps.");
                Console.WriteLine($"Took {Moment.Print(watch.Elapsed)} of real time (x{factor:F0} speed-up)");
                // statistics
                
                Console.WriteLine($"Stats: {FutureQueue.JumpCount} jumps, {cluster.Machines.Sum(m => m.Value.SocketCount)} sockets");

            }

            

        }

19 View Source File : Command.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas

public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            if (commandData == null)
            {
                return Result.Failed;
            }

            if (!System.IO.Directory.Exists(Constants.DefaultExportDirectory))
            {
                System.IO.Directory.CreateDirectory(Constants.DefaultExportDirectory);
            }

            if (string.IsNullOrEmpty(FileUtilities.GetCentralFileName(commandData.Application.ActiveUIDoreplacedent.Doreplacedent)))
            {
                WindowManager.ShowMessageBox("FAIL", "Please save the file before continuing");
                return Result.Failed;
            }

            var uidoc = commandData.Application.ActiveUIDoreplacedent;
            if (uidoc == null)
            {
                return Result.Failed;
            }

            var views = new List<ViewSheet>();

            if (uidoc.Doreplacedent.ActiveView.ViewType == ViewType.ProjectBrowser)
            {
                var s = uidoc.Selection.GetElementIds();
                foreach (var id in s)
                {
                    var projectBrowserView = uidoc.Doreplacedent.GetElement(id);
                    if (projectBrowserView is View)
                    {
                        var v = (View)projectBrowserView;
                        if (v.ViewType == ViewType.ProjectBrowser)
                        {
                            continue;
                        }
                        if (v is ViewSheet)
                        {
                            views.Add((ViewSheet)v);
                            continue;
                        }
                    }
                }
            }

            // Deselect all elements before continuing so they don't appear incorrectly
            uidoc.Selection.SetElementIds(new List<ElementId>());

            var manager = new Manager(uidoc);
            var log = new ExportLog();
            var vm = new ViewModels.SCexportViewModel(manager, views);
            var wm = WindowManager;
            wm.ShowDialog(vm, null, ViewModels.SCexportViewModel.DefaultWindowSettings);

            if (vm.CloseStatus != ViewModels.SCexportViewModel.CloseMode.Exit)
            {             
                string exportType = string.Empty;

                switch (vm.CloseStatus)
                {
                    case ViewModels.SCexportViewModel.CloseMode.Export:
                        exportType = "Exporting";
                        break;
                    case ViewModels.SCexportViewModel.CloseMode.Print:
                    case ViewModels.SCexportViewModel.CloseMode.PrintA3:
                    case ViewModels.SCexportViewModel.CloseMode.PrintA2:
                        exportType = "Printing";
                        break;
                }

                var progressVm = new ViewModels.ProgressMonitorViewModel
                {
                    MaximumValue = vm.SelectedSheets.Count, Value = 0
                };

                log.Clear();
                log.Start(exportType + " Started.");

                WindowManager.ShowWindow(progressVm, null, ViewModels.ProgressMonitorViewModel.DefaultWindowSettings);

                if (manager.SaveHistory)
                {
                    RecentExport.Save(manager, vm.SelectedSheets);
                }

                foreach (var sheet in vm.SelectedSheets)
                {
                    progressVm.ProgressSummary += @" --> " + exportType + @" " + sheet.FullExportName + "...";

                    switch (vm.CloseStatus)
                    {
                        case ViewModels.SCexportViewModel.CloseMode.Export:
                            manager.ExportSheet(sheet, log);
                            break;
                        case ViewModels.SCexportViewModel.CloseMode.Print:
                            manager.Print(sheet, manager.PrinterNameLargeFormat, 1, log);
                            break;
                        case ViewModels.SCexportViewModel.CloseMode.PrintA3:
                            manager.Print(sheet, manager.PrinterNameA3, 3, log);
                            break;
                        case ViewModels.SCexportViewModel.CloseMode.PrintA2:
                            manager.Print(sheet, manager.PrinterNameLargeFormat, 2, log);
                            break;
                        default:
                            return Result.Succeeded;
                    }

                    progressVm.Value++;
                    string niceTime = string.Format(
                        System.Globalization.CultureInfo.CurrentCulture,
                        "OK  [ time {0:hh\\.mm\\:ss}  total {1:hh\\.mm\\:ss}  ~remaining {2:hh\\.mm\\:ss}]",
                        log.LasreplacedemElapsedTime,
                        log.TimeSinceStart,
                        System.TimeSpan.FromTicks(log.TimeSinceStart.Ticks / progressVm.Value * (progressVm.MaximumValue - progressVm.Value)));
                    progressVm.ProgressSummary += niceTime + System.Environment.NewLine;

                    if (progressVm.CancelPressed)
                    {
                        break;
                    }
                }

                log.Stop("Finished");
                progressVm.Stop(log);
                progressVm.ProcessComplete = true;
            }
         
            if (manager.ShowExportLog || log.Errors > 0) {
                var exportLogViewModel = new ViewModels.ExportLogViewModel(log);
                WindowManager.ShowDialog(exportLogViewModel, null, ViewModels.ExportLogViewModel.DefaultWindowSettings);
            }

            return Result.Succeeded;
        }

19 View Source File : Tester.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public void Count()
        {
            TimeSpan ts = TimeSpan.FromTicks(RunTime);
            GC.Collect();
            ZeroTrace.SystemLog("Count", ExCount,
                $"{ts.TotalMilliseconds / ExCount}ms | {ExCount / (DateTime.Now - Start).TotalSeconds}/s",
                "Error", $"net:{NetError:D8} | worker:{WkError:D8} | time out:{TmError:D8} | bug:{BlError:D8}");
        }

19 View Source File : KeyRingProvider.cs
License : Apache License 2.0
Project Creator : Aguafrommars

private static TimeSpan GetRefreshPeriodWithJitter(TimeSpan refreshPeriod)
        {
            // We'll fudge the refresh period up to -20% so that multiple applications don't try to
            // hit a single repository simultaneously. For instance, if the refresh period is 1 hour,
            // we'll return a value in the vicinity of 48 - 60 minutes. We use the Random clreplaced since
            // we don't need a secure PRNG for this.
            return TimeSpan.FromTicks((long)(refreshPeriod.Ticks * (1.0d - (new Random().NextDouble() / 5))));
        }

19 View Source File : IntervalRange.cs
License : Apache License 2.0
Project Creator : akarnokd

internal void Run(IScheduler scheduler)
            {
                var idx = index;
                if (idx != end)
                {
                    downstream.OnNext(idx++);
                }
                if (idx == end)
                {
                    downstream.OnCompleted();
                    return;
                }
                else
                {
                    index = idx;
                }

                var now = scheduler.Now;
                var next = startTime + TimeSpan.FromTicks(period.Ticks * (++count));

                var delay = next - now;

                SetTask(scheduler.Schedule(this, delay, TASK));
            }

19 View Source File : EventStoreSnapshotStoreSpec.cs
License : Apache License 2.0
Project Creator : AkkaNetContrib

[Fact]
        public void SnapshotStore_should_not_delete_snapshots_with_non_matching_upper_timestamp_bounds()
        {
            var snapshotMetadata = _metadata[3];
            var criteria = new SnapshotSelectionCriteria(snapshotMetadata.SequenceNr,
                snapshotMetadata.Timestamp.Subtract(TimeSpan.FromTicks(1L)), 0L, new DateTime?());
            var message = new DeleteSnapshots(Pid, criteria);
            var testProbe = CreateTestProbe();
            Subscribe<DeleteSnapshots>(testProbe.Ref);
            SnapshotStore.Tell(message, _senderProbe.Ref);
            testProbe.ExpectMsg(message, new TimeSpan?());
            _senderProbe.ExpectMsg<DeleteSnapshotsSuccess>(m => m.Criteria.Equals(criteria), new TimeSpan?());
            SnapshotStore.Tell(
                new LoadSnapshot(Pid,
                    new SnapshotSelectionCriteria(snapshotMetadata.SequenceNr, snapshotMetadata.Timestamp, 0L,
                        new DateTime?()), long.MaxValue), _senderProbe.Ref);
            _senderProbe.ExpectMsg((Predicate<LoadSnapshotResult>) (result =>
            {
                if (result.ToSequenceNr == long.MaxValue && result.Snapshot != null &&
                    result.Snapshot.Metadata.Equals(_metadata[3]))
                    return result.Snapshot.Snapshot.ToString() == "s-4";
                return false;
            }), new TimeSpan?());
        }

19 View Source File : UnixTimestampUtils.cs
License : MIT License
Project Creator : alen-smajic

public static DateTime From(long timestamp)
		{
			return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Add(TimeSpan.FromTicks(timestamp));
		}

19 View Source File : JsonHelper.cs
License : MIT License
Project Creator : AlenToma

public static DateTimeOffset CreateDateTimeOffset(int year, int month, int day, int hour, int min, int sec, int milli, int extraTicks, TimeSpan offset)
        {
            var dt = new DateTimeOffset(year, month, day, hour, min, sec, milli, offset);

            if (extraTicks > 0)
                dt += TimeSpan.FromTicks(extraTicks);

            return dt;
        }

19 View Source File : ExperimentController.cs
License : MIT License
Project Creator : AlexanderFroemmgen

[HttpGet("{id}/remainingTime")]
        public IActionResult GetRemainingTime(int id)
        {
            var sim = _context.Experiments
                .Include(s => s.ExperimentInstances)
                .SingleOrDefault(s => s.Id == id);

            if (sim == null)
            {
                return NotFound();
            }

            var workStarted = sim.ExperimentInstances
                .Where(i => i.Status == ExperimentStatus.Finished || i.Status == ExperimentStatus.Error)
                .Select(i => i.WorkStarted)
                .DefaultIfEmpty().Min();

            var avgTimeSpan = TimeSpan.FromTicks(Convert.ToInt64(sim.ExperimentInstances
                .Where(i => i.Status == ExperimentStatus.Finished || i.Status == ExperimentStatus.Error)
                .Select(i => (i.WorkFinished - i.WorkStarted).Ticks)
                .DefaultIfEmpty().Average()));

            var activeWorkers =
                _context.Workers.Count(w => w.LastRequestTime > DateTime.UtcNow.AddTicks(-2 * avgTimeSpan.Ticks));

            var remainingExperiments =
                sim.ExperimentInstances.Count(
                    i => i.Status == ExperimentStatus.Pending || i.Status == ExperimentStatus.Running);

            var estimatedRemainingTime = TimeSpan.FromMilliseconds(-1);

            if (activeWorkers > 0)
            {
                estimatedRemainingTime = TimeSpan.FromTicks(avgTimeSpan.Ticks * remainingExperiments / activeWorkers);
            }

            var result = new
            {
                WorkStarted = workStarted,
                ElapsedTime = DateTime.UtcNow - workStarted,
                AverageTimeToCompletion = avgTimeSpan,
                ActiveWorkerCount = activeWorkers,
                RemainingExperimentCount = remainingExperiments,
                EstimatedRemainingTime = estimatedRemainingTime,
                EstimatedTimeOfCompletion = DateTime.UtcNow.Add(estimatedRemainingTime)
            };

            return new ObjectResult(result);
        }

19 View Source File : EasyCachingListenerHandler.cs
License : MIT License
Project Creator : alexvaluyskiy

public override void OnCustom(string name, Activity activity, object payload)
        {
            switch (name)
            {
                case "EasyCaching.WriteSetCacheBefore":
                    {
                        if (setBeforeOperationFetcher.TryFetch(payload, out var timestampBefore))
                        {
                            this.writeSetLocal.Value = timestampBefore;
                        }
                    }
                    break;
                case "EasyCaching.WriteSetCacheAfter":
                    {
                        var timestampBefore = this.writeSetLocal.Value;

                        if (setAfterOperationFetcher.TryFetch(payload, out var timestampAfter))
                        {
                            var elapsed = TimeSpan.FromTicks(timestampAfter - timestampBefore).TotalSeconds;

                            if (elapsed == 0)
                            {
                                return;
                            }

                            PrometheusCounters.EasyCachingOperationDuration.WithLabels("set").Observe(elapsed);
                        }
                    }
                    break;
                case "EasyCaching.WriteGetCacheBefore":
                    {
                        if (getBeforeOperationFetcher.TryFetch(payload, out var timestampBefore))
                        {
                            this.writeGetLocal.Value = timestampBefore;
                        }
                    }
                    break;
                case "EasyCaching.WriteGetCacheAfter":
                    {
                        var timestampBefore = this.writeGetLocal.Value;

                        if (getAfterOperationFetcher.TryFetch(payload, out var timeStampAfter))
                        {
                            var elapsed = TimeSpan.FromTicks(timeStampAfter - timestampBefore).TotalSeconds;
                            
                            if (elapsed == 0)
                            {
                                return;
                            }

                            PrometheusCounters.EasyCachingOperationDuration.WithLabels("get").Observe(elapsed);
                        }
                    }
                    break;
                case "EasyCaching.WriteRemoveCacheBefore":
                    {
                        if (removeBeforeOperationFetcher.TryFetch(payload, out var timestampBefore))
                        {
                            this.writeRemoveLocal.Value = timestampBefore;
                        }
                    }
                    break;
                case "EasyCaching.WriteRemoveCacheAfter":
                    {
                        var timestampBefore = this.writeRemoveLocal.Value;

                        if (removeAfterOperationFetcher.TryFetch(payload, out var timeStampAfter))
                        {
                            var elapsed = TimeSpan.FromTicks(timeStampAfter - timestampBefore).TotalSeconds;

                            if (elapsed == 0)
                            {
                                return;
                            }

                            PrometheusCounters.EasyCachingOperationDuration.WithLabels("remove").Observe(elapsed);
                        }
                    }
                    break;
            }
        }

19 View Source File : ConsoleApp.cs
License : MIT License
Project Creator : allisterb

protected virtual void Tick()
        {
            lastSystemTickTime = DateTime.UtcNow;
            double stepInterval;
            while (!this.IsClosing)
            {
                currentSystemTickTime = DateTime.UtcNow;
                // Check if more than an entire frame time by.
                stepInterval = TimeSpan.FromTicks(currentSystemTickTime.Ticks - lastSystemTickTime.Ticks).TotalMilliseconds;
                if ((stepInterval < (1000 / fps)))
                {
                    Thread.Sleep((int) (stepInterval / 2));
                }
                else
                {
                    lastSystemTickTime = currentSystemTickTime;
                    this.OnTick(true);
                    ReadAndDispatchConsoleKeys();
                }
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : aloneguid

private static void Perf()
      {
         var readTimes = new List<TimeSpan>();
         var uwts = new List<TimeSpan>();
         var gwts = new List<TimeSpan>();
         for (int i = 0; i < 10; i++)
         {
            ReadLargeFile(out TimeSpan readTime, out TimeSpan uwt, out TimeSpan gwt);
            readTimes.Add(readTime);
            uwts.Add(uwt);
            gwts.Add(gwt);
            Console.WriteLine("iteration #{0}: {1}, uwp: {2}, gwt: {3}", i, readTime, uwt, gwt);
         }

         Console.WriteLine("mean(read): {0}, mean(uw): {1}, mean(gw): {2}",
            TimeSpan.FromTicks((long)readTimes.Average(t => t.Ticks)),
            TimeSpan.FromTicks((long)uwts.Average(t => t.Ticks)),
            TimeSpan.FromTicks((long)gwts.Average(t => t.Ticks)));

      }

19 View Source File : NanoTimeTest.cs
License : MIT License
Project Creator : aloneguid

[Fact]
      public void ConvertToDateTimeOffset_PreservesTicks()
      {
         var dto = new DateTimeOffset(2021, 05, 14, 17, 52, 31, TimeSpan.Zero);
         dto = dto.Add(TimeSpan.FromTicks(1234567));
         var nanoTime = new NanoTime(dto);
         var convertedDto = (DateTimeOffset) nanoTime;

         replacedert.Equal(dto, convertedDto);
      }

19 View Source File : LongExtension.cs
License : MIT License
Project Creator : AlphaYu

public static TimeSpan FromTicks(this long value)
        {
            return TimeSpan.FromTicks(value);
        }

19 View Source File : DataBuffer.cs
License : MIT License
Project Creator : AndreasAmMueller

public TimeSpan GetTimeSpan(int index)
		{
			return TimeSpan.FromTicks(GetInt64(index));
		}

19 View Source File : ObjectGenerator.cs
License : GNU General Public License v3.0
Project Creator : andysal

[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
            private static Dictionary<Type, Func<long, object>> InitializeGenerators()
            {
                return new Dictionary<Type, Func<long, object>>
                {
                    { typeof(Boolean), index => true },
                    { typeof(Byte), index => (Byte)64 },
                    { typeof(Char), index => (Char)65 },
                    { typeof(DateTime), index => DateTime.Now },
                    { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
                    { typeof(DBNull), index => DBNull.Value },
                    { typeof(Decimal), index => (Decimal)index },
                    { typeof(Double), index => (Double)(index + 0.1) },
                    { typeof(Guid), index => Guid.NewGuid() },
                    { typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
                    { typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
                    { typeof(Int64), index => (Int64)index },
                    { typeof(Object), index => new object() },
                    { typeof(SByte), index => (SByte)64 },
                    { typeof(Single), index => (Single)(index + 0.1) },
                    { 
                        typeof(String), index =>
                        {
                            return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
                        }
                    },
                    { 
                        typeof(TimeSpan), index =>
                        {
                            return TimeSpan.FromTicks(1234567);
                        }
                    },
                    { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
                    { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
                    { typeof(UInt64), index => (UInt64)index },
                    { 
                        typeof(Uri), index =>
                        {
                            return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
                        }
                    },
                };
            }

19 View Source File : LocationServiceImplementation.cs
License : MIT License
Project Creator : anjoy8

public Task<Position> GetPositionAsync(TimeSpan? timeout = null, CancellationToken? cancelToken = null)
        {
            var timeoutMilliseconds = timeout.HasValue ? (int)timeout.Value.TotalMilliseconds : eShopOnContainers.Windows.Helpers.Timeout.Infinite;
            if (timeoutMilliseconds < 0 && timeoutMilliseconds != eShopOnContainers.Windows.Helpers.Timeout.Infinite)
                throw new ArgumentOutOfRangeException(nameof(timeout));

            if (!cancelToken.HasValue)
                cancelToken = CancellationToken.None;

            var pos = _locator.GetGeopositionAsync(TimeSpan.FromTicks(0), TimeSpan.FromDays(365));
            cancelToken.Value.Register(o => ((IAsyncOperation<Geoposition>)o).Cancel(), pos);
            var timer = new eShopOnContainers.Windows.Helpers.Timeout(timeoutMilliseconds, pos.Cancel);
            var tcs = new TaskCompletionSource<Position>();

            pos.Completed = (op, s) =>
            {
                timer.Cancel();
                switch (s)
                {
                    case AsyncStatus.Canceled:
                        tcs.SetCanceled();
                        break;
                    case AsyncStatus.Completed:
                        tcs.SetResult(GetPosition(op.GetResults()));
                        break;
                    case AsyncStatus.Error:
                        var ex = op.ErrorCode;
                        if (ex is UnauthorizedAccessException)
                            ex = new GeolocationException(GeolocationError.Unauthorized, ex);

                        tcs.SetException(ex);
                        break;
                }
            };
            return tcs.Task;           
        }

19 View Source File : AccCompiler.cs
License : GNU General Public License v3.0
Project Creator : anotak

public override bool Run()
		{
			ProcessStartInfo processinfo;
			Process process;
			TimeSpan deltatime;
			int line = 0;
			string sourcedir = Path.GetDirectoryName(sourcefile);
			
			// Create parameters
			string args = this.parameters;
			args = args.Replace("%FI", inputfile);
			args = args.Replace("%FO", outputfile);
			args = args.Replace("%FS", sourcefile);
			args = args.Replace("%PT", this.tempdir.FullName);
			args = args.Replace("%PS", sourcedir);
			
			// Setup process info
			processinfo = new ProcessStartInfo();
			processinfo.Arguments = args;
			processinfo.FileName = Path.Combine(this.tempdir.FullName, info.ProgramFile);
			processinfo.CreateNoWindow = false;
			processinfo.ErrorDialog = false;
			processinfo.UseShellExecute = true;
			processinfo.WindowStyle = ProcessWindowStyle.Hidden;
			processinfo.WorkingDirectory = this.workingdir;
			
			// Output info
			Logger.WriteLogLine("Running compiler...");
			Logger.WriteLogLine("Program:    " + processinfo.FileName);
			Logger.WriteLogLine("Arguments:  " + processinfo.Arguments);
			
			try
			{
				// Start the compiler
				process = Process.Start(processinfo);
			}
			catch(Exception e)
			{
				// Unable to start the compiler
				General.ShowErrorMessage("Unable to start the compiler (" + info.Name + "). " + e.GetType().Name + ": " + e.Message, MessageBoxButtons.OK);
				return false;
			}
			
			// Wait for compiler to complete
			process.WaitForExit();
			deltatime = TimeSpan.FromTicks(process.ExitTime.Ticks - process.StartTime.Ticks);
			Logger.WriteLogLine("Compiler process has finished.");
			Logger.WriteLogLine("Compile time: " + deltatime.TotalSeconds.ToString("########0.00") + " seconds");
			
			// Now find the error file
			string errfile = Path.Combine(this.workingdir, ACS_ERROR_FILE);
			if(File.Exists(errfile))
			{
				try
				{
					// Regex to find error lines
					Regex errlinematcher = new Regex(":[0-9]+: ", RegexOptions.Compiled | RegexOptions.CultureInvariant);
					
					// Read all lines
					string[] errlines = File.ReadAllLines(errfile);
					while(line < errlines.Length)
					{
						// Check line
						string linestr = errlines[line];
						Match match = errlinematcher.Match(linestr);
						if(match.Success && (match.Index > 0))
						{
							CompilerError err = new CompilerError();
							
							// The match without spaces and semicolon is the line number
							string linenr = match.Value.Replace(":", "").Trim();
							if(!int.TryParse(linenr, out err.linenumber))
								err.linenumber = CompilerError.NO_LINE_NUMBER;
							else
								err.linenumber--;
							
							// Everything before the match is the filename
							err.filename = linestr.Substring(0, match.Index);
							if(!Path.IsPathRooted(err.filename))
							{
								// Add working directory to filename
								err.filename = Path.Combine(processinfo.WorkingDirectory, err.filename);
							}
							
							// Everything after the match is the description
							err.description = linestr.Substring(match.Index + match.Length).Trim();
							
							// Report the error
							ReportError(err);
						}
						
						// Next line
						line++;
					}
				}
				catch(Exception e)
				{
					// Error reading errors (ironic, isn't it)
					ReportError(new CompilerError("Failed to retrieve compiler error report. " + e.GetType().Name + ": " + e.Message));
				}
			}
			
			return true;
		}

19 View Source File : NodesCompiler.cs
License : GNU General Public License v3.0
Project Creator : anotak

public override bool Run()
		{
			ProcessStartInfo processinfo;
			Process process;
			TimeSpan deltatime;
			
			// Create parameters
			string args = this.parameters;
			args = args.Replace("%FI", inputfile);
			args = args.Replace("%FO", outputfile);
			
			// Setup process info
			processinfo = new ProcessStartInfo();
			processinfo.Arguments = args;
			processinfo.FileName = Path.Combine(this.tempdir.FullName, info.ProgramFile);
			processinfo.CreateNoWindow = false;
			processinfo.ErrorDialog = false;
			processinfo.UseShellExecute = true;
			processinfo.WindowStyle = ProcessWindowStyle.Hidden;
			processinfo.WorkingDirectory = this.workingdir;
			
			// Output info
			Logger.WriteLogLine("Running compiler...");
			Logger.WriteLogLine("Program:    " + processinfo.FileName);
			Logger.WriteLogLine("Arguments:  " + processinfo.Arguments);
			
			try
			{
				// Start the compiler
				process = Process.Start(processinfo);
			}
			catch(Exception e)
			{
				// Unable to start the compiler
				General.ShowErrorMessage("Unable to start the compiler (" + info.Name + "). " + e.GetType().Name + ": " + e.Message, MessageBoxButtons.OK);
				return false;
			}
			
			// Wait for compiler to complete
			process.WaitForExit();
			deltatime = TimeSpan.FromTicks(process.ExitTime.Ticks - process.StartTime.Ticks);
			Logger.WriteLogLine("Compiler process has finished.");
			Logger.WriteLogLine("Compile time: " + deltatime.TotalSeconds.ToString("########0.00") + " seconds");
			return true;
		}

19 View Source File : Launcher.cs
License : GNU General Public License v3.0
Project Creator : anotak

public void TestAtSkill(int skill)
		{
			Cursor oldcursor = Cursor.Current;
			ProcessStartInfo processinfo;
			Process process;
			TimeSpan deltatime;
			string args;

			// Check if configuration is OK
			if((General.Map.ConfigSettings.TestProgram == "") ||
			   !File.Exists(General.Map.ConfigSettings.TestProgram))
			{
				// Show message
				Cursor.Current = Cursors.Default;
				DialogResult result = General.ShowWarningMessage("Your test program is not set for the current game configuration. Would you like to set up your test program now?", MessageBoxButtons.YesNo);
				if(result == DialogResult.Yes)
				{
					// Show game configuration on the right page
					General.MainWindow.ShowConfigurationPage(2);
				}
				return;
			}

			// No custom parameters?
			if(!General.Map.ConfigSettings.CustomParameters)
			{
				// Set parameters to the default ones
				General.Map.ConfigSettings.TestParameters = General.Map.Config.TestParameters;
				General.Map.ConfigSettings.TestShortPaths = General.Map.Config.TestShortPaths;
			}
			
			// Remove temporary file
			try { File.Delete(tempwad); }
			catch(Exception) { }
			
			// Save map to temporary file
			Cursor.Current = Cursors.WaitCursor;
			tempwad = General.MakeTempFilename(General.Map.TempPath, "wad");
			General.Plugins.OnMapSaveBegin(SavePurpose.Testing);
			if(General.Map.SaveMap(tempwad, SavePurpose.Testing))
			{
				// No compiler errors?
				if(General.Map.Errors.Count == 0)
				{
					// Make arguments
					args = ConvertParameters(General.Map.ConfigSettings.TestParameters, skill, General.Map.ConfigSettings.TestShortPaths);

					// Setup process info
					processinfo = new ProcessStartInfo();
					processinfo.Arguments = args;
					processinfo.FileName = General.Map.ConfigSettings.TestProgram;
					processinfo.CreateNoWindow = false;
					processinfo.ErrorDialog = false;
					processinfo.UseShellExecute = true;
					processinfo.WindowStyle = ProcessWindowStyle.Normal;
					processinfo.WorkingDirectory = Path.GetDirectoryName(processinfo.FileName);

					// Output info
					Logger.WriteLogLine("Running test program: " + processinfo.FileName);
					Logger.WriteLogLine("Program parameters:  " + processinfo.Arguments);

					// Disable interface
					General.MainWindow.DisplayStatus(StatusType.Busy, "Waiting for game application to finish...");

					try
					{
						// Start the program
						process = Process.Start(processinfo);

						// Wait for program to complete
						while(!process.WaitForExit(10))
						{
							General.MainWindow.Update();
						}

						// Done
						deltatime = TimeSpan.FromTicks(process.ExitTime.Ticks - process.StartTime.Ticks);
						Logger.WriteLogLine("Test program has finished.");
						Logger.WriteLogLine("Run time: " + deltatime.TotalSeconds.ToString("###########0.00") + " seconds");
					}
					catch(Exception e)
					{
						// Unable to start the program
						General.ShowErrorMessage("Unable to start the test program, " + e.GetType().Name + ": " + e.Message, MessageBoxButtons.OK); ;
					}
					
					General.MainWindow.DisplayReady();
				}
				else
				{
					General.MainWindow.DisplayStatus(StatusType.Warning, "Unable to test the map due to script errors.");
				}
			}
			
			// Clean up temp file
			CleanTempFile(General.Map);
			
			// Done
			General.Map.Graphics.Reset();
			General.Plugins.OnMapSaveEnd(SavePurpose.Testing);
			General.MainWindow.RedrawDisplay();
			General.MainWindow.FocusDisplay();
			Cursor.Current = oldcursor;
		}

19 View Source File : BclHelpers.cs
License : MIT License
Project Creator : AnotherEnd15

public static TimeSpan ReadTimeSpan(ProtoReader source)
        {
            long ticks = ReadTimeSpanTicks(source, out DateTimeKind kind);
            if (ticks == long.MinValue) return TimeSpan.MinValue;
            if (ticks == long.MaxValue) return TimeSpan.MaxValue;
            return TimeSpan.FromTicks(ticks);
        }

19 View Source File : BclHelpers.cs
License : MIT License
Project Creator : AnotherEnd15

static TimeSpan FromDurationSeconds(long seconds, int nanos)
        {

            long ticks = checked((seconds * TimeSpan.TicksPerSecond)
                + (nanos * TimeSpan.TicksPerMillisecond) / 1000000);
            return TimeSpan.FromTicks(ticks);
        }

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

private object _convertColumnValue(object value)
        {
            if (value == null) return value;

            var elementType = value.GetType();            

            var nullableType = Nullable.GetUnderlyingType(elementType);
            if (nullableType != null)
            {
                elementType = nullableType;
            }

            if (elementType.IsEnum)
                return value.ToString();

            switch(value)
            {
                case LocalDate ld:
                    return ld.ToDateTimeUnspecified();
                case LocalDateTime ldt:
                    return ldt.ToDateTimeUnspecified();
                case Instant i:
                    return i.ToDateTimeUtc();
                case OffsetDateTime odt:
                    return odt.ToDateTimeOffset();
                case OffsetDate od:
                    return od.At(LocalTime.Midnight).ToDateTimeOffset();
                case LocalTime lt:
                    return TimeSpan.FromTicks(lt.TickOfDay);
            }

            return value;
        }

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

public override void SetValue(IDbDataParameter parameter, LocalTime value)
        {
            parameter.Value = TimeSpan.FromTicks(value.TickOfDay);
            //DbType could throw depending on the Driver implementation
            // see: https://community.oracle.com/tech/developers/discussion/2502273/converting-to-odp-net-oracletype-cursor-converts-to-dbtype
            //parameter.DbType = DbType.Time;

            OnSetValue?.Invoke(this, parameter);
        }

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

public override TimeSpan Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            return TimeSpan.FromTicks(reader.GetInt64());
        }

19 View Source File : ValueAnimator.cs
License : Apache License 2.0
Project Creator : ascora

private TimeSpan GetTimerInterval()
        {
            return TimeSpan.FromTicks((long)Math.Floor(TimeSpan.TicksPerSecond / (decimal)FrameRate));
        }

19 View Source File : Chapter.cs
License : GNU General Public License v3.0
Project Creator : audiamus

public void CreateCueSheet (Book.Part part, int trackDurMins, bool splitTimeMode) {
      Log (3, this, () => this.ToString ());
      
      // chapter duration in sec
      double chLenSec = this.Time.Duration.TotalSeconds;

      // rounded number of tracks in chapter, observing desired track duration 
      int numTracks = Math.Max ((int)(chLenSec / (trackDurMins * 60) + 0.5), 1);

      // average track length in sec
      double aveTrackLen = chLenSec / numTracks;

      // average track length as TimeSpan
      var tsAveTrackLen = TimeSpan.FromSeconds (aveTrackLen);

      // search range for silence at desired end of track is +/- 1/3 ave track length
      var tsSearchRange = TimeSpan.FromSeconds (aveTrackLen / 3);

      // start 1st track at zero 
      // unless in time split mode where we start at the actual beginning of the chapter
      var tsStart = TimeSpan.Zero;
      if (splitTimeMode)
        tsStart = this.Time.Begin;

      // desired end of 1st track
      var tsEnd = tsStart + tsAveTrackLen;

      // max end is chapter duration unless in time split mode
      var tsChEnd = this.Time.Duration - TS_EPS_SILENCE;
      if (splitTimeMode)
        tsChEnd = this.Time.End;

      // filter silences
      var silences = this.Silences.Where (s => s.Duration >= TS_SHORT_SILENCE).ToList ();

      // while chapter length has not been reached, will be checked in loop
      while (true) {

        if (tsEnd < tsChEnd) {
          // upper search limit for silence
          var tsUpper = tsEnd + tsSearchRange;
          // lower search limit for silence
          var tsLower = tsEnd - tsSearchRange;

          // take the easy road using LINQ, find nearest silence or none, above and below
          var silUp = silences.Where (t => t.Begin >= tsEnd && t.Begin < tsUpper).FirstOrDefault ();
          var silDn = silences.Where (t => t.End > tsLower && t.End <= tsEnd).LastOrDefault ();

          // which silence shall it be
          TimeInterval sil = null;
          if (!(silUp is null || silDn is null)) {
            // up and down found, use nearest
            var deltaUp = silUp.Begin - tsEnd;
            var deltaDn = tsEnd - silDn.End;
            if (deltaUp < deltaDn)
              sil = silUp;
            else
              sil = silDn;
          } else {
            // not both found, use any present
            if (!(silUp is null))
              sil = silUp;
            else if (!(silDn is null))
              sil = silDn;
          }

          // silence has been found
          if (!(sil is null)) {
            // actual track end
            // add half of the silence interval, put other half of the silence into the next track. 
            // However, cut in stream will not be precise.
            var tsActualEnd = sil.Begin + TimeSpan.FromTicks (sil.Duration.Ticks / 2);

            // check for overshooting
            if (tsActualEnd > tsChEnd)
              tsActualEnd = tsChEnd;

            // actual difference
            var tsDelta = tsActualEnd - tsEnd;

            // create new track item
            var track = new Track (tsStart, tsActualEnd) {
              Chapter = this
            };
            part.Tracks.Add (track);

            // set for next track
            tsStart = tsActualEnd;
            tsEnd = tsStart + tsAveTrackLen - tsDelta;
            if (tsEnd + tsSearchRange > tsChEnd)
              tsEnd = tsChEnd;

          } else {
            // silence not found, extend track
            tsEnd += tsAveTrackLen;
          }
        }

        // at the end of the chapter
        if (tsEnd >= tsChEnd) {
          // last track without silence search
          var track = new Track (tsStart, tsChEnd) {
            Chapter = this
          };
          part.Tracks.Add (track);

          // done
          break;
        }
      }
    }

19 View Source File : SemanticComparerTest.cs
License : MIT License
Project Creator : AutoFixture

[Fact]
        public void SutEqualsIdenticalStrongType()
        {
            // Fixture setup
            var ticks = 8293247;
            var value = TimeSpan.FromTicks(ticks);
            var sut = new SemanticComparer<TimeSpan, TimeSpan>();
            var other = TimeSpan.FromTicks(ticks);
            // Exercise system
            var result = sut.Equals(value, other);
            // Verify outcome
            replacedert.True(result);
            // Teardown
        }

19 View Source File : SemanticComparerTest.cs
License : MIT License
Project Creator : AutoFixture

[Fact]
        public void SutEqualsIdenticalStrongTypeSequence()
        {
            // Fixture setup
            var sut = new SemanticComparer<TimeSpan, TimeSpan>();
            
            var ticks = 8293247;

            var value = TimeSpan.FromTicks(ticks);
            var values = new object[] { value, value, value };
            
            var other = TimeSpan.FromTicks(ticks);
            var others = new object[] { other, other, other };
            
            // Exercise system
            var result = values.SequenceEqual(others, sut);
            // Verify outcome
            replacedert.True(result);
            // Teardown
        }

19 View Source File : SemanticComparerTest.cs
License : MIT License
Project Creator : AutoFixture

[Fact]
        public void SutEqualsIdenticalWeakType()
        {
            // Fixture setup
            var ticks = 8293247;
            var value = TimeSpan.FromTicks(ticks);
            var sut = new SemanticComparer<TimeSpan, TimeSpan>();
            object other = TimeSpan.FromTicks(ticks);
            // Exercise system
            var result = sut.Equals(value, other);
            // Verify outcome
            replacedert.True(result);
            // Teardown
        }

19 View Source File : SemanticComparerTest.cs
License : MIT License
Project Creator : AutoFixture

[Fact]
        public void SutEqualsIdenticalWeakTypeSequence()
        {
            // Fixture setup
            var sut = new SemanticComparer<TimeSpan, TimeSpan>();

            var ticks = 8293247;

            var value = TimeSpan.FromTicks(ticks);
            var values = new object[] { value, value, value };

            object other = TimeSpan.FromTicks(ticks);
            object[] others = new object[] { other, other, other };

            // Exercise system
            var result = values.SequenceEqual(others, sut);
            // Verify outcome
            replacedert.True(result);
            // Teardown
        }

19 View Source File : DeployServerlessCommand.cs
License : Apache License 2.0
Project Creator : aws

private async Task<Stack> WaitForNoLongerInProgress(string stackName)
        {
            try
            {
                long start = DateTime.Now.Ticks;
                Stack currentStack = null;
                do
                {
                    if (currentStack != null)
                        this.Logger.WriteLine($"... Waiting for stack's state to change from {currentStack.StackStatus}: {TimeSpan.FromTicks(DateTime.Now.Ticks - start).TotalSeconds.ToString("0").PadLeft(3)} secs");
                    Thread.Sleep(POLLING_PERIOD);
                    currentStack = await GetExistingStackAsync(stackName);

                } while (currentStack != null && currentStack.StackStatus.ToString().EndsWith(IN_PROGRESS_SUFFIX));

                return currentStack;
            }
            catch (Exception e)
            {
                throw new LambdaToolsException($"Error waiting for stack state change: {e.Message}", LambdaToolsException.LambdaErrorCode.WaitingForStackError, e);
            }
        }

19 View Source File : RoleHelper.cs
License : Apache License 2.0
Project Creator : aws

public static string CreateRole(IAmazonIdenreplacedyManagementService iamClient, string roleName, string replacedumeRolePolicy, params string[] managedPolicies)
        {
            if (managedPolicies != null && managedPolicies.Length > 0)
            {
                for(int i = 0; i < managedPolicies.Length; i++)
                {
                    managedPolicies[i] = ExpandManagedPolicyName(iamClient, managedPolicies[i]);
                }
            }

            string roleArn;
            try
            {
                CreateRoleRequest request = new CreateRoleRequest
                {
                    RoleName = roleName,
                    replacedumeRolePolicyDoreplacedent = replacedumeRolePolicy
                };

                var response = iamClient.CreateRoleAsync(request).Result;
                roleArn = response.Role.Arn;
            }
            catch (Exception e)
            {
                throw new ToolsException($"Error creating IAM Role: {e.Message}", ToolsException.CommonErrorCode.IAMCreateRole, e);
            }

            if (managedPolicies != null && managedPolicies.Length > 0)
            {
                try
                {
                    foreach(var managedPolicy in managedPolicies)
                    {
                        var request = new AttachRolePolicyRequest
                        {
                            RoleName = roleName,
                            PolicyArn = managedPolicy
                        };
                        iamClient.AttachRolePolicyAsync(request).Wait();
                    }
                }
                catch (Exception e)
                {
                    throw new ToolsException($"Error replacedigning managed IAM Policy: {e.Message}", ToolsException.CommonErrorCode.IAMAttachRole, e);
                }
            }

            bool found = false;
            do
            {
                // There is no way check if the role has propagated yet so to
                // avoid error during deployment creation do a generous sleep.
                Console.WriteLine("Waiting for new IAM Role to propagate to AWS regions");
                long start = DateTime.Now.Ticks;
                while (TimeSpan.FromTicks(DateTime.Now.Ticks - start).TotalSeconds < SLEEP_TIME_FOR_ROLE_PROPOGATION.TotalSeconds)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                    Console.Write(".");
                    Console.Out.Flush();
                }
                Console.WriteLine("\t Done");


                try
                {
                    var getResponse = iamClient.GetRoleAsync(new GetRoleRequest { RoleName = roleName }).Result;
                    if (getResponse.Role != null)
                        found = true;
                }
                catch (NoSuchEnreplacedyException)
                {

                }
                catch (Exception e)
                {
                    throw new ToolsException("Error confirming new role was created: " + e.Message, ToolsException.CommonErrorCode.IAMGetRole, e);
                }
            } while (!found);


            return roleArn;
        }

19 View Source File : ECSBaseCommand.cs
License : Apache License 2.0
Project Creator : aws

public async Task AttemptToCreateServiceLinkRoleAsync()
        {
            try
            {
                await this.IAMClient.CreateServiceLinkedRoleAsync(new CreateServiceLinkedRoleRequest
                {
                    AWSServiceName = "ecs.amazonaws.com"
                });
                this.Logger.WriteLine("Created IAM Role service role for ecs.amazonaws.com");

                this.Logger.WriteLine("Waiting for new IAM Role to propagate to AWS regions");
                long start = DateTime.Now.Ticks;
                while (TimeSpan.FromTicks(DateTime.Now.Ticks - start).TotalSeconds < RoleHelper.SLEEP_TIME_FOR_ROLE_PROPOGATION.TotalSeconds)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                    Console.Write(".");
                    Console.Out.Flush();
                }
                Console.WriteLine("\t Done");
            }
            catch(Exception)
            {

            }
        }

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

public override TimeSpan ReadTimeSpan()
    {
      var ticks = this.ReadLong();
      return TimeSpan.FromTicks(ticks);
    }

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

public TimeSpan ReadTimeSpan()
    {
      var ticks = this.ReadLong();
      return TimeSpan.FromTicks(ticks);
    }

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

public void Action_RowGet_JSONDataMap(WebClient wc)
      {
        var start = DateTime.Now;

        System.Threading.Thread.Sleep(3000);

        //using (var wc = CreateWebClient())
        {
          string str = wc.DownloadString(m_ServerURI + "RowGet");

          if ("application/json" != wc.ResponseHeaders[HttpResponseHeader.ContentType]) throw new Exception();

          var obj = JSONReader.DeserializeDynamic(str);

          if (16 != obj.Data.Count) throw new Exception();
          if (777UL != obj.Data["ID"]) throw new Exception();
          if ("Test Name" != obj.Data["Name"]) throw new Exception();

          var date = DateTime.Parse(obj.Data["Date"]);
          if ((DateTime.Now - start).TotalSeconds < 2.0d) throw new Exception();
          if ("Ok" != obj.Data["Status"]) throw new Exception();

          var gotTs = TimeSpan.FromTicks((long)(ulong)(obj.Data["Span"]));
          if (TimeSpan.FromSeconds(1) != gotTs) throw new Exception();
        }
      }

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

[Run]
        public void TypeRowConversion()
        {
          var r = new WaveTestSite.Controllers.IntegrationTester.SpanDoc() { Span = TimeSpan.FromTicks(1) };

          var str = r.ToJson(JsonWritingOptions.CompactRowsAsMap);

          var map = JsonReader.DeserializeDataObject(str) as JsonDataMap;
          var gotRow = JsonReader.ToDoc<WaveTestSite.Controllers.IntegrationTester.SpanDoc>(map);
        }

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

[Run]
        public void Action_RowGet_JSONDataMap()
        {
          DateTime start = DateTime.Now;

          System.Threading.Thread.Sleep(3000);

          using (var wc = CreateWebClient())
          {
            string str = wc.DownloadString(INTEGRATION_HTTP_ADDR + "RowGet");

            Aver.IsTrue(wc.ResponseHeaders[HttpResponseHeader.ContentType].Contains(Azos.Web.ContentType.JSON));

            var obj = JsonReader.DeserializeDynamic(str);

            Aver.AreEqual(16, obj.Data.Count);
            Aver.AreObjectsEqual(777, obj.Data["ID"]);
            Aver.AreObjectsEqual("Test Name", obj.Data["Name"]);

            var date = DateTime.Parse(obj.Data["Date"]);
            Aver.IsTrue( (DateTime.Now - start).TotalSeconds >= 2.0d );
            Aver.AreEqual("Ok", obj.Data["Status"]);

            var gotTs = TimeSpan.FromTicks((long)(ulong)(obj.Data["Span"]));
            Aver.AreEqual(TimeSpan.FromSeconds(1), gotTs);
          }
        }

19 View Source File : ProcessExtensions.cs
License : Apache License 2.0
Project Creator : Azure-App-Service

public static TimeSpan GetTotalProcessorTime(this Process process, ITracer tracer)
        {
            try
            {
                var processes = process.GetChildren(tracer).Concat(new[] { process }).Select(p => new { Name = p.ProcessName, Id = p.Id, Cpu = p.TotalProcessorTime });
                var totalTime = TimeSpan.FromTicks(processes.Sum(p => p.Cpu.Ticks));
                var info = String.Join("+", processes.Select(p => String.Format("{0}({1},{2:0.000}s)", p.Name, p.Id, p.Cpu.TotalSeconds)).ToArray());
                tracer.Trace("Cpu: {0}=total({1:0.000}s)", info, totalTime.TotalSeconds);
                return totalTime;
            }
            catch (Exception ex)
            {
                tracer.TraceError(ex);
            }

            return process.TotalProcessorTime;
        }

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

[Fact]
        public void Should_ThrowException_When_NullName()
        {
            new Action(() =>
            {
                Arg.Time(null, TimeSpan.FromTicks(0));
            }).Should().ThrowExactly<ArgumentNullException>();

            new Action(() =>
            {
                Arg.Time(null, new DateTime(0));
            }).Should().ThrowExactly<ArgumentNullException>();

            new Action(() =>
            {
                Arg.Time(null, new DateTimeOffset(0, TimeSpan.Zero));
            }).Should().ThrowExactly<ArgumentNullException>();
        }

19 View Source File : Microseconds32.cs
License : MIT License
Project Creator : bibigone

public TimeSpan ToTimeSpan()
            => TimeSpan.FromTicks(ValueUsec * Microseconds64.UsecToTimeSpanTicksFactor);

19 View Source File : Microseconds64.cs
License : MIT License
Project Creator : bibigone

public TimeSpan ToTimeSpan()
            => TimeSpan.FromTicks(ValueUsec * UsecToTimeSpanTicksFactor);

See More Examples