Here are the examples of the csharp api System.Convert.ToDouble(long) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
76 Examples
19
Source : SystemExtensions.cs
with MIT License
from adrenak
with MIT License
from adrenak
public static DateTime ToHumanTime(this long unixTimeStamp) {
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return epoch.AddMilliseconds(Convert.ToDouble(unixTimeStamp));
}
19
Source : JsonTextReader.cs
with MIT License
from akaskela
with MIT License
from akaskela
private void ParseNumber(ReadType readType)
{
ShiftBufferIfNeeded();
char firstChar = _chars[_charPos];
int initialPosition = _charPos;
ReadNumberIntoBuffer();
// set state to PostValue now so that if there is an error parsing the number then the reader can continue
SetPostValueState(true);
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
object numberValue;
JsonToken numberType;
bool singleDigit = (char.IsDigit(firstChar) && _stringReference.Length == 1);
bool nonBase10 = (firstChar == '0' && _stringReference.Length > 1 && _stringReference.Chars[_stringReference.StartIndex + 1] != '.' && _stringReference.Chars[_stringReference.StartIndex + 1] != 'e' && _stringReference.Chars[_stringReference.StartIndex + 1] != 'E');
if (readType == ReadType.Readreplacedtring)
{
string number = _stringReference.ToString();
// validate that the string is a valid number
if (nonBase10)
{
try
{
if (number.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
{
Convert.ToInt64(number, 16);
}
else
{
Convert.ToInt64(number, 8);
}
}
catch (Exception ex)
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid number.".FormatWith(CultureInfo.InvariantCulture, number), ex);
}
}
else
{
double value;
if (!double.TryParse(number, NumberStyles.Float, CultureInfo.InvariantCulture, out value))
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid number.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
}
}
numberType = JsonToken.String;
numberValue = number;
}
else if (readType == ReadType.ReadAsInt32)
{
if (singleDigit)
{
// digit char values start at 48
numberValue = firstChar - 48;
}
else if (nonBase10)
{
string number = _stringReference.ToString();
try
{
int integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt32(number, 16) : Convert.ToInt32(number, 8);
numberValue = integer;
}
catch (Exception ex)
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid integer.".FormatWith(CultureInfo.InvariantCulture, number), ex);
}
}
else
{
int value;
ParseResult parseResult = ConvertUtils.Int32TryParse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length, out value);
if (parseResult == ParseResult.Success)
{
numberValue = value;
}
else if (parseResult == ParseResult.Overflow)
{
throw JsonReaderException.Create(this, "JSON integer {0} is too large or small for an Int32.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
}
else
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid integer.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
}
}
numberType = JsonToken.Integer;
}
else if (readType == ReadType.ReadAsDecimal)
{
if (singleDigit)
{
// digit char values start at 48
numberValue = (decimal)firstChar - 48;
}
else if (nonBase10)
{
string number = _stringReference.ToString();
try
{
// decimal.Parse doesn't support parsing hexadecimal values
long integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8);
numberValue = Convert.ToDecimal(integer);
}
catch (Exception ex)
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, number), ex);
}
}
else
{
string number = _stringReference.ToString();
decimal value;
if (decimal.TryParse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out value))
{
numberValue = value;
}
else
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
}
}
numberType = JsonToken.Float;
}
else if (readType == ReadType.ReadAsDouble)
{
if (singleDigit)
{
// digit char values start at 48
numberValue = (double)firstChar - 48;
}
else if (nonBase10)
{
string number = _stringReference.ToString();
try
{
// double.Parse doesn't support parsing hexadecimal values
long integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8);
numberValue = Convert.ToDouble(integer);
}
catch (Exception ex)
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid double.".FormatWith(CultureInfo.InvariantCulture, number), ex);
}
}
else
{
string number = _stringReference.ToString();
double value;
if (double.TryParse(number, NumberStyles.Float, CultureInfo.InvariantCulture, out value))
{
numberValue = value;
}
else
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid double.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
}
}
numberType = JsonToken.Float;
}
else
{
if (singleDigit)
{
// digit char values start at 48
numberValue = (long)firstChar - 48;
numberType = JsonToken.Integer;
}
else if (nonBase10)
{
string number = _stringReference.ToString();
try
{
numberValue = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8);
}
catch (Exception ex)
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid number.".FormatWith(CultureInfo.InvariantCulture, number), ex);
}
numberType = JsonToken.Integer;
}
else
{
long value;
ParseResult parseResult = ConvertUtils.Int64TryParse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length, out value);
if (parseResult == ParseResult.Success)
{
numberValue = value;
numberType = JsonToken.Integer;
}
else if (parseResult == ParseResult.Overflow)
{
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
string number = _stringReference.ToString();
if (number.Length > MaximumJavascriptIntegerCharacterLength)
{
throw JsonReaderException.Create(this, "JSON integer {0} is too large to parse.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
}
numberValue = BigIntegerParse(number, CultureInfo.InvariantCulture);
numberType = JsonToken.Integer;
#else
throw JsonReaderException.Create(this, "JSON integer {0} is too large or small for an Int64.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
#endif
}
else
{
string number = _stringReference.ToString();
if (_floatParseHandling == FloatParseHandling.Decimal)
{
decimal d;
if (decimal.TryParse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out d))
{
numberValue = d;
}
else
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, number));
}
}
else
{
double d;
if (double.TryParse(number, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out d))
{
numberValue = d;
}
else
{
throw JsonReaderException.Create(this, "Input string '{0}' is not a valid number.".FormatWith(CultureInfo.InvariantCulture, number));
}
}
numberType = JsonToken.Float;
}
}
}
ClearRecentString();
// index has already been updated
SetToken(numberType, numberValue, false);
}
19
Source : LivecoinServer.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private void Client_NewMarketDepth(OrderBookChannelSubscribedResponse orderBook)
{
if (_depths == null)
{
_depths = new List<MarketDepth>();
}
var newDepth = new MarketDepth();
newDepth.SecurityNameCode = orderBook.CurrencyPair;
List<MarketDepthLevel> ascs = new List<MarketDepthLevel>();
List<MarketDepthLevel> bids = new List<MarketDepthLevel>();
long biggestTimeStamp = 0;
foreach (var level in orderBook.Datas)
{
if (level.order_type == OrderBookEvent.OrderType.Ask)
{
ascs.Add(new MarketDepthLevel
{
Price = ParseDecimal(level.Price),
Ask = ParseDecimal(level.Quanreplacedy),
});
}
else
{
bids.Add(new MarketDepthLevel
{
Price = ParseDecimal(level.Price),
Bid = ParseDecimal(level.Quanreplacedy),
});
}
if (level.Timestamp > biggestTimeStamp)
{
biggestTimeStamp = level.Timestamp;
}
}
newDepth.Asks = ascs;
newDepth.Bids = bids;
if (biggestTimeStamp != 0)
{
newDepth.Time = new DateTime(1970, 1, 1).AddMilliseconds(Convert.ToDouble(biggestTimeStamp));
ServerTime = newDepth.Time;
}
_depths.Add(newDepth);
if (MarketDepthEvent != null)
{
MarketDepthEvent(newDepth.GetCopy());
}
}
19
Source : RandomValueGenerator.cs
with MIT License
from bing-framework
with MIT License
from bing-framework
public static TimeSpan Next(TimeSpan min, TimeSpan max)
{
if (max <= min)
{
throw new ArgumentException("最大值必须大于等于最小值.");
}
long minTicks = min.Ticks;
long maxTicks = max.Ticks;
double rn = (Convert.ToDouble(maxTicks) - Convert.ToDouble(minTicks)) * _random.NextDouble() +
Convert.ToDouble(minTicks);
return new TimeSpan(Convert.ToInt64(rn));
}
19
Source : RandomValueGenerator.cs
with MIT License
from bing-framework
with MIT License
from bing-framework
public static DateTime Next(DateTime min, DateTime max)
{
if (max <= min)
{
throw new ArgumentException("最大值必须大于等于最小值.");
}
long minTicks = min.Ticks;
long maxTicks = max.Ticks;
double rn = (Convert.ToDouble(maxTicks) - Convert.ToDouble(minTicks)) * _random.NextDouble() +
Convert.ToDouble(minTicks);
return new DateTime(Convert.ToInt64(rn));
}
19
Source : Isolator.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
private static string PrettyFormatRam(long ramInBytes)
{
return Math.Round(Convert.ToDouble(ramInBytes/(1024*1024))).ToStringInvariant();
}
19
Source : Isolator.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
private bool MonitorTask(Task task,
TimeSpan timeSpan,
Func<IsolatorLimitResult> withinCustomLimits,
long memoryCap = 1024,
int sleepIntervalMillis = 1000)
{
// default to always within custom limits
withinCustomLimits = withinCustomLimits ?? (() => new IsolatorLimitResult(TimeSpan.Zero, string.Empty));
var message = "";
var emaPeriod = 60d;
var memoryUsed = 0L;
var end = DateTime.Now + timeSpan;
var memoryLogger = DateTime.Now + TimeSpan.FromMinutes(1);
var isolatorLimitResult = new IsolatorLimitResult(TimeSpan.Zero, string.Empty);
//Convert to bytes
memoryCap *= 1024 * 1024;
var spikeLimit = memoryCap*2;
while (!task.IsCompleted && DateTime.Now < end)
{
// if over 80% allocation force GC then sample
var sample = Convert.ToDouble(GC.GetTotalMemory(memoryUsed > memoryCap * 0.8));
// find the EMA of the memory used to prevent spikes killing stategy
memoryUsed = Convert.ToInt64((emaPeriod-1)/emaPeriod * memoryUsed + (1/emaPeriod)*sample);
// if the rolling EMA > cap; or the spike is more than 2x the allocation.
if (memoryUsed > memoryCap || sample > spikeLimit)
{
message = $"Execution Security Error: Memory Usage Maxed Out - {PrettyFormatRam(memoryCap)}MB max, " +
$"with last sample of {PrettyFormatRam((long) sample)}MB.";
break;
}
if (DateTime.Now > memoryLogger)
{
if (memoryUsed > memoryCap * 0.8)
{
Log.Error(Invariant($"Execution Security Error: Memory usage over 80% capacity. Sampled at {sample}"));
}
//Log.Trace("Isolator.ExecuteWithTimeLimit(): " +
// $"Used: {PrettyFormatRam(memoryUsed)}, " +
// $"Sample: {PrettyFormatRam((long)sample)}, " +
// $"App: {PrettyFormatRam(OS.ApplicationMemoryUsed * 1024 * 1024)}, " +
// $"CurrentTimeStepElapsed: {isolatorLimitResult.CurrentTimeStepElapsed:mm':'ss'.'fff}");
memoryLogger = DateTime.Now.AddMinutes(1);
}
// check to see if we're within other custom limits defined by the caller
isolatorLimitResult = withinCustomLimits();
if (!isolatorLimitResult.IsWithinCustomLimits)
{
message = isolatorLimitResult.ErrorMessage;
break;
}
if (task.Wait(sleepIntervalMillis))
{
break;
}
}
if (task.IsCompleted == false && message == "")
{
message = $"Execution Security Error: Operation timed out - {timeSpan.TotalMinutes.ToStringInvariant()} minutes max. Check for recursive loops.";
Log.Trace($"Isolator.ExecuteWithTimeLimit(): {message}");
}
if (message != "")
{
CancellationTokenSource.Cancel();
Log.Error($"Security.ExecuteWithTimeLimit(): {message}");
throw new TimeoutException(message);
}
return task.IsCompleted;
}
19
Source : _Custom.cs
with MIT License
from CragonGame
with MIT License
from CragonGame
public static System.DateTime ToCSharpTime( long unixTime )
{
System.DateTime unixStartTime = new System.DateTime( 1970, 1, 1, 0, 0, 0, 0 );
return unixStartTime.AddSeconds( Convert.ToDouble( unixTime ) );
}
19
Source : _Custom.cs
with MIT License
from CragonGame
with MIT License
from CragonGame
public static tm localtime( time_t baseTime )
{
System.DateTime RefTime = new System.DateTime( 1970, 1, 1, 0, 0, 0, 0 );
RefTime = RefTime.AddSeconds( Convert.ToDouble( baseTime ) ).ToLocalTime();
tm tm = new tm();
tm.tm_sec = RefTime.Second;
tm.tm_min = RefTime.Minute;
tm.tm_hour = RefTime.Hour;
tm.tm_mday = RefTime.Day;
tm.tm_mon = RefTime.Month;
tm.tm_year = RefTime.Year;
tm.tm_wday = (int)RefTime.DayOfWeek;
tm.tm_yday = RefTime.DayOfYear;
tm.tm_isdst = RefTime.IsDaylightSavingTime() ? 1 : 0;
return tm;
}
19
Source : TimeSpan2.cs
with MIT License
from dahall
with MIT License
from dahall
double IConvertible.ToDouble(IFormatProvider provider) => Convert.ToDouble(core.Ticks);
19
Source : HttpHelper.cs
with Mozilla Public License 2.0
from daixin10310
with Mozilla Public License 2.0
from daixin10310
public void DownloadFile(string url, string fileName, Action<int> progressBar)
{
stopDown = false;
long lStartPos = 0;
Stream fs = null, ns = null;
fileLength = getDownLength(url);
if (fileLength > 0)
{
if (File.Exists(fileName))
{
fs = File.OpenWrite(fileName);
lStartPos = downLength = fs.Length;
progressBar((int)(Convert.ToDouble(downLength) / Convert.ToDouble(fileLength) * 100));
if (downLength == fileLength)
{
fs.Close();
fs.Dispose();
return;
}
else
{
fs.Seek(lStartPos, SeekOrigin.Current);
}
}
else
{
fs = new System.IO.FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
lStartPos = 0;
}
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
if (lStartPos > 0)
{
request.AddRange((int)lStartPos);
}
ns = request.GetResponse().GetResponseStream();
readSize = 1024 * 1024;
byte[] nbytes = new byte[readSize];
int nReadSize = 0;
nReadSize = ns.Read(nbytes, 0, readSize);
while (nReadSize > 0)
{
if (stopDown)
break;
//if (0 == getDownLength(url))
//{
// stopDown = true;
// break;
//}
//else
//{
downLength += nReadSize;
fs.Write(nbytes, 0, nReadSize);
nReadSize = ns.Read(nbytes, 0, readSize);
progressBar((int)(Convert.ToDouble(downLength) / Convert.ToDouble(fileLength) * 100));
//Application.DoEvents();
//}
}
fs.Close();
fs.Dispose();
ns.Close();
ns.Dispose();
}
catch (Exception ex)
{
if (fs != null)
{
fs.Close();
fs.Dispose();
}
if (ns != null)
{
ns.Close();
ns.Dispose();
}
}
}
}
19
Source : CLexer.cs
with MIT License
from damienbod
with MIT License
from damienbod
public CSymbol ScanNumber()
{
long value = 0;
int decimalDigits = 0;
bool period = false;
bool negative = false;
ClearToken();
char ch = _currChar;
if (ch == '+' || ch == '-')
{
if (ch == '-')
negative = true;
_token.Append(ch);
ch = ScanNextChar();
}
while (true)
{
if (char.IsDigit(ch))
{
_token.Append(ch);
if (decimalDigits < 10)
{
value = 10 * value + ch - '0';
if (period)
decimalDigits++;
}
}
else if (ch == '.')
{
if (period)
ContentReaderDiagnostics.ThrowContentReaderException("More than one period in number.");
period = true;
_token.Append(ch);
}
else
break;
ch = ScanNextChar();
}
if (negative)
value = -value;
if (period)
{
if (decimalDigits > 0)
{
_tokenAsReal = value / PowersOf10[decimalDigits];
//_tokenAsLong = value / PowersOf10[decimalDigits];
}
else
{
_tokenAsReal = value;
_tokenAsLong = value;
}
return CSymbol.Real;
}
_tokenAsLong = value;
_tokenAsReal = Convert.ToDouble(value);
Debug.replacedert(Int64.Parse(_token.ToString(), CultureInfo.InvariantCulture) == value);
if (value >= Int32.MinValue && value < Int32.MaxValue)
return CSymbol.Integer;
ContentReaderDiagnostics.ThrowNumberOutOfIntegerRange(value);
return CSymbol.Error;
}
19
Source : TimeSpanRoughAdvancedConverter.cs
with MIT License
from DataObjects-NET
with MIT License
from DataObjects-NET
double IAdvancedConverter<TimeSpan, double>.Convert(TimeSpan value)
{
return Convert.ToDouble(value.Ticks);
}
19
Source : Int64RoughAdvancedConverter.cs
with MIT License
from DataObjects-NET
with MIT License
from DataObjects-NET
double IAdvancedConverter<long, double>.Convert(long value)
{
return Convert.ToDouble(value);
}
19
Source : DateTimeRoughAdvancedConverter.cs
with MIT License
from DataObjects-NET
with MIT License
from DataObjects-NET
double IAdvancedConverter<DateTime, double>.Convert(DateTime value)
{
return Convert.ToDouble(value.Ticks - baseDateTimeTicks);
}
19
Source : Compiler.cs
with MIT License
from DataObjects-NET
with MIT License
from DataObjects-NET
private static SqlExpression DateTimeAddInterval(SqlExpression date, SqlExpression interval)
{
return DateAddSeconds(date, interval / Convert.ToDouble(NanosecondsPerSecond));
}
19
Source : BasicConvert.Overload.cs
with MIT License
from Dogwei
with MIT License
from Dogwei
double IXConverter<long, double>.Convert(long value)
=> Convert.ToDouble(value);
19
Source : FileHelper.cs
with Apache License 2.0
from donet5
with Apache License 2.0
from donet5
public static double GetFileSizeByKB(string filePath)
{
//创建一个文件对象
System.IO.FileInfo fi = new System.IO.FileInfo(filePath);
//获取文件的大小
return Convert.ToDouble(Convert.ToDouble(fi.Length) / 1024);
}
19
Source : FileHelper.cs
with Apache License 2.0
from donet5
with Apache License 2.0
from donet5
public static double GetFileSizeByMB(string filePath)
{
//创建一个文件对象
System.IO.FileInfo fi = new System.IO.FileInfo(filePath);
//获取文件的大小
return Convert.ToDouble(Convert.ToDouble(fi.Length) / 1024 / 1024);
}
19
Source : BVH_IO.cs
with GNU Lesser General Public License v3.0
from Edgar077
with GNU Lesser General Public License v3.0
from Edgar077
public void WriteMotions(KinectSkeleton skel, Body body)
{
sw.Start(); //Aufnahme der Bewegungen beginnt
for (int k = 0; k < bvhSkeletonWritten.Bones.Count; k++)
{
if (bvhSkeletonWritten.Bones[k].End == false)
{
float[] degVec = new float[3];
degVec = KinectSkeletonBVH.getEulerFromBone(bvhSkeletonWritten.Bones[k], skel, body);
int indexOffset = 0;
if (bvhSkeletonWritten.Bones[k].Root == true)
{
indexOffset = 3;
}
tempMotionVektor[bvhSkeletonWritten.Bones[k].MotionSpace + indexOffset] = degVec[0];
tempMotionVektor[bvhSkeletonWritten.Bones[k].MotionSpace + 1 + indexOffset] = degVec[1];
tempMotionVektor[bvhSkeletonWritten.Bones[k].MotionSpace + 2 + indexOffset] = degVec[2];
//// Textbox setzen
//string boneName = bvhSkeletonWritten.Bones[k].Name;
//if (boneName == textFeld.getDropDownJoint)
//{
// //Rotation
// string textBox = Math.Round(degVec[0], 1).ToString() + " " + Math.Round(degVec[1], 1).ToString() + " " + Math.Round(degVec[2], 1).ToString();
// textFeld.setTextBoxAngles = textBox;
// //Position
// JointType KinectJoint = KinectSkeletonBVH.getJointTypeFromBVHBone(bvhSkeletonWritten.Bones[k]);
// float x = skel.Joints[KinectJoint].Position.X;
// float y = skel.Joints[KinectJoint].Position.Y;
// float z = skel.Joints[KinectJoint].Position.Z;
// textFeld.setTextPosition = Math.Round(x, 2).ToString() + " " + Math.Round(y, 2).ToString() + " " + Math.Round(z, 2).ToString();
// //Length
// BVHBone tempBone = bvhSkeletonWritten.Bones.Find(i => i.Name == KinectJoint.ToString());
// float[] boneVec = KinectSkeletonBVH.getBoneVectorOutofJointPosition(tempBone, skel);
// float length = Math.Sqrt(Math.Pow(boneVec[0], 2) + Math.Pow(boneVec[1], 2) + Math.Pow(boneVec[2], 2));
// length = Math.Round(length, 2);
// textFeld.setTextBoxLength = length.ToString();
//}
}
}
//Root Bewegung
tempMotionVektor[0] = (float)-Math.Round(skel.Joints[JointType.SpineMid].X * 100, 2);
tempMotionVektor[1] = (float)Math.Round(skel.Joints[JointType.SpineMid].Y * 100, 2) + 120;
tempMotionVektor[2] = 300 - (float)Math.Round(skel.Joints[JointType.SpineMid].Z * 100, 2);
for(int i = 0; i < 3; i++)
{
if (tempMotionVektor[i] == float.NaN)
tempMotionVektor[i] = 0;
}
writeMotion(tempMotionVektor);
file.Flush();
elapsedTimeSec = (float)Math.Round(Convert.ToDouble(sw.ElapsedMilliseconds) / 1000, 2);
//textFeld.setTextBoxElapsedTime = elapsedTimeSec.ToString();
//textFeld.setTextBoxCapturedFrames = frameCounter.ToString();
avgFrameRate = (float)Math.Round(frameCounter / elapsedTimeSec, 2);
// textFeld.setTextBoxFrameRate = avgFrameRate.ToString();
}
19
Source : _Custom.cs
with Mozilla Public License 2.0
from ehsan2022002
with Mozilla Public License 2.0
from ehsan2022002
public static tm localtime(time_t baseTime)
{
System.DateTime RefTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
RefTime = RefTime.AddSeconds(Convert.ToDouble(baseTime)).ToLocalTime();
tm tm = new tm();
tm.tm_sec = RefTime.Second;
tm.tm_min = RefTime.Minute;
tm.tm_hour = RefTime.Hour;
tm.tm_mday = RefTime.Day;
tm.tm_mon = RefTime.Month;
tm.tm_year = RefTime.Year;
tm.tm_wday = (int)RefTime.DayOfWeek;
tm.tm_yday = RefTime.DayOfYear;
tm.tm_isdst = RefTime.IsDaylightSavingTime() ? 1 : 0;
return tm;
}
19
Source : _Custom.cs
with Mozilla Public License 2.0
from ehsan2022002
with Mozilla Public License 2.0
from ehsan2022002
public static System.DateTime ToCSharpTime(long unixTime)
{
System.DateTime unixStartTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
return unixStartTime.AddSeconds(Convert.ToDouble(unixTime));
}
19
Source : FileHelper.cs
with MIT License
from feiyit
with MIT License
from feiyit
public static double GetFileSizeByMb(string filePath)
{
//创建一个文件对象
FileInfo fi = new FileInfo(filePath);
//获取文件的大小
return Math.Round(Convert.ToDouble(Convert.ToDouble(fi.Length) / 1024 / 1024),2);
}
19
Source : ExtensionMethods.cs
with GNU General Public License v3.0
from firateski
with GNU General Public License v3.0
from firateski
public static int getPercent(this long current, long total)
{
double curr = Convert.ToDouble(current);
double tot = Convert.ToDouble(total);
var result = Convert.ToInt32((100 / tot) * curr);
if (result > 100)
return 100;
else
return result;
}
19
Source : Temporal.cs
with GNU General Public License v3.0
from fynydd
with GNU General Public License v3.0
from fynydd
public static T DateDiff<T>(this DateTime startDate, DateTime endDate, DateDiffComparisonType howtocompare, int startDateOffset = 0, int endDateOffset = 0)
{
double diff = 0;
startDate = (new DateTimeOffset(startDate, new TimeSpan(startDateOffset, 0, 0))).UtcDateTime;
endDate = (new DateTimeOffset(endDate, new TimeSpan(endDateOffset, 0, 0))).UtcDateTime;
try
{
#region Non-Fractional conversion options
if (howtocompare == DateDiffComparisonType.DaysWhole)
{
DateTime sd = new DateTime(startDate.Year, startDate.Month, startDate.Day, 0, 0, 0);
DateTime ed = new DateTime(endDate.Year, endDate.Month, endDate.Day, 0, 0, 0);
System.TimeSpan TS = new System.TimeSpan(ed.Ticks - sd.Ticks);
diff = Convert.ToDouble(TS.TotalDays);
}
else if (howtocompare == DateDiffComparisonType.Age)
{
int age = endDate.Year - startDate.Year; //people perceive their age in years
if (endDate.Month < startDate.Month || ((endDate.Month == startDate.Month) && (endDate.Day < startDate.Day)))
{
age--; //birthday in current year not yet reached, so we are 1 year younger
//note that this structure explicitly places March 1st as the non-leapyear birthday for those born on Feb 29th.
}
diff = Convert.ToDouble(age);
}
#endregion
else
{
System.TimeSpan TS = new System.TimeSpan(endDate.Ticks - startDate.Ticks);
#region Fractional conversion options
switch (howtocompare)
{
case DateDiffComparisonType.Minutes:
diff = Convert.ToDouble(TS.TotalMinutes);
break;
case DateDiffComparisonType.Hours:
diff = Convert.ToDouble(TS.TotalHours);
break;
case DateDiffComparisonType.Seconds:
diff = Convert.ToDouble(TS.TotalSeconds);
break;
case DateDiffComparisonType.Ticks:
diff = Convert.ToDouble(TS.Ticks);
break;
case DateDiffComparisonType.Milliseconds:
diff = Convert.ToDouble(TS.TotalMilliseconds);
break;
case DateDiffComparisonType.Months:
diff = Convert.ToDouble(TS.TotalDays / 30.438);
break;
case DateDiffComparisonType.Years:
diff = Convert.ToDouble(TS.TotalDays / 365.255);
break;
case DateDiffComparisonType.Quarters: //TO DO: not use a calculation, but instead use Jan 1, Apr 1, July 1, Oct 1 to determine current quarter of this year (and how many quarters of the initial year) and add the remaining years as 4 quarters each
diff = Convert.ToDouble((TS.TotalDays / 365.255) / 4);
break;
default:
diff = Convert.ToDouble(TS.TotalDays); break;
}
#endregion
}
}
catch
{
diff = -1;
}
return (T)Convert.ChangeType(diff, typeof(T));
}
19
Source : VersionDownloader.cs
with GNU General Public License v3.0
from GodLeaveMe
with GNU General Public License v3.0
from GodLeaveMe
private async Task DownloadFile(string url, string to, DownloadProgress progress, CancellationToken cancellationToken) {
using (var resp = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken)) {
using (var inStream = await resp.Content.ReadreplacedtreamAsync())
using (var outStream = new FileStream(to, FileMode.Create)) {
long? totalSize = resp.Content.Headers.ContentLength;
progress(0, totalSize);
long transferred = 0;
byte[] buf = new byte[1024 * 1024];
while (true) {
int n = await inStream.ReadAsync(buf, 0, buf.Length, cancellationToken);
if (n == 0)
break;
await outStream.WriteAsync(buf, 0, n, cancellationToken);
transferred += n;
progress(transferred, totalSize);
if (totalSize.HasValue)
{
App.WriteLine("下载进度: " + Math.Round(Convert.ToDouble(transferred) / Convert.ToDouble(totalSize.GetValueOrDefault()), 2) + "% (" + transferred + "/" + totalSize.GetValueOrDefault() + " byte)");
}
}
}
}
}
19
Source : ManagerForm.cs
with GNU General Public License v3.0
from hellzerg
with GNU General Public License v3.0
from hellzerg
internal void LoadCloneList()
{
clonelist.Items.Clear();
int counter = 0;
ByteSize totalsize = ByteSize.FromBytes(0);
if (Directory.Exists(Options.DataFolder))
{
string[] clones = Directory.GetDirectories(Options.DataFolder);
foreach (string clone in clones)
{
counter++;
clonelist.Items.Add(Path.GetFileName(clone));
DirectoryInfo di = new DirectoryInfo(clone);
totalsize += ByteSize.FromBytes(Convert.ToDouble(di.EnumerateFiles("*", SearchOption.AllDirectories).Sum(fi => fi.Length)));
}
}
clonesdetected.Text = "Backups: " + counter.ToString();
if (counter > 0)
{
totalsizetxt.Text = "Total size: " + totalsize;
}
else
{
totalsizetxt.Text = "Total size: -";
}
if (clonelist.Items.Count == 0)
{
clonelist.Visible = false;
label2.Visible = true;
}
else
{
clonelist.Visible = true;
label2.Visible = false;
}
}
19
Source : DateTimeEncoder.cs
with MIT License
from henck
with MIT License
from henck
private static DateTime JulianToDateTime(long julianDateAsLong)
{
if (julianDateAsLong == 0) return DateTime.MinValue;
double p = Convert.ToDouble(julianDateAsLong);
double s1 = p + 68569;
double n = Math.Floor(4 * s1 / 146097);
double s2 = s1 - Math.Floor(((146097 * n) + 3) / 4);
double i = Math.Floor(4000 * (s2 + 1) / 1461001);
double s3 = s2 - Math.Floor(1461 * i / 4) + 31;
double q = Math.Floor(80 * s3 / 2447);
double d = s3 - Math.Floor(2447 * q / 80);
double s4 = Math.Floor(q / 11);
double m = q + 2 - (12 * s4);
double j = (100 * (n - 49)) + i + s4;
return new DateTime(Convert.ToInt32(j), Convert.ToInt32(m), Convert.ToInt32(d));
}
19
Source : Module.cs
with GNU General Public License v3.0
from icipiqkm
with GNU General Public License v3.0
from icipiqkm
public void CheckUpdate(CheckUpdateTable table,bool isGetSize)
{
//编辑器模式模拟检查完成
if (GameConfig.gameModel == GameModel.Editor)
{
if (table != null && table.Complete != null)
{
table.Complete(Name, 0,string.Empty);
return;
}
}
CheckUpdateBehaviour cub = new GameObject(Name + "_CheckUpdateBehaviour").AddComponent<CheckUpdateBehaviour>();
cub.CheckUpdate(Name, isGetSize, (Md5File md5File, long size)=>{
_size = size;
_md5File = md5File;
_downloadQueue = md5File.DownloadQueue;
_sizeStr = Util.HumanReadableFilesize(Convert.ToDouble(_size));
if (table == null) return;
if (_downloadQueue == null)
{
Debug.LogError(string.Format("{0}:检查更新失败!", Name));
if (table.Error != null) table.Error(Name);
return;
}
Debug.Log(Name + " 需要下载 " + _sizeStr);
if (table.Complete != null) table.Complete(Name, _downloadQueue.Count, _sizeStr);
Destroy(cub.gameObject);
cub = null;
});
}
19
Source : MusicDataFetcher.cs
with MIT License
from jamesbrindle
with MIT License
from jamesbrindle
public MusicFileMetaData GetMusicFileMetaData(string path, out string metaDataString)
{
metaDataString = null;
try
{
var tags = GetMusicTagLibFile(path);
var sb = new StringBuilder();
string mbId = string.Empty;
string releaseMbId = string.Empty;
string artist = string.Empty;
string album = string.Empty;
string track = string.Empty;
TimeSpan? duration = null;
string durationString = string.Empty;
int bitsPerSecond = -1;
string bitsPerSecondString = string.Empty;
long fileSize = -1;
string fileSizeString = string.Empty;
if (tags != null && tags.Tag != null)
{
mbId = tags.Tag.MusicBrainzTrackId;
releaseMbId = tags.Tag.MusicBrainzReleaseId;
artist = tags.Tag.FirstPerformer ?? tags.Tag.FirstAlbumArtist;
album = tags.Tag.Album;
track = tags.Tag.replacedle;
bitsPerSecond = tags.Properties.AudioBitrate;
bitsPerSecondString = tags.Properties.AudioBitrate + " Kbps";
duration = tags.Properties.Duration;
try
{
fileSize = new FileInfo(path).Length;
if (fileSize != -1)
fileSizeString = Math.Round((Convert.ToDouble(fileSize) / Convert.ToDouble(1024) / Convert.ToDouble(1024)), 2) + "MB";
}
catch { }
durationString = string.Format("{0:00}:{1:00}:{2:00}",
tags.Properties.Duration.Hours,
tags.Properties.Duration.Minutes,
tags.Properties.Duration.Seconds);
sb.AppendLine();
sb.AppendLine("Artist: " + (string.IsNullOrEmpty(artist) ? "-" : artist));
sb.AppendLine("Album: " + (string.IsNullOrEmpty(album) ? "-" : album));
sb.AppendLine("Track: " + (string.IsNullOrEmpty(track) ? "-" : track));
sb.AppendLine("Duration: " + (string.IsNullOrEmpty(durationString) ? "-" : durationString));
sb.AppendLine("Bitrate: " + (string.IsNullOrEmpty(bitsPerSecondString) ? "-" : bitsPerSecondString));
sb.AppendLine("File Size: " + (string.IsNullOrEmpty(fileSizeString) ? "-" : fileSizeString));
metaDataString = sb.ToString();
}
return new MusicFileMetaData
{
MbId = mbId,
ReleaseMbId = releaseMbId,
Artist = artist,
Album = album,
Track = track,
Duration = (TimeSpan)duration,
Bitrate = bitsPerSecond,
FileSize = fileSize
};
}
catch (Exception e)
{
var _ = e;
#if DEBUG
Console.Out.WriteLine("GetMusicFileMetaData: " + e.Message);
#endif
}
return null;
}
19
Source : DownloadObject.cs
with GNU General Public License v3.0
from kengwang
with GNU General Public License v3.0
from kengwang
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
try
{
// 显示下载速度
speed = Convert.ToDouble(e.BytesReceived) / sw.Elapsed.TotalSeconds;
if (urls[blocknum].size == -1)
{
urls[blocknum].size = e.TotalBytesToReceive;
}
// 进度条
progress = (e.ProgressPercentage / urls.Count) + (blocknum * 100 / urls.Count);
// 下载了多少 还剩余多少
//labelDownloaded.Text = (Convert.ToDouble(e.BytesReceived) / 1024 / 1024).ToString("0.00") + " Mb's" + " / " + (Convert.ToDouble(e.TotalBytesToReceive) / 1024 / 1024).ToString("0.00") + " Mb's";
//正在下载区块 {0}/{5}: {1}/{2} {3}% 速度:{4}/s <{6}>
message = string.Format("正在下载区块{0}/{1}: {2}/{3} {4}% 速度:{5}/s <{6}>", blocknum + 1, urls.Count,
byteConvert.GetSize(e.BytesReceived), byteConvert.GetSize(e.TotalBytesToReceive),
progress.ToString(), byteConvert.GetSize(speed), "NaN");
}
catch (Exception ex)
{
status = -3;
message = "进度获取错误" + ex.Message;
}
}
19
Source : Program.cs
with Apache License 2.0
from kevinkovalchik
with Apache License 2.0
from kevinkovalchik
static int Run(Dictionary<string, object> opts)
{
if ((bool)opts["ExampleCommands"] == true)
{
Examples.CommandLineUsage();
Environment.Exit(0);
}
if ((bool)opts["ExampleModifications"] == true)
{
Examples.ExampleMods();
Environment.Exit(0);
}
List<string> files = new List<string>();
QcDataCollection qcDataCollection = new QcDataCollection();
WorkflowParameters parameters = new WorkflowParameters(opts);
if (parameters.InputFiles != null) // did the user give us a list of files?
{
List<string> problems = new List<string>();
files = parameters.InputFiles.ToList();
// check if the list provided contains only .raw files
foreach (string file in files)
{
if (!file.EndsWith(".raw", StringComparison.OrdinalIgnoreCase))
{
problems.Add(file);
}
}
if (problems.Count() == 1)
{
Console.WriteLine("\nERROR: {0} does not appear to be a .raw file. Invoke '>RawTools --help' if you need help.", problems.ElementAt(0));
Log.Error("Invalid file provided: {0}", problems.ElementAt(0));
//Console.Write("Press any key to exit...");
//Console.ReadKey();
return 1;
}
if (problems.Count() > 1)
{
Console.WriteLine("\nERROR: The following {0} files do not appear to be .raw files. Invoke '>RawTools --help' if you need help." +
"\n\n{1}", problems.Count(), String.Join("\n", problems));
Log.Error("Invalid files provided: {0}", String.Join(" ", problems));
//Console.Write("Press any key to exit...");
//Console.ReadKey();
return 1;
}
files = RawFileInfo.RemoveInAcquistionFiles(files);
// if the file location(s) are relative, we need to get the absolute path to them
files.EnsureAbsolutePaths();
Log.Information("Files to be processed, provided as list: {0}", String.Join(" ", files));
}
else if (!String.IsNullOrEmpty(parameters.RawFileDirectory)) // did the user give us a directory?
{
// if QC is being done, use the QC method snf get the qc data collection at the same time
if (parameters.QcParams.QcDirectory != null)
{
(files, qcDataCollection) = QcWorkflow.GetFileListAndQcFile(parameters, parameters.IncludeSubdirectories);
}
// if not, the parse method
else if (Directory.Exists(parameters.RawFileDirectory))
{
files = Directory.GetFiles(parameters.RawFileDirectory, "*.*", SearchOption.TopDirectoryOnly)
.Where(s => s.EndsWith(".raw", StringComparison.OrdinalIgnoreCase)).ToList();
}
else
{
Console.WriteLine("ERROR: The provided directory does not appear to be valid.");
Log.Error("Invalid directory provided: {0}", parameters.RawFileDirectory);
//Console.Write("Press any key to exit...");
//Console.ReadKey();
return 1;
}
files = RawFileInfo.RemoveInAcquistionFiles(files);
// if the file location(s) are relative, we need to get the absolute path to them
files.EnsureAbsolutePaths();
Log.Information("Files to be processed, provided as directory: {0}", String.Join(" ", files));
}
else
{
Console.WriteLine("ERROR: At least one of the following arguments is required: -f, -d");
Log.Error("No raw files or directory specified.");
return 1;
}
if (parameters.ParseParams.Quant)
{
List<string> possible = new List<string>() { "TMT0", "TMT2", "TMT6", "TMT10", "TMT11", "TMT16", "iTRAQ4", "iTRAQ8" };
if (!possible.Contains(parameters.ParseParams.LabelingReagents))
{
Console.WriteLine("ERROR: For quantification, the labeling reagent must be one of {TMT0, TMT2, TMT6, TMT10, TMT11, TMT16, iTRAQ4, iTRAQ8}");
Log.Error("Invalid labeling reagent provided: {0}", parameters.ParseParams.LabelingReagents);
//Console.Write("Press any key to exit...");
//Console.ReadKey();
return 1;
}
}
if (parameters.ParseParams.Chromatogram != null)
{
List<string> possible = new List<string>() { "1", "2", "3", "T", "B" };
foreach (var x in parameters.ParseParams.Chromatogram)
{
if (!possible.Contains(x.ToString()))
{
Console.WriteLine("ERROR: Incorrect format for -chro. See help.");
Log.Error("Invalid chromatogram argument provided: {Chro}", parameters.ParseParams.Chromatogram);
//Console.Write("Press any key to exit...");
//Console.ReadKey();
return 1;
}
}
}
System.Diagnostics.Stopwatch singleFileTime = new System.Diagnostics.Stopwatch();
System.Diagnostics.Stopwatch totalTime = new System.Diagnostics.Stopwatch();
totalTime.Start();
foreach (string file in files)
{
singleFileTime.Start();
Console.WriteLine("\nProcessing: {0}\n", file);
//using (IRawDataPlus rawFile = RawFileReaderFactory.ReadFile(fileName:file))
using (IRawFileThreadManager rawFile = RawFileReaderFactory.CreateThreadManager(file))
{
if (parameters.ParseParams.OutputDirectory == null)
{
parameters.ParseParams.OutputDirectory = Path.GetDirectoryName(file);
}
WorkFlowsDDA.UniversalDDA(rawFile, parameters, qcDataCollection);
}
singleFileTime.Stop();
Console.WriteLine("\nElapsed time: {0} s", Math.Round(Convert.ToDouble(singleFileTime.ElapsedMilliseconds) / 1000.0, 2));
singleFileTime.Reset();
}
if (parameters.LogDump)
{
Write.LogDump.WriteToDisk(parameters);
}
totalTime.Stop();
Console.WriteLine("\nTime to process all {0} files: {1}", files.Count(), totalTime.Elapsed);
//Console.Write("Press any key to exit...");
//Console.ReadKey();
return 0;
}
19
Source : DiscordTimestamps.cs
with MIT License
from Lachee
with MIT License
from Lachee
public static DateTime FromUnixMilliseconds(long unixTime)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return epoch.AddMilliseconds(Convert.ToDouble(unixTime));
}
19
Source : SocketClient.cs
with MIT License
from ldqk
with MIT License
from ldqk
public static bool ReceiveFile(this Socket socket, string path, string filename, long size, Action<int> progress)
{
if (!Directory.Exists(path))
{
return false;
}
//主要是防止有重名文件
string savepath = GetPath(path, filename); //得到文件路径
//缓冲区
byte[] file = new byte[m_maxpacket];
int receivedata = m_maxpacket; //每次要接收的长度
long offset = 0; //循环接收的总长度
long lastdata = size; //剩余多少还没接收
int mark = 0;
using var fs = new FileStream(savepath, FileMode.OpenOrCreate, FileAccess.Write);
if (size <= 0)
{
return false;
}
bool ret = false;
while (true)
{
if (lastdata < receivedata)
{
receivedata = Convert.ToInt32(lastdata);
}
var count = socket.Receive(file, 0, receivedata, SocketFlags.None); //每次接收的实际长度
if (count > 0)
{
fs.Write(file, 0, count);
offset += count;
lastdata -= count;
mark = 0;
}
else
{
mark++; //连续5次接收为0字节 则跳出循环
if (mark == 10)
{
break;
}
}
//接收进度
progress(Convert.ToInt32(Convert.ToDouble(offset) / Convert.ToDouble(size) * 100));
//接收完毕
if (offset == size)
{
ret = true;
break;
}
}
return ret;
}
19
Source : SocketClient.cs
with MIT License
from ldqk
with MIT License
from ldqk
public static bool SendFile(this Socket socket, string path, bool issend, Action<int> progress)
{
if (!File.Exists(path))
{
return false;
}
var fileinfo = new FileInfo(path);
string filename = fileinfo.Name;
long length = fileinfo.Length;
//发送文件信息
if (issend)
{
SendVarData(socket, filename + "|" + length);
}
//发送文件
long offset = 0;
byte[] b = new byte[m_maxpacket];
int mark = 0;
using var fs = new FileStream(path, FileMode.Open, FileAccess.Read);
int senddata = b.Length;
//循环读取发送
while (true)
{
int count = fs.Read(b, 0, senddata);
if (count > 0)
{
socket.Send(b, 0, count, SocketFlags.None);
offset += count;
mark = 0;
}
else
{
mark++;
if (mark == 10)
{
break;
}
}
progress(Convert.ToInt32(Convert.ToDouble(offset) / Convert.ToDouble(length) * 100));
if (offset == length)
{
return true;
}
Thread.Sleep(50); //设置等待时间,以免粘包
}
return false;
}
19
Source : ParseTreeEvaluator.cs
with MIT License
from Macad3D
with MIT License
from Macad3D
protected override object EvalIntegerLiteral(ParseTree tree, params object[] paramlist)
{
if (this.GetValue(tree, TokenType.DECIMALINTEGERLITERAL, 0) != null)
return Convert.ToDouble(this.GetValue(tree, TokenType.DECIMALINTEGERLITERAL, 0));
if (this.GetValue(tree, TokenType.HEXINTEGERLITERAL, 0) != null)
{
string hex = this.GetValue(tree, TokenType.HEXINTEGERLITERAL, 0).ToString();
return Convert.ToDouble(Convert.ToInt64(hex.Substring(2, hex.Length - 2), 16));
}
tree.Errors.Add(new ParseError("illegal IntegerLiteral format", 1002, this));
return null;
}
19
Source : DataExtraction.cs
with MIT License
from mahalex
with MIT License
from mahalex
public static double[] LongToDouble(long[] source)
{
var result = new double[source.Length];
for (var i = 0; i < source.Length; i++)
{
result[i] = Convert.ToDouble(source[i]);
}
return result;
}
19
Source : BitmexConverter.cs
with Apache License 2.0
from Marfusios
with Apache License 2.0
from Marfusios
public static double ConvertToBtc(string from, long value)
{
var valueDouble = Convert.ToDouble(value);
return ConvertToBtc(from, valueDouble);
}
19
Source : Int64Extensions.cs
with GNU General Public License v3.0
from ME3Tweaks
with GNU General Public License v3.0
from ME3Tweaks
public static double ToDouble(this long value)
{
return Convert.ToDouble(value);
}
19
Source : BaseMsGraphCustomAction.cs
with MIT License
from microsoft
with MIT License
from microsoft
protected void FireTelemetryEvent(long latency, Exception exCaught)
#pragma warning restore CA1030 // Use events where appropriate
{
try
{
var metric = new Dictionary<string, double>();
metric.Add(this.TelemetryLatencyPropertyName, Convert.ToDouble(latency));
var properties = new Dictionary<string, string>();
if (exCaught != null)
{
properties.Add($"{this.TelemetryExceptionPropertyName}-Message", exCaught.Message);
properties.Add($"{this.TelemetryExceptionPropertyName}-StackTrace", exCaught.StackTrace);
properties.Add($"{this.TelemetryExceptionPropertyName}-ExceptionType", exCaught.GetType().FullName);
}
// Log the latency and any exception that we caught.
// Telemetry client is something that is handled by the base Dialog clreplaced, and by extension the SDK
// platform itself. If the bot has telemetry enabled with the instrumentation key, then this would
// automatically show up on their Application Insight monitoring log events.
this.TelemetryClient.TrackEvent(this.TelemetryEventName, properties, metric);
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
// If exception is found, don't do anything to crash the bot. This isn't quite that important.
this.TelemetryClient.TrackException(ex);
}
}
19
Source : TransformationAttributes.cs
with MIT License
from microsoft
with MIT License
from microsoft
public static object Transform( EngineIntrinsics engineIntrinsics,
string dbgProviderPath,
bool skipGlobalSymbolTest,
bool throwOnFailure,
bool dbgMemoryPreplacedthru,
bool allowList,
object inputData )
{
//Console.WriteLine( "vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv" );
//Console.WriteLine( "{0} 1: inputData type: {1}", DebuggingTag, inputData.GetType().FullName );
//Console.WriteLine( "{0} 2: dynamic type: {1}", DebuggingTag, ((dynamic) inputData).GetType().FullName );
//Console.WriteLine( "{0} 3: ToString(): {1}", DebuggingTag, inputData.ToString() );
//Console.WriteLine( "{0} 4: dynamic ToString(): {1}", DebuggingTag, ((dynamic) inputData).ToString() );
var pso = inputData as PSObject;
if( allowList )
{
var objList = inputData as IList;
if( (null != pso) && (pso.BaseObject is IList) )
{
objList = (IList) pso.BaseObject;
}
if( null != objList )
{
ulong[] addrs = new ulong[ objList.Count ];
try
{
for( int i = 0; i < objList.Count; i++ )
{
addrs[ i ] = (ulong) Transform( engineIntrinsics,
dbgProviderPath,
skipGlobalSymbolTest,
true, // throwOnFailure,
dbgMemoryPreplacedthru,
false, // we don't allow nested arrays
objList[ i ] );
} // end for( each obj )
return addrs;
}
catch( Exception e_temp )
{
if( throwOnFailure ||
(!(e_temp is DbgProviderException) && !(e_temp is MetadataException)) )
{
throw;
}
}
} // end if( it's an array )
} // end if( allowList )
if( null != pso )
{
// Addresses are always expressed in hexadecimal.
//
// Thus you can type a leading "0x", but it is redundant and not
// necessary.
//
// If the address contains a backtick, or for some reason is expressed in
// decimal with a leading "0n", or has hex-only digits ([a-f]) but no
// leading "0x", then PowerShell will parse it as a string. Then we can
// handle parsing it ourselves (in this method).
//
// However... if the user /did/ use a leading "0x" and there is no
// backtick, OR if the address contains no hex-only digits and there is no
// backtick, OR if the address ended with "eN" (where N is a digit)...
// then PowerShell will have parsed it as a number (giving us either an
// UInt32, or a UInt64, or a double, depending on how big).
//
// In that case, we need to figure out whether or not the user typed an
// "0x", because if they did not, that means that PowerShell parsed it
// incorrectly (as a base-10 number, and possibly using scientific
// notation, instead of a base-16 number).
//
// Fortunately, if we have the PSObject for that typed number, we can get
// the originally typed string, which will let us know if there was an
// "0x" or not.
//
// Update: "if we have the PSObject for that typed number, we can get the
// originally typed string": unfortunately, that is not always true, such
// as when the address is piped in. TODO: can we change PowerShell to
// allow us to get the string as originally typed in more cases?
//Console.WriteLine( "{0} 5: BaseObject type: {1}", DebuggingTag, pso.BaseObject.GetType().FullName );
if( (pso.BaseObject is int) ||
(pso.BaseObject is long) ||
(pso.BaseObject is double) ||
(pso.BaseObject is float) )
{
// The standard way to get the originally typed string is to use
// LanguagePrimitives.ConvertTo< string >. However, it seems that it
// wants to /always/ give us a string back, even if it doesn't have
// the originally typed string. So if we use that method, we don't
// know if the string we get back actually is what was originally
// typed or not.
//var asTyped = LanguagePrimitives.ConvertTo< string >( pso );
// This /will/ get what the user actually typed (if it was typed),
// but relies on reflection to get at PS internals. :(
var asTyped = _GetAsTyped_usingIckyPrivateReflection( pso );
//Console.WriteLine( "As typed: {0}", asTyped );
if( null != asTyped )
{
if( asTyped.StartsWith( "0x", StringComparison.OrdinalIgnoreCase ) )
{
// Yes, they typed an "0x", so PS correctly parsed as hex.
//
// The cast to (int) first is to un-box. Then to (uint) to
// prevent sign extension.
if( pso.BaseObject is int )
return (ulong) (uint) (int) pso.BaseObject;
if( pso.BaseObject is long )
return unchecked( (ulong) (long) pso.BaseObject );
// Should not reach here.
Util.Fail( "How could the typed string start with 0x but get parsed as something besides an int or long?" );
}
inputData = asTyped; // we'll re-parse it below as base-16
}
else
{
// If we get here, then it /was/ typed, but piped in:
//
// 01234000 | ConvertTo-Number
// 0x01234000 | ConvertTo-Number
//
// So PS parsed it... but if we ended up with an integer type, we
// don't know if it parsed as decimal or hex, so we can't be sure
// how to undo that parsing. :( For now we'll have to just replacedume
// that the user knows that they need to use 0x when piping in.
//
// That sounds bad, because actually a user probably will /not/
// know that, but the alternative is worse; a user who directly
// specifies hex ("0x01230000 | something") should never get the
// wrong result.
//
// TODO: see if we can get PS to preserve the as-typed value for
// things that are piped in.
inputData = pso.BaseObject;
}
}
else
{
inputData = pso.BaseObject;
}
}
//Console.WriteLine( "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" );
if( dbgMemoryPreplacedthru && (inputData is DbgMemory) )
return inputData;
// Some commands do not require an address.
if( null == inputData )
return (ulong) 0;
if( inputData is ulong )
return inputData;
// We used to replacedume that this was probably a base-16 number without any
// letters in it, so PS interpreted it as a base-10 number, so then we would
// undo that. And hope it was right. But unfortunately, that messed up the
// scenario where you replacedign a number to a variable ("$blah = 123"), so I'm
// going the other way now--we'll replacedume it's already correct. Unfortunately,
// that means that on 32-bit, you'll need to always use "0x" to be safe. :(
// if( (inputData is int) || (inputData is long) )
// {
// inputData = inputData.ToString();
// }
if( inputData is int )
return (ulong) (uint) (int) inputData; // 1st cast unboxes; 2nd prevents sign extension
if( inputData is long )
return (ulong) (long) inputData; // need two casts in order to unbox first.
if( inputData is uint )
{
// This can happen, for instance, when using the register variables for a
// 32-bit process ("u $eip").
return (ulong) (uint) inputData; // need two casts in order to unbox first.
}
if( inputData is byte )
{
// This can happen because we [ab]use AddressTransformationAttribute to
// convert lots of numeric data, not just addresses. (For instance, the
// "eb" command.)
return (ulong) (byte) inputData; // need two casts in order to unbox first.
}
if( inputData is double )
{
// This can happen when doing arithmetic. For instance, this will yield
// Double:
//
// [UInt32] $ui1 = 0x03
// [UInt32] $ui2 = 0x01
// ($ui2 - $ui1).GetType()
//
// To determine if it's really something that can be represented as a
// ulong, we'll round-trip it through a ulong back to a double, and then
// see if the bits representation matches the original double.
double dOrig = (double) inputData;
Int64 origBits = BitConverter.DoubleToInt64Bits( dOrig );
unchecked
{
ulong asUlong = (ulong) (long) dOrig;
double d2 = Convert.ToDouble( (long) asUlong );
Int64 d2Bits = BitConverter.DoubleToInt64Bits( d2 );
if( d2Bits == origBits )
{
// We round-tripped back to double: it doesn't have any fractional
// part.
return asUlong;
}
}
} // end if( inputData is double )
Exception e = null;
string str = inputData as string;
if( null != str )
{
// Some commands do not require an address.
if( 0 == str.Length )
return (ulong) 0;
if( (1 == str.Length) && (str[ 0 ] == '.') )
{
dbgProviderPath = _GetDbgProviderPath( dbgProviderPath, engineIntrinsics );
var regSet = DbgProvider.GetRegisterSetForPath( dbgProviderPath );
return regSet.Pseudo[ "$ip" ].Value;
}
ulong address;
if( DbgProvider.TryParseHexOrDecimalNumber( str, out address ) )
return address;
// Mabye it's a symbolic name?
if( !skipGlobalSymbolTest )
{
dbgProviderPath = _GetDbgProviderPath( dbgProviderPath, engineIntrinsics );
var debugger = DbgProvider.GetDebugger( dbgProviderPath );
try
{
address = debugger.GetOffsetByName( str );
return address;
}
catch( DbgProviderException dpe )
{
e = dpe;
}
}
}
// Check for implicit conversion to ulong. (For instance, types that derive
// from DbgPointerValueBase have this.)
ulong addr;
if( _TryImplicitConversionTo( inputData, out addr ) )
return addr;
if( !throwOnFailure )
return null;
if( null != e )
{
ExceptionDispatchInfo.Capture( e ).Throw();
}
// https://github.com/PowerShell/PowerShell/issues/7600
//
// For parameter binding to be able to continue (for example, to try binding
// by property name), this exception needs to wrap a PSInvalidCastException.
throw CreateRecoverableAtme( "Could not convert '{0}' to an address.", inputData );
}
19
Source : SignedBytes.cs
with MIT License
from microsoft
with MIT License
from microsoft
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(this.bytes);
}
19
Source : NumericConverter.cs
with MIT License
from MudBlazor
with MIT License
from MudBlazor
private double OnSet(T arg)
{
if (arg == null)
return double.NaN; // <-- this catches all nullable values which are null. no nullchecks necessary below!
try
{
// double
if (typeof(T) == typeof(double))
return (double)(object)arg;
else if (typeof(T) == typeof(double?))
return ((double?)(object)arg).Value;
// string
if (typeof(T) == typeof(string))
return double.Parse((string)(object)arg, NumberStyles.Any, Culture);
// sbyte
if (typeof(T) == typeof(sbyte))
return Convert.ToDouble((sbyte)(object)arg);
if (typeof(T) == typeof(sbyte?))
return Convert.ToDouble(((sbyte?)(object)arg).Value);
// byte
if (typeof(T) == typeof(byte))
return Convert.ToDouble((byte)(object)arg);
if (typeof(T) == typeof(byte?))
return Convert.ToDouble(((byte?)(object)arg).Value);
// short
if (typeof(T) == typeof(short))
return Convert.ToDouble((short)(object)arg);
if (typeof(T) == typeof(short?))
return Convert.ToDouble(((short?)(object)arg).Value);
// ushort
if (typeof(T) == typeof(ushort))
return Convert.ToDouble((ushort)(object)arg);
if (typeof(T) == typeof(ushort?))
return Convert.ToDouble(((ushort?)(object)arg).Value);
// int
else if (typeof(T) == typeof(int))
return Convert.ToDouble((int)(object)arg);
else if (typeof(T) == typeof(int?))
return Convert.ToDouble(((int?)(object)arg).Value);
// uint
else if (typeof(T) == typeof(uint))
return Convert.ToDouble((uint)(object)arg);
else if (typeof(T) == typeof(uint?))
return Convert.ToDouble(((uint?)(object)arg).Value);
// long
else if (typeof(T) == typeof(long))
return Convert.ToDouble((long)(object)arg);
else if (typeof(T) == typeof(long?))
return Convert.ToDouble(((long?)(object)arg).Value);
// ulong
else if (typeof(T) == typeof(ulong))
return Convert.ToDouble((ulong)(object)arg);
else if (typeof(T) == typeof(ulong?))
return Convert.ToDouble(((ulong?)(object)arg).Value);
// float
else if (typeof(T) == typeof(float))
return Convert.ToDouble((float)(object)arg);
else if (typeof(T) == typeof(float?))
return Convert.ToDouble(((float?)(object)arg).Value);
// decimal
else if (typeof(T) == typeof(decimal))
return Convert.ToDouble((decimal)(object)arg);
else if (typeof(T) == typeof(decimal?))
return Convert.ToDouble(((decimal?)(object)arg).Value);
else
{
UpdateSetError("Unable to convert to double from type " + typeof(T).Name);
return double.NaN;
}
}
catch (FormatException e)
{
UpdateSetError("Conversion error: " + e.Message);
return double.NaN;
}
}
19
Source : NumericConverter.cs
with MIT License
from MudBlazor
with MIT License
from MudBlazor
public static double From<T>(T v)
{
if (typeof(T) == typeof(sbyte))
return Convert.ToDouble((sbyte)(object)v);
if (typeof(T) == typeof(byte))
return Convert.ToDouble((byte)(object)v);
if (typeof(T) == typeof(short))
return Convert.ToDouble((short)(object)v);
if (typeof(T) == typeof(ushort))
return Convert.ToDouble((ushort)(object)v);
if (typeof(T) == typeof(int))
return Convert.ToDouble((int)(object)v);
if (typeof(T) == typeof(uint))
return Convert.ToDouble((uint)(object)v);
if (typeof(T) == typeof(long))
return Convert.ToDouble((long)(object)v);
if (typeof(T) == typeof(ulong))
return Convert.ToDouble((ulong)(object)v);
if (typeof(T) == typeof(float))
return Convert.ToDouble((float)(object)v);
if (typeof(T) == typeof(double))
return Convert.ToDouble((double)(object)v);
if (typeof(T) == typeof(decimal))
return Convert.ToDouble((decimal)(object)v);
if (typeof(T) == typeof(sbyte?))
return Convert.ToDouble((sbyte?)(object)v);
if (typeof(T) == typeof(byte?))
return Convert.ToDouble((byte?)(object)v);
if (typeof(T) == typeof(short?))
return Convert.ToDouble((short?)(object)v);
if (typeof(T) == typeof(ushort?))
return Convert.ToDouble((ushort?)(object)v);
if (typeof(T) == typeof(int?))
return Convert.ToDouble((int?)(object)v);
if (typeof(T) == typeof(uint?))
return Convert.ToDouble((uint?)(object)v);
if (typeof(T) == typeof(long?))
return Convert.ToDouble((long?)(object)v);
if (typeof(T) == typeof(ulong?))
return Convert.ToDouble((ulong?)(object)v);
if (typeof(T) == typeof(float?))
return Convert.ToDouble((float?)(object)v);
if (typeof(T) == typeof(double?))
return Convert.ToDouble((double?)(object)v);
if (typeof(T) == typeof(decimal?))
return Convert.ToDouble((decimal?)(object)v);
return default;
}
19
Source : CustomWebAuthenticationValidator.cs
with MIT License
from nelemans1971
with MIT License
from nelemans1971
public static void UpdateHitsPerSecond()
{
HitsPerSecondLog hitsPerSecondlog;
lock (lockObject)
{
if (calcHitsPerSecond == null)
{
return;
}
hitsPerSecondlog = (HitsPerSecondLog)calcHitsPerSecond;
calcHitsPerSecond = null;
}
// Hier berekenen we de avg, min en max request per seconds waarde
long totalHits = 0;
for (int i = 0; i < hitsPerSecondlog.HitPerSecondArray.Length; i++)
{
totalHits += ((HitsPerSecondLog)hitsPerSecondlog).HitPerSecondArray[i];
} //for
// Nu min, max en average berekenen over deze periode (10 minuten)
double hitPerSecond = Convert.ToDouble(totalHits) / hitsPerSecondlog.HitPerSecondArray.Length; // nu in hits per seconds
// Hebben we een overrun/overroll
if ((DateTime.Now.Date - currentDTMinMaxAvgHits.Date).TotalDays != 0)
{
lock (lockObject)
{
previousMinMaxAvgHits = currentMinMaxAvgHits;
currentDTMinMaxAvgHits = DateTime.Now.Date;
currentMinMaxAvgHits = null;
}
}
lock (lockObject)
{
if (currentMinMaxAvgHits == null)
{
currentMinMaxAvgHits = NewHitsPerDayArray(); // array voor de hele dag
}
if (hitPerSecond > maxHitsPerSecond)
{
maxHitsPerSecond = hitPerSecond;
}
if (minHitsPerSecond < 0 || hitPerSecond < minHitsPerSecond)
{
minHitsPerSecond = hitPerSecond;
}
// Store hits account for the whole day
int minutes = Convert.ToInt32((DateTime.Now - currentDTMinMaxAvgHits.Date).TotalMinutes);
if (currentMinMaxAvgHits.Length > minutes)
{
currentMinMaxAvgHits[minutes].avgHitsPerSecond = hitPerSecond; // GEEN gemiddeld avergae gebruiken hier
currentMinMaxAvgHits[minutes].minHitsPerSecond = minHitsPerSecond;
currentMinMaxAvgHits[minutes].maxHitsPerSecond = maxHitsPerSecond;
}
// Was er al een meting?
if (avgHitsPerSecond < 0)
{
avgHitsPerSecond = hitPerSecond;
}
else
{
avgHitsPerSecond = (avgHitsPerSecond + hitPerSecond) / 2;
}
}
}
19
Source : AtomicInt64.cs
with Apache License 2.0
from NightOwl888
with Apache License 2.0
from NightOwl888
double IConvertible.ToDouble(IFormatProvider? provider) => Convert.ToDouble(Value);
19
Source : Extensions.cs
with MIT License
from NtreevSoft
with MIT License
from NtreevSoft
public static DateTime FromTotalSeconds(long seconds)
{
var delta = TimeSpan.FromSeconds(Convert.ToDouble(seconds));
return new DateTime(1970, 1, 1) + delta;
}
19
Source : MsgPack.cs
with MIT License
from NYAN-x-CAT
with MIT License
from NYAN-x-CAT
public Double GetAsFloat()
{
switch (this.valueType)
{
case MsgPackType.Integer:
return Convert.ToDouble((Int64)this.innerValue);
case MsgPackType.String:
return Double.Parse((String)this.innerValue);
case MsgPackType.Float:
return (Double)this.innerValue;
case MsgPackType.Single:
return (Single)this.innerValue;
case MsgPackType.DateTime:
return Convert.ToInt64((DateTime)this.innerValue);
default:
return 0;
}
}
19
Source : AccountRegedit.cs
with Apache License 2.0
from oneflyingfish
with Apache License 2.0
from oneflyingfish
private void ChooseImageButton_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
fileDialog.Filter = "图片(*.png ;*.jpg)|*.png;*.jpg";
fileDialog.replacedle = "选择图像(尽量选择正方形图片)";
fileDialog.Multiselect = false;//不可选取多个文件
if(fileDialog.ShowDialog()==DialogResult.OK)
{
FileInfo fileInfo = new FileInfo(fileDialog.FileName);
double length = Convert.ToDouble(fileInfo.Length);
if (!fileInfo.FullName.ToLower().EndsWith(".png") || (fileInfo.Length > 31457280))
{
MessageBox.Show("目前仅支持小于30KB的png图像");
return;
}
this.ImagePathTextBox.Text = fileDialog.FileName;
}
}
19
Source : ApplyForm.cs
with Apache License 2.0
from oneflyingfish
with Apache License 2.0
from oneflyingfish
private void sendbutton_Click(object sender, EventArgs e)
{
if (this.sendbutton.Text == "发送请求")
{
switch (currentFunction)
{
case FunctionChoice.AddFriend:
if (!this.accountTextbox.Text.EndsWith(".com") || this.accountTextbox.Text == "")
{
MessageBox.Show("请输入正确的好友邮箱");
return;
}
//云验证账户,并请求昵称???
FunctionWords functionWordsForFriendUserName = this.SendNewsAndReceiveAnswer(FunctionKind.SeekForUserName, this.accountTextbox.Text, "", null);
if(functionWordsForFriendUserName!=null &&functionWordsForFriendUserName.stringList.Count>0)
{
this.userNameTextBox.Text = functionWordsForFriendUserName.stringList[0];
this.showBusyLabel.Text = "已返回昵称,请确认";
break;
}
this.showBusyLabel.Text = "账户不存在";
return;
case FunctionChoice.AddToGroup:
if (this.accountTextbox.Text.EndsWith(".com") || this.accountTextbox.Text == "")
{
MessageBox.Show("请输入正确的群号");
return;
}
//云验证账户,并请求昵称???
FunctionWords functionWordsForGroupUserName = this.SendNewsAndReceiveAnswer(FunctionKind.SeekForUserName, this.accountTextbox.Text, "", null);
if (functionWordsForGroupUserName != null && functionWordsForGroupUserName.stringList.Count > 0)
{
this.userNameTextBox.Text = functionWordsForGroupUserName.stringList[0];
this.showBusyLabel.Text = "已返回昵称,请确认";
break;
}
this.showBusyLabel.Text = "账户不存在";
return;
case FunctionChoice.CreateGroup:
if (this.userNameTextBox.Text == "")
{
MessageBox.Show("请输入正确的昵称");
return;
}
//云请求群号,返回群号???
FunctionWords functionWordsForCreateGroup= this.SendNewsAndReceiveAnswer(FunctionKind.SeekForNewGroupAccount,"","", null);
if (functionWordsForCreateGroup != null && functionWordsForCreateGroup.stringList.Count > 0)
{
this.accountTextbox.Text = functionWordsForCreateGroup.stringList[0];
this.showBusyLabel.Text = "已返回群号,请确认";
break;
}
this.showBusyLabel.Text = "服务器异常,请稍后重试";
return;
default:
return;
}
this.sendbutton.Text = "确认";
}
else if (this.sendbutton.Text == "确认")
{
if(this.userNameTextBox.Text=="" || this.accountTextbox.Text=="")
{
MessageBox.Show("错误: 似乎存在信息不完整,请重试");
this.sendbutton.Text = "发送请求";
return;
}
switch (currentFunction)
{
case FunctionChoice.AddFriend:
//发送请求???
CallServer.AddSendNews(MessageProtocol.GetStartBytes(FunctionKind.ApplyToAddFriend), MessageBirdCommon.UserInformation.Account.ToTxtBytes(), MessageBirdCommon.UserInformation.UserName.ToTxtBytes(), this.accountTextbox.Text.ToTxtBytes(), MessageProtocol.GetEndBytes());
break;
case FunctionChoice.AddToGroup:
//发送请求???
CallServer.AddSendNews(MessageProtocol.GetStartBytes(FunctionKind.ApplyToAddGroup), MessageBirdCommon.UserInformation.Account.ToTxtBytes(), MessageBirdCommon.UserInformation.UserName.ToTxtBytes(), this.accountTextbox.Text.ToTxtBytes(), MessageProtocol.GetEndBytes());
break;
case FunctionChoice.CreateGroup:
//发送请求???
MessageBox.Show("请选择小于30KB的png图片");
OpenFileDialog fileDialog = new OpenFileDialog();
DialogResult result = fileDialog.ShowDialog();
if (result == DialogResult.OK)
{
FileInfo fileInfo = new FileInfo(fileDialog.FileName);
double length = Convert.ToDouble(fileInfo.Length);
if(!fileInfo.FullName.ToLower().EndsWith(".png") || (fileInfo.Length> 31457280))
{
MessageBox.Show("目前仅支持小于30KB的png图像");
return;
}
Bitmap image= new Bitmap(Image.FromFile(fileDialog.FileName));
CallServer.AddSendNews(MessageProtocol.GetStartBytes(FunctionKind.RequestToRegeditGroup), MessageBirdCommon.UserInformation.Account.ToTxtBytes(), MessageBirdCommon.UserInformation.UserName.ToTxtBytes(), this.accountTextbox.Text.ToTxtBytes(),image.ToImageBytes(), MessageProtocol.GetEndBytes());
}
else
{
return;
}
break;
default:
return;
}
MessageBox.Show("申请信息已发出");
this.sendbutton.Text = "发送请求";
}
}
See More Examples