public FileConfigurationStore(IList<string> filePaths) { if (filePaths == null || filePaths.Count == 0 || !filePaths.All(c => !String.IsNullOrWhiteSpace(c))) throw new ArgumentNullException("filePaths", "The parameter filePaths cannot be empty or contains empty string"); this.fileIniDataParser = new FileIniDataParser(); this.fileIniDataParser.Parser.Configuration.CommentString = "#"; this.filePaths = filePaths; }
public static IEnumerable<EntitySet> Convert( IList<EntitySet> sourceEntitySets, Version targetEntityFrameworkVersion, string providerInvariantName, string providerManifestToken, IDbDependencyResolver dependencyResolver) { Debug.Assert(sourceEntitySets != null, "sourceEntitySets != null"); Debug.Assert(sourceEntitySets.All(e => e.DefiningQuery == null), "unexpected defining query"); Debug.Assert(!string.IsNullOrWhiteSpace(providerInvariantName), "invalid providerInvariantName"); Debug.Assert(!string.IsNullOrWhiteSpace(providerManifestToken), "invalid providerManifestToken"); Debug.Assert(dependencyResolver != null, "dependencyResolver != null"); if (!sourceEntitySets.Any()) { // it's empty anyways return sourceEntitySets; } var providerServices = dependencyResolver.GetService<DbProviderServices>(providerInvariantName); Debug.Assert(providerServices != null, "providerServices != null"); var transientWorkspace = CreateTransientMetadataWorkspace( sourceEntitySets, targetEntityFrameworkVersion, providerInvariantName, providerManifestToken, providerServices.GetProviderManifest(providerManifestToken)); return sourceEntitySets.Select( e => CloneWithDefiningQuery( e, CreateDefiningQuery(e, transientWorkspace, providerServices))); }
internal static CompareResult Create(IList<StringDifferencePair> stringDifferenceEnumerable) { return Set( stringDifferenceEnumerable.All(sd => sd.Similar), stringDifferenceEnumerable ); }
private static void CleanOldFiles(IList<string> files, string referencesFile, string sourceFolder, bool needsExtending) { if (needsExtending) { files = files.Select(x => string.Format("{0}{1}", x, Program.NEEDS_EXTENDING_EXTENSION)).ToList(); } var lines = File.ReadAllLines(referencesFile).ToList(); var stringBuilder = new StringBuilder(); var linesToRemove = lines .Where(x => IsAReferenceInFolderButNotSubfolder(x, sourceFolder) && files.All(y => y != GetFileName(x))) .ToList(); foreach (var line in linesToRemove) { lines.Remove(line); } var linesToAdd = files .Where(x => lines.All(y => GetFileName(y) != x)) .Select(x => string.Format("/// <reference path=\"{0}/{1}.ts\" />", sourceFolder.Replace('\\', '/'), x)) .ToList(); lines.AddRange(linesToAdd); if (linesToRemove.Any() || linesToAdd.Any()) { File.WriteAllLines(referencesFile, lines); } }
public PropertyChangeWatcher AddWatcher(IList<string> propertyNames, Action handler) { Contract.Requires(handler != null); Contract.Requires(propertyNames != null); Contract.Requires(propertyNames.Count > 0); Contract.Requires(propertyNames.AllUnique()); Util.ThrowUnless(propertyNames.All(name => OwnerType.HasPublicInstanceProperty(name)), "The target object does not contain one or more of the properties provided"); lock (_handlers) { foreach (var key in propertyNames) { Util.ThrowUnless<ArgumentException>(!IsWatching(key), "Must not already be watching property '{0}'".DoFormat(key)); } if (_handlers.Count == 0) { _owner.PropertyChanged += _owner_PropertyChanged; } foreach (var propertyName in propertyNames) { _handlers[propertyName] = handler; } return this; } }
private static IEnumerable<Sim> Compare(Quest fromQuest, string[] fromRoute, IList<Quest> questDB) { DolRoute EL = new DolRoute(); var simList = new List<Sim>(); questDB.All(quest => { if (quest.ID == fromQuest.ID) return true; if (quest.RouteForSim.Count != 0) { var min = quest.RouteForSim.Min(route => { if (route.Count < 2) return 2001; var value = EL.Compute(fromRoute, route.ToArray()); return value; }); if (min < 2000) { simList.Add(new Sim() { CompareID = quest.ID, QuestID = fromQuest.ID, Value = min, StartCity = EL.GetCityID(fromRoute[0]) }); } } return true; }); return simList.OrderBy(sim => sim.Value).Take(300); }
static void SlowButSureAssertCollected(IList<WeakReference> nextIterationHolder) { GC.GetTotalMemory(true); if(nextIterationHolder.All(wr => !wr.IsAlive)) return; GC.Collect(); if(nextIterationHolder.All(wr => !wr.IsAlive)) return; GC.GetTotalMemory(true); var notCollected = nextIterationHolder.Select(wr => wr.Target).Where(t => t != null).ToArray(); if(notCollected.Length == 0) return; var objectsReport = string.Join("\n", notCollected.GroupBy(o => o.GetType()).OrderBy(gr => gr.Key.FullName) .Select(gr => string.Format("\t{0} object(s) of type {1}:\n{2}", gr.Count(), gr.Key.FullName , string.Join("\n", gr.Select(o => o.ToString()).OrderBy(s => s).Select(s => string.Format("\t\t{0}", s))) ))); throw new Exception(string.Format("{0} garbage object(s) not collected:\n{1}", notCollected.Length, objectsReport)); }
public bool ValidateBarcodes(IList<string> barcodes) { if (barcodes == null) { return false; } return barcodes.All(b => m_productRepository.GetByBarcodes(b).IsNotEmpty()); }
private bool ContainsRequiredHeaders(IList<string> headers) { var requiredHeaders = new List<string>(); requiredHeaders.Add("header1"); requiredHeaders.Add("header2"); return headers.All(requiredHeaders.Contains) && headers.Count == requiredHeaders.Count; }
private static void LoadNextTheme(string currentThemeName, IList<Theme> allThemes) { if (allThemes.All(x => !x.Active)) return; // No active theme, so exit immediatly. var idx = GetCurrentThemeIndex(allThemes, currentThemeName); var themeToLoad = GetNextActiveTheme(allThemes, idx); ThemeLoader.LoadTheme(themeToLoad); }
private static Language? TopScore(IList<AnalysisResult> source) { if (source.All(x => x.Score == 0)) { return null; } return source?.Aggregate((l, r) => l.Score > r.Score ? l : r).Language; }
public override double GetDiscountAmount(IList<BasketItem> items) { //If there is no bread, do not fuss if (items.All(i => i.ItemType != BasketItemType.Milk)) { return 0.0; } return items.First(i => i.ItemType == BasketItemType.Milk).Price; }
protected static int HeightOf(IList<RectangularStep> upstream) { if (upstream == null || upstream.Count == 0) throw new ArgumentException(); int height = upstream[0].Height; if (!upstream.All(step => step.Height == height)) throw new ArgumentException(); return height; }
public string BuildMessage(IList<TeamCityModel> buildStatuses, out bool notify) { var success = buildStatuses.Count == _expectedBuildCount && buildStatuses.All(buildStatus => IsSuccesfullBuild(buildStatus.build)); notify = !success; return success ? BuildSuccessMessage(buildStatuses.First().build) : BuildFailureMessage(buildStatuses.Select(m => m.build).ToList()); }
public static void ListsEqual(IList<BrokenRule> expected, IList<BrokenRule> actual) { Assert.NotNull(expected); Assert.NotNull(actual); Assert.Equal(expected.Count, actual.Count); Assert.True(expected.All( ex => actual.Any(act=> AreEqual(ex,act)) )); }
protected static int WidthOf(IList<RectangularStep> upstream) { if (upstream == null || upstream.Count == 0) throw new ArgumentException(); int width = upstream[0].Width; if (!upstream.All(step => step.Width == width)) throw new ArgumentException(); return width; }
static ArgumentProcessor() { // Initialise the set of valid descriptors. // To add a new argument, just add it to the list. Descriptors = new List<ArgumentDescriptor>(); Descriptors.Add(CmdLineArgPropertyProvider.Descriptor); Debug.Assert(Descriptors.All(d => d.Prefixes != null && d.Prefixes.Any()), "All descriptors must provide at least one prefix"); Debug.Assert(Descriptors.Select(d => d.Id).Distinct().Count() == Descriptors.Count, "All descriptors must have a unique id"); }
public override double GetDiscountAmount(IList<BasketItem> items) { //If there is no bread, do not fuss if (items.All(i => i.ItemType != BasketItemType.Bread)) { return 0.0; } //We know that there is bread here; double breadPrice = items.First(i => i.ItemType == BasketItemType.Bread).Price; return breadPrice / 2; }
/// <summary> /// Returns the submission status for an entire assignment. /// </summary> public static SubmissionStatus ForAssignment( IList<SubmissionStatus> questionStatus) { var completion = questionStatus.All(q => q.Completion == Completion.Completed) ? Completion.Completed : questionStatus.Any(q => q.Completion != Completion.NotStarted) ? Completion.InProgress : Completion.NotStarted; var late = questionStatus.Any(q => q.Late); return new SubmissionStatus(completion, late); }
public async Task<int> ThinkAsync(IList<char> gameBoard) { // Copy the contents of the IList to a string. char[] arrayTmp = new char[9]; gameBoard.CopyTo(arrayTmp, 0); string board = new String(arrayTmp); // Frequently take the center square if the board is empty. System.Random random = new System.Random((int)System.DateTime.Now.Ticks); if (random.Next() % 2 == 0 && gameBoard.All<char>((ch) => ch == m_emptySymbol.Symbol)) { return 4; } // Approximate counts of iterations the algorithm makes for each number of available moves at the root level. uint[] allIterations = { 0u, 2u, 5u, 15u, 50u, 200u, 930u, 7300u, 60000u, 550000u }; var moves = MiniMax.AvailableMoves(board, m_emptySymbol.Symbol); uint totalIterations = allIterations[moves.Length - 1]; // Report every 1%. uint nextReportIter = totalIterations / 100; uint iterBy = nextReportIter; // This is called on every iteration of the minimax algorithm. MiniMax.CallBackFn callback = /*[total_iterations, &next_report_iter, iter_by, reporter]*/(int iter_count) => { if (iter_count == nextReportIter) { double progress = 100.0 * iter_count / totalIterations; //reporter.report(Math.Min(progress, 100.0)); nextReportIter += iterBy; } }; // Run the minimax algorithm in parallel if there are enough iterations. // Otherwise, run it serially, as the overhead of parallelism may not benefit. int iterCount = 0; System.Tuple<int, int> t; //if (totalIterations > 500) //{ // t = parallel_minimax(board, m_symbol, m_opponentSymbol, m_emptySymbol, m_symbol, iterCount, callback); //} //else //{ t = await MiniMax.Minimax(board, m_symbol.Symbol, m_opponentSymbol.Symbol, m_emptySymbol.Symbol, m_symbol.Symbol, iterCount, callback); //} // Return the index part. return t.Item1; }
public static IEnumerable <PKM> FilterByBatchInstruction(IEnumerable <PKM> res, IList <string> BatchInstructions) { if (BatchInstructions?.All(string.IsNullOrWhiteSpace) != false) { return(res); // none specified; } var lines = BatchInstructions.Where(z => !string.IsNullOrWhiteSpace(z)); var filters = StringInstruction.GetFilters(lines).ToArray(); BatchEditing.ScreenStrings(filters); return(res.Where(pkm => BatchEditing.IsFilterMatch(filters, pkm))); // Compare across all filters }
static ArgumentProcessor() { // Initialise the set of valid descriptors. // To add a new argument, just add it to the list. Descriptors = new List<ArgumentDescriptor>(); Descriptors.Add(new ArgumentDescriptor( id: KeywordIds.AnalyzerRef, prefixes: new string[] { "/analyzer:", "/a:" }, required: true, allowMultiple: false, description: CmdLineResources.ArgDescription_AnalzyerRef)); Descriptors.Add(new ArgumentDescriptor( id: KeywordIds.SqaleXmlFile, prefixes: new string[] { "/sqale:", "/s:" }, required: false, allowMultiple: false, description: CmdLineResources.ArgDescription_SqaleXmlFile)); Debug.Assert(Descriptors.All(d => d.Prefixes != null && d.Prefixes.Any()), "All descriptors must provide at least one prefix"); Debug.Assert(Descriptors.Select(d => d.Id).Distinct().Count() == Descriptors.Count, "All descriptors must have a unique id"); }
/// <summary>Compares the two Lists of Transports and says if they are equal.</summary> /// <param name="transports1">first List of Transports</param> /// <param name="transports2">second List of Transports</param> /// <returns> /// True if both lists are null or if both lists contain the same transport values /// </returns> public static bool ContainSameTransports(IList<SecurityKeyDataTransports> transports1, IList<SecurityKeyDataTransports> transports2) { if (transports1 == null && transports2 == null) { return true; } if (transports1 == null || transports2 == null) { return false; } return transports1.All(transports2.Contains) && transports2.All(transports1.Contains); }
public void ApplyUniverslaLinkSettings(IList<LibraryFileLink> targetLinks, LibraryFileLink templateLink = null) { foreach (var template in SettingsTemplates) { if (templateLink == null) templateLink = ParentFolder.AllLinks .FirstOrDefault(link => link.Type == template.FileType && targetLinks.All(tl => tl != link)); if (templateLink == null) continue; foreach (var targetLink in targetLinks) ApplyUniversalLinkSettings(template.SettingsType, targetLink, templateLink); } }
public static bool Validieren(Schicht schicht, IList<Validierungsfehler> fehler, int okGrenzwert = int.MaxValue) { if (schicht == null) return false; if (schicht.GeldNachher < schicht.GeldVorher) fehler.Add(new Validierungsfehler { Meldung = "Schicht: nachher weniger Geld in der Kasse als vorher", Schwere = 1 }); if (schicht.Trinkgeld < 0.0F) fehler.Add(new Validierungsfehler { Meldung = "Schicht: Trinkgeld negativ", Schwere = 1 }); if (schicht.Abzaehlen < 0.0F) fehler.Add(new Validierungsfehler { Meldung = "Schicht: Abzählen negativ", Schwere = 1 }); if (schicht.GeldNachher < schicht.GeldVorher) fehler.Add(new Validierungsfehler { Meldung = "Schicht: nachher weniger Geld in der Kasse als vorher", Schwere = 1 }); if (schicht.Ende < schicht.Anfang) fehler.Add(new Validierungsfehler { Meldung = "Schicht: Ende liegt vor Anfang", Schwere = 0 }); if (!schicht.Fahrzeuge.Any()) fehler.Add(new Validierungsfehler { Meldung = "Schicht: kein Fahrzeug", Schwere = 0 }); if (!schicht.Fahrzeuge.All(p => p.Fahrten.Any())) fehler.Add(new Validierungsfehler { Meldung = "Fahrzeug: keine Fahrten", Schwere = 0 }); if (schicht.Fahrzeuge.Any(p => p.Nummer == 0)) fehler.Add(new Validierungsfehler { Meldung = "Fahrzeug: Nummer ungültig", Schwere = 1 }); if (Math.Round(schicht.Fahrzeuge.Sum(p => p.Preisdifferenz), 2) >= 0.01F) fehler.Add(new Validierungsfehler { Meldung = "Fahrzeug: Diff. zw. Uhr und Einzelfahrpreisen ist nicht 0.00 €", Schwere = 0 }); return fehler.All(p => p.Schwere >= okGrenzwert); }
public void Put(IList<Telefone> telefones , int copId , Contexto ctx) { try { var tels = ctx.DbTelefone.Where(x => x.CoperativaId == copId).ToList(); foreach (var telefone in tels.Where(telefone => telefones.All(x => x.Id != telefone.Id))) ctx.DbTelefone.Remove(telefone); foreach (var telefone in telefones) ctx.DbTelefone.AddOrUpdate(telefone); } catch (Exception ex) { throw ex; } }
public List<KeyValuePair<int, Quest>> FindSim(Quest target, IList<Quest> questList) { var result=new SortedList<int, Quest>(); questList.All(quest => { var value = GetSimValue(target, quest); if (value == Int32.MaxValue) return true; while (result.ContainsKey(value) == true) value += 1; result.Add(value, quest); if (value == Int32.MinValue) return false; return true; }); return result.OrderBy(x => x.Key).Take(10).ToList(); }
protected ServiceProxyBase( object unavailableImpl, Type typeInterface, IList<MethodInfo> mRefs, IList<EventInfo> eRefs ) { Debug.Assert( mRefs.All( r => r != null ) && mRefs.Distinct().SequenceEqual( mRefs ) ); _typeInterface = typeInterface; _status = RunningStatus.Disabled; RawImpl = _unavailableImpl = unavailableImpl; _mRefs = new MEntry[mRefs.Count]; for( int i = 0; i < mRefs.Count; i++ ) { _mRefs[i].Method = mRefs[i]; } _eRefs = new EEntry[eRefs.Count]; for( int i = 0; i < eRefs.Count; i++ ) { _eRefs[i].Event = eRefs[i]; } }
static ArgumentProcessor() { // Initialise the set of valid descriptors. // To add a new argument, just add it to the list. Descriptors = new List<ArgumentDescriptor>(); Descriptors.Add(new ArgumentDescriptor( id: BeginId, prefixes: new string[] { BeginVerb }, required: false, allowMultiple: false, description: Resources.CmdLine_ArgDescription_Begin, isVerb: true)); Descriptors.Add(new ArgumentDescriptor( id: EndId, prefixes: new string[] { EndVerb }, required: false, allowMultiple: false, description: Resources.CmdLine_ArgDescription_End, isVerb: true)); Descriptors.Add(FilePropertyProvider.Descriptor); Descriptors.Add(CmdLineArgPropertyProvider.Descriptor); Debug.Assert(Descriptors.All(d => d.Prefixes != null && d.Prefixes.Any()), "All descriptors must provide at least one prefix"); Debug.Assert(Descriptors.Select(d => d.Id).Distinct().Count() == Descriptors.Count, "All descriptors must have a unique id"); }
public bool AreSolvable(IList<IList<Group>> groups) { var initial = groups[0]; int ng = initial.Count; if (!groups.All(gr => gr.Count == ng)) return false; for (int k = 1; k < groups.Count; k++) { var group = groups[k]; for (int j = 0; j < ng; j++) if (initial[j].Letter != group[j].Letter) return false; } return true; }
public void GetCombinedBaseTemplates(IItem item, IList<IItem> baseTemplates, IEnumerable<IItem> items) { if (item != null && baseTemplates.All(i => i.Id != item.Id)) { baseTemplates.Add(item); var baseTemplateField = item.SharedFields.FirstOrDefault(i => IsBaseTemplateField(i.Id)); if (baseTemplateField != null) { foreach (var value in baseTemplateField.Value.Split(StringSeparators, StringSplitOptions.None)) { var baseTemplateItem = items.FirstOrDefault(i => IsIdEqual(i.Id, value)); this.GetCombinedBaseTemplates(baseTemplateItem, baseTemplates, items); } } } }
public IList <TRunDetail> Execute() { var iterationResults = new List <TRunDetail>(); // Create a timer for the max duration of experiment. When given time has // elapsed, MaxExperimentTimeExpiredEvent is called to interrupt training // of current model. Timer is not used if no experiment time is given, or // is not a positive number. if (_experimentSettings.MaxExperimentTimeInSeconds > 0) { _maxExperimentTimeTimer = new Timer( new TimerCallback(MaxExperimentTimeExpiredEvent), null, _experimentSettings.MaxExperimentTimeInSeconds * 1000, Timeout.Infinite ); } // If given max duration of experiment is 0, only 1 model will be trained. // _experimentSettings.MaxExperimentTimeInSeconds is of type uint, it is // either 0 or >0. else { _experimentTimerExpired = true; } // Add second timer to check for the cancelation signal from the main MLContext // to the active child MLContext. This timer will propagate the cancelation // signal from the main to the child MLContexs if the main MLContext is // canceled. _mainContextCanceledTimer = new Timer(new TimerCallback(MainContextCanceledEvent), null, 1000, 1000); // Pseudo random number generator to result in deterministic runs with the provided main MLContext's seed and to // maintain variability between training iterations. int?mainContextSeed = ((ISeededEnvironment)_context.Model.GetEnvironment()).Seed; _newContextSeedGenerator = (mainContextSeed.HasValue) ? RandomUtils.Create(mainContextSeed.Value) : null; do { try { var iterationStopwatch = Stopwatch.StartNew(); // get next pipeline var getPipelineStopwatch = Stopwatch.StartNew(); // A new MLContext is needed per model run. When max experiment time is reached, each used // context is canceled to stop further model training. The cancellation of the main MLContext // a user has instantiated is not desirable, thus additional MLContexts are used. _currentModelMLContext = _newContextSeedGenerator == null ? new MLContext() : new MLContext(_newContextSeedGenerator.Next()); _currentModelMLContext.Log += RelayCurrentContextLogsToLogger; var pipeline = PipelineSuggester.GetNextInferredPipeline(_currentModelMLContext, _history, _datasetColumnInfo, _task, _optimizingMetricInfo.IsMaximizing, _experimentSettings.CacheBeforeTrainer, _logger, _trainerAllowList); // break if no candidates returned, means no valid pipeline available if (pipeline == null) { break; } // evaluate pipeline _logger.Trace($"Evaluating pipeline {pipeline.ToString()}"); (SuggestedPipelineRunDetail suggestedPipelineRunDetail, TRunDetail runDetail) = _runner.Run(pipeline, _modelDirectory, _history.Count + 1); _history.Add(suggestedPipelineRunDetail); WriteIterationLog(pipeline, suggestedPipelineRunDetail, iterationStopwatch); runDetail.RuntimeInSeconds = iterationStopwatch.Elapsed.TotalSeconds; runDetail.PipelineInferenceTimeInSeconds = getPipelineStopwatch.Elapsed.TotalSeconds; ReportProgress(runDetail); iterationResults.Add(runDetail); // if model is perfect, break if (_metricsAgent.IsModelPerfect(suggestedPipelineRunDetail.Score)) { break; } // If after third run, all runs have failed so far, throw exception if (_history.Count() == 3 && _history.All(r => !r.RunSucceeded)) { throw new InvalidOperationException($"Training failed with the exception: {_history.Last().Exception}"); } } catch (OperationCanceledException e) { // This exception is thrown when the IHost/MLContext of the trainer is canceled due to // reaching maximum experiment time. Simply catch this exception and return finished // iteration results. _logger.Warning(_operationCancelledMessage, e.Message); return(iterationResults); } catch (AggregateException e) { // This exception is thrown when the IHost/MLContext of the trainer is canceled due to // reaching maximum experiment time. Simply catch this exception and return finished // iteration results. For some trainers, like FastTree, because training is done in parallel // in can throw multiple OperationCancelledExceptions. This causes them to be returned as an // AggregateException and misses the first catch block. This is to handle that case. if (e.InnerExceptions.All(exception => exception is OperationCanceledException)) { _logger.Warning(_operationCancelledMessage, e.Message); return(iterationResults); } throw; } } while (_history.Count < _experimentSettings.MaxModels && !_experimentSettings.CancellationToken.IsCancellationRequested && !_experimentTimerExpired); return(iterationResults); }
private bool IsAvailableSettings(IList <string> settings) { return(settings.All(x => availableSettings.Contains(x))); }
/// <summary> /// Wrapper method to check if a list of integers contains all positives. /// </summary> /// <param name="items">A list of ints to check. If null, this will pass.</param> /// <returns>The list that was passed in.</returns> public static IList <int> RequiresContainsAllPositive(IList <int> items) { Contract.Requires(items?.All(i => i > 0) ?? true); return(items); }
/// <summary> /// Determine if the specified row should be processed, or not. /// </summary> /// /// <param name="row">The row.</param> /// <returns>True, if the row should be processed.</returns> private bool ShouldProcess(LoadedRow row) { return(_excludedFields.All(field => !row.Data[field.FieldNumber].Trim().Equals(field.FieldValue.Trim()))); }
/// <see cref="IPersonRepository.AddChangeLogs" /> public bool AddChangeLogs(IList <PersonChangeLog> changes) { return(changes.All(AddChangeLog)); }
public void TestLinqWhereOnDictionaryProperty() { // TODO: Move to Linq test namespace InsertBasicClass(1); using (var session = OpenSession()) using (var trans = session.BeginTransaction()) { IQueryable <BasicClass> bcs = null; IList <BasicClass> bcsList = null; // IDictionary[] bcs = session.Query <BasicClass>() .Where(bc => (string)bc.StringMap["keyZero"] == "string zero"); Assert.That(bcs.Count(), Is.EqualTo(1)); bcsList = bcs.ToList <BasicClass>(); Assert.That(bcsList.All(f => f.StringMap != null), Is.True); Assert.That(bcsList.All(f => f.StringMap.Count == 3), Is.True); Assert.That(bcsList.All(f => ((f.StringMap.Contains("keyZero")) && ((string)f.StringMap["keyZero"] == "string zero"))), Is.True); // IDictionary<,>[] bcs = session.Query <BasicClass>() .Where(bc => bc.StringMapGeneric["keyOne"] == "string one"); Assert.That(bcs.Count(), Is.EqualTo(1)); bcsList = bcs.ToList <BasicClass>(); Assert.That(bcsList.All(f => f.StringMapGeneric != null), Is.True); Assert.That(bcsList.All(f => f.StringMapGeneric.Count == 3), Is.True); Assert.That(bcsList.All(f => ((f.StringMapGeneric.ContainsKey("keyOne")) && (f.StringMapGeneric["keyOne"] == "string one"))), Is.True); // IDictionary.Contains bcs = session.Query <BasicClass>() .Where(bc => bc.StringMap.Contains("keyZero")); Assert.That(bcs.Count(), Is.EqualTo(1)); bcsList = bcs.ToList <BasicClass>(); Assert.That(bcsList.All(f => f.StringMap != null), Is.True); Assert.That(bcsList.All(f => f.StringMap.Count == 3), Is.True); Assert.That(bcsList.All(f => ((f.StringMap.Contains("keyZero")) && ((string)f.StringMap["keyZero"] == "string zero"))), Is.True); // IDictionary<,>.ContainsKey bcs = session.Query <BasicClass>() .Where(bc => bc.StringMapGeneric.ContainsKey("keyZero")); Assert.That(bcs.Count(), Is.EqualTo(1)); bcsList = bcs.ToList <BasicClass>(); Assert.That(bcsList.All(f => f.StringMapGeneric != null), Is.True); Assert.That(bcsList.All(f => f.StringMapGeneric.Count == 3), Is.True); Assert.That(bcsList.All(f => ((f.StringMapGeneric.ContainsKey("keyOne")) && (f.StringMapGeneric["keyOne"] == "string one"))), Is.True); session.Delete("from BasicClass"); trans.Commit(); } }
public void Salvar(DateTime data, IList <QuotaSalvarVm> quotasSalvarVm) { try { _unitOfWork.BeginTransaction(); //consulta as quotas que estão salvas na data IList <Quota> quotasSalvas = _quotas.FiltraPorData(data).List(); #region Remover Quotas IList <Quota> quotasParaRemover = quotasSalvas .Where(qs => quotasSalvarVm.All(qc => qc.Data != qs.Data || qc.CodigoTerminal != qs.CodigoTerminal || qc.CodigoMaterial != (int)qs.Material || qc.CodigoFornecedor != qs.Fornecedor.Codigo)).ToList(); foreach (var quota in quotasParaRemover) { if (quota.Agendamentos.Any()) { throw new ExcluirQuotaComAgendamentoException(quota.Fornecedor.Nome); } _quotas.Delete(quota); } #endregion #region Atualizar Quotas IList <Quota> quotasParaAtualizar = quotasSalvas .Where(qs => quotasSalvarVm.Any(qc => qc.Data == qs.Data && qc.CodigoTerminal == qs.CodigoTerminal && qc.CodigoMaterial == (int)qs.Material && qc.CodigoFornecedor == qs.Fornecedor.Codigo)).ToList(); foreach (var quota in quotasParaAtualizar) { //obtem view model corresponde a entidade que quero atualizar QuotaSalvarVm quotaSalvarVm = quotasSalvarVm.First(qa => qa.Data == quota.Data && qa.CodigoTerminal == quota.CodigoTerminal && qa.CodigoMaterial == (int)quota.Material && qa.CodigoFornecedor == quota.Fornecedor.Codigo); //único campo que pode ser atualizado é o campo de peso quota.AlterarPeso(quotaSalvarVm.Peso); _quotas.Save(quota); } #endregion #region Adicionar Quotas IList <QuotaSalvarVm> quotasParaAdicionar = quotasSalvarVm.Where(qc => quotasSalvas.All(qs => qc.Data != qs.Data || qc.CodigoTerminal != qs.CodigoTerminal || qc.CodigoMaterial != (int)qs.Material || qc.CodigoFornecedor != qs.Fornecedor.Codigo)).ToList(); foreach (var quotaSalvarVm in quotasParaAdicionar) { string[] codigoDosNovosFornecedores = quotasParaAdicionar.Select(x => x.CodigoFornecedor).Distinct().ToArray(); IList <Fornecedor> fornecedores = _fornecedores.BuscaListaPorCodigo(codigoDosNovosFornecedores).List(); var materialDeCarga = (Enumeradores.MaterialDeCarga) Enum.Parse(typeof(Enumeradores.MaterialDeCarga), Convert.ToString(quotaSalvarVm.CodigoMaterial)); Fornecedor fornecedor = fornecedores.First(x => x.Codigo == quotaSalvarVm.CodigoFornecedor); var quota = new Quota(materialDeCarga, fornecedor, quotaSalvarVm.CodigoTerminal, quotaSalvarVm.Data, quotaSalvarVm.Peso); _quotas.Save(quota); } #endregion _unitOfWork.Commit(); } catch (Exception) { _unitOfWork.RollBack(); throw; } }
/// <see cref="IPersonRepository.UpdateSocialLinks" /> public bool UpdateSocialLinks(IList <PersonSocialLink> links, int userId) { return(links.All(link => UpdateSocialLink(link, userId) != null)); }
public static void AcceptChanges(ProgressMonitor monitor, IList <Change> changes, MonoDevelop.Ide.ITextFileProvider fileProvider) { var rctx = new RefactoringOptions(null, null); var handler = new RenameHandler(changes); FileService.FileRenamed += handler.FileRename; var ws = IdeApp.TypeSystemService.Workspace as MonoDevelopWorkspace; string originalName; int originalOffset; try { for (int i = 0; i < changes.Count; i++) { var change = changes [i] as TextReplaceChange; if (change == null) { continue; } if (ws.TryGetOriginalFileFromProjection(change.FileName, change.Offset, out originalName, out originalOffset)) { change.FileName = originalName; change.Offset = originalOffset; } } if (changes.All(x => x is TextReplaceChange)) { List <Change> newChanges = new List <Change> (changes); newChanges.Sort((Change x, Change y) => ((TextReplaceChange)x).Offset.CompareTo(((TextReplaceChange)y).Offset)); changes = newChanges; } for (int i = 0; i < changes.Count; i++) { changes [i].PerformChange(monitor, rctx); var replaceChange = changes [i] as TextReplaceChange; if (replaceChange == null) { continue; } for (int j = i + 1; j < changes.Count; j++) { var change = changes [j] as TextReplaceChange; if (change == null) { continue; } if (replaceChange.Offset >= 0 && change.Offset >= 0 && replaceChange.FileName == change.FileName) { if (replaceChange.Offset < change.Offset) { change.Offset -= replaceChange.RemovedChars; if (!string.IsNullOrEmpty(replaceChange.InsertedText)) { change.Offset += replaceChange.InsertedText.Length; } } else if (replaceChange.Offset < change.Offset + change.RemovedChars) { change.RemovedChars = Math.Max(0, change.RemovedChars - replaceChange.RemovedChars); change.Offset = replaceChange.Offset + (!string.IsNullOrEmpty(replaceChange.InsertedText) ? replaceChange.InsertedText.Length : 0); } } } } } catch (Exception e) { LoggingService.LogError("Error while applying refactoring changes", e); } finally { FileService.FileRenamed -= handler.FileRename; TextReplaceChange.FinishRefactoringOperation(); } }
protected override bool HasErrorLights(IList <string> propertyNames, CarSensorInfo sensor) { return(!propertyNames.All(x => _validPropertyNames.Contains(x))); }
public void Build(IList <DocumentBuildParameters> parameters, string outputDirectory) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } if (parameters.Count == 0) { throw new ArgumentException("Parameters are empty.", nameof(parameters)); } var markdownServiceProvider = GetMarkdownServiceProvider(); var logCodesLogListener = new LogCodesLogListener(); Logger.RegisterListener(logCodesLogListener); // Load schema driven processor from template var sdps = LoadSchemaDrivenDocumentProcessors(parameters[0]).ToList(); BuildInfo lastBuildInfo = null; var currentBuildInfo = new BuildInfo { BuildStartTime = DateTime.UtcNow, DocfxVersion = EnvironmentContext.Version, }; try { using (new PerformanceScope("LoadLastBuildInfo")) { lastBuildInfo = BuildInfo.Load(_intermediateFolder, true); } EnrichCurrentBuildInfo(currentBuildInfo, lastBuildInfo); _postProcessorsManager.IncrementalInitialize(_intermediateFolder, currentBuildInfo, lastBuildInfo, parameters[0].ForcePostProcess, parameters[0].MaxParallelism); var manifests = new List <Manifest>(); bool transformDocument = false; if (parameters.All(p => p.Files.Count == 0)) { Logger.LogWarning( "No file found, nothing will be generated. Please make sure docfx.json is correctly configured.", code: WarningCodes.Build.EmptyInputFiles); } var noContentFound = true; var emptyContentGroups = new List <string>(); foreach (var parameter in parameters) { if (parameter.CustomLinkResolver != null) { if (_container.TryGetExport(parameter.CustomLinkResolver, out ICustomHrefGenerator chg)) { parameter.ApplyTemplateSettings.HrefGenerator = chg; } else { Logger.LogWarning($"Custom href generator({parameter.CustomLinkResolver}) is not found."); } } FileAbstractLayerBuilder falBuilder; if (_intermediateFolder == null) { falBuilder = FileAbstractLayerBuilder.Default .ReadFromRealFileSystem(EnvironmentContext.BaseDirectory) .WriteToRealFileSystem(parameter.OutputBaseDir); } else { falBuilder = FileAbstractLayerBuilder.Default .ReadFromRealFileSystem(EnvironmentContext.BaseDirectory) .WriteToLink(Path.Combine(_intermediateFolder, currentBuildInfo.DirectoryName)); } if (!string.IsNullOrEmpty(parameter.FALName)) { if (_container.TryGetExport <IInputFileAbstractLayerBuilderProvider>( parameter.FALName, out var provider)) { falBuilder = provider.Create(falBuilder, parameter); } else { Logger.LogWarning($"Input fal builder provider not found, name: {parameter.FALName}."); } } EnvironmentContext.FileAbstractLayerImpl = falBuilder.Create(); if (parameter.ApplyTemplateSettings.TransformDocument) { transformDocument = true; } if (parameter.Files.Count == 0) { manifests.Add(new Manifest() { SourceBasePath = StringExtension.ToNormalizedPath(EnvironmentContext.BaseDirectory) }); } else { if (!parameter.Files.EnumerateFiles().Any(s => s.Type == DocumentType.Article)) { if (!string.IsNullOrEmpty(parameter.GroupInfo?.Name)) { emptyContentGroups.Add(parameter.GroupInfo.Name); } } else { noContentFound = false; } parameter.Metadata = _postProcessorsManager.PrepareMetadata(parameter.Metadata); if (!string.IsNullOrEmpty(parameter.VersionName)) { Logger.LogInfo($"Start building for version: {parameter.VersionName}"); } using (new LoggerPhaseScope("BuildCore")) { manifests.Add(BuildCore(parameter, markdownServiceProvider, currentBuildInfo, lastBuildInfo)); } } } if (noContentFound) { Logger.LogWarning( "No content file found. Please make sure the content section of docfx.json is correctly configured.", code: WarningCodes.Build.EmptyInputContents); } else if (emptyContentGroups.Count > 0) { Logger.LogWarning( $"No content file found in group: {string.Join(",", emptyContentGroups)}. Please make sure the content section of docfx.json is correctly configured.", code: WarningCodes.Build.EmptyInputContents); } using (new LoggerPhaseScope("Postprocess", LogLevel.Verbose)) { var generatedManifest = ManifestUtility.MergeManifest(manifests); generatedManifest.SitemapOptions = parameters.FirstOrDefault()?.SitemapOptions; ManifestUtility.RemoveDuplicateOutputFiles(generatedManifest.Files); ManifestUtility.ApplyLogCodes(generatedManifest.Files, logCodesLogListener.Codes); // We can only globally shrink once to avoid invalid reference. // Shrink multiple times may remove files that are already linked in saved manifest. if (_intermediateFolder != null) { // TODO: shrink here is not safe as post processor may update it. // should shrink once at last to handle everything, or make FAL support copy on writes generatedManifest.Files.Shrink(_intermediateFolder, parameters[0].MaxParallelism); currentBuildInfo.SaveVersionsManifet(_intermediateFolder); } EnvironmentContext.FileAbstractLayerImpl = FileAbstractLayerBuilder.Default .ReadFromManifest(generatedManifest, parameters[0].OutputBaseDir) .WriteToManifest(generatedManifest, parameters[0].OutputBaseDir) .Create(); using (new PerformanceScope("Process")) { _postProcessorsManager.Process(generatedManifest, outputDirectory); } using (new PerformanceScope("Dereference")) { if (parameters[0].KeepFileLink) { var count = (from f in generatedManifest.Files from o in f.OutputFiles select o.Value into v where v.LinkToPath != null select v).Count(); if (count > 0) { Logger.LogInfo($"Skip dereferencing {count} files."); } } else { generatedManifest.Dereference(parameters[0].OutputBaseDir, parameters[0].MaxParallelism); } } using (new PerformanceScope("SaveManifest")) { // Save to manifest.json EnvironmentContext.FileAbstractLayerImpl = FileAbstractLayerBuilder.Default .ReadFromRealFileSystem(parameters[0].OutputBaseDir) .WriteToRealFileSystem(parameters[0].OutputBaseDir) .Create(); SaveManifest(generatedManifest); } using (new PerformanceScope("Cleanup")) { EnvironmentContext.FileAbstractLayerImpl = null; // overwrite intermediate cache files if (_intermediateFolder != null && transformDocument) { try { if (Logger.WarningCount >= Logger.WarningThrottling) { currentBuildInfo.IsValid = false; currentBuildInfo.Message = $"Warning count {Logger.WarningCount} exceeds throttling {Logger.WarningThrottling}"; } currentBuildInfo.Save(_intermediateFolder); if (_cleanupCacheHistory) { ClearCacheExcept(currentBuildInfo.DirectoryName); } } catch (Exception ex) { Logger.LogWarning($"Error happened while saving cache. Message: {ex.Message}."); } } } } } catch { // Leave cache folder there as it contains historical data // exceptions happens in this build does not corrupt the cache theoretically // however the cache file created by this build will never be cleaned up with DisableIncrementalFolderCleanup option if (_intermediateFolder != null && _cleanupCacheHistory) { ClearCacheExcept(lastBuildInfo?.DirectoryName); } throw; } finally { Logger.UnregisterListener(logCodesLogListener); } IMarkdownServiceProvider GetMarkdownServiceProvider() { using (new PerformanceScope(nameof(GetMarkdownServiceProvider))) { var result = CompositionContainer.GetExport <IMarkdownServiceProvider>(_container, parameters[0].MarkdownEngineName); if (result == null) { Logger.LogError($"Unable to find markdown engine: {parameters[0].MarkdownEngineName}"); throw new DocfxException($"Unable to find markdown engine: {parameters[0].MarkdownEngineName}"); } Logger.LogInfo($"Markdown engine is {parameters[0].MarkdownEngineName}", code: InfoCodes.Build.MarkdownEngineName); return(result); } } void EnrichCurrentBuildInfo(BuildInfo current, BuildInfo last) { current.CommitFromSHA = _commitFromSHA; current.CommitToSHA = _commitToSHA; if (_intermediateFolder != null) { current.PluginHash = ComputePluginHash(_assemblyList); current.TemplateHash = _templateHash; if (!_cleanupCacheHistory && last != null) { // Reuse the directory for last incremental if cleanup is disabled current.DirectoryName = last.DirectoryName; } else { current.DirectoryName = IncrementalUtility.CreateRandomDirectory(Environment.ExpandEnvironmentVariables(_intermediateFolder)); } } } }
public void ItOnlyGetsGameDefinitionsForTheCurrentPlayersGamingGroup() { Assert.True(_actualGameDefinitionSummaries.All(game => game.GamingGroupId == testUserWithDefaultGamingGroup.CurrentGamingGroupId)); }
public override async Task CollectFanArtAsync(Guid mediaItemId, IDictionary <Guid, IList <MediaItemAspect> > aspects) { IResourceLocator mediaItemLocator = null; if (!BaseInfo.IsVirtualResource(aspects)) { mediaItemLocator = GetResourceLocator(aspects); } if (!aspects.ContainsKey(MovieAspect.ASPECT_ID) || mediaItemLocator == null) { return; } IFanArtCache fanArtCache = ServiceRegistration.Get <IFanArtCache>(); using (IResourceAccessor mediaItemAccessor = mediaItemLocator.CreateAccessor()) { IList <Tuple <Guid, string> > actors = GetActors(aspects); //Check if loading nfo is needed if ((actors?.All(a => IsInCache(a.Item1)) ?? true) && IsInCache(mediaItemId)) { return; //Everything was already saved } NfoMovieReader movieNfoReader = await MOVIE_EXTRACTOR.TryGetNfoMovieReaderAsync(mediaItemAccessor, true).ConfigureAwait(false); if (movieNfoReader != null) { //Movie fanart var stubs = movieNfoReader.GetMovieStubs(); var mainStub = stubs?.FirstOrDefault(); if (AddToCache(mediaItemId)) { if (mainStub?.Thumb != null) { await fanArtCache.TrySaveFanArt(mediaItemId, mainStub.Title, FanArtTypes.Poster, p => TrySaveFileImage(mainStub.Thumb, p, "Thumb", "Nfo.")).ConfigureAwait(false); } await TrySaveFanArt(fanArtCache, FanArtTypes.FanArt, "FanArt", mainStub?.FanArt, mediaItemId, mainStub?.Title).ConfigureAwait(false); await TrySaveFanArt(fanArtCache, FanArtTypes.DiscArt, "DiscArt", mainStub?.DiscArt, mediaItemId, mainStub?.Title).ConfigureAwait(false); await TrySaveFanArt(fanArtCache, FanArtTypes.Logo, "Logo", mainStub?.Logos, mediaItemId, mainStub?.Title).ConfigureAwait(false); await TrySaveFanArt(fanArtCache, FanArtTypes.ClearArt, "ClearArt", mainStub?.ClearArt, mediaItemId, mainStub?.Title).ConfigureAwait(false); await TrySaveFanArt(fanArtCache, FanArtTypes.Banner, "Banner", mainStub?.Banners, mediaItemId, mainStub?.Title).ConfigureAwait(false); await TrySaveFanArt(fanArtCache, FanArtTypes.Thumbnail, "Landscape", mainStub?.Landscape, mediaItemId, mainStub?.Title).ConfigureAwait(false); } //Actor fanart if (actors != null) { foreach (var actor in actors) { if (!IsInCache(actor.Item1)) { var existingThumbs = fanArtCache.GetFanArtFiles(actor.Item1, FanArtTypes.Thumbnail); var actorStub = mainStub?.Actors?.FirstOrDefault(a => string.Equals(a?.Name, actor.Item2, StringComparison.InvariantCultureIgnoreCase)); if (actorStub != null || existingThumbs.Any()) //We have a thumb already or no thumb is available, so no need to check again { AddToCache(actor.Item1); } if (actorStub?.Thumb != null) { await fanArtCache.TrySaveFanArt(actor.Item1, actor.Item2, FanArtTypes.Thumbnail, p => TrySaveFileImage(actorStub.Thumb, p, "Thumb", "Nfo.")).ConfigureAwait(false); } } } } } } }
public static int Solve(string passportsInput) { var passports = passportsInput.Split(Environment.NewLine + Environment.NewLine); return(passports.Count(x => RequiredFields.All(x.Contains))); }
public bool AreAllSimple() => typeMapDifferences.All(tmd => tmd.DifferenceType != DifferenceType.DataTypeChange);
void IConfigurationAction.Configure(BehaviorGraph graph) { graph.Behaviors .Where(chain => _wheres.All(x => x.Matches(chain))) .Each(chain => _actions.Each(x => x.Modify(chain))); }
public void TestInsertedEntitiesIdentities_OutputIdentity() { _context.BulkInsert(_collection, InsertOptions.OutputIdentity); Assert.True(_collection.All(model => model.Id != 0)); }
/// <see cref="IPersonRepository.UpdatePersonFacts" /> public bool UpdatePersonFacts(IList <PersonFact> facts, int userId) { return(facts.All(fact => UpdatePersonFact(fact, userId) != null)); }
async void OnDismiss(object sender, EventArgs e) { Button button = (Button)sender; button.IsEnabled = false; this.IsBusy = true; try { int Id = 0; string status = "Pending"; int jobid = jobdetail.Id; if (jobseeker != null) { string proposal = proposalCell.Text.TrimEnd(); if (string.IsNullOrEmpty(proposal)) { await DisplayAlert("Alert Message", "Please fill up the proposal.", "Cancel"); } else if (proposalCell.Text.Length > 200) { await DisplayAlert("Alert Message", "Porposal statement should not be more than 200 characters.", "Cancel"); } else { int count = 0; var checkjs = await jsmanager.GetApplyJob(jobseeker.Username); foreach (Submission applied in checkjs) { if (applies.All(b => b.Id != applied.Id)) { if (applied.Jobid == jobdetail.Id) { applies.Add(applied); count++; } } } if (count == 0) { //apply Submission submission = new Submission(Id, status, proposal, jobdetail.Title, jobid, jobseeker.Name, jobseeker.Username); var submit = await jsmanager.CreateSubmission(submission); if (submit != null) { await DisplayAlert("Apply Successful", "Application submitted.", "Cancel"); await Navigation.PopModalAsync(); } else { await DisplayAlert("Apply Failed", "Application fail to submit. Something wents wrong.", "Cancel"); await Navigation.PopModalAsync(); } } else { await DisplayAlert("Apply Failed", "You have already apply for this job.", "Cancel"); await Navigation.PopModalAsync(); } } } else { string description = descriptionCell.Text.TrimEnd(); string convert = salaryCell.Text.TrimEnd(); string salarytype = salaryType.Items[salaryType.SelectedIndex]; string jobstatus = Status.Items[Status.SelectedIndex]; if (string.IsNullOrEmpty(description) || string.IsNullOrEmpty(convert)) { await DisplayAlert("Alert Message", "Please fill up the job description and salary.", "Cancel"); } else { try { decimal salary1 = decimal.Parse(convert); decimal salary = Math.Round(salary1, 2); if (salary <= 0 || salary > 210000) { await DisplayAlert("Alert Message", "Salary must be greater than 0 and lesser than 210,000.", "Cancel"); } else { if (jobstatus.Equals("End")) { if (await this.DisplayAlert("End Job?", "You can't change the job details anymore once you have end the job's status. Are you sure, you still want to proceed?", "Yes", "Cancel") == true) { //update Job job = new Job(jobdetail.Id, jobdetail.Title, description, salary, salarytype, jobstatus, jobdetail.Entusername); var update = await entmanager.UpdateJob(job); if (update != null) { await DisplayAlert("Update Successful", "Application updated.", "Cancel"); await Navigation.PopModalAsync(); } else { await DisplayAlert("Update Failed", "Application fail to update.", "Cancel"); await Navigation.PopModalAsync(); } } } else { //update Job job = new Job(jobdetail.Id, jobdetail.Title, description, salary, salarytype, jobstatus, jobdetail.Entusername); var update = await entmanager.UpdateJob(job); if (update != null) { await DisplayAlert("Update Successful", "Application updated.", "Cancel"); await Navigation.PopModalAsync(); } else { await DisplayAlert("Update Failed", "Application fail to update.", "Cancel"); await Navigation.PopModalAsync(); } } } } catch (Exception ex) { await DisplayAlert("Alert Message", "Something wents wrong.", "Cancel"); } } } } finally { this.IsBusy = false; button.IsEnabled = true; } }
static void Main(string[] args) { Console.WriteLine("### ADVENT OF CODE PUZZLE RUNNER ###"); Console.WriteLine("Building puzzle list..."); var puzzleType = typeof(Puzzle); var puzzleImplementationTypesDictionary = new Dictionary <int, Dictionary <int, Type> >(); Assembly.GetExecutingAssembly().GetTypes().Where(t => (!(t.IsAbstract || t.IsInterface)) && puzzleType.IsAssignableFrom(t)).ForEach(t => { var yearAttribute = t.GetCustomAttribute <YearAttribute>(); if (yearAttribute == null) { Console.WriteLine("Puzzle implementation {0}.{1} did not have a year attribute", t.Namespace, t.Name); return; } var dayAttribute = t.GetCustomAttribute <DayAttribute>(); if (dayAttribute == null) { Console.WriteLine("Puzzle implementation {0}.{1} did not have a day attribute", t.Namespace, t.Name); return; } if (!puzzleImplementationTypesDictionary.ContainsKey(yearAttribute.YearValue)) { puzzleImplementationTypesDictionary.Add(yearAttribute.YearValue, new Dictionary <int, Type>()); } if (puzzleImplementationTypesDictionary[yearAttribute.YearValue].ContainsKey(dayAttribute.DayValue)) { Console.WriteLine("Multiple puzzle implementations exist for the same day: Year {0}, Day {1}", yearAttribute.YearValue, dayAttribute.DayValue); return; } puzzleImplementationTypesDictionary[yearAttribute.YearValue].Add(dayAttribute.DayValue, t); }); if (puzzleImplementationTypesDictionary.Count == 0) { Console.WriteLine("No puzzle implementations exist. Press any key to exit..."); Console.ReadLine(); return; } var implementationCount = puzzleImplementationTypesDictionary.Select(kvp => kvp.Value.Count).Sum(); Console.WriteLine("Found {0} puzzle implementation{1}", implementationCount, implementationCount == 1 ? "" : "s"); var currentDayEST = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.CreateCustomTimeZone("EST", new TimeSpan(-5, 0, 0), "EST", "EST")); Console.WriteLine("Checking for sovled puzzles..."); // Check for solution file if (!Directory.Exists("Data")) { Directory.CreateDirectory("Data"); } if (!File.Exists(Path.Combine("Data", "SolvedPuzzles.txt"))) { File.Create(Path.Combine("Data", "SolvedPuzzles.txt")).Close(); } var solvedPuzzles = File.ReadAllLines(Path.Combine("Data", "SolvedPuzzles.txt")).ToList(); Console.WriteLine("Current day in EST: {0}/{1}/{2}", currentDayEST.Year, currentDayEST.Month, currentDayEST.Day); var running = true; var selectedYear = default(int?); var selectedDay = default(int?); var partsToRun = new List <int>(); var autoSubmit = default(bool?); if (currentDayEST.Month == 12 && currentDayEST.Day < 26) { Console.WriteLine("Currently in Advent period! Checking for today's puzzle..."); if (!puzzleImplementationTypesDictionary.ContainsKey(currentDayEST.Year) || !puzzleImplementationTypesDictionary[currentDayEST.Year].ContainsKey(currentDayEST.Day)) { Console.WriteLine("No implementation exists year for today's puzzle. Go to https://adventofcode.com/{0}/day/{1} for puzzle details! Proceeding to puzzle selection...", currentDayEST.Year, currentDayEST.Day); } else { if (!solvedPuzzles.Contains(currentDayEST.Year.ToString() + "_" + currentDayEST.Day.ToString() + "_1")) { Console.WriteLine("Part 1 not yet solved - running solution..."); Console.WriteLine(); selectedYear = currentDayEST.Year; selectedDay = currentDayEST.Day; partsToRun.Add(1); autoSubmit = true; } else if (!solvedPuzzles.Contains(currentDayEST.Year.ToString() + "_" + currentDayEST.Day.ToString() + "_2")) { Console.WriteLine("Part 2 not yet solved - running solution..."); Console.WriteLine(); selectedYear = currentDayEST.Year; selectedDay = currentDayEST.Day; partsToRun.Add(2); autoSubmit = true; } else { Console.WriteLine("Today's puzzle has already been solved! Proceeding to puzzle selection..."); } } } else { Console.WriteLine("Outside of advent period. Proceeding to puzzle selection..."); } while (running) { while (selectedYear == null) { Console.WriteLine(); Console.WriteLine("Select year:"); puzzleImplementationTypesDictionary.Keys.OrderBy(k => k).ForEach(i => Console.WriteLine("{0}", i)); var userInput = Console.ReadLine(); var selection = 0; if (!int.TryParse(userInput, out selection) || !puzzleImplementationTypesDictionary.ContainsKey(selection)) { Console.WriteLine("Invalid input, please select one of the available options..."); Console.WriteLine("Press ESC to quit or any key to continue..."); if (Console.ReadKey().Key == ConsoleKey.Escape) { return; } continue; } selectedYear = selection; } while (selectedDay == null) { Console.WriteLine(); Console.WriteLine("Year {0}", selectedYear); Console.WriteLine("Select day:"); puzzleImplementationTypesDictionary[selectedYear.Value].Keys.OrderBy(k => k).ForEach(i => Console.WriteLine("{0}", i)); var userInput = Console.ReadLine(); var selection = 0; if (!int.TryParse(userInput, out selection) || !puzzleImplementationTypesDictionary[selectedYear.Value].ContainsKey(selection)) { Console.WriteLine("Invalid input, please select one of the available options..."); Console.WriteLine("Press ESC to quit or any key to continue..."); if (Console.ReadKey().Key == ConsoleKey.Escape) { return; } continue; } selectedDay = selection; } while (partsToRun.Count == 0) { Console.WriteLine(); Console.Write("Choose puzzle part to run [1/2/(B)oth]: "); var userInput = Console.ReadKey(); if (userInput.Key == ConsoleKey.D1 || userInput.Key == ConsoleKey.NumPad1) { partsToRun.Add(1); } else if (userInput.Key == ConsoleKey.D2 || userInput.Key == ConsoleKey.NumPad2) { partsToRun.Add(2); } else if (userInput.Key == ConsoleKey.B) { partsToRun.AddRange(new[] { 1, 2 }); } else { Console.WriteLine("Invalid input, please select 1, 2, or (B)oth..."); Console.WriteLine("Press ESC to quit or any key to continue..."); if (Console.ReadKey().Key == ConsoleKey.Escape) { return; } continue; } } while (autoSubmit == null) { Console.WriteLine(); Console.Write("Automatically submit solution to AoC? [Y/N]: "); var userInput = Console.ReadKey(); if (userInput.Key == ConsoleKey.Y) { autoSubmit = true; } else if (userInput.Key == ConsoleKey.N) { autoSubmit = false; } else { Console.WriteLine("Invalid input, please select (Y)es or (N)o..."); Console.WriteLine("Press ESC to quit or any key to continue..."); if (Console.ReadKey().Key == ConsoleKey.Escape) { return; } continue; } } Console.Clear(); var puzzleToRun = Activator.CreateInstance(puzzleImplementationTypesDictionary[selectedYear.Value][selectedDay.Value]) as Puzzle; partsToRun.Sort(); Console.WriteLine("Running solution for {0}/12/{1} part{2} {3} - solution will{4} be submitted on completion", selectedYear, selectedDay, partsToRun.Count == 1 ? "": "s", string.Join(" & ", partsToRun.Select(i => i.ToString())), autoSubmit.Value ? "" : " not"); foreach (var partToRun in partsToRun.OrderBy(i => i)) { Console.WriteLine("Part {0}", partToRun); IList <PuzzleResult> puzzleTestResults = null; var exceptionInTests = false; try { puzzleTestResults = puzzleToRun.Test(partToRun); } catch (Exception ex) { Console.WriteLine("Exception during tests for part {0}:", partToRun); Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); exceptionInTests = true; } if (!exceptionInTests && (puzzleTestResults == null || puzzleTestResults.Count() == 0 || puzzleTestResults.All(result => { if (result.SolutionResponse != SolutionResponse.Correct) { Console.WriteLine("Test failed with message: '{0}'", result.FullTextResponse); } return(result.SolutionResponse == SolutionResponse.Correct); }))) { if (!Directory.Exists(Path.Combine("Data", selectedYear.ToString(), selectedDay.ToString()))) { Directory.CreateDirectory(Path.Combine("Data", selectedYear.ToString(), selectedDay.ToString())); } if (!File.Exists(Path.Combine("Data", selectedYear.ToString(), selectedDay.ToString(), "SolutionHistory.txt"))) { File.Create(Path.Combine("Data", selectedYear.ToString(), selectedDay.ToString(), "SolutionHistory.txt")).Close(); } var solutionHistory = File.ReadAllLines(Path.Combine("Data", selectedYear.ToString(), selectedDay.ToString(), "SolutionHistory.txt")).Select(s => new SubmittedSolution(s.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))).Where(ss => ss.Part == partToRun).ToList(); Console.WriteLine("All tests passed, continuing with solution..."); var solutionResult = puzzleToRun.Solve(partToRun, autoSubmit.Value, solutionHistory); Console.WriteLine("Solution:"); Console.WriteLine(solutionResult.Solution); Console.WriteLine("Calculated in:"); Console.WriteLine("{0}:{1}:{2}.{3}", solutionResult.ExecutionTime.Hours, solutionResult.ExecutionTime.Minutes, solutionResult.ExecutionTime.Seconds, solutionResult.ExecutionTime.Milliseconds); if (solutionResult.RepeatedSubmission || solutionResult.ComparedWithCached) { Console.WriteLine(); Console.Write("SUBMISSION SKIPPED - "); Console.WriteLine(solutionResult.RepeatedSubmission ? "Duplicate submission in history" : "Correct solution was already found in submission history"); } if (autoSubmit.Value) { Console.WriteLine(); Console.Write("Solution was "); switch (solutionResult.SolutionResponse) { case SolutionResponse.Correct: Console.WriteLine("correct!"); if (!solvedPuzzles.Contains(selectedYear.Value.ToString() + "_" + selectedDay.Value.ToString() + "_" + partToRun.ToString())) { solvedPuzzles.Add(selectedYear.Value.ToString() + "_" + selectedDay.Value.ToString() + "_" + partToRun.ToString()); File.WriteAllLines(Path.Combine("Data", "SolvedPuzzles.txt"), solvedPuzzles); } break; case SolutionResponse.IncorrectNoInformation: Console.WriteLine("incorrect..."); break; case SolutionResponse.IncorrectTooHigh: Console.WriteLine("incorrect, the answer was too high..."); break; case SolutionResponse.IncorrectTooLow: Console.WriteLine("incorrect, the answer was too low..."); break; case SolutionResponse.WaitToSubmit: Console.WriteLine("submitted too soon..."); Console.WriteLine("Wait another {0}m {1}s until submitting again", solutionResult.WaitTime?.Minutes, solutionResult.WaitTime?.Seconds); break; case SolutionResponse.AlreadySolved: Console.WriteLine("ignored, the correct solution has already been submitted for this puzzle..."); Console.WriteLine("Attemping to fetch previous solution..."); Console.WriteLine(); var puzzlePageText = Connectivity.FetchPuzzlePage(selectedYear.Value, selectedDay.Value); var answerParser = new Regex("Your puzzle answer was <code>(?<answer>.*?)<\\/code>", RegexOptions.Singleline); var answerMatches = answerParser.Matches(puzzlePageText); if (answerMatches.Count < partToRun) { Console.WriteLine("The submitted solution for part {0} was ignored, but {1} answer{2} were found on the page...", partToRun, answerMatches.Count, answerMatches.Count == 1 ? "" : "s"); } for (var matchCounter = 0; matchCounter < answerMatches.Count; ++matchCounter) { var thisMatch = answerMatches[matchCounter]; solutionHistory.Add(new SubmittedSolution(matchCounter + 1, thisMatch.Groups["answer"].Value, SolutionResponse.Correct)); if (partToRun == (matchCounter + 1)) { Console.Write("By comparison with previous submission, this solution was "); if (solutionResult.Solution == thisMatch.Groups["answer"].Value) { Console.WriteLine("correct!"); } else { var parsedSubmission = 0; var parsedHistoric = 0; if (int.TryParse(solutionResult.Solution, out parsedSubmission) && int.TryParse(thisMatch.Groups["answer"].Value, out parsedHistoric)) { if (parsedSubmission > parsedHistoric) { Console.WriteLine("incorrect, the answer was too high..."); } else { Console.WriteLine("incorrect, the answer was too low..."); } } else { Console.WriteLine("incorrect..."); } } } } if (answerMatches.Count > 0) { File.WriteAllLines(Path.Combine("Data", selectedYear.ToString(), selectedDay.ToString(), "SolutionHistory.txt"), solutionHistory.Select(ss => ss.ToString()).ToList()); } break; case SolutionResponse.NotSubmitted: Console.WriteLine("was not submitted..."); break; case SolutionResponse.Unrecognised: default: Console.WriteLine("unknown - unable to parse response"); Console.WriteLine("Full response from AoC:"); Console.WriteLine(solutionResult.FullTextResponse); break; } var validResponses = new List <SolutionResponse> { SolutionResponse.Correct, SolutionResponse.IncorrectNoInformation, SolutionResponse.IncorrectTooHigh, SolutionResponse.IncorrectTooLow }; if (validResponses.Any(valid => valid == solutionResult.SolutionResponse) && solutionHistory.All(ss => ss.Response != SolutionResponse.Correct) && solutionHistory.All(ss => ss.Solution != solutionResult.Solution)) { solutionHistory.Add(new SubmittedSolution(partToRun, solutionResult.Solution, solutionResult.SolutionResponse)); File.WriteAllLines(Path.Combine("Data", selectedYear.ToString(), selectedDay.ToString(), "SolutionHistory.txt"), solutionHistory.Select(ss => ss.ToString()).ToList()); } } } else { Console.WriteLine("One or more tests failed, revise solution..."); } Console.WriteLine(); } Console.WriteLine("Execution complete!"); Console.WriteLine("Press ESC to exit or any key to return to puzzle selection..."); if (Console.ReadKey().Key == ConsoleKey.Escape) { return; } else { selectedYear = default(int?); selectedDay = default(int?); partsToRun = new List <int>(); autoSubmit = default(bool?); } } }
/// <see cref="IPersonRepository.UpdatePersonFacts" /> public bool UpdateEventFacts(IList <EventFact> facts, int userId) { return(facts.All(fact => UpdateEventFact(fact, userId) != null)); }
private static bool EveryoneLost(IList <PlayerRank> playerRanks) { return(playerRanks.All(x => x.GameRank != 1)); }
/// <see cref="IEventRepository.AddConnections" /> public bool AddConnections(IList <EventConnection> connections, int userId) { return(connections.All(el => SaveConnection(el, userId) != null)); }
/// <summary> /// Wrapper method to check if a list of objects contains no nulls using contracts. /// </summary> /// <typeparam name="T">The type of object in the list.</typeparam> /// <param name="items">A list of items to check. If null, this will pass.</param> /// <returns>The list that was passed in.</returns> public static IList <T> RequiresContainsNoNulls <T>(IList <T> items) { Contract.Requires(items?.All(i => i != null) ?? true); return(items); }
private static Benchmark[] GetFilteredBenchmarks(IList <Benchmark> benchmarks, IList <IFilter> filters) { return(benchmarks.Where(benchmark => filters.All(filter => filter.Predicate(benchmark))).ToArray()); }
/// <summary> /// Builds the full build script from the list of snippets for each platform. /// </summary> /// <returns>Finalized build script as a string.</returns> private string BuildScriptFromSnippets( BuildScriptGeneratorContext context, string installationScript, IList <BuildScriptSnippet> buildScriptSnippets, IDictionary <string, string> toolsToVersion, List <string> directoriesToExcludeFromCopyToIntermediateDir, List <string> directoriesToExcludeFromCopyToBuildOutputDir, IEnumerable <PlatformDetectorResult> detectionResults) { string script; string benvArgs = StringExtensions.JoinKeyValuePairs(toolsToVersion); benvArgs = $"{benvArgs} {Constants.BenvDynamicInstallRootDirKey}=\"{_cliOptions.DynamicInstallRootDir}\""; Dictionary <string, string> buildProperties = buildScriptSnippets .Where(s => s.BuildProperties != null) .SelectMany(s => s.BuildProperties) .ToDictionary(p => p.Key, p => p.Value); buildProperties[ManifestFilePropertyKeys.OperationId] = context.OperationId; var sourceDirInBuildContainer = _cliOptions.SourceDir; if (!string.IsNullOrEmpty(_cliOptions.IntermediateDir)) { sourceDirInBuildContainer = _cliOptions.IntermediateDir; } buildProperties[ManifestFilePropertyKeys.SourceDirectoryInBuildContainer] = sourceDirInBuildContainer; var allPlatformNames = detectionResults .Where(s => s.Platform != null) .Select(s => s.Platform) .ToList(); foreach (var eachPlatformName in allPlatformNames) { _logger.LogInformation($"Build Property Key:{ManifestFilePropertyKeys.PlatformName} value: {eachPlatformName} is written into manifest"); if (buildProperties.ContainsKey(ManifestFilePropertyKeys.PlatformName)) { var previousValue = buildProperties[ManifestFilePropertyKeys.PlatformName]; buildProperties[ManifestFilePropertyKeys.PlatformName] = string.Join( ",", previousValue, eachPlatformName); } else { buildProperties[ManifestFilePropertyKeys.PlatformName] = eachPlatformName; } } (var preBuildCommand, var postBuildCommand) = PreAndPostBuildCommandHelper.GetPreAndPostBuildCommands( context.SourceRepo, _cliOptions); var outputIsSubDirOfSourceDir = false; if (!string.IsNullOrEmpty(_cliOptions.DestinationDir)) { outputIsSubDirOfSourceDir = DirectoryHelper.IsSubDirectory( _cliOptions.DestinationDir, _cliOptions.SourceDir); } // Copy the source content to destination only if all the platforms involved in generating the build script // say yes. var copySourceDirectoryContentToDestinationDirectory = buildScriptSnippets.All( snippet => snippet.CopySourceDirectoryContentToDestinationDirectory); if (!string.IsNullOrEmpty(_cliOptions.AppType) && !string.IsNullOrWhiteSpace(_cliOptions.AppType)) { _logger.LogInformation($"Build Property Key {Constants.AppType} with value {_cliOptions.AppType} is written into manifest"); buildProperties[Constants.AppType] = _cliOptions.AppType; } var buildScriptProps = new BaseBashBuildScriptProperties() { OsPackagesToInstall = _cliOptions.RequiredOsPackages ?? new string[0], BuildScriptSnippets = buildScriptSnippets.Select(s => s.BashBuildScriptSnippet), BenvArgs = benvArgs, PreBuildCommand = preBuildCommand, PostBuildCommand = postBuildCommand, DirectoriesToExcludeFromCopyToIntermediateDir = directoriesToExcludeFromCopyToIntermediateDir, DirectoriesToExcludeFromCopyToBuildOutputDir = directoriesToExcludeFromCopyToBuildOutputDir, ManifestFileName = FilePaths.BuildManifestFileName, ManifestDir = context.ManifestDir, BuildProperties = buildProperties, BenvPath = FilePaths.Benv, PlatformInstallationScript = installationScript, OutputDirectoryIsNested = outputIsSubDirOfSourceDir, CopySourceDirectoryContentToDestinationDirectory = copySourceDirectoryContentToDestinationDirectory, }; LogScriptIfGiven("pre-build", buildScriptProps.PreBuildCommand); LogScriptIfGiven("post-build", buildScriptProps.PostBuildCommand); script = TemplateHelper.Render( TemplateHelper.TemplateResource.BaseBashScript, buildScriptProps, _logger); return(script); }
public TimeSpan UpdateState(string instrumentationKey, string authApiKey) { if (string.IsNullOrWhiteSpace(instrumentationKey)) { return(this.timings.ServicePollingInterval); } if (this.firstStateUpdate) { this.ResetLastSuccessful(); this.firstStateUpdate = false; } CollectionConfigurationInfo configurationInfo; if (this.IsCollectingData) { // we are currently collecting IList <QuickPulseDataSample> dataSamplesToSubmit = this.onSubmitSamples(); if (!dataSamplesToSubmit.Any()) { // no samples to submit, do nothing return(this.DetermineBackOffs()); } else { // we have samples if (dataSamplesToSubmit.Any(sample => sample.CollectionConfigurationAccumulator.GetRef() != 0)) { // some samples are still being processed, wait a little to give them a chance to finish Thread.Sleep(this.coolDownTimeout); bool allCooledDown = dataSamplesToSubmit.All(sample => sample.CollectionConfigurationAccumulator.GetRef() == 0); QuickPulseEventSource.Log.CollectionConfigurationSampleCooldownEvent(allCooledDown); } } bool?keepCollecting = this.serviceClient.SubmitSamples( dataSamplesToSubmit, instrumentationKey, this.currentConfigurationETag, authApiKey, out configurationInfo, this.collectionConfigurationErrors.ToArray()); QuickPulseEventSource.Log.SampleSubmittedEvent(this.currentConfigurationETag, configurationInfo?.ETag, keepCollecting.ToString()); switch (keepCollecting) { case null: // the request has failed, so we need to return the samples back to the submitter this.onReturnFailedSamples(dataSamplesToSubmit); break; case true: // the service wants us to keep collecting this.UpdateConfiguration(configurationInfo); break; case false: // the service wants us to stop collection this.onStopCollection(); break; } this.lastSuccessfulSubmit = keepCollecting.HasValue ? this.timeProvider.UtcNow : this.lastSuccessfulSubmit; this.IsCollectingData = keepCollecting ?? this.IsCollectingData; } else { // we are currently idle and pinging the service waiting for it to ask us to start collecting data bool?startCollection = this.serviceClient.Ping( instrumentationKey, this.timeProvider.UtcNow, this.currentConfigurationETag, authApiKey, out configurationInfo); QuickPulseEventSource.Log.PingSentEvent(this.currentConfigurationETag, configurationInfo?.ETag, startCollection.ToString()); switch (startCollection) { case null: // the request has failed break; case true: // the service wants us to start collection now this.UpdateConfiguration(configurationInfo); this.onStartCollection(); break; case false: // the service wants us to remain idle and keep pinging break; } this.lastSuccessfulPing = startCollection.HasValue ? this.timeProvider.UtcNow : this.lastSuccessfulPing; this.IsCollectingData = startCollection ?? this.IsCollectingData; } return(this.DetermineBackOffs()); }
public override async Task CollectFanArtAsync(Guid mediaItemId, IDictionary <Guid, IList <MediaItemAspect> > aspects) { IResourceLocator mediaItemLocator = null; if (!BaseInfo.IsVirtualResource(aspects)) { mediaItemLocator = GetResourceLocator(aspects); } if (!aspects.ContainsKey(EpisodeAspect.ASPECT_ID) || mediaItemLocator == null) { return; } IFanArtCache fanArtCache = ServiceRegistration.Get <IFanArtCache>(); using (IResourceAccessor mediaItemAccessor = mediaItemLocator.CreateAccessor()) { EpisodeInfo episodeInfo = new EpisodeInfo(); if (!episodeInfo.FromMetadata(aspects)) { return; } //Episode fanart if (AddToCache(mediaItemId)) { var existingThumbs = fanArtCache.GetFanArtFiles(mediaItemId, FanArtTypes.Thumbnail); int?season = episodeInfo.SeasonNumber; int?episode = episodeInfo.EpisodeNumbers != null && episodeInfo.EpisodeNumbers.Any() ? episodeInfo.EpisodeNumbers.First() : (int?)null; if (!existingThumbs.Any()) //Only get thumb if needed for better performance { NfoSeriesEpisodeReader episodeReader = await SERIES_EXTRACTOR.TryGetNfoSeriesEpisodeReaderAsync(mediaItemAccessor, season, episode, true).ConfigureAwait(false); if (episodeReader != null) { var stubs = episodeReader.GetEpisodeStubs(); var mainStub = stubs?.FirstOrDefault(); if (mainStub?.Thumb != null) { await fanArtCache.TrySaveFanArt(mediaItemId, episodeInfo.ToString(), FanArtTypes.Thumbnail, p => TrySaveFileImage(mainStub.Thumb, p, "Thumb", "Nfo.")).ConfigureAwait(false); } } } } //Series fanart if (RelationshipExtractorUtils.TryGetLinkedId(SeriesAspect.ROLE_SERIES, aspects, out Guid seriesMediaItemId)) { IList <Tuple <Guid, string> > actors = GetActors(aspects); RelationshipExtractorUtils.TryGetLinkedId(SeasonAspect.ROLE_SEASON, aspects, out Guid seasonMediaItemId); //Check if loading nfo is needed if ((actors?.All(a => IsInCache(a.Item1)) ?? true) && IsInCache(seriesMediaItemId) && (seasonMediaItemId == Guid.Empty || IsInCache(seasonMediaItemId))) { return; //Everything was already saved } NfoSeriesReader seriesNfoReader = await SERIES_EXTRACTOR.TryGetNfoSeriesReaderAsync(mediaItemAccessor, true).ConfigureAwait(false); if (seriesNfoReader != null) { var stubs = seriesNfoReader.GetSeriesStubs(); var mainStub = stubs?.FirstOrDefault(); if (AddToCache(seriesMediaItemId)) { var series = episodeInfo.CloneBasicInstance <SeriesInfo>(); if (mainStub?.Thumbs?.Count > 0) { await TrySaveThumbStubs(fanArtCache, mainStub.Thumbs, null, seriesMediaItemId, series.ToString()); } } if (seasonMediaItemId != Guid.Empty && episodeInfo.SeasonNumber.HasValue && AddToCache(seasonMediaItemId)) { var season = episodeInfo.CloneBasicInstance <SeasonInfo>(); if (mainStub?.Thumbs?.Count > 0) { await TrySaveThumbStubs(fanArtCache, mainStub.Thumbs, episodeInfo.SeasonNumber, seasonMediaItemId, season.ToString()); } } //Actor fanart //We only want the series actors because thumb loading is disabled on episode actors for performance reasons, so we might need to //load the series nfo multiple time before we have all actors depending on what actors are in the episode foreach (var actor in actors) { if (!IsInCache(actor.Item1)) { var existingThumbs = fanArtCache.GetFanArtFiles(actor.Item1, FanArtTypes.Thumbnail); var actorStub = mainStub?.Actors?.FirstOrDefault(a => string.Equals(a?.Name, actor.Item2, StringComparison.InvariantCultureIgnoreCase)); if (actorStub != null || existingThumbs.Any()) //We have a thumb already or no thumb is available, so no need to check again { AddToCache(actor.Item1); } if (actorStub?.Thumb != null) { await fanArtCache.TrySaveFanArt(actor.Item1, actor.Item2, FanArtTypes.Thumbnail, p => TrySaveFileImage(actorStub.Thumb, p, "Thumb", "Nfo.")).ConfigureAwait(false); } } } } } } }
public void DataRolledBackBetweenLogicalTests() { IList <dynamic> queryResult = null; const string firstPostBody = "this is the body of the first post."; const string secondPostBody = "body of the second post."; When("querying a database within a spec", () => queryResult = GetPosts()); Given("a post is created in a test context.", () => CreatePost(firstPostBody)).Verify(() => Then("the current context can find the single post created.", () => queryResult.Count.ShouldEqual(1)). Then("a subsequent assertion from within the same context should find the same single post, but it should not be duplicated.", () => queryResult.All(p => p.Body.Equals(firstPostBody)).ShouldBeTrue())); Given("a post is created in a context following but separate from a previous context.", () => CreatePost(secondPostBody)).Verify(() => Then("the current context should only find the single post created in this context.", () => queryResult.Count.ShouldEqual(1))); }