Ejemplo n.º 1
0
        public async Task <List <DomainReservation> > QueryReservations(QueryReservationCommand cmd)
        {
            var query = new ReservationQuery();

            if (cmd.UserId.HasValue)
            {
                query.ForOwner(await _users.FindById(cmd.UserId.Value));
            }
            if (cmd.ResourceId.HasValue)
            {
                query.ForResource(await _resources.FindById(cmd.ResourceId.Value));
            }

            query.CollideWith(
                cmd.StartTime.GetValueOrDefault(Instant.FromUnixTimeMilliseconds(0)),
                cmd.EndTime.GetValueOrDefault(Instant.MaxValue)
                );

            if (cmd.StatusList != null && cmd.StatusList.Length > 0)
            {
                query.WithStatuses((await _statuses.All()).Where(st => cmd.StatusList.Contains(st.Status)));
            }

            return((await _reservations.Query(query))
                   .Select(r => _mapper.Map <DomainReservation>(r))
                   .ToList());
        }
Ejemplo n.º 2
0
        public void FromUnixTimeMilliseconds_Valid()
        {
            Instant actual   = Instant.FromUnixTimeMilliseconds(12345L);
            Instant expected = Instant.FromUnixTimeTicks(12345L * NodaConstants.TicksPerMillisecond);

            Assert.AreEqual(expected, actual);
        }
        protected bool SqliteDataToMarkdownModel(SqliteDataReader reader, MarkdownPage page)
        {
            page.Id          = Guid.Parse(reader.GetString(reader.GetOrdinal("id")));
            page.Content     = reader.GetString(reader.GetOrdinal("content"));
            page.Created     = Instant.FromUnixTimeMilliseconds(reader.GetInt64(reader.GetOrdinal("created")));
            page.LastChanged = Instant.FromUnixTimeMilliseconds(reader.GetInt64(reader.GetOrdinal("changed")));
            page.IsLocked    = reader.GetBoolean(reader.GetOrdinal("locked"));

            var link = reader.GetString(reader.GetOrdinal("link"));
            var path = link.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);

            if (path.Length > 1)
            {
                string[] path2 = new string[path.Length - 1];
                Array.Copy(path, path2, path.Length - 1);

                page.Path = Path.of(path2, path[path.Length - 1]);
            }
            else
            {
                page.Path = Path.ofLink(link);
            }

            return(true);
        }
Ejemplo n.º 4
0
            public Data()
            {
                Id = Guid.NewGuid();
                var milliseconds = SystemClock.Instance.GetCurrentInstant().ToUnixTimeMilliseconds();

                Created               = Instant.FromUnixTimeMilliseconds(milliseconds).InZone(provider.GetSystemDefault());
                CreatedDateTime       = Created.LocalDateTime;
                CreatedDate           = CreatedDateTime.Date;
                CreatedTime           = CreatedDateTime.TimeOfDay;
                CreatedOffsetDateTime = Created.ToOffsetDateTime();
                CreatedOffsetTime     = CreatedOffsetDateTime.ToOffsetTime();

                Duration = Duration.FromHours(29.5);

                var b = new PeriodBuilder
                {
                    Years        = 1,
                    Months       = 10,
                    Weeks        = 3,
                    Days         = 4,
                    Hours        = 25,
                    Minutes      = 65,
                    Seconds      = 100,
                    Milliseconds = 4,
                    Nanoseconds  = 3,
                    Ticks        = 3
                };

                Period = b.Build();
            }
Ejemplo n.º 5
0
        public async Task Flush()
        {
            var bucketName = _bucket.Name;

            var writeOptions = WriteOptions.CreateNew().BatchSize(10).FlushInterval(100_000).Build();

            _writeApi = Client.GetWriteApi(writeOptions);
            var listener = new WriteApiTest.EventListener(_writeApi);

            var record = "h2o_feet,location=coyote_creek level\\ water_level=1.0 1";

            _writeApi.WriteRecord(bucketName, _organization.Id, WritePrecision.Ns, record);
            _writeApi.Flush();
            listener.WaitToSuccess();

            var query = await _queryApi.QueryAsync(
                $"from(bucket:\"{bucketName}\") |> range(start: 1970-01-01T00:00:00.000000001Z)",
                _organization.Id);

            Assert.AreEqual(1, query.Count);

            var records = query[0].Records;

            Assert.AreEqual(1, records.Count);
            Assert.AreEqual("h2o_feet", records[0].GetMeasurement());
            Assert.AreEqual(1, records[0].GetValue());
            Assert.AreEqual("level water_level", records[0].GetField());

            var instant = Instant.Add(Instant.FromUnixTimeMilliseconds(0), Duration.FromNanoseconds(1L));

            Assert.AreEqual(instant, records[0].GetTime());
        }
        public IEnumerable <GenericPageHistory> ConvertToHistoryPageModels(SqliteDataReader reader)
        {
            var pages = new List <GenericPageHistory>();

            while (reader.Read())
            {
                var page = new GenericPage();
                if (SqliteDataToPageModel(reader, page))
                {
                    var action = (PageAction)reader.GetInt32(reader.GetOrdinal("action"));

                    var pageHistory = new GenericPageHistory(page)
                    {
                        ValidFrom =
                            Instant.FromUnixTimeMilliseconds(reader.GetInt64(reader.GetOrdinal("valid_from"))),
                        ValidTo = Instant.FromUnixTimeMilliseconds(reader.GetInt64(reader.GetOrdinal("valid_to"))),
                        Action  = (PageAction)reader.GetInt16(reader.GetOrdinal("action"))
                    };

                    pages.Add(pageHistory);
                }
            }

            return(pages);
        }
        public void NullableIntervalRoundTripTest()
        {
            var interval = new Interval(start: Instant.FromJulianDate(0), end: Instant.FromUnixTimeMilliseconds(0));

            Assert.That(interval.HasStart);
            Assert.That(interval.HasEnd);
            RoundTripTest((Interval?)interval);
        }
        public void IntervalWithStartAndEndRoundTripTest()
        {
            var interval = new Interval(start: Instant.FromJulianDate(0), end: Instant.FromUnixTimeMilliseconds(0));

            Assert.That(interval.HasStart);
            Assert.That(interval.HasEnd);
            RoundTripTest(interval);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Converts a Java Date value to a UTC DateTime value
        /// </summary>
        /// <param name="javaDate">The Java date</param>
        /// <returns></returns>
        private static DateTime FromJavaDate(Date javaDate)
        {
            // Convert javaDate to UTC Instant (Epoch)
            var instant = Instant.FromUnixTimeMilliseconds(javaDate.getTime());

            // Convert to .Net UTC DateTime
            return(instant.ToDateTimeUtc());
        }
Ejemplo n.º 10
0
        public void IntervalWithEndRoundTripTest()
        {
            var interval = new Interval(end: Instant.FromUnixTimeMilliseconds(0), start: null);

            Assert.That(!interval.HasStart);
            Assert.That(interval.HasEnd);
            RoundTripTest(interval);
        }
Ejemplo n.º 11
0
        /// <inheritdoc/>
        public override async Task Handle(UpdateDailyOutflow command)
        {
            var root = await _repository.Find <Wallet>(command.Target);

            if (root == null)
            {
                throw new ArgumentNullException(nameof(command.Address));
            }

            var coin = await _repository.Find <Coin>(root.Coin);

            if (coin == null)
            {
                throw new ArgumentNullException(nameof(root.Coin));
            }

            var txResults = await GetTransactions(command);

            if (txResults == null)
            {
                return;
            }

            var outflows = new Dictionary <Instant, (Instant time, double amount)>();

            foreach (var tx in txResults)
            {
                var dateTime = Instant.FromUnixTimeMilliseconds(tx.ReceiveTime).InUtc().LocalDateTime;
                var date     = new LocalDate(dateTime.Year, dateTime.Month, dateTime.Day);
                var instant  = date.AtMidnight().InUtc().ToInstant();
                var amount   = tx.Amount;
                if (tx.To == command.Target)
                {
                    amount *= -1;
                }

                if (outflows.ContainsKey(instant))
                {
                    amount += outflows[instant].amount;
                }
                outflows[instant] = (Instant.FromUnixTimeMilliseconds(tx.ReceiveTime), amount);
            }

            ICommand changeBalanceCommand = null;
            var      idx = 0;

            foreach (var v in outflows)
            {
                changeBalanceCommand = new RetroactiveCommand <ChangeWalletBalance>(new ChangeWalletBalance(command.Address, new Quantity(-v.Value.amount, coin.Asset), $"Out{command.Index}_{idx}"), v.Value.time);
                await _balanceHandler.Handle(changeBalanceCommand);

                ++idx;
            }

            command.EventType = changeBalanceCommand?.EventType;
        }
Ejemplo n.º 12
0
        protected Instant?ExtractTimestampFromFilename(string filename, string regex)
        {
            var match = Regex.Match(filename, regex);

            if (match.Success)
            {
                return(Instant.FromUnixTimeMilliseconds(long.Parse(match.Groups[1].Value)));
            }
            return(null);
        }
        public virtual void SupportsFromFromUnixTimeMilliseconds(TestEntity <long> testEntity)
        {
            AddToDatabase(testEntity);

            var minimum = Instant.FromUnixTimeMilliseconds(testEntity.TestProperty);

            ExecuteWithQueryable <TestEntity <long> >(q =>
            {
                var foundEntities = q.Where(x => Instant.FromUnixTimeMilliseconds(x.TestProperty) == minimum).ToList();
            });
        }
Ejemplo n.º 14
0
        protected Instant?ExtractTimestamp(JToken obj)
        {
            var timestampToken = obj["clientMeta"]?["timestamp"];

            if (timestampToken == null)
            {
                return(null);
            }

            return(Instant.FromUnixTimeMilliseconds(timestampToken.Value <long>()));
        }
Ejemplo n.º 15
0
        public async Task PruneAttendance(IMessage message)
        {
            var zoneId = (await Prompt(message.Author, $"What zone ID? (Hint: {_raidIds.Last().Value})",
                                       message.Channel))?.Content;

            var attendanceReports = (await _attendanceRepo.GetAllAsync()).Where(att => att.ZoneId == zoneId && !att.Excluded);

            var raidGroupings = attendanceReports.GroupBy(r =>
                                                          Instant.FromUnixTimeMilliseconds(r.Timestamp).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))
                                .ToList();

            foreach (var raids in raidGroupings)
            {
                if (raids.Count() > 1)
                {
                    var raidsToMerge = string.Join("\n", raids.Select((r, idx) =>
                                                                      $"[{idx + 1}] {raids.Key} - {r.LogUrl} - {r.Attendees.Count} attendees"));

                    var response = await Prompt(message.Author,
                                                $"Detected possible duplicate reports.\n\n{raidsToMerge}\n" +
                                                "Pick an action: \n`merge`\n`pick <id>`\n`ignore`",
                                                message.Channel, 60000);

                    if (response?.Content == "merge")
                    {
                        var recordToKeep = raids.First();
                        foreach (var recordToExclude in raids.Skip(1))
                        {
                            recordToKeep.Attendees = recordToKeep.Attendees.Concat(recordToExclude.Attendees)
                                                     .Distinct()
                                                     .ToList();

                            recordToExclude.Excluded = true;
                            _attendanceRepo.AddOrEdit(recordToExclude);
                        }

                        _attendanceRepo.AddOrEdit(recordToKeep);
                    }
                    else if (response?.Content.StartsWith("pick ") == true)
                    {
                        var idx          = int.Parse(response.Content.Replace("pick ", "").Trim()) - 1;
                        var recordToKeep = raids.ElementAt(idx);

                        foreach (var recordToExclude in raids.Where(r => r.Id != recordToKeep.Id))
                        {
                            recordToExclude.Excluded = true;
                            _attendanceRepo.AddOrEdit(recordToExclude);
                        }
                    }
                }
            }

            await message.Channel.SendMessageAsync("✅ Attendance pruned.");
        }
Ejemplo n.º 16
0
        private long MidnightTonightInMilliseconds()
        {
            long now = SystemClock.Instance.GetCurrentInstant().ToUnixTimeMilliseconds();

            var nowDateTime = new ZonedDateTime(Instant.FromUnixTimeMilliseconds(now),
                                                DateTimeZoneProviders.Bcl.GetSystemDefault());

            return(new LocalDateTime(nowDateTime.Year, nowDateTime.Month, nowDateTime.Day, 23, 59, 59)
                   .InZoneLeniently(DateTimeZoneProviders.Bcl.GetSystemDefault())
                   .ToInstant()
                   .ToUnixTimeMilliseconds());
        }
Ejemplo n.º 17
0
        public AggregatorSystem.ProcessedContentAdditions Process(RawContentTransferObject contentTransferObject)
        {
            var content = new RawContent(Id: Guid.NewGuid(),
                                         RetrieveTime: Instant.FromUnixTimeMilliseconds(contentTransferObject.RetrieveTime),
                                         Type: contentTransferObject.Type,
                                         Content: contentTransferObject.Content,
                                         Context: contentTransferObject.Context,
                                         SourceUri: contentTransferObject.SourceUri);

            // TODO: error handling...
            return(system.ProcessRawContent(content));
        }
Ejemplo n.º 18
0
        public static UserIdentityModel ToDomainIdentityModel(this UserDbEntity dbEntity)
        {
            var regDate = Instant.FromUnixTimeMilliseconds(dbEntity.RegistrationDate);

            return(new UserIdentityModel(
                       dbEntity.Id,
                       dbEntity.Email,
                       dbEntity.Name,
                       dbEntity.Role,
                       dbEntity.PasswordHash,
                       regDate));
        }
Ejemplo n.º 19
0
        public static UserModel ToDomainModel(this UserDbEntity dbEntity)
        {
            var regDate = Instant.FromUnixTimeMilliseconds(dbEntity.RegistrationDate);

            return(new UserModel
            {
                Id = dbEntity.Id,
                Email = dbEntity.Email,
                Name = dbEntity.Name,
                RegistrationDate = regDate
            });
        }
Ejemplo n.º 20
0
        public void Given_a_valid_Instant_When_WithCreated_is_called_Then_Created_Should_be_set()
        {
            // Arrange.
            IClock          clock   = ConstantClockStub.Create(0);
            BlogPostBuilder builder = BlogPostBuilder.Create(clock);
            Instant         created = Instant.FromUnixTimeMilliseconds(100000);

            // Act.
            builder = builder.WithCreated(created);

            // Assert.
            builder.Created.Should().Be(created);
        }
Ejemplo n.º 21
0
        /// <inheritdoc/>
        public override async Task Handle(UpdateDailyMining command)
        {
            var root = await _repository.Find <Wallet>(command.Target);

            if (root == null)
            {
                throw new ArgumentNullException(nameof(command.Address));
            }

            var coin = await _repository.Find <Coin>(root.Coin);

            if (coin == null)
            {
                throw new ArgumentNullException(nameof(root.Coin));
            }

            var minedBlocks = await GetMinedBlocks(command);

            if (minedBlocks == null)
            {
                return;
            }

            var blocks = new Dictionary <Instant, (Instant time, double amount)>();

            foreach (var block in minedBlocks)
            {
                var dateTime = Instant.FromUnixTimeMilliseconds(block.Timestamp).InUtc().LocalDateTime;
                var date     = new LocalDate(dateTime.Year, dateTime.Month, dateTime.Day);
                var instant  = date.AtMidnight().InUtc().ToInstant();
                var amount   = block.Feereward;
                if (blocks.ContainsKey(instant))
                {
                    amount += blocks[instant].amount;
                }
                blocks[instant] = (Instant.FromUnixTimeMilliseconds(block.Timestamp), amount);
            }

            ICommand mineCommand = null;
            var      idx         = 0;

            foreach (var v in blocks)
            {
                mineCommand = new RetroactiveCommand <MineCoin>(new MineCoin(command.Address, new Quantity(v.Value.amount, coin.Asset), $"Mining{command.Index}_{idx}"), v.Value.time);
                await _mineHandler.Handle(mineCommand);

                ++idx;
            }

            command.EventType = mineCommand?.EventType;
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Returns a new <see cref="Tick"/> from the given <see cref="string"/>.
        /// </summary>
        /// <param name="symbol">The symbol to create the tick with.</param>
        /// <param name="values">The string containing tick values.</param>
        /// <returns>The created <see cref="Tick"/>.</returns>
        public static TradeTick FromSerializableString(Symbol symbol, string values)
        {
            Debug.NotEmptyOrWhiteSpace(values, nameof(values));

            var pieces = values.Split(',', 5);

            return(new TradeTick(
                       symbol,
                       Price.Create(pieces[0]),
                       Quantity.Create(pieces[1]),
                       pieces[2].ToEnum <Maker>(),
                       new MatchId(pieces[3]),
                       Instant.FromUnixTimeMilliseconds(Convert.ToInt64(pieces[4])).InUtc()));
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Returns a new <see cref="Bar"/> from the given <see cref="string"/>.
        /// </summary>
        /// <param name="barString">The bar string.</param>
        /// <returns>The created <see cref="Bar"/>.</returns>
        public static Bar FromSerializableString(string barString)
        {
            Debug.NotEmptyOrWhiteSpace(barString, nameof(barString));

            var values = barString.Split(',', 6);

            return(new Bar(
                       Price.Create(Parser.ToDecimal(values[0])),
                       Price.Create(Parser.ToDecimal(values[1])),
                       Price.Create(Parser.ToDecimal(values[2])),
                       Price.Create(Parser.ToDecimal(values[3])),
                       Quantity.Create(Parser.ToDecimal(values[4])),
                       Instant.FromUnixTimeMilliseconds(Convert.ToInt64(values[5])).InUtc()));
        }
Ejemplo n.º 24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Bar"/> class.
 /// </summary>
 /// <param name="open">The open price.</param>
 /// <param name="high">The high price.</param>
 /// <param name="low">The low price.</param>
 /// <param name="close">The close price.</param>
 /// <param name="volume">The volume.</param>
 /// <param name="unixTimestamp">The unix timestamp in milliseconds.</param>
 public Bar(
     Price open,
     Price high,
     Price low,
     Price close,
     Quantity volume,
     long unixTimestamp)
 {
     this.Open      = open;
     this.High      = high;
     this.Low       = low;
     this.Close     = close;
     this.Volume    = volume;
     this.Timestamp = Instant.FromUnixTimeMilliseconds(unixTimestamp).InUtc();
 }
Ejemplo n.º 25
0
        private AppointmentData UpdateStartEndTimes(AppointmentData input)
        {
            //Update start time and end time in each appointment
            foreach (Appointment appointment in input.data)
            {
                Duration duration  = Duration.FromHours(1);
                Instant  startTime = Instant.FromUnixTimeMilliseconds(Convert.ToInt64(appointment.date));
                Instant  endTime   = startTime + duration;
                var      timeZone  = DateTimeZoneProviders.Tzdb["America/New_York"];
                appointment.startTime = startTime.InZone(timeZone).LocalDateTime.ToString("hh:mm tt", CultureInfo.InvariantCulture);
                appointment.endTime   = endTime.InZone(timeZone).LocalDateTime.ToString("hh:mm tt", CultureInfo.InvariantCulture);
            }

            return(input);
        }
Ejemplo n.º 26
0
        public void UnixConversions_ExtremeValues()
        {
            // Round down to a whole second to make round-tripping work.
            var max = Instant.MaxValue - Duration.FromSeconds(1) + Duration.Epsilon;

            Assert.AreEqual(max, Instant.FromUnixTimeSeconds(max.ToUnixTimeSeconds()));
            Assert.AreEqual(max, Instant.FromUnixTimeMilliseconds(max.ToUnixTimeMilliseconds()));
            Assert.AreEqual(max, Instant.FromUnixTimeTicks(max.ToUnixTimeTicks()));

            var min = Instant.MinValue;

            Assert.AreEqual(min, Instant.FromUnixTimeSeconds(min.ToUnixTimeSeconds()));
            Assert.AreEqual(min, Instant.FromUnixTimeMilliseconds(min.ToUnixTimeMilliseconds()));
            Assert.AreEqual(min, Instant.FromUnixTimeTicks(min.ToUnixTimeTicks()));
        }
Ejemplo n.º 27
0
        public override Instant?Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            BsonType type = context.Reader.GetCurrentBsonType();

            if (type == BsonType.Null)
            {
                context.Reader.ReadNull();
                return(null);
            }
            if (type == BsonType.DateTime)
            {
                return(Instant.FromUnixTimeMilliseconds(context.Reader.ReadDateTime()));
            }
            throw CreateCannotBeDeserializedException();
        }
Ejemplo n.º 28
0
    public JObject ToJson(LookupContext ctx, APIVersion v)
    {
        var o = new JObject();

        o.Add("timestamp", Instant.FromUnixTimeMilliseconds((long)(Message.Mid >> 22) + 1420070400000).ToString());
        o.Add("id", Message.Mid.ToString());
        o.Add("original", Message.OriginalMid.ToString());
        o.Add("sender", Message.Sender.ToString());
        o.Add("channel", Message.Channel.ToString());
        o.Add("guild", Message.Guild?.ToString());
        o.Add("system", System?.ToJson(ctx, v));
        o.Add("member", Member?.ToJson(ctx, v: v));

        return(o);
    }
Ejemplo n.º 29
0
        public OffsetTime Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            var bsonType = context.Reader.GetCurrentBsonType();

            if (bsonType != BsonType.Document)
            {
                throw new InvalidOperationException($"{bsonType} is not a document.");
            }
            context.Reader.ReadStartDocument();
            var dtValue           = context.Reader.ReadDateTime("time");
            var offSetNanoSeconds = context.Reader.ReadInt64("offset");

            context.Reader.ReadEndDocument();

            return(Instant.FromUnixTimeMilliseconds(dtValue).WithOffset(Offset.FromNanoseconds(offSetNanoSeconds)).ToOffsetTime());
        }
        private DateTime GetCurrentPlaybackTime()
        {
            lock (PlaybackLock)
            {
                var now = SystemClock.Instance.GetCurrentInstant();

                if (_anchorTime == 0 && _initiatedTime == 0)
                {
                    return(now.ToDateTimeUtc());
                }

                var     current         = now.ToUnixTimeTicks() / NodaConstants.TicksPerMillisecond;
                long    currentAnchor   = ((long)((current - _initiatedTime) * _scale) + _anchorTime);
                Instant whereWeShouldBe = Instant.FromUnixTimeMilliseconds(currentAnchor);

                return(whereWeShouldBe.ToDateTimeUtc());
            }
        }