public void WriteTimestamp(ModuleVM vm) { var ts = vm.Timestamp; if (ts != null) { var date = Epoch.AddSeconds(ts.Value); var dateString = date.ToString(CultureInfo.CurrentUICulture.DateTimeFormat); output.Write(dateString, TextTokenKind.Text); } }
public RateLimit(JObject data) { remaining = data["remaining"].Value <int>(); limit = data["limit"].Value <int>(); int dateAsInt = data["reset"].Value <int>(); resetTime = Epoch.AddSeconds(Convert.ToDouble(dateAsInt)); resetTime = resetTime.ToLocalTime(); }
public Interval GetInterval(IntervalKey intervalKey, Epoch epoch) { var ts = TimeSpan.FromMinutes(intervalKey.Duration); return(new Interval { IntervalKey = intervalKey, From = epoch.RoundDown(ts), To = epoch.AddSeconds(1).RoundUp(ts) }); }
public void GeneratesExpectedIntervalCountFor1d() { var from = new Epoch(new DateTime(2018, 1, 1, 0, 30, 0, DateTimeKind.Utc)); var to = from.AddSeconds((int)TimeSpan.FromDays(5).TotalSeconds); var intervalKey = IntervalFactory.GetIntervalKey("1D"); var intervals = IntervalFactory.GenerateIntervals(intervalKey, from, to); Assert.AreEqual(6, intervals.Count); }
private static DateTimeOffset ReadLastModifiedTime(byte[] header, string fileName) { var unixTimeStamp = ReadOctal(header, 136, 12); if (!unixTimeStamp.HasValue) { throw new InvalidDataException($"Invalid timestamp for file entry [{fileName}] "); } return(Epoch.AddSeconds(unixTimeStamp.Value)); }
public static string GetAbsoluteDisplayTime(long unixTime) { if (CustomFormatter != null) { return(CustomFormatter.GetAbsoluteDisplayTime(unixTime)); } var utcTime = Epoch.AddSeconds(Convert.ToDouble(unixTime)); var localTime = utcTime.ToLocalTime(); return(localTime.ToString("g", CultureInfo.CurrentCulture)); }
public static string GetBubbleDisplayTime(long unixTime, bool lowercase = false, bool absoluteTime = false) { if (CustomFormatter != null) { return(CustomFormatter.GetBubbleDisplayTime(unixTime, lowercase, absoluteTime)); } var utcTime = Epoch.AddSeconds(Convert.ToDouble(unixTime)); var localTime = utcTime.ToLocalTime(); return(localTime.ToString("t", CultureInfo.CurrentCulture)); }
static void InitializeExeFieldsFrom(IPEImage peImage, out bool isExe, out bool isDll, out DateTime?timestamp, ref string version, out string assemblySimpleName) { isExe = (peImage.ImageNTHeaders.FileHeader.Characteristics & Characteristics.Dll) == 0; isDll = !isExe; // Roslyn sets bit 31 if /deterministic is used (the low 31 bits is not a timestamp) if (peImage.ImageNTHeaders.FileHeader.TimeDateStamp < 0x80000000) { timestamp = Epoch.AddSeconds(peImage.ImageNTHeaders.FileHeader.TimeDateStamp); } else { timestamp = null; } try { if (string.IsNullOrEmpty(version)) { using (var mod = ModuleDefMD.Load(peImage)) { if (string.IsNullOrEmpty(version)) { version = mod.Assembly?.Version.ToString(); } assemblySimpleName = UTF8String.ToSystemString(mod.Assembly?.Name); } } else { using (var md = MetaDataCreator.CreateMetaData(peImage)) { var row = md.TablesStream.ReadAssemblyRow(1); if (row == null) { assemblySimpleName = null; } else { assemblySimpleName = md.StringsStream.Read(row.Name); } } } } catch { assemblySimpleName = null; } }
public override void historicalData(int reqId, IBApi.Bar bar) { Tuple <ISubject <Bar>, bool> historical_data; if (_historicalDataDict.TryGetValue(reqId, out historical_data)) { DateTime timestamp; if (historical_data.Item2) // intraday { long epochtime = long.Parse(bar.Time); // the "time" string is in Epoch seconds timestamp = Epoch.AddSeconds(epochtime); } else { timestamp = DateTime.ParseExact(bar.Time, "yyyyMMdd", DateTimeFormatInfo.InvariantInfo); } historical_data.Item1.OnNext(new Bar(timestamp.Ticks, (decimal)bar.Open + Zero00, (decimal)bar.High + Zero00, (decimal)bar.Low + Zero00, (decimal)bar.Close + Zero00, bar.Volume, (decimal)bar.WAP)); } }
public override void historicalData(int reqId, string date, double open, double high, double low, double close, int volume, int count, double WAP, bool hasGaps) { Tuple <ISubject <Bar>, bool> historical_data; if (_historicalDataDict.TryGetValue(reqId, out historical_data)) { DateTime timestamp; if (historical_data.Item2) // intraday { long epochtime = long.Parse(date); // the "date" string is in Epoch seconds timestamp = Epoch.AddSeconds(epochtime); } else { timestamp = DateTime.ParseExact(date, "yyyyMMdd", DateTimeFormatInfo.InvariantInfo); } historical_data.Item1.OnNext(new Bar(timestamp.Ticks, (decimal)open + Zero00, (decimal)high + Zero00, (decimal)low + Zero00, (decimal)close + Zero00, volume, (decimal)WAP)); } }
/// <summary> /// Decodes the specified token. /// </summary> /// <param name="token">The token.</param> /// <returns>The decoded token; Or null if it's invalid.</returns> private static Token Decode(string token) { var parts = token?.Split('.') ?? new string[0]; using (var hash = new HMACSHA256(Settings.ValidationKey)) { if (parts.Length != 3 || parts[0] != Header || Base64UrlEncoder.Encode(hash.ComputeHash(Encoding.Default.GetBytes($"{parts[0]}.{parts[1]}"))) != parts[2]) { return(null); } var payload = JsonConvert.DeserializeObject <Token>(Base64UrlEncoder.DecodeString(parts[1])); if (payload.Issuer != Issuer || Epoch.AddSeconds(payload.Expiration) < DateTime.UtcNow) { return(null); } return(payload); } }
static void InitializeExeFieldsFrom(IPEImage peImage, out bool isExe, out DateTime?timestamp, ref string version) { isExe = (peImage.ImageNTHeaders.FileHeader.Characteristics & Characteristics.Dll) == 0; // Roslyn sets bit 31 if /deterministic is used (the low 31 bits is not a timestamp) if (peImage.ImageNTHeaders.FileHeader.TimeDateStamp < 0x80000000) { timestamp = Epoch.AddSeconds(peImage.ImageNTHeaders.FileHeader.TimeDateStamp); } else { timestamp = null; } if (string.IsNullOrEmpty(version)) { using (var mod = ModuleDefMD.Load(peImage)) version = mod.Assembly?.Version.ToString(); } }
/// <summary> /// Returns false if the given token from in <paramref name="request"/> as a token that is older /// than the expiration time specified in <see cref="Program.Settings"/> or doesn't match the token /// in <see cref="CurrentUser"/>. /// </summary> /// <remarks> /// In case this returns false, the response value must be returned to the client. /// </remarks> /// <param name="request">The request from whom to take the user info.</param> /// <param name="response">A response JObject. In case of an error, this will be an error JSON. Otherwise always null.</param> /// <returns>True if the verification went succesfully. Otherwise false.</returns> private bool VerifyToken(JObject request, out JObject response) { if (!GetUser(request, out response)) { return(false); } // Calculate token age long expiration = (long)Program.Settings["authenticationSettings"]["expiration"]; long token = (long)request["token"]; long tokenAge = (long)(DateTime.UtcNow - Epoch.AddSeconds(token).ToLocalTime()).TotalSeconds; // In case of token mismatch or expired token, return "ExpiredToken" if (token != CurrentUser.Token || tokenAge > expiration) { response = Templates.ExpiredToken; return(false); } // Verification succeeded return(true); }
public static string GetLastSeenDisplayTime(long unixTime) { if (CustomFormatter != null) { return(CustomFormatter.GetLastSeenDisplayTime(unixTime)); } var utcTime = Epoch.AddSeconds(Convert.ToDouble(unixTime)); var localTime = utcTime.ToLocalTime(); var isYesterday = DateTime.Today - localTime.Date == TimeSpan.FromDays(1); var isToday = DateTime.Today == localTime.Date; if (isYesterday) { return("Last seen yesterday at " + localTime.ToString("t", CultureInfo.CurrentCulture)); } if (isToday) { return("Last seen today at " + localTime.ToString("t", CultureInfo.CurrentCulture)); } return("Last seen " + localTime.ToString("g", CultureInfo.CurrentCulture)); }
public static DateTime FromUnixTime(long unixTime) { return(Epoch.AddSeconds(unixTime)); }
DateTime EpochToDate(uint val) { return(Epoch.AddSeconds(val)); }
/// <summary> /// Reads the value as a <see cref="DateTime"/> /// </summary> /// <returns></returns> public DateTime ReadDateTime() => Epoch.AddSeconds(ReadValue());
public static DateTime FromUnixTime(double unixTime) => Epoch.AddSeconds(unixTime);
public async Task <MarketTick> GetTick(ExchangeEnum exchange, SymbolCodeEnum symbolCode, Epoch at) { using (var context = ContextFactory.CreateDbContext(null)) { var minAt = at.AddSeconds((int)TimeSpan.FromDays(-1).TotalSeconds); var buyTradeQuery = from t in context.ExchangeTrade where t.ExchangeId == (int)exchange && t.SymbolId == (int)symbolCode && t.Timestamp >= minAt.TimestampMilliseconds && t.Timestamp <= at.TimestampMilliseconds && t.OrderSideId == (int)OrderSideEnum.Buy orderby t.ExchangeId, t.SymbolId, t.Timestamp descending select t; var buyTrade = await buyTradeQuery.FirstOrDefaultAsync(); var sellTradeQuery = from t in context.ExchangeTrade where t.ExchangeId == (int)exchange && t.SymbolId == (int)symbolCode && t.Timestamp >= minAt.TimestampMilliseconds && t.Timestamp <= at.TimestampMilliseconds && t.OrderSideId == (int)OrderSideEnum.Sell orderby t.ExchangeId, t.SymbolId, t.Timestamp descending select t; var sellTrade = await sellTradeQuery.FirstOrDefaultAsync(); ExchangeTradeEntity lastTrade = null; if (buyTrade != null && sellTrade != null) { lastTrade = buyTrade.Timestamp <= sellTrade.Timestamp ? buyTrade : sellTrade; } else { var lastTradeQuery = from t in context.ExchangeTrade where t.ExchangeId == (int)exchange && t.SymbolId == (int)symbolCode && t.Timestamp >= minAt.TimestampMilliseconds && t.Timestamp <= at.TimestampMilliseconds orderby t.ExchangeId, t.SymbolId, t.Timestamp descending select t; lastTrade = await lastTradeQuery.FirstOrDefaultAsync(); } if (lastTrade == null) { return(null); } return(new MarketTick { Exchange = exchange, SymbolCode = symbolCode, Epoch = at, BuyPrice = buyTrade != null ? buyTrade.Price : lastTrade.Price, SellPrice = sellTrade != null ? sellTrade.Price : lastTrade.Price, LastPrice = lastTrade.Price }); } }
internal static DateTime ToDateTime(this ulong unixTimeStamp) { var dtDateTime = Epoch.AddSeconds(unixTimeStamp); return(dtDateTime); }
// convert unix timestamp into a year public static DateTime TimestampToDate(int timeStamp) => Epoch.AddSeconds(timeStamp);
public static Date UnixTimeToDateTime(ulong timestamp) => new Date(Epoch.AddSeconds(timestamp));
/// <summary> /// Parses a string containing a token and returns the token it contains, /// if that token is valid. /// </summary> /// <param name="key">The shared secret key with which the token was originally signed.</param> /// <param name="token">The original token string representation.</param> public static SecurityToken FromString(string key, string token) { // Decode the incoming string and do a basic sanity check. byte[] RawData = token.Base64WebSafeDecode(); if (RawData.Length < (HMAC_SIZE + 1)) { throw new SecurityTokenInvalidException("String is too small to be a valid " + typeof(SecurityToken).Name); } // Recompute the HMAC using the provided key (as the key is a secret and // cannot be encoded into the token itself), and make sure it matches. If // not, then the token is corrupt and cannot be trusted. byte[] RawHMAC = RawData.Skip(RawData.Length - HMAC_SIZE).ToArray(); RawData = RawData.Take(RawData.Length - HMAC_SIZE).ToArray(); if (RawData.GetHMACSHA1Bytes(key).Base64Encode() != RawHMAC.Base64Encode()) { throw new SecurityTokenInvalidException("HMAC validation failed."); } // Extract the flags from the payload. SecurityTokenFlags Flags = (SecurityTokenFlags)RawData.First(); RawData = RawData.Skip(1).ToArray(); // If data was encrypted, decrypt it. SymmetricAlgorithm Alg = CreateCipher(key); if ((Flags & SecurityTokenFlags.EncryptedCTS) != 0) { RawData = Alg.CTSDecrypt(Alg.CTSDecrypt(RawData).Reverse().ToArray()); } else if ((Flags & SecurityTokenFlags.EncryptedCBC) != 0) { RawData = Alg.CBCDecrypt(Alg.CTSDecrypt(RawData).Reverse().ToArray()); } // If the data was originally deflated, decompress it. if ((Flags & SecurityTokenFlags.Deflated) != 0) { RawData = RawData.DeflateDecompress().ToArray(); } // If the data contains an expiration date, then decode the expiration date // and make sure the token has not expired. DateTime Exp = DateTime.MaxValue; if ((Flags & SecurityTokenFlags.ExpireDate) != 0) { Exp = Epoch.AddSeconds(BitConverter.ToUInt32(RawData.Skip(RawData.Length - sizeof(UInt32)).EndianFlip().ToArray(), 0)); if (Exp < DateTime.UtcNow) { throw new SecurityTokenExpiredException("Token has expired."); } RawData = RawData.Take(RawData.Length - sizeof(UInt32)).ToArray(); } // The remaining data is the key/value pair data, packed as an even number of // strings, each prefixed with a big-endian uint16 length specifier, followed // by that many bytes of UTF-8-encoded string data. After unpacking strings, // rebuild the original dictionary. Queue <string> Values = new Queue <string>(); while (RawData.Length > 0) { ushort StrLen = BitConverter.ToUInt16(RawData.Take(2).EndianFlip().ToArray(), 0); Values.Enqueue(Encoding.UTF8.GetString(RawData.Skip(2).Take(StrLen).ToArray())); RawData = RawData.Skip(StrLen + 2).ToArray(); } Dictionary <string, string> NewData = new Dictionary <string, string>(); while (Values.Count > 0) { NewData[Values.Dequeue()] = Values.Dequeue(); } // Return a security token containing the original expiration, key, and // payload data. Note that if any of the checks above fails (payload validation, // matching key, expiration) then an exception will be thrown instead of // returning any token. return(new SecurityToken { Expires = Exp, Key = key, Data = NewData }); }
public static DateTime GetLocalTime(long unixTime) { var utcTime = Epoch.AddSeconds(Convert.ToDouble(unixTime)); return(utcTime.ToLocalTime()); }
public static DateTime?FromUnixTime(string unixTime) { return(long.TryParse(unixTime, out long seconds) ? Epoch.AddSeconds(seconds) : default(DateTime?)); }
public object?GetValue(IDataSource data, long offset) { var value = data.Read <uint>(offset); return(value == 0 ? null : (object)Epoch.AddSeconds(value)); }
/// <summary> /// Converts <see cref="BroTime"/> to a .NET <see cref="DateTime"/>. /// </summary> /// <returns>This <see cref="BroTime"/> as a .NET <see cref="DateTime"/>.</returns> public DateTime ToDateTime() { return(Epoch.AddSeconds(m_value)); }
public DateTime ToDateTime() { return(Epoch.AddSeconds(_seconds)); }
DateTime EpochToDate(uint val) => Epoch.AddSeconds(val);
public static DateTimeOffset FromUnixTime(long time) { return(Epoch.AddSeconds(time)); }