Here are the examples of the csharp api System.TimeSpan.FromHours(double) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1233 Examples
19
Source : DiskStationProxyBase.cs
with GNU General Public License v3.0
from bonarr
with GNU General Public License v3.0
from bonarr
private HttpRequestBuilder BuildRequest(DownloadStationSettings settings, DiskStationApiInfo apiInfo, string methodName, int apiVersion, HttpMethod httpVerb = HttpMethod.GET)
{
var requestBuilder = new HttpRequestBuilder(settings.UseSsl, settings.Host, settings.Port).Resource($"webapi/{apiInfo.Path}");
requestBuilder.Method = httpVerb;
requestBuilder.LogResponseContent = true;
requestBuilder.SuppressHttpError = true;
requestBuilder.AllowAutoRedirect = false;
requestBuilder.Headers.ContentType = "application/json";
if (apiVersion < apiInfo.MinVersion || apiVersion > apiInfo.MaxVersion)
{
throw new ArgumentOutOfRangeException(nameof(apiVersion));
}
if (httpVerb == HttpMethod.POST)
{
if (apiInfo.NeedsAuthentication)
{
requestBuilder.AddFormParameter("_sid", _sessionCache.Get(GenerateSessionCacheKey(settings), () => AuthenticateClient(settings), TimeSpan.FromHours(6)));
}
requestBuilder.AddFormParameter("api", apiInfo.Name);
requestBuilder.AddFormParameter("version", apiVersion);
requestBuilder.AddFormParameter("method", methodName);
}
else
{
if (apiInfo.NeedsAuthentication)
{
requestBuilder.AddQueryParam("_sid", _sessionCache.Get(GenerateSessionCacheKey(settings), () => AuthenticateClient(settings), TimeSpan.FromHours(6)));
}
requestBuilder.AddQueryParam("api", apiInfo.Name);
requestBuilder.AddQueryParam("version", apiVersion);
requestBuilder.AddQueryParam("method", methodName);
}
return requestBuilder;
}
19
Source : SharedFolderResolver.cs
with GNU General Public License v3.0
from bonarr
with GNU General Public License v3.0
from bonarr
public OsPath RemapToFullPath(OsPath sharedFolderPath, DownloadStationSettings settings, string serialNumber)
{
var index = sharedFolderPath.FullPath.IndexOf('/', 1);
var sharedFolder = index == -1 ? sharedFolderPath : new OsPath(sharedFolderPath.FullPath.Substring(0, index));
var mapping = _cache.Get($"{serialNumber}:{sharedFolder}", () => GetPhysicalPath(sharedFolder, settings), TimeSpan.FromHours(1));
var fullPath = mapping.PhysicalPath + (sharedFolderPath - mapping.SharedFolder);
return fullPath;
}
19
Source : IndexerStatusCheck.cs
with GNU General Public License v3.0
from bonarr
with GNU General Public License v3.0
from bonarr
public override HealthCheck Check()
{
var enabledIndexers = _indexerFactory.GetAvailableProviders();
var backOffIndexers = enabledIndexers.Join(_indexerStatusService.GetBlockedIndexers(),
i => i.Definition.Id,
s => s.IndexerId,
(i, s) => new { Indexer = i, Status = s })
.Where(v => (v.Status.MostRecentFailure - v.Status.InitialFailure) > TimeSpan.FromHours(1))
.ToList();
if (backOffIndexers.Empty())
{
return new HealthCheck(GetType());
}
if (backOffIndexers.Count == enabledIndexers.Count)
{
return new HealthCheck(GetType(), HealthCheckResult.Error, "All indexers are unavailable due to failures", "#indexers-are-unavailable-due-to-failures");
}
return new HealthCheck(GetType(), HealthCheckResult.Warning, string.Format("Indexers unavailable due to failures: {0}", string.Join(", ", backOffIndexers.Select(v => v.Indexer.Definition.Name))), "#indexers-are-unavailable-due-to-failures");
}
19
Source : XbmcService.cs
with GNU General Public License v3.0
from bonarr
with GNU General Public License v3.0
from bonarr
private XbmcVersion GetJsonVersion(XbmcSettings settings)
{
return _xbmcVersionCache.Get(settings.Address, () =>
{
var response = _proxy.GetJsonVersion(settings);
_logger.Debug("Getting version from response: " + response);
var result = Json.Deserialize<XbmcJsonResult<JObject>>(response);
var versionObject = result.Result.Property("version");
if (versionObject.Value.Type == JTokenType.Integer)
{
return new XbmcVersion((int)versionObject.Value);
}
if (versionObject.Value.Type == JTokenType.Object)
{
return Json.Deserialize<XbmcVersion>(versionObject.Value.ToString());
}
throw new InvalidCastException("Unknown Version structure!: " + versionObject);
}, TimeSpan.FromHours(12));
}
19
Source : PlexServerService.cs
with GNU General Public License v3.0
from bonarr
with GNU General Public License v3.0
from bonarr
public void UpdateLibrary(Series series, PlexServerSettings settings)
{
try
{
_logger.Debug("Sending Update Request to Plex Server");
var version = _versionCache.Get(settings.Host, () => GetVersion(settings), TimeSpan.FromHours(2));
ValidateVersion(version);
var sections = GetSections(settings);
var partialUpdates = _partialUpdateCache.Get(settings.Host, () => PartialUpdatesAllowed(settings, version), TimeSpan.FromHours(2));
if (partialUpdates)
{
UpdatePartialSection(series, sections, settings);
}
else
{
sections.ForEach(s => UpdateSection(s.Id, settings));
}
}
catch(Exception ex)
{
_logger.Warn(ex, "Failed to Update Plex host: " + settings.Host);
throw;
}
}
19
Source : PlexServerService.cs
with GNU General Public License v3.0
from bonarr
with GNU General Public License v3.0
from bonarr
public void UpdateMovieSections(Movie movie, PlexServerSettings settings)
{
try
{
_logger.Debug("Sending Update Request to Plex Server");
var version = _versionCache.Get(settings.Host, () => GetVersion(settings), TimeSpan.FromHours(2));
ValidateVersion(version);
var sections = GetSections(settings);
var partialUpdates = _partialUpdateCache.Get(settings.Host, () => PartialUpdatesAllowed(settings, version), TimeSpan.FromHours(2));
// TODO: Investiate partial updates later, for now just update all movie sections...
//if (partialUpdates)
//{
// UpdatePartialSection(series, sections, settings);
//}
//else
//{
sections.ForEach(s => UpdateSection(s.Id, settings));
//}
}
catch (Exception ex)
{
_logger.Warn(ex, "Failed to Update Plex host: " + settings.Host);
throw;
}
}
19
Source : SagaHandlerTests.cs
with MIT License
from BookBeat
with MIT License
from BookBeat
[Test]
public async Task Initialize_should_start_new_saga_when_start_message_is_received()
{
//arrange
var id = "something-unique";
var store = new Mock<ISagaStore>();
var saga = new TestSaga();
var startMessage = new TestSagaStartMessage(id);
var handler = new SagaHandler<TestSagaData, TestSagaStartMessage>(store.Object, saga, startMessage);
//act
await handler.Initialize();
//replacedert
store.Verify(x => x.Create(saga.ParreplacedionKey, id, It.IsAny<TestSagaData>(), TimeSpan.FromHours(1)), Times.Once);
}
19
Source : SagaMiddlewareTests.cs
with MIT License
from BookBeat
with MIT License
from BookBeat
[Test]
public async Task Should_complete_message_if_saga_already_is_started()
{
//arrange
var parreplacedionKey = "a";
var id = "b";
var sagaStore = new Mock<ISagaStore>();
sagaStore.Setup(x => x.Create<SagaData>(parreplacedionKey, id, It.IsAny<SagaData>(), TimeSpan.FromHours(1))).ThrowsAsync(new SagaAlreadyStartedException(parreplacedionKey, id));
var di = new Mock<IDependencyInjection>();
di.Setup(x => x.GetInstance<IProcessMessage<SagaStartMessage>>(typeof(IProcessCommand<SagaStartMessage, Settings>))).Returns(new Saga());
var hostConfiguration = new Mock<IHostConfiguration>();
hostConfiguration.Setup(x => x.Log).Returns(Mock.Of<ILog>());
hostConfiguration.Setup(x => x.DependencyInjection).Returns(di.Object); // TODO: setup dependency injection
var messageStateHandler = new Mock<IMessageStateHandler<SagaStartMessage>>();
messageStateHandler.Setup(x => x.MessageScope).Returns(di.Object);
var pipelineInformation = new Mock<IPipelineInformation>();
pipelineInformation.Setup(x => x.HostConfiguration).Returns(hostConfiguration.Object);
pipelineInformation.Setup(x => x.ProcessorInterfaceType).Returns(typeof(IProcessCommand<SagaStartMessage, Settings>));
var middleware = new SagaMiddleware(sagaStore.Object);
//act
await middleware.ProcessAsync(messageStateHandler.Object, pipelineInformation.Object, null, CancellationToken.None);
//replacedert
messageStateHandler.Verify(x => x.CompleteAsync(), Times.Once);
}
19
Source : SagaMiddlewareTests.cs
with MIT License
from BookBeat
with MIT License
from BookBeat
[Test]
public async Task If_Saga_implements_ISagaDuplicateDetected_then_ProcessDuplicateAsync_should_be_called_and_should_complete_message_if_saga_already_is_started()
{
//arrange
var parreplacedionKey = "a";
var id = "b";
var sagaStore = new Mock<ISagaStore>();
sagaStore.Setup(x => x.Create<SagaData>(parreplacedionKey, id, It.IsAny<SagaData>(), TimeSpan.FromHours(1))).ThrowsAsync(new SagaAlreadyStartedException(parreplacedionKey, id));
var di = new Mock<IDependencyInjection>();
var countable = new Mock<ICountable>();
di.Setup(x => x.GetInstance<IProcessMessage<SagaStartMessage>>(typeof(IProcessCommand<SagaStartMessage, Settings>))).Returns(new SagaDuplicateWithDuplicate(countable.Object));
var hostConfiguration = new Mock<IHostConfiguration>();
hostConfiguration.Setup(x => x.Log).Returns(Mock.Of<ILog>());
hostConfiguration.Setup(x => x.DependencyInjection).Returns(di.Object); // TODO: setup dependency injection
var messageStateHandler = new Mock<IMessageStateHandler<SagaStartMessage>>();
messageStateHandler.Setup(x => x.MessageScope).Returns(di.Object);
var pipelineInformation = new Mock<IPipelineInformation>();
pipelineInformation.Setup(x => x.HostConfiguration).Returns(hostConfiguration.Object);
pipelineInformation.Setup(x => x.ProcessorInterfaceType).Returns(typeof(IProcessCommand<SagaStartMessage, Settings>));
var middleware = new SagaMiddleware(sagaStore.Object);
//act
await middleware.ProcessAsync(messageStateHandler.Object, pipelineInformation.Object, null, CancellationToken.None);
//replacedert
countable.Verify(x=> x.Count(), Times.Once);
messageStateHandler.Verify(x => x.CompleteAsync(), Times.Once);
}
19
Source : SagaMiddlewareTests.cs
with MIT License
from BookBeat
with MIT License
from BookBeat
[Test]
public void If_Saga_implements_ISagaDuplicateDetected_then_ProcessDuplicateAsync_throws_then_Exception_should_be_thrown()
{
//arrange
var parreplacedionKey = "a";
var id = "b";
var sagaStore = new Mock<ISagaStore>();
sagaStore.Setup(x => x.Create<SagaData>(parreplacedionKey, id, It.IsAny<SagaData>(), TimeSpan.FromHours(1))).ThrowsAsync(new SagaAlreadyStartedException(parreplacedionKey, id));
var di = new Mock<IDependencyInjection>();
var countable = new Mock<ICountable>();
di.Setup(x => x.GetInstance<IProcessMessage<SagaStartMessage>>(typeof(IProcessCommand<SagaStartMessage, Settings>))).Returns(new SagaDuplicateWithDuplicate(countable.Object, true));
var hostConfiguration = new Mock<IHostConfiguration>();
hostConfiguration.Setup(x => x.Log).Returns(Mock.Of<ILog>());
hostConfiguration.Setup(x => x.DependencyInjection).Returns(di.Object); // TODO: setup dependency injection
var messageStateHandler = new Mock<IMessageStateHandler<SagaStartMessage>>();
messageStateHandler.Setup(x => x.MessageScope).Returns(di.Object);
var pipelineInformation = new Mock<IPipelineInformation>();
pipelineInformation.Setup(x => x.HostConfiguration).Returns(hostConfiguration.Object);
pipelineInformation.Setup(x => x.ProcessorInterfaceType).Returns(typeof(IProcessCommand<SagaStartMessage, Settings>));
var middleware = new SagaMiddleware(sagaStore.Object);
//act
middleware.Awaiting(x=> x.ProcessAsync(messageStateHandler.Object, pipelineInformation.Object, null, CancellationToken.None))
.Should().Throw<ApplicationException>();
//replacedert
countable.Verify(x=> x.Count(), Times.Once);
messageStateHandler.Verify(x => x.CompleteAsync(), Times.Never);
}
19
Source : SagaMiddlewareTests.cs
with MIT License
from BookBeat
with MIT License
from BookBeat
[Test]
public async Task Should_load_sagadata_and_call_next_when_success()
{
//arrange
var parreplacedionKey = "a";
var id = "b";
var sagaStore = new Mock<ISagaStore>();
sagaStore.Setup(x => x.Create(parreplacedionKey, id, It.IsAny<SagaData>(), TimeSpan.FromHours(1))).ReturnsAsync(new SagaData{Data = "loaded"});
var saga = new Saga();
var di = new Mock<IDependencyInjection>();
di.Setup(x => x.GetInstance<IProcessMessage<SagaStartMessage>>(typeof(IProcessCommand<SagaStartMessage, Settings>))).Returns(saga);
var hostConfiguration = new Mock<IHostConfiguration>();
hostConfiguration.Setup(x => x.Log).Returns(Mock.Of<ILog>());
hostConfiguration.Setup(x => x.DependencyInjection).Returns(di.Object);
var messageStateHandler = new Mock<IMessageStateHandler<SagaStartMessage>>();
messageStateHandler.Setup(x => x.MessageScope).Returns(di.Object);
var pipelineInformation = new Mock<IPipelineInformation>();
pipelineInformation.Setup(x => x.HostConfiguration).Returns(hostConfiguration.Object);
pipelineInformation.Setup(x => x.ProcessorInterfaceType).Returns(typeof(IProcessCommand<SagaStartMessage, Settings>));
var next = new Mock<IMessageProcessor>();
var middleware = new SagaMiddleware(sagaStore.Object);
//act
await middleware.ProcessAsync(messageStateHandler.Object, pipelineInformation.Object, next.Object, CancellationToken.None);
//replacedert
next.Verify(x=> x.ProcessAsync(messageStateHandler.Object, CancellationToken.None), Times.Once);
saga.Data.Data.Should().Be("loaded");
}
19
Source : NetworkInterfaceViewModel.cs
with GNU General Public License v3.0
from BornToBeRoot
with GNU General Public License v3.0
from BornToBeRoot
private void InitialBandwidthChart()
{
var dayConfig = Mappers.Xy<LvlChartsDefaultInfo>()
.X(dayModel => (double)dayModel.DateTime.Ticks / TimeSpan.FromHours(1).Ticks)
.Y(dayModel => dayModel.Value);
Series = new SeriesCollection(dayConfig)
{
new LineSeries
{
replacedle = "Download",
Values = new ChartValues<LvlChartsDefaultInfo>(),
PointGeometry = null
},
new LineSeries
{
replacedle = "Upload",
Values = new ChartValues<LvlChartsDefaultInfo>(),
PointGeometry = null
}
};
FormatterDate = value => new DateTime((long)(value * TimeSpan.FromHours(1).Ticks)).ToString("hh:mm:ss");
FormatterSpeed = value => $"{FileSizeConverter.GetBytesReadable((long)value * 8)}it/s";
}
19
Source : PingMonitorViewModel.cs
with GNU General Public License v3.0
from BornToBeRoot
with GNU General Public License v3.0
from BornToBeRoot
private void InitialTimeChart()
{
var dayConfig = Mappers.Xy<LvlChartsDefaultInfo>()
.X(dayModel => (double)dayModel.DateTime.Ticks / TimeSpan.FromHours(1).Ticks)
.Y(dayModel => dayModel.Value);
Series = new SeriesCollection(dayConfig)
{
new LineSeries
{
replacedle = "Time",
Values = new ChartValues<LvlChartsDefaultInfo>(),
PointGeometry = null
}
};
FormatterDate = value => new DateTime((long)(value * TimeSpan.FromHours(1).Ticks)).ToString("hh:mm:ss");
FormatterPingTime = value => $"{value} ms";
}
19
Source : LocalTimeProviderTest.cs
with Apache License 2.0
from bosima
with Apache License 2.0
from bosima
[DataTestMethod]
public async Task TestGetCurrentUtcTimeAsync()
{
var currentUtcTime = await GetTimeProvider().GetCurrentUtcTimeAsync();
replacedert.AreEqual(true, currentUtcTime.Offset == TimeSpan.FromHours(0));
replacedert.AreEqual(true, currentUtcTime <= DateTimeOffset.UtcNow);
}
19
Source : RedisTimeProviderTest.cs
with Apache License 2.0
from bosima
with Apache License 2.0
from bosima
[DataTestMethod]
public async Task TestGetCurrentUtcTimeAsync()
{
var currentUtcTime = await GetTimeProvider().GetCurrentUtcTimeAsync();
replacedert.AreEqual(true, currentUtcTime.Offset == TimeSpan.FromHours(0));
replacedert.AreEqual(true, currentUtcTime.Year >= 2021);
}
19
Source : FluentTimeSpanExtensions.cs
with Apache License 2.0
from BoundfoxStudios
with Apache License 2.0
from BoundfoxStudios
public static TimeSpan Hours(this int hours)
{
return TimeSpan.FromHours(hours);
}
19
Source : FluentTimeSpanExtensions.cs
with Apache License 2.0
from BoundfoxStudios
with Apache License 2.0
from BoundfoxStudios
public static TimeSpan Hours(this double hours)
{
return TimeSpan.FromHours(hours);
}
19
Source : FluentTimeSpanExtensions.cs
with Apache License 2.0
from BoundfoxStudios
with Apache License 2.0
from BoundfoxStudios
public static TimeSpan Hours(this int hours, TimeSpan offset)
{
return TimeSpan.FromHours(hours).Add(offset);
}
19
Source : TumbleBitManager.cs
with MIT License
from BreezeHub
with MIT License
from BreezeHub
private static string TimeSpanInWordFormat(decimal fromHours)
{
if (fromHours == 0)
return "N/A";
var timeSpan = TimeSpan.FromHours((double)fromHours);
var days = timeSpan.Days.ToString();
var hours = timeSpan.Hours.ToString();
var formattedTimeSpan = string.Empty;
if (timeSpan.Days > 0)
{
formattedTimeSpan = $"{days} days";
if (timeSpan.Hours > 0)
formattedTimeSpan += $", and {hours} hours";
}
else
{
if (timeSpan.Hours > 0)
formattedTimeSpan = $"{hours} hours";
}
return formattedTimeSpan;
}
19
Source : PuzzleProtocolsTests.cs
with MIT License
from BreezeHub
with MIT License
from BreezeHub
[Fact]
public void CanCalculateStandardPhases()
{
StandardCycles cycles = new StandardCycles(Network.Main.Consensus, true);
replacedert.NotNull(cycles.GetStandardCycle("shorty"));
cycles = new StandardCycles(Network.Main.Consensus, false);
replacedert.Null(cycles.GetStandardCycle("shorty"));
var kotori = cycles.GetStandardCycle("kotori");
replacedert.Equal(Money.Coins(1), kotori.Denomination);
replacedert.Equal(TimeSpan.FromHours(4), kotori.GetLength(false));
replacedert.Equal(TimeSpan.FromHours(19.5), kotori.GetLength(true));
replacedert.Equal(Money.Coins(6), kotori.CoinsPerDay());
}
19
Source : StoryModel.cs
with MIT License
from brminnick
with MIT License
from brminnick
static string GetAgeOfStory(in DateTimeOffset storyCreatedAt)
{
var timespanSinceStoryCreated = DateTimeOffset.UtcNow - storyCreatedAt;
return timespanSinceStoryCreated switch
{
TimeSpan storyAge when storyAge < TimeSpan.FromHours(1) => $"{Math.Ceiling(timespanSinceStoryCreated.TotalMinutes)} minutes",
TimeSpan storyAge when storyAge >= TimeSpan.FromHours(1) && storyAge < TimeSpan.FromHours(2) => $"{Math.Floor(timespanSinceStoryCreated.TotalHours)} hour",
TimeSpan storyAge when storyAge >= TimeSpan.FromHours(2) && storyAge < TimeSpan.FromHours(24) => $"{Math.Floor(timespanSinceStoryCreated.TotalHours)} hours",
TimeSpan storyAge when storyAge >= TimeSpan.FromHours(24) && storyAge < TimeSpan.FromHours(48) => $"{Math.Floor(timespanSinceStoryCreated.TotalDays)} day",
TimeSpan storyAge when storyAge >= TimeSpan.FromHours(48) => $"{Math.Floor(timespanSinceStoryCreated.TotalDays)} days",
_ => string.Empty,
};
19
Source : BackgroundFetchService.cs
with MIT License
from brminnick
with MIT License
from brminnick
async Task<IReadOnlyList<Repository>> GetTrendingRepositories(CancellationToken cancellationToken)
{
if (!_gitHubUserService.IsDemoUser && !string.IsNullOrEmpty(_gitHubUserService.Alias))
{
var repositoriesFromDatabase = await _repositoryDatabase.GetRepositories().ConfigureAwait(false);
IReadOnlyList<string> favoriteRepositoryUrls = repositoriesFromDatabase.Where(x => x.IsFavorite is true).Select(x => x.Url).ToList();
var retrievedRepositoryList = new List<Repository>();
await foreach (var repository in _gitHubGraphQLApiService.GetRepositories(_gitHubUserService.Alias, cancellationToken).ConfigureAwait(false))
{
if (favoriteRepositoryUrls.Contains(repository.Url))
retrievedRepositoryList.Add(repository with { IsFavorite = true });
else
retrievedRepositoryList.Add(repository);
}
var retrievedRepositoryList_NoDuplicatesNoForks = RepositoryService.RemoveForksAndDuplicates(retrievedRepositoryList);
IReadOnlyList<Repository> repositoriesToUpdate = repositoriesFromDatabase.Where(x => _gitHubUserService.ShouldIncludeOrganizations || x.OwnerLogin == _gitHubUserService.Alias) // Only include organization repositories if `ShouldIncludeOrganizations` is true
.Where(x => x.DataDownloadedAt < DateTimeOffset.Now.Subtract(TimeSpan.FromHours(12))) // Cached repositories that haven't been updated in 12 hours
.Concat(retrievedRepositoryList_NoDuplicatesNoForks) // Add downloaded repositories
.GroupBy(x => x.Name).Select(x => x.FirstOrDefault(x => x.ContainsTrafficData) ?? x.First()).ToList(); // Remove duplicate repositories
var trendingRepositories = new List<Repository>();
await foreach (var retrievedRepositoryWithViewsAndClonesData in _gitHubApiRepositoriesService.UpdateRepositoriesWithViewsClonesAndStarsData(repositoriesToUpdate, cancellationToken).ConfigureAwait(false))
{
try
{
await _repositoryDatabase.SaveRepository(retrievedRepositoryWithViewsAndClonesData).ConfigureAwait(false);
}
catch (Exception e)
{
_replacedyticsService.Report(e);
}
if (retrievedRepositoryWithViewsAndClonesData.IsTrending)
trendingRepositories.Add(retrievedRepositoryWithViewsAndClonesData);
}
return trendingRepositories;
}
return Array.Empty<Repository>();
}
19
Source : RepositoryViewModel.cs
with MIT License
from brminnick
with MIT License
from brminnick
async Task ExecutePullToRefreshCommand(string repositoryOwner)
{
HttpResponseMessage? finalResponse = null;
IReadOnlyList<Repository>? repositoriesFromDatabase = null;
var cancellationTokenSource = new CancellationTokenSource();
GitHubAuthenticationService.LoggedOut += HandleLoggedOut;
GitHubAuthenticationService.AuthorizeSessionStarted += HandleAuthorizeSessionStarted;
GitHubUserService.ShouldIncludeOrganizationsChanged += HandleShouldIncludeOrganizationsChanged;
replacedyticsService.Track("Refresh Triggered", "Sorting Option", _mobileSortingService.CurrentOption.ToString());
var repositoriesFromDatabaseTask = _repositoryDatabase.GetRepositories();
try
{
const int minimumBatchCount = 100;
var favoriteRepositoryUrls = await _repositoryDatabase.GetFavoritesUrls().ConfigureAwait(false);
var repositoryList = new List<Repository>();
await foreach (var repository in _gitHubGraphQLApiService.GetRepositories(repositoryOwner, cancellationTokenSource.Token).ConfigureAwait(false))
{
if (favoriteRepositoryUrls.Contains(repository.Url))
repositoryList.Add(repository with { IsFavorite = true });
else
repositoryList.Add(repository);
//Batch the VisibleRepositoryList Updates to avoid overworking the UI Thread
if (!_gitHubUserService.IsDemoUser && repositoryList.Count > minimumBatchCount)
{
//Only display the first update to avoid unncessary work on the UIThread
var shouldUpdateVisibleRepositoryList = !VisibleRepositoryList.Any() || repositoryList.Count >= minimumBatchCount;
AddRepositoriesToCollection(repositoryList, _searchBarText, shouldUpdateVisibleRepositoryList);
repositoryList.Clear();
}
}
//Add Remaining Repositories to _repositoryList
AddRepositoriesToCollection(repositoryList, _searchBarText);
repositoriesFromDatabase = await repositoriesFromDatabaseTask.ConfigureAwait(false);
IReadOnlyList<Repository> repositoriesToUpdate = repositoriesFromDatabase.Where(x => _gitHubUserService.ShouldIncludeOrganizations || x.OwnerLogin == _gitHubUserService.Alias) // Only include organization repositories if `ShouldIncludeOrganizations` is true
.Where(x => x.DataDownloadedAt < DateTimeOffset.Now.Subtract(TimeSpan.FromHours(12))) // Cached repositories that haven't been updated in 12 hours
.Concat(_repositoryList) // Add downloaded repositories
.OrderByDescending(x => x.DataDownloadedAt) // Ensure the newest data is ordered first
.GroupBy(x => x.Name).Select(x => x.FirstOrDefault(x => x.ContainsTrafficData) ?? x.First()).ToList(); // Remove duplicate repositories, selecting the First repository to ensure the Repository newest data is selected because the First repository has the newest data thanks to `OrderByDescending(x => x.DataDownloadedAt)`
var completedRepositories = new List<Repository>();
await foreach (var retrievedRepositoryWithViewsAndClonesData in _gitHubApiRepositoriesService.UpdateRepositoriesWithViewsClonesAndStarsData(repositoriesToUpdate, cancellationTokenSource.Token).ConfigureAwait(false))
{
completedRepositories.Add(retrievedRepositoryWithViewsAndClonesData);
//Batch the VisibleRepositoryList Updates to avoid overworking the UI Thread
if (!_gitHubUserService.IsDemoUser && completedRepositories.Count > minimumBatchCount)
{
AddRepositoriesToCollection(completedRepositories, _searchBarText);
completedRepositories.Clear();
}
}
//Add Remaining Repositories to VisibleRepositoryList
AddRepositoriesToCollection(completedRepositories, _searchBarText);
if (!_gitHubUserService.IsDemoUser)
{
//Rate Limiting may cause some data to not return successfully from the GitHub API
var missingRepositories = _gitHubUserService.ShouldIncludeOrganizations switch
{
true => getDistictRepositories(_repositoryList, repositoriesFromDatabase, x => x.ContainsTrafficData),
false => getDistictRepositories(_repositoryList, repositoriesFromDatabase, x => x.ContainsTrafficData && x.OwnerLogin == _gitHubUserService.Alias)
};
AddRepositoriesToCollection(missingRepositories, _searchBarText);
//Call EnsureSuccessStatusCode to confirm the above API calls executed successfully
finalResponse = await _gitHubApiV3Service.GetGitHubApiResponse(cancellationTokenSource.Token).ConfigureAwait(false);
finalResponse.EnsureSuccessStatusCode();
}
RefreshState = RefreshState.Succeeded;
}
19
Source : StoryModel.cs
with MIT License
from brminnick
with MIT License
from brminnick
static string GetAgeOfStory(DateTimeOffset storyCreatedAt)
{
var timespanSinceStoryCreated = DateTimeOffset.UtcNow - storyCreatedAt;
return timespanSinceStoryCreated switch
{
TimeSpan storyAge when storyAge < TimeSpan.FromHours(1) => $"{Math.Ceiling(timespanSinceStoryCreated.TotalMinutes)} minutes",
TimeSpan storyAge when storyAge >= TimeSpan.FromHours(1) && storyAge < TimeSpan.FromHours(2) => $"{Math.Floor(timespanSinceStoryCreated.TotalHours)} hour",
TimeSpan storyAge when storyAge >= TimeSpan.FromHours(2) && storyAge < TimeSpan.FromHours(24) => $"{Math.Floor(timespanSinceStoryCreated.TotalHours)} hours",
TimeSpan storyAge when storyAge >= TimeSpan.FromHours(24) && storyAge < TimeSpan.FromHours(48) => $"{Math.Floor(timespanSinceStoryCreated.TotalDays)} day",
TimeSpan storyAge when storyAge >= TimeSpan.FromHours(48) => $"{Math.Floor(timespanSinceStoryCreated.TotalDays)} days",
_ => string.Empty,
};
19
Source : TextResultsListViewModel.cs
with MIT License
from brminnick
with MIT License
from brminnick
async Task UpdateTextResultsListFromRemoteDatabase()
{
try
{
var textMoodList = await TextResultsService.GetTextModels();
var recentTextMoodList = TextMoodModelServices.GetRecentTextModels(new List<ITextMoodModel>(textMoodList), TimeSpan.FromHours(1));
TextList.Clear();
foreach (var textMoodModel in recentTextMoodList.OrderByDescending(x => x.CreatedAt))
TextList.Add(textMoodModel);
}
catch (Exception e)
{
DebugServices.Report(e);
OnErrorTriggered(e.InnerException?.Message ?? e.Message);
}
}
19
Source : GivenATaskScheduler.cs
with MIT License
from brthor
with MIT License
from brthor
[Fact]
public async Task ItExecutesAScheduledTaskAtTheSpecifiedDateTimeOffsetOnlyOnce()
{
Func<string, TaskScheduler, Task> configureSchedulerAction = async (semapreplacedFile, taskScheduler) =>
{
await taskScheduler.AddScheduledTask(() => TaskQueueTestFixture.WriteSemapreplaced(semapreplacedFile),
new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(IntervalSeconds), TimeSpan.FromHours(0)));
};
await TaskSchedulerTestHelpers.replacedertTaskSchedulerWritesSemapreplacedOnlyOnce(
IntervalSeconds,
configureSchedulerAction);
}
19
Source : TaskQueueConfiguration.cs
with MIT License
from brthor
with MIT License
from brthor
public static TaskQueueConfiguration Default()
{
return new TaskQueueConfiguration
{
QueueName = "Gofer.NET.Default",
ThreadSafe = true,
MessageRetryTimeSpan = TimeSpan.FromHours(1),
BatchSize = 20
};
}
19
Source : MemoryCacheService.cs
with MIT License
from brunohbrito
with MIT License
from brunohbrito
public void Set<T>(string key, T value, TimeSpan? ttl = null)
{
_memoryCache.Set(key, value, ttl ?? TimeSpan.FromHours(1));
}
19
Source : ViewModel.cs
with MIT License
from bstollnitz
with MIT License
from bstollnitz
private void UpdateIsInternetConnected()
{
ConnectionProfile connectionProfile = NetworkInformation.GetInternetConnectionProfile();
if (connectionProfile != null)
{
ConnectionName = connectionProfile.ProfileName;
ConnectionCost = connectionProfile.GetConnectionCost();
DataUsage = connectionProfile.GetLocalUsage(DateTimeOffset.Now - TimeSpan.FromHours(24), DateTimeOffset.Now);
switch (connectionProfile.GetNetworkConnectivityLevel())
{
case NetworkConnectivityLevel.None:
ConnectionStatus = "None";
break;
case NetworkConnectivityLevel.LocalAccess:
ConnectionStatus = "Local access";
break;
case NetworkConnectivityLevel.ConstrainedInternetAccess:
ConnectionStatus = "Constrained internet access";
break;
case NetworkConnectivityLevel.InternetAccess:
ConnectionStatus = "Internet access";
break;
}
}
else
{
ConnectionName = "None";
ConnectionStatus = "None";
ConnectionCost = null;
DataUsage = null;
}
}
19
Source : JudgerCoordinatorService.cs
with MIT License
from BUAA-SE-Compiling
with MIT License
from BUAA-SE-Compiling
protected async ValueTask<bool> DispatchJob(Judger judger, Job job) {
var redis = await this.redis.GetDatabase();
await redis.StringSetAsync(FormatJobStdout(job.Id), "", expiry: TimeSpan.FromHours(2), flags: CommandFlags.FireAndForget);
await redis.StringSetAsync(FormatJobError(job.Id), "", expiry: TimeSpan.FromHours(2), flags: CommandFlags.FireAndForget);
try {
await judger.Socket.SendMessage(new MultipleNewJobServerMsg() {
Jobs = new List<Job> { job },
ReplyTo = null
});
job.Judger = judger.Id;
job.Stage = JobStage.Dispatched;
job.DispatchTime = DateTimeOffset.Now;
return true;
} catch { return false; }
}
19
Source : JudgerCoordinatorService.cs
with MIT License
from BUAA-SE-Compiling
with MIT License
from BUAA-SE-Compiling
protected async ValueTask<bool> DispatchJobs(
Judger judger,
List<Job> jobs,
FlowSnake? replyTo = null) {
var redis = await this.redis.GetDatabase();
try {
await judger.Socket.SendMessage(new MultipleNewJobServerMsg() {
Jobs = jobs,
ReplyTo = replyTo
});
foreach (var job in jobs) {
await redis.StringSetAsync(FormatJobStdout(job.Id), "", expiry: TimeSpan.FromHours(2), flags: CommandFlags.FireAndForget);
await redis.StringSetAsync(FormatJobError(job.Id), "", expiry: TimeSpan.FromHours(2), flags: CommandFlags.FireAndForget);
job.Judger = judger.Id;
job.Stage = JobStage.Dispatched;
job.DispatchTime = DateTimeOffset.Now;
}
return true;
} catch { return false; }
}
19
Source : TimeSpanExtensions.cs
with Apache License 2.0
from busterwood
with Apache License 2.0
from busterwood
public static string ToHuman(this TimeSpan time)
{
if (time == TimeSpan.Zero)
return "0 ms";
if (time < TimeSpan.FromMilliseconds(1))
return time.TotalMilliseconds.ToString("N1") + " ms";
if (time < TimeSpan.FromSeconds(1))
return time.TotalMilliseconds.ToString("N0") + " ms";
if (time <= TimeSpan.FromSeconds(10))
return time.TotalSeconds.ToString("N1") + " s";
if (time < TimeSpan.FromHours(1))
return time.TotalMinutes.ToString("N1") + " min";
if (time < TimeSpan.FromDays(1))
return time.TotalHours.ToString("N1") + " hours";
if (time < TimeSpan.FromDays(365))
return time.TotalDays.ToString("N1") + " days";
return (time.TotalDays / 365.0d).ToString("N1") + " years";
}
19
Source : Startup.cs
with MIT License
from cajuncoding
with MIT License
from cajuncoding
public override void Configure(IFunctionsHostBuilder builder)
{
string sqlConnectionString = Environment.GetEnvironmentVariable("SqlConnectionString");
//RepoDb Bootstrapper for Sql Server
RepoDb.SqlServerBootstrap.Initialize();
var services = builder.Services;
// Add the custom services like repositories etc ...
services.AddTransient<ICharacterRepository, CharacterRepository>(c => new CharacterRepository(sqlConnectionString));
services.AddSingleton<IReviewRepository, ReviewRepository>();
// Add GraphQL Services
//Updated to Initialize StarWars with new v11 configuration...
services
.AddGraphQLServer()
.AddQueryType(d => d.Name("Query"))
.AddMutationType(d => d.Name("Mutation"))
//Disabled Subscriptions for v11 and Azure Functions Example due to
// supportability in Server-less architecture...
//.AddSubscriptionType(d => d.Name("Subscription"))
.AddType<CharacterQueries>()
.AddType<ReviewQueries>()
.AddType<ReviewMutations>()
//Disabled Subscriptions for v11 and Azure Functions Example due to
// supportability in Serverless architecture...
//.AddType<ReviewSubscriptions>()
.AddType<Human>()
.AddType<HumanFieldResolvers>()
.AddType<Droid>()
.AddType<Starship>()
//*******************************************************************************************
//*******************************************************************************************
//Enable extensions for Pre-Processed Results!
//NOTE This allows all OOTB behaviors except for when we want to control the processing
// of results for sorting, paging, etc. and do not want redundant post-processing to occur
// by HotChocolate internals...
//NOTE: This Adds Sorting & Paging providers/conventions by default!
.SetPagingOptions(new PagingOptions()
{
DefaultPageSize = 2,
IncludeTotalCount = true,
MaxPageSize = 5
})
.ModifyRequestOptions(o =>
{
//Enable better Debugging Experience!
if (Debugger.IsAttached)
{
o.ExecutionTimeout = TimeSpan.FromHours(1);
}
}
)
.AddPreProcessedResultsExtensions()
//*******************************************************************************************
//*******************************************************************************************
//Now Required in v11 to support the Attribute Usage (e.g. you may see the
// error: No filter convention found for scope `none`
.AddFiltering();
//.AddSorting();
//Finally Initialize AzureFunctions Executor Proxy here...
//You man Provide a specific SchemaName for multiple Functions (e.g. endpoints).
//TODO: Test multiple SchemaNames...
services.AddAzureFunctionsGraphQL(options =>
{
options.AzureFunctionsRoutePath = "/api/graphql/playground";
});
}
19
Source : SmokerRelayClient.cs
with MIT License
from CamSoper
with MIT License
from CamSoper
private async Task AddAuthToken(HttpRequestMessage request)
{
TokenProvider tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(_keyName, _key);
string token = (await tokenProvider.GetTokenAsync(request.RequestUri.AbsoluteUri, TimeSpan.FromHours(1))).TokenString;
request.Headers.Add("ServiceBusAuthorization", token);
}
19
Source : JobWorkerMultiPartitionTest.cs
with Apache License 2.0
from camunda-community-hub
with Apache License 2.0
from camunda-community-hub
[Test]
public async Task ShouldHandleAllJobs()
{
// given
var handledJobs = new List<IJob>();
foreach (int i in Enumerable.Range(1, 3))
{
await zeebeClient.NewCreateProcessInstanceCommand()
.ProcessDefinitionKey(processDefinitionKey)
.Send();
}
// when
using (var signal = new EventWaitHandle(false, EventResetMode.AutoReset))
{
using (zeebeClient.NewWorker()
.JobType("oneTask")
.Handler(async (jobClient, job) =>
{
await jobClient.NewCompleteJobCommand(job).Send();
handledJobs.Add(job);
if (handledJobs.Count >= 3)
{
signal.Set();
}
})
.MaxJobsActive(5)
.Name("csharpWorker")
.Timeout(TimeSpan.FromHours(10))
.PollInterval(TimeSpan.FromSeconds(5))
.Open())
{
signal.WaitOne(TimeSpan.FromSeconds(5));
}
}
replacedert.AreEqual(3, handledJobs.Count);
}
19
Source : JobWorkerMultiPartitionTest.cs
with Apache License 2.0
from camunda-community-hub
with Apache License 2.0
from camunda-community-hub
[Test]
public async Task ShouldActivateAllJobs()
{
// given
foreach (int i in Enumerable.Range(1, 3))
{
await zeebeClient.NewCreateProcessInstanceCommand()
.ProcessDefinitionKey(processDefinitionKey)
.Send();
}
// when
var activateJobsResponse = await zeebeClient.NewActivateJobsCommand()
.JobType("oneTask")
.MaxJobsToActivate(5)
.WorkerName("csharpWorker")
.Timeout(TimeSpan.FromHours(10))
.Send();
replacedert.AreEqual(3, activateJobsResponse.Jobs.Count);
}
19
Source : Application.cs
with Apache License 2.0
from caos
with Apache License 2.0
from caos
public async Task<string> GetSignedJwtAsync(string issuer, TimeSpan? lifeSpan = null)
{
using var rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(await GetRsaParametersAsync());
if (lifeSpan != null && (lifeSpan < TimeSpan.FromSeconds(1) || lifeSpan > TimeSpan.FromHours(1)))
{
throw new ArgumentException("The lifespan is below 1 second or above 1 hour.", nameof(lifeSpan));
}
return JWT.Encode(
new Dictionary<string, object>
{
{ "iss", ClientId },
{ "sub", ClientId },
{ "iat", DateTimeOffset.UtcNow.ToUnixTimeSeconds() },
{ "exp", (DateTimeOffset.UtcNow + (lifeSpan ?? TimeSpan.FromHours(1))).ToUnixTimeSeconds() },
{ "aud", issuer },
},
rsa,
JwsAlgorithm.RS256,
new Dictionary<string, object>
{
{ "kid", KeyId },
});
}
19
Source : ZitadelApiValidator.cs
with Apache License 2.0
from caos
with Apache License 2.0
from caos
private Func<string, HttpRequestMessage> RequestConstructor()
{
_oidcConfiguration ??= _configuration.GetConfigurationAsync().Result;
if (_options.BasicAuthCredentials == null && _options.JwtProfileKey == null && _options.JwtProfile == null)
{
throw new ApplicationException(
"Neither BasicAuth nor JwtPrivateKey credentials configured in Zitadel API authentication.");
}
if (_options.JwtProfileKey != null || _options.JwtProfile != null)
{
var app = _options.JwtProfile ??
(_options.JwtProfileKey?.Content != null
? Application.LoadFromJsonString(_options.JwtProfileKey.Content)
: Application.LoadFromJsonFile(_options.JwtProfileKey?.Path ?? string.Empty));
string? jwt = null;
_appRenew = Observable
.Timer(TimeSpan.Zero, TimeSpan.FromMinutes(55))
.Select(_ => app.GetSignedJwt(_options.Issuer, TimeSpan.FromHours(1)))
.Subscribe(appJwt => jwt = appJwt);
return token =>
{
jwt ??= app.GetSignedJwt(_options.Issuer);
return new()
{
Method = HttpMethod.Post,
#if NET5_0_OR_GREATER
RequestUri = new(_oidcConfiguration.IntrospectionEndpoint),
#elif NETCOREAPP3_1_OR_GREATER
RequestUri = new(
_oidcConfiguration.AdditionalData["introspection_endpoint"]?.ToString() ??
throw new("No Introspect Endpoint Found")),
#endif
Content = new FormUrlEncodedContent(
new[]
{
new KeyValuePair<string?, string?>(
"client_replacedertion_type",
"urn:ietf:params:oauth:client-replacedertion-type:jwt-bearer"),
new KeyValuePair<string?, string?>(
"client_replacedertion",
$"{jwt}"),
new KeyValuePair<string?, string?>("token", token),
}),
};
};
}
return token => new()
{
Method = HttpMethod.Post,
#if NET5_0_OR_GREATER
RequestUri = new(_oidcConfiguration.IntrospectionEndpoint),
#elif NETCOREAPP3_1_OR_GREATER
RequestUri = new(
_oidcConfiguration.AdditionalData["introspection_endpoint"]?.ToString() ??
throw new("No Introspect Endpoint Found")),
#endif
Headers = { { AuthorizationHeader, _options.BasicAuthCredentials!.HttpCredentials } },
Content = new FormUrlEncodedContent(new[] { new KeyValuePair<string?, string?>("token", token) }),
};
}
19
Source : IntradayReversalCurrencyMarketsAlpha.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
private bool ShouldEmitInsight(QCAlgorithm algorithm, Symbol symbol)
{
var timeOfDay = algorithm.Time.TimeOfDay;
return algorithm.Securities[symbol].HasData &&
timeOfDay >= TimeSpan.FromHours(10) &&
timeOfDay <= TimeSpan.FromHours(15);
}
19
Source : BasicTemplateFuturesHistoryAlgorithm.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
public override void Initialize()
{
SetStartDate(2013, 10, 8);
SetEndDate(2013, 10, 9);
SetCash(1000000);
foreach (var root in roots)
{
// set our expiry filter for this futures chain
AddFuture(root, Resolution.Minute).SetFilter(TimeSpan.Zero, TimeSpan.FromDays(182));
}
SetBenchmark(d => 1000000);
Schedule.On(DateRules.EveryDay(), TimeRules.Every(TimeSpan.FromHours(1)), MakeHistoryCall);
}
19
Source : BasicTemplateOptionsFrameworkAlgorithm.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
public override void Initialize()
{
UniverseSettings.Resolution = Resolution.Minute;
SetStartDate(2014, 06, 05);
SetEndDate(2014, 06, 06);
SetCash(100000);
// set framework models
SetUniverseSelection(new EarliestExpiringWeeklyAtTheMoneyPutOptionUniverseSelectionModel(SelectOptionChainSymbols));
SetAlpha(new ConstantOptionContractAlphaModel(InsightType.Price, InsightDirection.Up, TimeSpan.FromHours(0.5)));
SetPortfolioConstruction(new SingleSharePortfolioConstructionModel());
SetExecution(new ImmediateExecutionModel());
SetRiskManagement(new NullRiskManagementModel());
}
19
Source : CheeseMilkHourlyRebalance.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
public override void OnData(Slice data)
{
var contract = data.FutureChains.Values.SelectMany(c => c.Contracts.Values)
.OrderBy(c => c.Symbol.ID.Date)
.FirstOrDefault()?
.Symbol;
if (contract == null)
{
return;
}
if (_contract != contract || (_fast == null && _slow == null))
{
_fast = EMA(contract, 600);
_slow = EMA(contract, 1200);
_contract = contract;
}
if (!_fast.IsReady || !_slow.IsReady)
{
return;
}
if (Time - _lastTrade <= TimeSpan.FromHours(1) || Time.TimeOfDay <= new TimeSpan(10, 50, 0) || Time.TimeOfDay >= new TimeSpan(12, 30, 0))
{
return;
}
if (!Portfolio.ContainsKey(contract) || (Portfolio[contract].Quanreplacedy <= 0 && _fast > _slow))
{
SetHoldings(contract, 0.5);
_lastTrade = Time;
}
else if (Portfolio.ContainsKey(contract) && Portfolio[contract].Quanreplacedy >= 0 && _fast < _slow)
{
SetHoldings(contract, -0.5);
_lastTrade = Time;
}
}
19
Source : ScheduledUniverseSelectionModelRegressionAlgorithm.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
public override void Initialize()
{
UniverseSettings.Resolution = Resolution.Hour;
// Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
// Commented so regression algorithm is more sensitive
//Settings.MinimumOrderMarginPortfolioPercentage = 0.005m;
SetStartDate(2017, 01, 01);
SetEndDate(2017, 02, 01);
// selection will run on mon/tues/thurs at 00:00/12:00
SetUniverseSelection(new ScheduledUniverseSelectionModel(
DateRules.Every(DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Thursday),
TimeRules.Every(TimeSpan.FromHours(12)),
SelectSymbols
));
SetAlpha(new ConstantAlphaModel(InsightType.Price, InsightDirection.Up, TimeSpan.FromDays(1)));
SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel());
}
19
Source : DailyHistoryForMinuteResolutionRegressionAlgorithm.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
public override void Initialize()
{
SetStartDate(2018, 3, 26);
SetEndDate(2018, 4, 10);
foreach (var symbol in _symbols)
{
AddSecurity(symbol, Resolution.Minute);
}
Schedule.On(DateRules.EveryDay(), TimeRules.Every(TimeSpan.FromHours(1)), MakeHistoryCall);
}
19
Source : ExtendedMarketHoursHistoryRegressionAlgorithm.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
public override void Initialize()
{
SetStartDate(2013, 10, 07);
SetEndDate(2013, 10, 09);
SetCash(100000);
AddEquity("SPY", Resolution.Minute, extendedMarketHours:true, fillDataForward:false);
Schedule.On("RunHistoryCall", DateRules.EveryDay(), TimeRules.Every(TimeSpan.FromHours(1)), RunHistoryCall);
}
19
Source : InternalSubscriptionHistoryRequestAlgorithm.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
SetHoldings("AAPL", 1);
var spy = QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA);
var history = History(new[] { spy }, TimeSpan.FromDays(10));
if (!history.Any() || !history.All(slice => slice.Bars.All(pair => pair.Value.Period == TimeSpan.FromHours(1))))
{
throw new Exception("Unexpected history result for internal subscription");
}
// we add SPY using Daily > default benchmark using hourly
AddEquity("SPY", Resolution.Daily);
history = History(new[] { spy }, TimeSpan.FromDays(10));
if (!history.Any() || !history.All(slice => slice.Bars.All(pair => pair.Value.Period == TimeSpan.FromDays(1))))
{
throw new Exception("Unexpected history result for user subscription");
}
}
}
19
Source : ScaledFillForwardDataRegressionAlgorithm.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
public override void Initialize()
{
SetStartDate(2014, 6, 5);
SetEndDate(2014, 6, 9);
_twx = AddEquity("TWX", Resolution.Minute, extendedMarketHours: true).Symbol;
Schedule.On(DateRules.EveryDay(_twx), TimeRules.Every(TimeSpan.FromHours(1)), PlotPrice);
}
19
Source : TimeRulesDefaultTimeZoneRegressionAlgorithm.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
public override void Initialize()
{
SetStartDate(2017, 01, 01);
SetEndDate(2017, 02, 01);
SetUniverseSelection(new ScheduledUniverseSelectionModel(
DateRules.EveryDay(),
TimeRules.At(9, 31),
SelectSymbolsAt
));
Schedule.On(DateRules.EveryDay(), TimeRules.Every(TimeSpan.FromHours(6)), () =>
{
_scheduleEventEveryCallCount++;
if (Time.Hour != 0
&& Time.Hour != 6
&& Time.Hour != 12
&& Time.Hour != 18)
{
throw new Exception($"Unexpected every 6 hours scheduled event time: {Time}");
}
});
Schedule.On(DateRules.EveryDay(), TimeRules.Noon, () =>
{
_scheduleEventNoonCallCount++;
if (Time.Hour != 12)
{
throw new Exception($"Unexpected Noon scheduled event time: {Time}");
}
});
Schedule.On(DateRules.EveryDay(), TimeRules.Midnight, () =>
{
_scheduleEventMidnightCallCount++;
if (Time.Hour != 0)
{
throw new Exception($"Unexpected Midnight scheduled event time: {Time}");
}
});
}
19
Source : DayTimeInForce.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
public override bool IsOrderExpired(Security security, Order order)
{
var exchangeHours = security.Exchange.Hours;
var orderTime = order.Time.ConvertFromUtc(exchangeHours.TimeZone);
var time = security.LocalTime;
bool expired;
switch (order.SecurityType)
{
case SecurityType.Forex:
case SecurityType.Cfd:
// With real brokerages (IB, Oanda, FXCM have been verified) FX orders expire at 5 PM NewYork time.
// For now we use this fixed cut-off time, in future we might get this value from brokerage models,
// to support custom brokerage implementations.
var cutOffTimeZone = TimeZones.NewYork;
var cutOffTimeSpan = TimeSpan.FromHours(17);
orderTime = order.Time.ConvertFromUtc(cutOffTimeZone);
var expiryTime = orderTime.Date.Add(cutOffTimeSpan);
if (orderTime.TimeOfDay > cutOffTimeSpan)
{
// order submitted after 5 PM, expiry on next date
expiryTime = expiryTime.AddDays(1);
}
expired = time.ConvertTo(exchangeHours.TimeZone, cutOffTimeZone) >= expiryTime;
break;
case SecurityType.Crypto:
// expires at midnight UTC
expired = time.Date > orderTime.Date;
break;
case SecurityType.Equity:
case SecurityType.Option:
case SecurityType.Future:
case SecurityType.FutureOption:
case SecurityType.IndexOption:
default:
// expires at market close
expired = time >= exchangeHours.GetNextMarketClose(orderTime, false);
break;
}
return expired;
}
19
Source : Extensions.cs
with Apache License 2.0
from Capnode
with Apache License 2.0
from Capnode
public static TimeSpan ToTimeSpan(this Resolution resolution)
{
switch (resolution)
{
case Resolution.Tick:
// ticks can be instantaneous
return TimeSpan.FromTicks(0);
case Resolution.Second:
return TimeSpan.FromSeconds(1);
case Resolution.Minute:
return TimeSpan.FromMinutes(1);
case Resolution.Hour:
return TimeSpan.FromHours(1);
case Resolution.Daily:
return TimeSpan.FromDays(1);
default:
throw new ArgumentOutOfRangeException("resolution");
}
}
See More Examples