public static void DebugIfNeeded(List<IObject> displayList) { string behindThis = _behindThis; if (behindThis == null) return; string whyIsThis = _whyIsThis; bool renderDebug = _renderDebug; _behindThis = null; Dictionary<string, List<string>> map = new Dictionary<string, List<string>>(); const string sortWord = "Sort "; const string backwardsWord = "backwards "; foreach (var obj in displayList) { foreach (var property in obj.Properties.Ints.AllProperties()) { if (!property.Key.Contains(sortWord)) continue; if (renderDebug && property.Key.Contains(backwardsWord)) continue; if (!renderDebug && !property.Key.Contains(backwardsWord)) continue; string comparedId = property.Key.Substring(renderDebug ? property.Key.IndexOf(sortWord) + sortWord.Length : property.Key.IndexOf(backwardsWord) + backwardsWord.Length); if (property.Value > 0) map.GetOrAdd(comparedId, () => new List<string>()).Add(obj.ID); else map.GetOrAdd(obj.ID, () => new List<string>()).Add(comparedId); } } string chain = getChain(whyIsThis, behindThis, map, new HashSet<string>()); Debug.WriteLine(chain == null ? string.Format("{0} is not behind {1}", whyIsThis, behindThis) : string.Format("{0}{1}", whyIsThis, chain)); }
public void Dictionary_GetOrAdd_Adds_Unexisting_Key() { var dictionary = new Dictionary<int, string>(); Assert.Equal("test", dictionary.GetOrAdd(1, v => "test")); Assert.Equal("test", dictionary.GetOrAdd(1, v => "test2")); }
public void TestGetOrAdd() { var dict = new Dictionary<string, string>(); dict.GetOrAdd("x", () => "a"); dict.GetOrAdd("x", () => { throw new Exception("Should not be reached."); }); dict.Should().Equal(new Dictionary<string, string> {["x"] = "a"}); }
public void GetOrAdd() { var dictionary = new Dictionary<int, string> { { 0, "Zero" } }; dictionary.GetOrAdd(0, "0").ShouldBe("Zero"); dictionary.GetOrAdd(1, "One").ShouldBe("One"); dictionary.GetOrAdd(2, () => "Two").ShouldBe("Two"); dictionary.GetOrAdd(3, i => i.ToString()).ShouldBe("3"); }
public void WhenGettingTwice_ThenGetsExisting() { var dictionary = new Dictionary<string, Guid>(); var value = dictionary.GetOrAdd("foo", key => Guid.NewGuid()); var value2 = dictionary.GetOrAdd("foo", key => Guid.NewGuid()); Assert.Equal(value, value2); }
public void TestMiscDictionaryGetOrAdd() { string key0 = "Blinky"; var dict = new Dictionary<string, int>(); int value0 = 0; dict.GetOrAdd(key0, v => value0 = v, () => 42); Assert.Equal(0, value0); dict.GetOrAdd(key0, v => value0 = v, () => 42); Assert.Equal(42, value0); }
public void GetOrAddTest() { var stringValues = new Dictionary<string, string> { ["key1"] = "Hoge" }; Assert.AreEqual("Hoge", stringValues.GetOrAdd("key1", key => "Fuga")); Assert.AreEqual("Hoge", stringValues["key1"]); Assert.AreEqual("key2_Piyo", stringValues.GetOrAdd("key2", key => key + "_Piyo")); Assert.AreEqual("key2_Piyo", stringValues["key2"]); }
public void GetOrAdd() { var d = new Dictionary<string, StockStatus>() { {"AAPL", new StockStatus { Price = 530.12m, Position = "Sell" }}, {"GOOG", new StockStatus { Price = 123.5m, Position = "Buy" }} }; d.GetOrAdd("AAPL").Position = "Buy"; d.GetOrAdd("YHOO").Price = 1.99m; Console.Out.WriteLine(d.ToString<string, StockStatus>()); Assert.That(d["AAPL"].Position, Is.EqualTo("Buy"), "Incorrect position."); Assert.That(d.Keys, Has.Count.EqualTo(3), "Incorrect number of keys."); Assert.That(d["YHOO"].Price, Is.EqualTo(1.99m), "Incorrect price."); }
public void GetOrAdd() { // Type var @this = new Dictionary<string, string>(); // Examples string value1 = @this.GetOrAdd("Fizz", "Buzz"); // return "Buzz"; string value2 = @this.GetOrAdd("Fizz", "Buzz2"); // return "Buzz"; // The Dictionary already contains the key string value3 = @this.GetOrAdd("Fizz2", s => "Buzz"); // return "Buzz"; // Unit Test Assert.AreEqual("Buzz", value1); Assert.AreEqual("Buzz", value2); Assert.AreEqual("Buzz", value3); }
public IEnumerable<RemoteInfo> Load(IEnumerable<ConfigurationEntry> config) { var remotes = new Dictionary<string, RemoteInfo>(); foreach (var entry in config) { var keyParts = entry.Key.Split('.'); if (keyParts.Length == 3 && keyParts[0] == "tfs-remote") { var id = keyParts[1]; var key = keyParts[2]; var remote = remotes.GetOrAdd(id); remote.Id = id; if (key == "url") remote.Url = entry.Value; else if (key == "repository") remote.Repository = entry.Value; else if (key == "username") remote.Username = entry.Value; else if (key == "password") remote.Password = entry.Value; else if (key == "ignore-paths") remote.IgnoreRegex = entry.Value; else if (key == "legacy-urls") remote.Aliases = entry.Value.Split(','); else if (key == "autotag") remote.Autotag = bool.Parse(entry.Value); } } return remotes.Values; }
public GlobalCache(Dictionary<IAdapter, Consumer> consumers, int version) { GlobalSignalLookup = new Dictionary<Guid, List<Consumer>>(); GlobalDestinationLookup = consumers; BroadcastConsumers = new List<Consumer>(); Version = version; // Generate routes for all signals received by each consumer adapter foreach (var kvp in consumers) { var consumerAdapter = kvp.Key; var consumer = kvp.Value; if ((object)consumerAdapter.InputMeasurementKeys != null) { // Create routes for each of the consumer's input signals foreach (Guid signalID in consumerAdapter.InputMeasurementKeys.Select(key => key.SignalID)) { GlobalSignalLookup.GetOrAdd(signalID, id => new List<Consumer>()).Add(consumer); } } else { // Add this consumer to the broadcast routes to begin receiving all measurements BroadcastConsumers.Add(consumer); } } // Broadcast consumers receive all measurements, so add them to every signal route foreach (List<Consumer> consumerList in GlobalSignalLookup.Values) { consumerList.AddRange(BroadcastConsumers); } }
public int AddNewErrors(IVsEnumExternalErrors pErrors) { var projectErrors = new HashSet<DiagnosticData>(); var documentErrorsMap = new Dictionary<DocumentId, HashSet<DiagnosticData>>(); var errors = new ExternalError[1]; uint fetched; while (pErrors.Next(1, errors, out fetched) == VSConstants.S_OK && fetched == 1) { var error = errors[0]; DiagnosticData diagnostic; if (error.bstrFileName != null) { diagnostic = CreateDocumentDiagnosticItem(error); if (diagnostic != null) { var diagnostics = documentErrorsMap.GetOrAdd(diagnostic.DocumentId, _ => new HashSet<DiagnosticData>()); diagnostics.Add(diagnostic); continue; } projectErrors.Add(CreateProjectDiagnosticItem(error)); } else { projectErrors.Add(CreateProjectDiagnosticItem(error)); } } _diagnosticProvider.AddNewErrors(_projectId, projectErrors, documentErrorsMap); return VSConstants.S_OK; }
public void Dictionary_GetOrAdd_Gets_An_Existing_Value() { var dictionary = new Dictionary<int, string>(); dictionary.Add(1, "1"); Assert.Equal("1", dictionary.GetOrAdd(1, v => "test")); }
public IEnumerable<RemoteInfo> Load(IEnumerable<ConfigurationEntry<string>> config) { var remotes = new Dictionary<string, RemoteInfo>(); foreach (var entry in config) { var keyParts = entry.Key.Split('.'); if (keyParts.Length >= 3 && keyParts[0] == "tfs-remote") { // The branch name may contain dots ("maint-1.0.0") which must be considered since split on "." var id = string.Join(".", keyParts, 1, keyParts.Length - 2); var key = keyParts.Last(); var remote = remotes.GetOrAdd(id); remote.Id = id; if (key == "url") remote.Url = entry.Value; else if (key == "repository") remote.Repository = entry.Value; else if (key == "username") remote.Username = entry.Value; else if (key == "password") remote.Password = entry.Value; else if (key == "ignore-paths") remote.IgnoreRegex = entry.Value; else if (key == "legacy-urls") remote.Aliases = entry.Value.Split(','); else if (key == "autotag") remote.Autotag = bool.Parse(entry.Value); } } return remotes.Values; }
private Dictionary<SyntaxToken, SyntaxToken> CreateOldToNewTokensMap( Dictionary<TriviaLocation, PreviousNextTokenPair> tokenPairs, Dictionary<TriviaLocation, LeadingTrailingTriviaPair> triviaPairs) { var map = new Dictionary<SyntaxToken, SyntaxToken>(); foreach (var pair in CreateUniqueTokenTriviaPairs(tokenPairs, triviaPairs)) { var localCopy = pair; var previousToken = map.GetOrAdd(localCopy.Item1.PreviousToken, _ => localCopy.Item1.PreviousToken); map[localCopy.Item1.PreviousToken] = previousToken.WithTrailingTrivia(localCopy.Item2.TrailingTrivia); var nextToken = map.GetOrAdd(localCopy.Item1.NextToken, _ => localCopy.Item1.NextToken); map[localCopy.Item1.NextToken] = nextToken.WithLeadingTrivia(localCopy.Item2.LeadingTrivia); } return map; }
public void WhenGettingNonExisting_ThenCreatesValue() { var id = Guid.NewGuid(); var dictionary = new Dictionary<string, Guid>(); var value = dictionary.GetOrAdd("foo", key => id); Assert.Equal(id, value); }
private IImage loadImage(ITexture texture, IBitmap bitmap, string id, ILoadImageConfig config, ISpriteSheet spriteSheet) { manipulateImage(bitmap, config); bitmap.LoadTexture(null); GLImage image = new GLImage(bitmap, id, texture, spriteSheet, config); string imageId = image.ID; _textures?.GetOrAdd(imageId, () => image.Texture); image.OnImageDisposed.Subscribe(() => _textures.Remove(imageId)); return(image); }
public UpgradeManager(ActorInitializer init) { upgrades = Exts.Lazy(() => { var ret = new Dictionary<string, UpgradeState>(); foreach (var up in init.Self.TraitsImplementing<IUpgradable>()) foreach (var t in up.UpgradeTypes) ret.GetOrAdd(t).Traits.Add(up); return ret; }); }
private Dictionary<SyntaxToken, SyntaxToken> CreateOldToNewTokensMap( Dictionary<TriviaLocation, SyntaxToken> tokens, Dictionary<TriviaLocation, SyntaxAnnotation> annotations) { var token = default(SyntaxToken); var map = new Dictionary<SyntaxToken, SyntaxToken>(); var emptyList = SpecializedCollections.EmptyEnumerable<SyntaxTrivia>(); token = map.GetOrAdd(tokens[TriviaLocation.BeforeBeginningOfSpan], _ => tokens[TriviaLocation.BeforeBeginningOfSpan]); map[tokens[TriviaLocation.BeforeBeginningOfSpan]] = token.WithTrailingTrivia(emptyList).WithAdditionalAnnotations(annotations[TriviaLocation.BeforeBeginningOfSpan]); token = map.GetOrAdd(tokens[TriviaLocation.AfterBeginningOfSpan], _ => tokens[TriviaLocation.AfterBeginningOfSpan]); map[tokens[TriviaLocation.AfterBeginningOfSpan]] = token.WithLeadingTrivia(emptyList).WithAdditionalAnnotations(annotations[TriviaLocation.AfterBeginningOfSpan]); token = map.GetOrAdd(tokens[TriviaLocation.BeforeEndOfSpan], _ => tokens[TriviaLocation.BeforeEndOfSpan]); map[tokens[TriviaLocation.BeforeEndOfSpan]] = token.WithTrailingTrivia(emptyList).WithAdditionalAnnotations(annotations[TriviaLocation.BeforeEndOfSpan]); token = map.GetOrAdd(tokens[TriviaLocation.AfterEndOfSpan], _ => tokens[TriviaLocation.AfterEndOfSpan]); map[tokens[TriviaLocation.AfterEndOfSpan]] = token.WithLeadingTrivia(emptyList).WithAdditionalAnnotations(annotations[TriviaLocation.AfterEndOfSpan]); return map; }
private static Dictionary<string, List<PropertyInfo>> GetPropertiesDependencies([NotNull]Type type) { var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public); var dependencies = new Dictionary<string, List<PropertyInfo>>(properties.Length); foreach (var property in properties) { var dependsOnAttributes = property.GetCustomAttributes<DependsOnAttribute>(); foreach (var dependsOnAttribute in dependsOnAttributes) { var propertyInfos = dependencies.GetOrAdd(dependsOnAttribute.PropertyName, () => new List<PropertyInfo>()); propertyInfos.Add(property); } } return dependencies; }
private void PrepareForImport(Options[] options, Action<string> logger) { var folderIdsByName = new Dictionary<string, List<Tuple<string, string>>>(); AddFoldersRecusive(_session.Folders, folderIdsByName); foreach (var profile in options) { var ids = folderIdsByName.GetOrAdd(profile.OutlookFolderEntryId).FirstOrDefault(); if (ids != null) { profile.OutlookFolderEntryId = ids.Item1; profile.OutlookFolderStoreId = ids.Item2; profile.OutlookFolderAccountName = _optionTasks.GetFolderAccountNameOrNull(profile.OutlookFolderStoreId); } else { logger($"Warning: did not find Folder '{profile.OutlookFolderEntryId}'"); profile.OutlookFolderEntryId = null; profile.OutlookFolderStoreId = null; profile.OutlookFolderAccountName = null; } } }
protected async Task<IDictionary<SyntaxNode, ISet<INamedTypeSymbol>>> GetAllReferencedDefinitionsAsync( Compilation compilation, IEnumerable<ISymbol> members, CancellationToken cancellationToken) { var namespaceScopeToReferencedDefinitions = new Dictionary<SyntaxNode, ISet<INamedTypeSymbol>>(); var root = await Document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); Func<SyntaxNode, ISet<INamedTypeSymbol>> createSet = _ => new HashSet<INamedTypeSymbol>(); var annotatedNodes = root.GetAnnotatedNodesAndTokens(SymbolAnnotation.Kind); foreach (var annotatedNode in annotatedNodes) { cancellationToken.ThrowIfCancellationRequested(); SyntaxNode namespaceScope = null; var annotations = annotatedNode.GetAnnotations(SymbolAnnotation.Kind); foreach (var annotation in annotations) { cancellationToken.ThrowIfCancellationRequested(); foreach (var namedType in SymbolAnnotation.GetSymbols(annotation, compilation).OfType<INamedTypeSymbol>()) { cancellationToken.ThrowIfCancellationRequested(); if (!IsBuiltIn(namedType)) { namespaceScope = namespaceScope ?? this.GetInnermostNamespaceScope(annotatedNode); var referencedDefinitions = namespaceScopeToReferencedDefinitions.GetOrAdd( namespaceScope, createSet); referencedDefinitions.Add(namedType); } } } } return namespaceScopeToReferencedDefinitions; }
public Brush GetSolidBrush(Color color) { return(_solidBrushes.GetOrAdd(color, _ => new SolidBrush(color))); }
public void GetOrAdd() { var dictionary = new Dictionary<string, string>(); dictionary.GetOrAdd("fookey", "bar").Should().Be("bar"); dictionary.GetOrAdd("fookey", "foo").Should().Be("bar"); Action action = () => dictionary.GetOrAdd(null, ""); action.ShouldThrow<ArgumentNullException>() .And.ParamName.Should().Be("key"); dictionary = null; action.ShouldThrow<ArgumentNullException>() .And.ParamName.Should().Be("source"); }
public Tiling CreateTiling( [NotNull] TilingDefinition tilingDefinition, [NotNull] ShapeSet shapes, [NotNull] StyleManager styleManager) { if (tilingDefinition == null) throw new ArgumentNullException(nameof(tilingDefinition)); if (shapes == null) throw new ArgumentNullException(nameof(shapes)); if (styleManager == null) throw new ArgumentNullException(nameof(styleManager)); if (!Tilings.Values.Contains(tilingDefinition)) { throw new ArgumentException( Strings.Template_CreateTiling_UnknownTilingDefinition, nameof(tilingDefinition)); } HashSet<ShapeTemplate> templates = new HashSet<ShapeTemplate>(shapes.Select(s => s.Template)); if (!templates.SetEquals(ShapeTemplates.Values)) throw new ArgumentException(Strings.Template_CreateTiling_WrongShapes, nameof(shapes)); Dictionary<int, ShapeLines> shapeLines = new Dictionary<int, ShapeLines>(); List<Tile> tiles = new List<Tile>(shapes.Count); // TODO Order shapes so that the nth shape is adjacent to at least one of the previous shapes foreach (Shape shape in shapes) { Debug.Assert(shape != null, "shape != null"); string label = null; Matrix3x2 transform = default(Matrix3x2); if (tiles.Count < 1) { label = tilingDefinition.AdjacentParts .Where(l => l.Value.ShapeTemplate == shape.Template) .OrderBy(l => l.Label, StringComparer.InvariantCulture) .First().Label; transform = Matrix3x2.Identity; } else { foreach (Tile t in tiles) { foreach (EdgePartShape partShape in t.PartShapes) { Debug.Assert(partShape != null, "partShape != null"); Labeled<EdgePart> adjacent; if (!tilingDefinition.AdjacentParts.TryGetAdjacent( partShape.Part.WithLabel(t.Label), out adjacent)) continue; Debug.Assert(adjacent.Value != null, "adjacent.Value != null"); if (adjacent.Value.ShapeTemplate != shape.Template) continue; label = adjacent.Label; transform = EdgePartPosition.Create(adjacent.Value, shape) .GetTransformTo(t.GetEdgePartPosition(partShape.Part)); } if (label != null) break; } if (label == null) throw new InvalidDataException(); } EdgePartShape[] partShapes = shape.Template.EdgeParts[tilingDefinition] .Select( ep => new EdgePartShape( ep, shapes.GetEdge(ep.EdgePattern.EdgeName), shapeLines.GetOrAdd(ep.PartShapeID, _ => ShapeLines.CreateDefault()))) .ToArray(); Tile tile = new Tile(label, shape, transform, partShapes); tile.Style = styleManager.GetStyle(tile); tiles.Add(tile); } return new Tiling(this, tilingDefinition, tiles, styleManager); }
public static bool CanDynamicCastFrom(this Type tInterface, params Type[] types) { return(_isCastableFromTypesCache.GetOrAdd(new Types(tInterface, types), () => !GetMissingMethods(tInterface, types).Any())); }
internal static bool Matches(string regExp, string valueToCheck) { var regex = Cache.GetOrAdd(regExp, pattern => new Regex(pattern)); return(regex.IsMatch(valueToCheck)); }
public void WatchDirectory(string path, string extension) { var extensions = _directories.GetOrAdd(path, _ => new HashSet <string>(StringComparer.OrdinalIgnoreCase)); extensions.Add(extension); }
public ILibraryExport GetLibraryExport(ILibraryKey target) { Project project; // Can't find a project file with the name so bail if (!_projectResolver.TryResolveProject(target.Name, out project)) { return(null); } Logger.TraceInformation("[{0}]: GetLibraryExport({1}, {2}, {3}, {4})", GetType().Name, target.Name, target.TargetFramework, target.Configuration, target.Aspect); var targetFrameworkInformation = project.GetTargetFramework(target.TargetFramework); // This is the target framework defined in the project. If there were no target frameworks // defined then this is the targetFramework specified if (targetFrameworkInformation.FrameworkName != null) { target = target.ChangeTargetFramework(targetFrameworkInformation.FrameworkName); } var key = Tuple.Create( target.Name, target.TargetFramework, target.Configuration, target.Aspect); var cache = (ICache)_serviceProvider.GetService(typeof(ICache)); return(cache.Get <ILibraryExport>(key, ctx => { // Get the composite library export provider var exportProvider = (ILibraryExportProvider)_serviceProvider.GetService(typeof(ILibraryExportProvider)); var libraryManager = (ILibraryManager)_serviceProvider.GetService(typeof(ILibraryManager)); var metadataReferences = new List <IMetadataReference>(); var sourceReferences = new List <ISourceReference>(); if (!string.IsNullOrEmpty(targetFrameworkInformation.AssemblyPath)) { var assemblyPath = ResolvePath(project, target.Configuration, targetFrameworkInformation.AssemblyPath); var pdbPath = ResolvePath(project, target.Configuration, targetFrameworkInformation.PdbPath); metadataReferences.Add(new CompiledProjectMetadataReference(project, assemblyPath, pdbPath)); } else { var provider = project.LanguageServices?.ProjectReferenceProvider ?? Project.DefaultLanguageService; // Find the default project exporter var projectReferenceProvider = _projectReferenceProviders.GetOrAdd(provider, typeInfo => { return LanguageServices.CreateService <IProjectReferenceProvider>(_serviceProvider, _projectLoadContext.Value, typeInfo); }); Logger.TraceInformation("[{0}]: GetProjectReference({1}, {2}, {3}, {4})", provider.TypeName, target.Name, target.TargetFramework, target.Configuration, target.Aspect); // Get the exports for the project dependencies var projectExport = new Lazy <ILibraryExport>(() => ProjectExportProviderHelper.GetExportsRecursive( cache, libraryManager, exportProvider, target, dependenciesOnly: true)); // Resolve the project export IMetadataProjectReference projectReference = projectReferenceProvider.GetProjectReference( project, target, () => projectExport.Value); metadataReferences.Add(projectReference); // Shared sources foreach (var sharedFile in project.Files.SharedFiles) { sourceReferences.Add(new SourceFileReference(sharedFile)); } } return new LibraryExport(metadataReferences, sourceReferences); })); }
public void Add(ITextBuffer subjectBuffer, object key, TProperty value) { var bufferMap = _subjectBufferMap.GetOrAdd(subjectBuffer, _ => new Dictionary <object, TProperty>()); bufferMap[key] = value; }
public Font GetFont(ILabelSymbolizer symb) { var fontDesc = string.Format("{0};{1};{2}", symb.FontFamily, symb.FontSize, symb.FontStyle); return(_symbFonts.GetOrAdd(fontDesc, _ => symb.GetFont())); }
private static void ExecuteMapMethod(Type sourceType, Type targetType, IMappingContainer container, object sourceValue, object targetValue) { _mapMethods.GetOrAdd(Pair.Create(sourceType, targetType), key => CreateMapMethod(key.First, key.Second))?.DynamicInvoke(container, sourceValue, targetValue); }
/// <summary> /// Default constructor, takes a set of AssetBundleBuild and converts them to the appropriate properties. /// </summary> /// <param name="bundleBuilds">The set of AssetbundleBuild to be built.</param> public BundleBuildContent(IEnumerable <AssetBundleBuild> bundleBuilds) { if (bundleBuilds == null) { throw new ArgumentNullException("bundleBuilds"); } Assets = new List <GUID>(); Scenes = new List <GUID>(); Addresses = new Dictionary <GUID, string>(); BundleLayout = new Dictionary <string, List <GUID> >(); #if UNITY_2019_3_OR_NEWER CustomAssets = new List <CustomContent>(); AdditionalFiles = new Dictionary <string, List <ResourceFile> >(); #endif foreach (var bundleBuild in bundleBuilds) { List <GUID> guids; BundleLayout.GetOrAdd(bundleBuild.assetBundleName, out guids); ValidationMethods.Status bundleType = ValidationMethods.Status.Invalid; for (int i = 0; i < bundleBuild.assetNames.Length; i++) { string assetPath = bundleBuild.assetNames[i]; GUID asset = new GUID(AssetDatabase.AssetPathToGUID(assetPath)); // Ensure the path is valid ValidationMethods.Status status = ValidationMethods.ValidAsset(asset); if (status == ValidationMethods.Status.Invalid) { throw new ArgumentException(string.Format("Asset '{0}' is not a valid Asset or Scene.", assetPath)); } // Ensure we do not have a mixed bundle if (bundleType == ValidationMethods.Status.Invalid) { bundleType = status; } else if (bundleType != status) { throw new ArgumentException(string.Format("Asset Bundle '{0}' is invalid because it contains mixed Asset and Scene types.", bundleBuild.assetBundleName)); } string address = bundleBuild.addressableNames != null && i < bundleBuild.addressableNames.Length && !string.IsNullOrEmpty(bundleBuild.addressableNames[i]) ? bundleBuild.addressableNames[i] : AssetDatabase.GUIDToAssetPath(asset.ToString()); // Add the guid to the bundle map guids.Add(asset); // Add the guid & address Addresses.Add(asset, address); // Add the asset to the correct collection if (status == ValidationMethods.Status.Asset) { Assets.Add(asset); } else if (status == ValidationMethods.Status.Scene) { Scenes.Add(asset); } } } }
private static object ExecuteConvertMethod(Type sourceType, Type targetType, IMappingContainer container, object sourceValue) { return(_convertMethods.GetOrAdd(Pair.Create(sourceType, targetType), key => CreateConvertMethod(key.First, key.Second)).DynamicInvoke(container, sourceValue)); }
internal TBuilder GetBuilder <TBuilder>(string memberName, Func <MemberMetadataStorage, TBuilder> createBuilderCallBack) where TBuilder : IPropertyMetadataBuilder { MemberMetadataStorage storage = storages.GetOrAdd(memberName ?? string.Empty, () => new MemberMetadataStorage()); return((TBuilder)createBuilderCallBack(storage)); }
public PaletteReference Palette(string name) { // HACK: This is working around the fact that palettes are defined on traits rather than sequences // and can be removed once this has been fixed. return(name == null ? null : palettes.GetOrAdd(name, createPaletteReference)); }
private IEnumerable <IResolutionContext> ResolveOtherBranch(IToken token, IResolutionContext context) { var parent = closestParents.GetOrAdd(token, () => GetClosestParent(token)); return(context.ResolveFromClosestParent(token, parent)); }
public ReturnCode Run() { Dictionary <string, ulong> fileOffsets = new Dictionary <string, ulong>(); List <KeyValuePair <string, List <ResourceFile> > > bundleResources; { Dictionary <string, List <ResourceFile> > bundleToResources = new Dictionary <string, List <ResourceFile> >(); foreach (var pair in m_Results.WriteResults) { string bundle = m_WriteData.FileToBundle[pair.Key]; List <ResourceFile> resourceFiles; bundleToResources.GetOrAdd(bundle, out resourceFiles); resourceFiles.AddRange(pair.Value.resourceFiles); foreach (ResourceFile serializedFile in pair.Value.resourceFiles) { if (!serializedFile.serializedFile) { continue; } ObjectSerializedInfo firstObject = pair.Value.serializedObjects.First(x => x.header.fileName == serializedFile.fileAlias); fileOffsets[serializedFile.fileName] = firstObject.header.offset; } } bundleResources = bundleToResources.ToList(); } Dictionary <string, HashSet <string> > bundleDependencies = new Dictionary <string, HashSet <string> >(); foreach (var files in m_WriteData.AssetToFiles.Values) { if (files.IsNullOrEmpty()) { continue; } string bundle = m_WriteData.FileToBundle[files.First()]; HashSet <string> dependencies; bundleDependencies.GetOrAdd(bundle, out dependencies); dependencies.UnionWith(files.Select(x => m_WriteData.FileToBundle[x])); dependencies.Remove(bundle); } IList <CacheEntry> entries = bundleResources.Select(x => GetCacheEntry(x.Key, x.Value, m_Parameters.GetCompressionForIdentifier(x.Key))).ToList(); IList <CachedInfo> cachedInfo = null; IList <CachedInfo> uncachedInfo = null; if (m_Parameters.UseCache && m_Cache != null) { m_Cache.LoadCachedData(entries, out cachedInfo); uncachedInfo = new List <CachedInfo>(); } for (int i = 0; i < bundleResources.Count; i++) { string bundleName = bundleResources[i].Key; ResourceFile[] resourceFiles = bundleResources[i].Value.ToArray(); BuildCompression compression = m_Parameters.GetCompressionForIdentifier(bundleName); string writePath; BundleDetails details; if (cachedInfo != null && cachedInfo[i] != null) { if (!m_Tracker.UpdateInfoUnchecked(string.Format("{0} (Cached)", bundleName))) { return(ReturnCode.Canceled); } details = (BundleDetails)cachedInfo[i].Data[0]; details.FileName = string.Format("{0}/{1}", m_Parameters.OutputFolder, bundleName); HashSet <string> dependencies; if (bundleDependencies.TryGetValue(bundleName, out dependencies)) { details.Dependencies = dependencies.ToArray(); } else { details.Dependencies = new string[0]; } writePath = string.Format("{0}/{1}", m_Cache.GetCachedArtifactsDirectory(entries[i]), bundleName); } else { if (!m_Tracker.UpdateInfoUnchecked(bundleName)) { return(ReturnCode.Canceled); } details = new BundleDetails(); writePath = string.Format("{0}/{1}", m_Parameters.TempOutputFolder, bundleName); if (m_Parameters.UseCache && m_Cache != null) { writePath = string.Format("{0}/{1}", m_Cache.GetCachedArtifactsDirectory(entries[i]), bundleName); } Directory.CreateDirectory(Path.GetDirectoryName(writePath)); details.FileName = string.Format("{0}/{1}", m_Parameters.OutputFolder, bundleName); details.Crc = ContentBuildInterface.ArchiveAndCompress(resourceFiles, writePath, compression); details.Hash = CalculateHashVersion(fileOffsets, resourceFiles); HashSet <string> dependencies; if (bundleDependencies.TryGetValue(bundleName, out dependencies)) { details.Dependencies = dependencies.ToArray(); } else { details.Dependencies = new string[0]; } if (uncachedInfo != null) { uncachedInfo.Add(GetCachedInfo(m_Cache, entries[i], resourceFiles, details)); } } SetOutputInformation(writePath, details.FileName, bundleName, details); } if (m_Parameters.UseCache && m_Cache != null) { m_Cache.SaveCachedData(uncachedInfo); } return(ReturnCode.Success); }
public void Execute() { ValidateFacets(); //We only want to run the base query once, so we capture all of the facet-ing terms then run the query // once through the collector and pull out all of the terms in one shot var allCollector = new GatherAllCollector(); var facetsByName = new Dictionary <string, Dictionary <string, FacetValue> >(); using (var currentState = Database.IndexStorage.GetCurrentStateHolder(Index)) { var currentIndexSearcher = currentState.IndexSearcher; var baseQuery = Database.IndexStorage.GetDocumentQuery(Index, IndexQuery, Database.IndexQueryTriggers); currentIndexSearcher.Search(baseQuery, allCollector); var indexReader = currentIndexSearcher.IndexReader; var fields = Facets.Values.Select(x => x.Name) .Concat(Ranges.Select(x => x.Key)); var fieldsToRead = new HashSet <string>(fields); IndexedTerms.ReadEntriesForFields(currentState, fieldsToRead, allCollector.Documents, (term, doc) => { var facets = Facets.Values.Where(facet => facet.Name == term.Field); foreach (var facet in facets) { switch (facet.Mode) { case FacetMode.Default: var facetValues = facetsByName.GetOrAdd(facet.DisplayName); FacetValue existing; if (facetValues.TryGetValue(term.Text, out existing) == false) { existing = new FacetValue { Range = GetRangeName(term) }; facetValues[term.Text] = existing; } ApplyFacetValueHit(existing, facet, doc, null, indexReader); break; case FacetMode.Ranges: List <ParsedRange> list; if (Ranges.TryGetValue(term.Field, out list)) { for (int i = 0; i < list.Count; i++) { var parsedRange = list[i]; if (parsedRange.IsMatch(term.Text)) { var facetValue = Results.Results[term.Field].Values[i]; ApplyFacetValueHit(facetValue, facet, doc, parsedRange, indexReader); } } } break; default: throw new ArgumentOutOfRangeException(); } } }); UpdateFacetResults(facetsByName); CompleteFacetCalculationsStage1(currentState); CompleteFacetCalculationsStage2(); } }
public ExcelImportResult Import(string file, int projectColumn, int taskColumn, int dateColumn, int fromColumn, int toColumn, int rateColumn, int descriptionColumn) { var excelPackage = new ExcelPackage(new FileInfo(file)); var worksheet = excelPackage.Workbook.Worksheets.First(); var clients = new Dictionary<Guid, Domain.Client>(); var projects = new Dictionary<Guid, Domain.Project>(); var result = new ExcelImportResult(); var toAdd = new List<TimeRegistration>(); for (int r = 2; r <= worksheet.Dimension.End.Row; r++) { try { Guid projectId; Guid.TryParse(worksheet.Cells[r, projectColumn].Text, out projectId); var project = projects.GetOrAdd(projectId, key => _aggregateRootRepository.GetById<Domain.Project>(key)); var client = clients.GetOrAdd(project.ClientId, key => _aggregateRootRepository.GetById<Domain.Client>(key)); if (project == null) { result.Errors.Add(r, "Project not found."); continue; } DateTime date; DateTime from; DateTime to; decimal rate; if (!DateTime.TryParseExact(worksheet.Cells[r, dateColumn].Text, "yyyy-M-d", CultureInfo.InvariantCulture, DateTimeStyles.None, out date)) { result.Errors.Add(r, "Date does not contain a valid date."); continue; } if (!DateTime.TryParseExact(worksheet.Cells[r, fromColumn].Text, "H:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out from)) { result.Errors.Add(r, "From does not contain a valid time."); continue; } if (!DateTime.TryParseExact(worksheet.Cells[r, toColumn].Text, "H:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out to)) { result.Errors.Add(r, "To does not contain a valid time."); continue; } if (!decimal.TryParse(worksheet.Cells[r, rateColumn].Text, out rate)) { result.Errors.Add(r, "Rate does not contain a valid number."); continue; } toAdd.Add(new Domain.TimeRegistration(_idGenerator.NextGuid(), client, project, new Domain.ValueObjects.Task { Name = worksheet.Cells[r, taskColumn].Text, Rate = rate }, worksheet.Cells[r, descriptionColumn].Text, new Date(date.Year, date.Month, date.Day), new Time(from.Hour, from.Minute), new Time(to.Hour, to.Minute))); } catch (Exception ex) { result.Errors.Add(r, ex.Message); } } if (!result.Errors.Any()) { foreach (var timeRegistration in toAdd) { _aggregateRootRepository.Save(timeRegistration); result.Success++; } } return result; }
public U this[T key] => cache.GetOrAdd(key, loader);
private static Dictionary<Project, Dictionary<Document, List<ValueTuple<ISymbol, IReferenceFinder>>>> CreateProjectMap( ConcurrentDictionary<Document, ConcurrentQueue<ValueTuple<ISymbol, IReferenceFinder>>> map) { Contract.Requires(map.Count > 0); var projectMap = new Dictionary<Project, Dictionary<Document, List<ValueTuple<ISymbol, IReferenceFinder>>>>(); foreach (var kv in map) { var documentMap = projectMap.GetOrAdd(kv.Key.Project, s_documentMapGetter); var queue = documentMap.GetOrAdd(kv.Key, s_queueGetter); queue.AddRange(kv.Value); } ValidateProjectMap(projectMap); return projectMap; }
public string GetContextualName(IJsCsGlue glue) { var found = _AlreadyComputed.GetOrAdd(glue, _ => $"\"~{(string.Join("~", _Context.Reverse()))}\""); return((found.CollectionStatus == CollectionStatus.Found) ? found.Item : null); }
private Dictionary <DiagnosticData, int> GetErrorSet <T>(Dictionary <T, Dictionary <DiagnosticData, int> > map, T key) { return(map.GetOrAdd(key, _ => new Dictionary <DiagnosticData, int>(DiagnosticDataComparer.Instance))); }
public PaletteReference Palette(string name) { return(palettes.GetOrAdd(name, createPaletteReference)); }
/// <summary> /// Given a list of symbols, determine which are not recommended at the same position in linked documents. /// </summary> /// <param name="expectedSymbols">The symbols recommended in the active context.</param> /// <param name="linkedContextSymbolLists">The symbols recommended in linked documents</param> /// <returns>The list of projects each recommended symbol did NOT appear in.</returns> protected Dictionary<ISymbol, List<ProjectId>> FindSymbolsMissingInLinkedContexts(HashSet<ISymbol> expectedSymbols, IEnumerable<Tuple<DocumentId, AbstractSyntaxContext, IEnumerable<ISymbol>>> linkedContextSymbolLists) { var missingSymbols = new Dictionary<ISymbol, List<ProjectId>>(LinkedFilesSymbolEquivalenceComparer.IgnoreAssembliesInstance); foreach (var linkedContextSymbolList in linkedContextSymbolLists) { var symbolsMissingInLinkedContext = expectedSymbols.Except(linkedContextSymbolList.Item3, LinkedFilesSymbolEquivalenceComparer.IgnoreAssembliesInstance); foreach (var missingSymbol in symbolsMissingInLinkedContext) { missingSymbols.GetOrAdd(missingSymbol, (m) => new List<ProjectId>()).Add(linkedContextSymbolList.Item1.ProjectId); } } return missingSymbols; }
public void AddFrameOrders(int clientId, int frame, byte[] orders) { var frameData = framePackets.GetOrAdd(frame); frameData.Add(clientId, orders); }
public void Route(object sender, EventArgs <ICollection <IMeasurement> > e) { ICollection <IMeasurement> measurements = e?.Argument; if (measurements == null) { return; } GlobalCache globalCache; List <Producer> producers; List <Consumer> consumers; // Get the global cache from the routing tables globalCache = Interlocked.CompareExchange(ref m_routingTables.m_globalCache, null, null); // Return if routes are still being calculated if ((object)globalCache == null) { return; } lock (m_localCacheLock) { // Check the version of the local cache against that of the global cache. // We need to clear the local cache if the versions don't match because // that means routes have changed if (m_version != globalCache.Version) { // Dump the signal lookup m_localSignalLookup.Clear(); // Best if we hang onto producers for adapters that still have routes foreach (Consumer consumer in m_localDestinationLookup.Keys.Where(consumer => !globalCache.GlobalDestinationLookup.ContainsKey(consumer.Adapter)).ToList()) { m_localDestinationLookup[consumer].QueueProducer.Dispose(); m_localDestinationLookup.Remove(consumer); } // Update the local cache version m_version = globalCache.Version; } foreach (IMeasurement measurement in measurements) { // Attempt to look up the signal in the local cache if (!m_localSignalLookup.TryGetValue(measurement.ID, out producers)) { // Not in the local cache - check the global cache and fall back on broadcast consumers if (!globalCache.GlobalSignalLookup.TryGetValue(measurement.ID, out consumers)) { consumers = globalCache.BroadcastConsumers; } // Get a producer for each of the consumers producers = consumers .Select(consumer => m_localDestinationLookup.GetOrAdd(consumer, c => new Producer(c.Manager))) .ToList(); // Add this signal to the local cache m_localSignalLookup.Add(measurement.ID, producers); } // Add this measurement to the producers' list foreach (Producer producer in producers) { producer.Measurements.Add(measurement); } } // Produce measurements to consumers in the local destination // cache which have measurements to be received foreach (Producer producer in m_localDestinationLookup.Values) { if (producer.Measurements.Count > 0) { producer.QueueProducer.Produce(producer.Measurements); producer.Measurements.Clear(); } } } }
public void GetOrAddOverload() { var dictionary = new Dictionary<string, string>(); Func<string, string> adder = (key) => { key.Should().Be("fookey"); return "bar"; }; dictionary.GetOrAdd("fookey", adder).Should().Be("bar"); dictionary.GetOrAdd("fookey", adder).Should().Be("bar"); Action action = () => dictionary.GetOrAdd(null, addValueFactory: adder); action.ShouldThrow<ArgumentNullException>() .And.ParamName.Should().Be("key"); action = () => dictionary.GetOrAdd("fookey", addValueFactory: null); action.ShouldThrow<ArgumentNullException>() .And.ParamName.Should().Be("addValueFactory"); dictionary = null; action.ShouldThrow<ArgumentNullException>() .And.ParamName.Should().Be("source"); }
public IEnumerable <IResolutionContext> GetItems(IToken token, IResolutionContext context) { var resolver = resolvers.GetOrAdd(token, () => GetAllResolver(token)); return(resolver(token, context)); }
internal async Task PublishDiagnosticsAsync(CodeAnalysis.Document document) { // Retrieve all diagnostics for the current document grouped by their actual file uri. var fileUriToDiagnostics = await GetDiagnosticsAsync(document, CancellationToken.None).ConfigureAwait(false); // Get the list of file uris with diagnostics (for the document). // We need to join the uris from current diagnostics with those previously published // so that we clear out any diagnostics in mapped files that are no longer a part // of the current diagnostics set (because the diagnostics were fixed). // Use sorted set to have consistent publish ordering for tests and debugging. var urisForCurrentDocument = _documentsToPublishedUris.GetOrValue(document.Id, ImmutableSortedSet.Create <Uri>(s_uriComparer)).Union(fileUriToDiagnostics.Keys); // Update the mapping for this document to be the uris we're about to publish diagnostics for. _documentsToPublishedUris[document.Id] = urisForCurrentDocument; // Go through each uri and publish the updated set of diagnostics per uri. foreach (var fileUri in urisForCurrentDocument) { // Get the updated diagnostics for a single uri that were contributed by the current document. var diagnostics = fileUriToDiagnostics.GetOrValue(fileUri, ImmutableArray <LanguageServer.Protocol.Diagnostic> .Empty); if (_publishedFileToDiagnostics.ContainsKey(fileUri)) { // Get all previously published diagnostics for this uri excluding those that were contributed from the current document. // We don't need those since we just computed the updated values above. var diagnosticsFromOtherDocuments = _publishedFileToDiagnostics[fileUri].Where(kvp => kvp.Key != document.Id).SelectMany(kvp => kvp.Value); // Since diagnostics are replaced per uri, we must publish both contributions from this document and any other document // that has diagnostic contributions to this uri, so union the two sets. diagnostics = diagnostics.AddRange(diagnosticsFromOtherDocuments); } await SendDiagnosticsNotificationAsync(fileUri, diagnostics).ConfigureAwait(false); // There are three cases here -> // 1. There are no diagnostics to publish for this fileUri. We no longer need to track the fileUri at all. // 2. There are diagnostics from the current document. Store the diagnostics for the fileUri and document // so they can be published along with contributions to the fileUri from other documents. // 3. There are no diagnostics contributed by this document to the fileUri (could be some from other documents). // We should clear out the diagnostics for this document for the fileUri. if (diagnostics.IsEmpty) { // We published an empty set of diagnostics for this uri. We no longer need to keep track of this mapping // since there will be no previous diagnostics that we need to clear out. _documentsToPublishedUris.MultiRemove(document.Id, fileUri); // There are not any diagnostics to keep track of for this file, so we can stop. _publishedFileToDiagnostics.Remove(fileUri); } else if (fileUriToDiagnostics.ContainsKey(fileUri)) { // We do have diagnostics from the current document - update the published diagnostics map // to contain the new diagnostics contributed by this document for this uri. var documentsToPublishedDiagnostics = _publishedFileToDiagnostics.GetOrAdd(fileUri, (_) => new Dictionary <DocumentId, ImmutableArray <LanguageServer.Protocol.Diagnostic> >()); documentsToPublishedDiagnostics[document.Id] = fileUriToDiagnostics[fileUri]; } else { // There were diagnostics from other documents, but none from the current document. // If we're tracking the current document, we can stop. _publishedFileToDiagnostics.GetOrDefault(fileUri)?.Remove(document.Id); _documentsToPublishedUris.MultiRemove(document.Id, fileUri); } } }
public Pen GetPen(Color color) { return(_pens.GetOrAdd(color, _ => new Pen(color))); }
public void Execute() { ValidateFacets(); //We only want to run the base query once, so we capture all of the facet-ing terms then run the query // once through the collector and pull out all of the terms in one shot var allCollector = new GatherAllCollector(); var facetsByName = new Dictionary<string, Dictionary<string, FacetValue>>(); using (var currentState = Database.IndexStorage.GetCurrentStateHolder(Index)) { var currentIndexSearcher = currentState.IndexSearcher; var baseQuery = Database.IndexStorage.GetDocumentQuery(Index, IndexQuery, Database.IndexQueryTriggers); currentIndexSearcher.Search(baseQuery, allCollector); var fields = Facets.Values.Select(x => x.Name) .Concat(Ranges.Select(x => x.Key)); var fieldsToRead = new HashSet<string>(fields); IndexedTerms.ReadEntriesForFields(currentState, fieldsToRead, allCollector.Documents, (term, doc) => { var facets = Facets.Values.Where(facet => facet.Name == term.Field); foreach (var facet in facets) { switch (facet.Mode) { case FacetMode.Default: var facetValues = facetsByName.GetOrAdd(facet.DisplayName); FacetValue existing; if (facetValues.TryGetValue(term.Text, out existing) == false) { existing = new FacetValue { Range = GetRangeName(term) }; facetValues[term.Text] = existing; } ApplyFacetValueHit(existing, facet, doc, null); break; case FacetMode.Ranges: List<ParsedRange> list; if (Ranges.TryGetValue(term.Field, out list)) { for (int i = 0; i < list.Count; i++) { var parsedRange = list[i]; if (parsedRange.IsMatch(term.Text)) { var facetValue = Results.Results[term.Field].Values[i]; ApplyFacetValueHit(facetValue, facet, doc, parsedRange); } } } break; default: throw new ArgumentOutOfRangeException(); } } }); UpdateFacetResults(facetsByName); CompleteFacetCalculationsStage1(currentState); CompleteFacetCalculationsStage2(); } }
/// <summary> /// Determina se o tipo possui um construtor padrão /// </summary> public static bool HasDefaultConstructor(this Type type) { // ReSharper disable once PossibleInvalidOperationException return(_hasDefaultConstructor.GetOrAdd(type, () => type.IsValueType || type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null) != null).Value); }
private Dictionary<SyntaxToken, LeadingTrailingTriviaPair> CreateTokenLeadingTrailingTriviaMap( Dictionary<TriviaLocation, SyntaxToken> tokens) { var tuple = default(LeadingTrailingTriviaPair); var map = new Dictionary<SyntaxToken, LeadingTrailingTriviaPair>(); tuple = map.GetOrAdd(tokens[TriviaLocation.BeforeBeginningOfSpan], _ => default(LeadingTrailingTriviaPair)); map[tokens[TriviaLocation.BeforeBeginningOfSpan]] = new LeadingTrailingTriviaPair { LeadingTrivia = tuple.LeadingTrivia, TrailingTrivia = _triviaList[TriviaLocation.BeforeBeginningOfSpan] }; tuple = map.GetOrAdd(tokens[TriviaLocation.AfterBeginningOfSpan], _ => default(LeadingTrailingTriviaPair)); map[tokens[TriviaLocation.AfterBeginningOfSpan]] = new LeadingTrailingTriviaPair { LeadingTrivia = _triviaList[TriviaLocation.AfterBeginningOfSpan], TrailingTrivia = tuple.TrailingTrivia }; tuple = map.GetOrAdd(tokens[TriviaLocation.BeforeEndOfSpan], _ => default(LeadingTrailingTriviaPair)); map[tokens[TriviaLocation.BeforeEndOfSpan]] = new LeadingTrailingTriviaPair { LeadingTrivia = tuple.LeadingTrivia, TrailingTrivia = _triviaList[TriviaLocation.BeforeEndOfSpan] }; tuple = map.GetOrAdd(tokens[TriviaLocation.AfterEndOfSpan], _ => default(LeadingTrailingTriviaPair)); map[tokens[TriviaLocation.AfterEndOfSpan]] = new LeadingTrailingTriviaPair { LeadingTrivia = _triviaList[TriviaLocation.AfterEndOfSpan], TrailingTrivia = tuple.TrailingTrivia }; return map; }
public virtual void RegisterSpawnPoint(SpawnPoint spawnPoint) { //Debug.Log($"Registering spawnpoint {spawnPoint.name} of type '{spawnPoint.Tag}'"); _spawnPoints.GetOrAdd(spawnPoint.Tag).SpawnPoints.Add(spawnPoint); }
// Reads statistics from the archive and stores them in a format that can // be easily manipulated to determine which devices belong in which levels. private void ReadStatistics() { ArchiveLocator locator; DateTime startTime; DateTime endTime; Dictionary<int, Aggregate> aggregateLookup; Aggregate currentAggregate; int currentHistorianID; Dictionary<string, DeviceStats> deviceStatsLookup; DeviceStats deviceStats; SignalStats signalStats; string signalName; int index; deviceStatsLookup = new Dictionary<string, DeviceStats>(); // Create the statistics reader for reading statistics from the archive using (StatisticsReader statisticsReader = new StatisticsReader()) { // Create the archive locator to // determine the location of the archive locator = new ArchiveLocator() { ArchiveLocation = m_archiveLocation, ArchiveLocationName = "Statistics", ArchiveName = "STAT" }; endTime = m_reportDate.ToUniversalTime() + TimeSpan.FromDays(1); startTime = endTime - TimeSpan.FromDays(ReportDays); // Set up and open the statistics reader statisticsReader.StartTime = startTime; statisticsReader.EndTime = endTime; statisticsReader.ArchiveFilePath = locator.ArchiveFilePath; statisticsReader.Open(); // Create lookup tables for each aggregateLookup = new Dictionary<int, Aggregate>(); foreach (MetadataRecord record in statisticsReader.MetadataRecords) { if (IsDesiredDeviceStat(record.Synonym1)) { deviceStats = deviceStatsLookup.GetOrAdd(GetDeviceNameForStat(record.Synonym1), name => new DeviceStats() { Name = name, MeasurementsExpected = new Aggregate(ReportDays), MeasurementsReceived = new Aggregate(ReportDays), SignalStatsLookup = new Dictionary<string, SignalStats>() }); if (record.Synonym1.EndsWith("!PMU-ST5", StringComparison.Ordinal)) aggregateLookup[record.HistorianID] = deviceStats.MeasurementsExpected; else if (record.Synonym1.EndsWith("!PMU-ST4", StringComparison.Ordinal)) aggregateLookup[record.HistorianID] = deviceStats.MeasurementsReceived; } else if (IsDesiredSignalStat(record.Synonym1)) { signalName = GetSignalName(record.Synonym1); deviceStats = deviceStatsLookup.GetOrAdd(GetDeviceNameForSignal(signalName), name => new DeviceStats() { Name = name, MeasurementsExpected = new Aggregate(ReportDays), MeasurementsReceived = new Aggregate(ReportDays), SignalStatsLookup = new Dictionary<string, SignalStats>() }); signalStats = deviceStats.SignalStatsLookup.GetOrAdd(signalName, name => new SignalStats() { Name = name, MeasurementsLatched = new Aggregate(ReportDays), MeasurementsUnreasonable = new Aggregate(ReportDays) }); if (record.Synonym1.StartsWith("980!")) aggregateLookup[record.HistorianID] = signalStats.MeasurementsLatched; else if (record.Synonym1.StartsWith("900!")) aggregateLookup[record.HistorianID] = signalStats.MeasurementsUnreasonable; } } currentAggregate = null; currentHistorianID = -1; foreach (IDataPoint dataPoint in statisticsReader.Read(aggregateLookup.Keys)) { index = (dataPoint.Time.ToDateTime() - startTime).Days; if (index < 0 || index >= ReportDays) continue; if (dataPoint.HistorianID != currentHistorianID) { aggregateLookup.TryGetValue(dataPoint.HistorianID, out currentAggregate); currentHistorianID = dataPoint.HistorianID; } if ((object)currentAggregate != null) currentAggregate.Add(index, dataPoint.Value); } } // Store the statistics data to be used in the report m_deviceStatsList = deviceStatsLookup.Values.ToList(); }
ITraitContainer InnerGet(Type t) { return(traits.GetOrAdd(t, CreateTraitContainer)); }
private static void Main(string[] args) { string input = ""; string output = ""; Parser.Default.ParseArguments <Options>(args) .WithParsed(o => { input = o.Input; Console.WriteLine($"Input Dir: {input}"); output = string.IsNullOrWhiteSpace(o.Output) ? AppDomain.CurrentDomain.BaseDirectory : o.Output; Console.WriteLine($"Output Dir: {output}"); }); try { if (Directory.Exists(input)) { Dictionary <string, HashSet <string> > resultDict = new Dictionary <string, HashSet <string> >(); string[] files = Directory.GetFiles(input, "*.dll", SearchOption.AllDirectories); foreach (string file in files) { using (ModuleDefMD module = ModuleDefMD.Load(file)) { foreach (TypeDef type in module.GetTypes()) { foreach (MethodDef method in type.Methods) { if (!method.HasBody) { continue; } bool localizable = false; string operandType = ""; foreach (Instruction instr in method.Body.Instructions) { if (instr.OpCode == OpCodes.Call && instr.Operand.ToString().IndexOf("IStringLocalizer`1", StringComparison.InvariantCulture) >= 0) { MethodDef md = instr.Operand as MethodDef; if (md?.ReturnType != null && md.ReturnType.IsGenericInstanceType) { GenericInstSig sig = md.ReturnType as GenericInstSig; if (sig?.GenericArguments != null && sig.GenericArguments.Count > 0) { localizable = true; operandType = sig.GenericArguments[0].TypeName; } } continue; } if (instr.OpCode == OpCodes.Ldstr && localizable && !string.IsNullOrEmpty(operandType)) { HashSet <string> resources = resultDict.GetOrAdd(operandType, s => new HashSet <string>()); string value = WebUtility.HtmlEncode((string)instr.Operand); if (!string.IsNullOrWhiteSpace(value)) { resources.Add(value); Console.WriteLine($"Resource: {operandType}{Environment.NewLine}Value: {value}"); Console.WriteLine("==========================================================="); } } localizable = false; operandType = ""; } } } } if (!Directory.Exists(output)) { Directory.CreateDirectory(output); } string resxTemplate = ReadResource("ResxTemplate.xml"); string resxTemplateItem = ReadResource("ResxTemplateItem.xml"); foreach (KeyValuePair <string, HashSet <string> > keyValuePair in resultDict) { StringBuilder builder = new StringBuilder(); foreach (string str in keyValuePair.Value) { builder.AppendLine(string.Format(resxTemplateItem, str, str)); } string resxFile = Path.Combine(output, $"{keyValuePair.Key}.en-US.resx"); if (File.Exists(resxFile)) { File.Delete(resxFile); } //File.WriteAllText(resxFile, PrettyXml(string.Format(resxTemplate, builder))); File.WriteAllText(resxFile, string.Format(resxTemplate, builder.ToString().TrimEnd(Environment.NewLine.ToCharArray()))); } } } else { Console.WriteLine($"Input Directory '{input}' does not exists!"); } } catch (Exception ex) { Console.WriteLine($"Exception: {ex.Message}"); Console.ReadKey(); } Console.WriteLine("Press any key to exit"); Console.ReadKey(); }
private List <INode> GetNodesChain(IToken token) { return(nodeChains.GetOrAdd(token, () => node.Tree.GetNode(token).GetParentalChain())); }