コード例 #1
0
        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);
            }
        }
コード例 #2
0
        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();
        }
コード例 #3
0
ファイル: Minute.cs プロジェクト: w1r2p1/cryptocurrency
        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)
            });
        }
コード例 #4
0
        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);
        }
コード例 #5
0
        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));
        }
コード例 #6
0
        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));
        }
コード例 #7
0
        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));
        }
コード例 #8
0
        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;
            }
        }
コード例 #9
0
        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));
            }
        }
コード例 #10
0
        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));
            }
        }
コード例 #11
0
        /// <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);
            }
        }
コード例 #12
0
        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();
            }
        }
コード例 #13
0
        /// <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);
        }
コード例 #14
0
        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));
        }
コード例 #15
0
ファイル: Helpers.cs プロジェクト: bravesoftdz/tvrename
 public static DateTime FromUnixTime(long unixTime)
 {
     return(Epoch.AddSeconds(unixTime));
 }
コード例 #16
0
 DateTime EpochToDate(uint val)
 {
     return(Epoch.AddSeconds(val));
 }
コード例 #17
0
ファイル: SimpleData.cs プロジェクト: pashav15/pashav
 /// <summary>
 /// Reads the value as a <see cref="DateTime"/>
 /// </summary>
 /// <returns></returns>
 public DateTime ReadDateTime() => Epoch.AddSeconds(ReadValue());
コード例 #18
0
 public static DateTime FromUnixTime(double unixTime) => Epoch.AddSeconds(unixTime);
コード例 #19
0
        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
                });
            }
        }
コード例 #20
0
        internal static DateTime ToDateTime(this ulong unixTimeStamp)
        {
            var dtDateTime = Epoch.AddSeconds(unixTimeStamp);

            return(dtDateTime);
        }
コード例 #21
0
 // convert unix timestamp into a year
 public static DateTime TimestampToDate(int timeStamp) => Epoch.AddSeconds(timeStamp);
コード例 #22
0
 public static Date UnixTimeToDateTime(ulong timestamp) => new Date(Epoch.AddSeconds(timestamp));
コード例 #23
0
ファイル: SecurityToken.cs プロジェクト: Khrove/LowPay
        /// <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
            });
        }
コード例 #24
0
        public static DateTime GetLocalTime(long unixTime)
        {
            var utcTime = Epoch.AddSeconds(Convert.ToDouble(unixTime));

            return(utcTime.ToLocalTime());
        }
コード例 #25
0
 public static DateTime?FromUnixTime(string unixTime)
 {
     return(long.TryParse(unixTime, out long seconds) ? Epoch.AddSeconds(seconds) : default(DateTime?));
 }
コード例 #26
0
        public object?GetValue(IDataSource data, long offset)
        {
            var value = data.Read <uint>(offset);

            return(value == 0 ? null : (object)Epoch.AddSeconds(value));
        }
コード例 #27
0
 /// <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));
 }
コード例 #28
0
ファイル: UnixTimeStamp.cs プロジェクト: bobthemighty/Jwt4Net
 public DateTime ToDateTime()
 {
     return(Epoch.AddSeconds(_seconds));
 }
コード例 #29
0
ファイル: ImageFileHeaderVM.cs プロジェクト: idkwim/dnSpy
 DateTime EpochToDate(uint val) => Epoch.AddSeconds(val);
コード例 #30
0
ファイル: UnixTime.cs プロジェクト: Xperitos/Xperitos.Common
 public static DateTimeOffset FromUnixTime(long time)
 {
     return(Epoch.AddSeconds(time));
 }