private static void ProcessSettings(Service service, IReadOnlyDictionary<string, string> settings) { if (settings.ContainsKey("BasePath")) service.BasePath = settings["BasePath"]; if (settings.ContainsKey("Host")) service.Host = settings["Host"]; if (settings.Keys.Any(k => k.StartsWith("Info"))) service.Info = new Info(); if (settings.ContainsKey("InfoDescription")) service.Info.Description = settings["InfoDescription"]; if (settings.ContainsKey("InfoVersion")) service.Info.Version = settings["InfoVersion"]; if (settings.ContainsKey("InfoTermsOfService")) service.Info.TermsOfService = settings["InfoTermsOfService"]; if (settings.ContainsKey("InfoTitle")) service.Info.Title = settings["InfoTitle"]; if (settings.Keys.Any(k => k.StartsWith("InfoContact"))) service.Info.Contact = new InfoContact(); if (settings.ContainsKey("InfoContactName")) service.Info.Contact.Name = settings["InfoContactName"]; if (settings.ContainsKey("InfoContactUrl")) service.Info.Contact.Url = settings["InfoContactUrl"]; if (settings.ContainsKey("InfoContactEmail")) service.Info.Contact.Email = settings["InfoContactEmail"]; if (settings.Keys.Any(k => k.StartsWith("InfoLicense"))) service.Info.License = new InfoLicense(); if (settings.ContainsKey("InfoLicenseUrl")) service.Info.License.Url = settings["InfoLicenseUrl"]; if (settings.ContainsKey("InfoLicenseName")) service.Info.License.Name = settings["InfoLicenseName"]; }
public RootGuardianActorRef(ActorSystemImpl system, Props props, MessageDispatcher dispatcher, Func<Mailbox> createMailbox, //TODO: switch from Func<Mailbox> createMailbox to MailboxType mailboxType IInternalActorRef supervisor, ActorPath path, IInternalActorRef deadLetters, IReadOnlyDictionary<string, IInternalActorRef> extraNames) : base(system,props,dispatcher,createMailbox,supervisor,path) { _deadLetters = deadLetters; _extraNames = extraNames; }
public SymbolChanges(DefinitionMap definitionMap, IEnumerable<SemanticEdit> edits) { Debug.Assert(definitionMap != null); Debug.Assert(edits != null); this.definitionMap = definitionMap; this.changes = CalculateChanges(edits); }
public static bool CheckProperyType(IReadOnlyDictionary<string, string> data, KeyValuePair<string, string> param) { var result = true; switch (param.Value) { case "Int32": int number; if (data.ContainsKey(param.Key)) result = int.TryParse(data[param.Key], out number); break; case "Guid": Guid guid; if (data.ContainsKey(param.Key)) result = Guid.TryParse(data[param.Key], out guid); break; case "DateTime": DateTime dateTime; if (data.ContainsKey(param.Key)) result = DateTime.TryParse(data[param.Key], out dateTime); break; } return result; }
public StopwatchTimer(MetricsCollector collector, string measurement, IReadOnlyDictionary<string, string> tags = null) { _collector = collector; _measurement = measurement; _tags = tags; _stopwatch.Start(); }
public TemplateRoute( IRouter target, string routeName, string routeTemplate, IDictionary<string, object> defaults, IDictionary<string, object> constraints, IDictionary<string, object> dataTokens, IInlineConstraintResolver inlineConstraintResolver) { if (target == null) { throw new ArgumentNullException(nameof(target)); } _target = target; _routeTemplate = routeTemplate ?? string.Empty; Name = routeName; _dataTokens = dataTokens == null ? RouteValueDictionary.Empty : new RouteValueDictionary(dataTokens); // Data we parse from the template will be used to fill in the rest of the constraints or // defaults. The parser will throw for invalid routes. _parsedTemplate = TemplateParser.Parse(RouteTemplate); _constraints = GetConstraints(inlineConstraintResolver, RouteTemplate, _parsedTemplate, constraints); _defaults = GetDefaults(_parsedTemplate, defaults); _matcher = new TemplateMatcher(_parsedTemplate, Defaults); _binder = new TemplateBinder(_parsedTemplate, Defaults); }
public async Task<IList<Mutation>> Validate(ParsedMutation mutation, IReadOnlyList<SignatureEvidence> authentication, IReadOnlyDictionary<AccountKey, AccountStatus> accounts) { await ValidateAccountMutations(mutation.AccountMutations, accounts, authentication); await ValidateDataMutations(mutation.DataRecords, authentication); return new Mutation[0]; }
private void LazyLoadWearLimits() { if (_wearLimitsBeforeWashing != null) return; var jsonContent = File.ReadAllText(_jsonFilePath); _wearLimitsBeforeWashing = JsonConvert.DeserializeObject<IReadOnlyDictionary<ClothingArticleType, ushort>>(jsonContent); }
internal AsyncMethodToStateMachineRewriter( MethodSymbol method, int methodOrdinal, AsyncMethodBuilderMemberCollection asyncMethodBuilderMemberCollection, SyntheticBoundNodeFactory F, FieldSymbol state, FieldSymbol builder, IReadOnlySet<Symbol> hoistedVariables, IReadOnlyDictionary<Symbol, CapturedSymbolReplacement> nonReusableLocalProxies, SynthesizedLocalOrdinalsDispenser synthesizedLocalOrdinals, VariableSlotAllocator slotAllocatorOpt, int nextFreeHoistedLocalSlot, DiagnosticBag diagnostics) : base(F, method, state, hoistedVariables, nonReusableLocalProxies, synthesizedLocalOrdinals, slotAllocatorOpt, nextFreeHoistedLocalSlot, diagnostics, useFinalizerBookkeeping: false) { _method = method; _asyncMethodBuilderMemberCollection = asyncMethodBuilderMemberCollection; _asyncMethodBuilderField = builder; _exprReturnLabel = F.GenerateLabel("exprReturn"); _exitLabel = F.GenerateLabel("exitLabel"); _exprRetValue = method.IsGenericTaskReturningAsync(F.Compilation) ? F.SynthesizedLocal(asyncMethodBuilderMemberCollection.ResultType, syntax: F.Syntax, kind: SynthesizedLocalKind.AsyncMethodReturnValue) : null; _dynamicFactory = new LoweredDynamicOperationFactory(F, methodOrdinal); _awaiterFields = new Dictionary<TypeSymbol, FieldSymbol>(TypeSymbol.EqualsIgnoringDynamicComparer); _nextAwaiterId = slotAllocatorOpt?.PreviousAwaiterSlotCount ?? 0; }
static void WriteRenderings(IEnumerable<IGrouping<string, PropertyToken>> tokensWithFormat, IReadOnlyDictionary<string, LogEventPropertyValue> properties, TextWriter output) { output.Write(",\"Renderings\":{"); var rdelim = ""; foreach (var ptoken in tokensWithFormat) { output.Write(rdelim); rdelim = ","; JsonValueFormatter.WriteQuotedJsonString(ptoken.Key, output); output.Write(":["); var fdelim = ""; foreach (var format in ptoken) { output.Write(fdelim); fdelim = ","; output.Write("{\"Format\":"); JsonValueFormatter.WriteQuotedJsonString(format.Format, output); output.Write(",\"Rendering\":"); var sw = new StringWriter(); format.Render(properties, sw); JsonValueFormatter.WriteQuotedJsonString(sw.ToString(), output); output.Write('}'); } output.Write(']'); } output.Write('}'); }
protected Score(params BonusSource[] bonusSources) { bonusSources = bonusSources ?? new BonusSource[]{}; var sources = bonusSources.ToDictionary(b => b.Name); BonusSources = new ReadOnlyDictionary<string, BonusSource>(sources); }
protected override async Task AfterTestAssemblyStartingAsync() { await base.AfterTestAssemblyStartingAsync(); _assemblyLoaders = AssemblyLoaderAttribute.GetAssemblyLoaders(TestAssembly.Assembly); var assembly = TestAssembly.Assembly; var importedAssemblyFixtureTypes = assembly.GetCustomAttributes(typeof (AssemblyFixtureImportAttribute)) .SelectMany(ai => ai.GetConstructorArguments()) .OfType<Type[]>() .SelectMany(a => a); var assemblyFixtureTypes = assembly.GetTypes(false) .Where(t => t.GetCustomAttributes(typeof(AssemblyFixtureAttribute).AssemblyQualifiedName).Any()) .Select(t => t.ToRuntimeType()) .Concat(importedAssemblyFixtureTypes) .ToList(); var fixtures = new Dictionary<Type, object>(); foreach (var type in assemblyFixtureTypes) { await Aggregator.RunAsync(() => AddAssemblyFixtureAsync(fixtures, type)); } _assemblyFixtureMappings = new ReadOnlyDictionary<Type, object>(fixtures); }
static DataTypes() { Dictionary<string, Type> names = new Dictionary<string, Type>(); Dictionary<Type, string> types = new Dictionary<Type, string>(); Dictionary<string, bool> graphs = new Dictionary<string, bool>(); ISet<Type> intTypes = new HashSet<Type>(); ISet<Type> floatTypes = new HashSet<Type>(); AddType(names, types, graphs, "void", typeof(void), false, null); AddType(names, types, graphs, "string", typeof(string), false, null); AddType(names, types, graphs, "float", typeof(float), true, floatTypes); AddType(names, types, graphs, "double", typeof(double), true, floatTypes); AddType(names, types, graphs, "int32", typeof(Int32), true, intTypes); AddType(names, types, graphs, "uint32", typeof(UInt32), true, intTypes); AddType(names, types, graphs, "int64", typeof(Int64), true, intTypes); //AddType(names, types, graphs, "uint64", typeof(UInt64), true, intTypes); AddType(names, types, graphs, "int16", typeof(Int16), true, intTypes); AddType(names, types, graphs, "uint16", typeof(UInt16), true, intTypes); AddType(names, types, graphs, "int8", typeof(sbyte), true, intTypes); AddType(names, types, graphs, "uint8", typeof(byte), true, intTypes); AddType(names, types, graphs, "bool", typeof(bool), false, null); s_nameToType = names; s_typeToName = types; s_allowShowGraphForName = graphs; s_intTypes = intTypes; s_floatTypes = floatTypes; }
public void SetApplicationData(IReadOnlyDictionary<string, object> applicationData) { // creating fake context is the only way to access HttpApplicationFactory.ApplicationState var context = new HttpContext(new SimpleWorkerRequest("", "", new StringWriter())); foreach (var pair in applicationData) { context.Application[pair.Key] = pair.Value; } }
public DocumentMap(MetadataReader reader) { _reader = reader; // group ignoring case, we will match the case within the group _map = GetDocumentsByFileName(reader).GroupBy(StringComparer.OrdinalIgnoreCase); }
/// <summary> /// Initializes a new instance of the <see cref="PipelineArgument"/> class. /// </summary> public PipelineArgument(IReadOnlyDictionary<string, string> propertyBag, IDocument document, IRuleSet rules, IPipelineMember successor) { PropertyBag = propertyBag; Document = document; Rules = rules; Successor = successor; }
public NpkDirDifferences(IReadOnlyList<ImgInfo> imgsInFirstButNotSecond, IReadOnlyDictionary<NpkPath, FrameCountDifferenceInfo> imgsWithFewerFramesInSecond, IReadOnlyList<ImgInfo> imgsInSecondButNotFirst, IReadOnlyDictionary<NpkPath, FrameCountDifferenceInfo> imgsWithMoreFramesInSecond) { ImgsInFirstButNotSecond = imgsInFirstButNotSecond; ImgsWithFewerFramesInSecond = imgsWithFewerFramesInSecond; ImgsInSecondButNotFirst = imgsInSecondButNotFirst; ImgsWithMoreFramesInSecond = imgsWithMoreFramesInSecond; }
public AccountContactsFactory(IEventStoreClient eventStoreClient, ILoggerFactory loggerFactory, IEnumerable<IAccountContactProvider> accountContactProviders) { _eventStoreClient = eventStoreClient; _loggerFactory = loggerFactory; _accountContactProviders = accountContactProviders.ToReadOnlyDictionary(acp => acp.Provider); }
public Preset(IEnumerable<KeyValuePair<string, string>> names, IReadOnlyDictionary<string,object> properties) { foreach (var lang in names) PresetName[lang.Key] = lang.Value; foreach (var prop in properties) State[prop.Key] = prop.Value; }
static object PossiblyConvertBody(object messageBody, IReadOnlyDictionary<string, string> headers) { var legacySubscriptionMessage = messageBody as LegacySubscriptionMessage; if (legacySubscriptionMessage == null) { return messageBody; } string returnAddress; var topic = legacySubscriptionMessage.Type; if (!headers.TryGetValue(Headers.ReturnAddress, out returnAddress)) { throw new RebusApplicationException($"Got legacy subscription message but the '{Headers.ReturnAddress}' header was not present on it!"); } var subscribe = legacySubscriptionMessage.Action == 0; if (subscribe) { return new SubscribeRequest { Topic = topic, SubscriberAddress = returnAddress }; } return new UnsubscribeRequest { Topic = topic, SubscriberAddress = returnAddress }; }
public override ContentItem GetContent(IReadOnlyDictionary<string, Argument> invocation, bool throwExceptionIfNotFound) { var uri = invocation["url"].AsUri(); var request = WebRequest.Create(uri); request.UseDefaultCredentials = true; var response = this.GetResponse(uri.AbsoluteUri, request); var result = new ContentItem { ContentType = response.ContentType }; using (var stream = response.GetResponseStream()) { if (stream == Stream.Null || stream == null) { if (throwExceptionIfNotFound) { throw new StoreItemNotFoundException(this.Name, uri.AbsoluteUri); } return null; } using (var reader = new StreamReader(stream)) { result.Content = reader.ReadToEnd(); } } return result; }
public Task Validate(ParsedMutation mutation, IReadOnlyList<SignatureEvidence> authentication, IReadOnlyDictionary<AccountKey, AccountStatus> accounts) { if (this.alwaysValid) return Task.FromResult(0); else throw new TransactionInvalidException("Disabled"); }
public override PropertyTreeMetaObject BindAddChild(OperatorDefinition definition, IReadOnlyDictionary<string, PropertyTreeMetaObject> arguments) { var result = definition.Apply(null, component, arguments); if (result == null) return Null; return CreateChild(result); }
public DownloadsScoreProvider(IndexReader reader, IReadOnlyDictionary<string, int[]> idMapping, Downloads downloads, RankingResult ranking, QueryBoostingContext context, double baseBoost) : base(reader) { _idMapping = idMapping; _downloads = downloads; _baseBoost = baseBoost; _ranking = ranking; _context = context; // We need the reader name: Lucene *may* have multiple segments (which are smaller indices) // and RankingsHandler provides us with the per-segment document numbers. // // If no segments are present (small index) we use an empty string, which is what // Lucene also uses internally. var segmentReader = reader as SegmentReader; _readerName = segmentReader != null ? segmentReader.SegmentName : string.Empty; }
public LanguageServiceMetadata(IDictionary<string, object> data) : base(data) { this.ServiceType = (string)data.GetValueOrDefault("ServiceType"); this.Layer = (string)data.GetValueOrDefault("Layer"); this.Data = (IReadOnlyDictionary<string, object>)data; }
internal static string CreateTableIfNotExists(string tableName, CreateFlags createFlags, IReadOnlyDictionary<string, ColumnMapping> columns) { bool fts3 = (createFlags & CreateFlags.FullTextSearch3) != 0; bool fts4 = (createFlags & CreateFlags.FullTextSearch4) != 0; bool fts = fts3 || fts4; var @virtual = fts ? "VIRTUAL " : string.Empty; var @using = fts3 ? "USING FTS3 " : fts4 ? "USING FTS4 " : string.Empty; // Build query. var query = "CREATE " + @virtual + "TABLE IF NOT EXISTS \"" + tableName + "\" " + @using + "(\n"; var decls = columns.Select(c => SQLBuilder.SqlDecl(c.Key, c.Value)); var decl = string.Join(",\n", decls.ToArray()); query += decl; var fkconstraints = string.Join( ",\n", columns.Where(x => x.Value.ForeignKeyConstraint != null).Select(x => string.Format("FOREIGN KEY(\"{0}\") REFERENCES \"{1}\"(\"{2}\")", x.Key, x.Value.ForeignKeyConstraint.TableName, x.Value.ForeignKeyConstraint.ColumnName))); query += (fkconstraints.Length != 0) ? "," + fkconstraints : ""; query += ")"; return query; }
public RedisEntity(RedisAccount account, BindingTemplate channelOrKeyPath, Mode mode, IReadOnlyDictionary<string, object> bindingData) { Account = account; Mode = mode; _channelOrKeyPath = channelOrKeyPath; _bindingData = bindingData; }
/// <summary> /// Initializes a new instance of <see cref="CommandHandlerRegistry"/> with the specified <paramref name="typeLocator"/> and <paramref name="serviceProvider"/>. /// </summary> /// <param name="aggregateStore">The <see cref="Aggregate"/> store.</param> /// <param name="typeLocator">The type locator use to retrieve all known <see cref="Aggregate"/> types.</param> /// <param name="serviceProvider">The service locator used to retrieve singleton command handler dependencies.</param> public CommandHandlerRegistry(IStoreAggregates aggregateStore, ILocateTypes typeLocator, IServiceProvider serviceProvider) { Verify.NotNull(typeLocator, nameof(typeLocator)); Verify.NotNull(serviceProvider, nameof(serviceProvider)); knownCommandHandlers = DiscoverCommandHandlers(aggregateStore, typeLocator, serviceProvider); }
public async override Task Activate(INavigationService navigationService, NavigationContextBase navigationContext, IReadOnlyDictionary<string, object> pageState) { await base.Activate(navigationService, navigationContext, pageState); MyNavigationContext context = navigationContext as MyNavigationContext; if (pageState != null) { /********************************************************* * If you store state on deactivation and it is provided * here, you know that the user has used the back button * or returned from app suspension and should restore state. *********************************************************/ this.Value1 = pageState[nameof(this.Value1)] as string; this.Value2 = pageState[nameof(this.Value2)] as string; this.Value3 = pageState[nameof(this.Value3)] as string; } else if (context != null) { /********************************************************* * Alternatively, if the user has navigated to the page * for the first time, there won't be existing page state * to restore. The context can be used to populate the page. *********************************************************/ this.Value1 = context.Value1; this.Value2 = context.Value2; this.Value3 = context.Value3; } }
/// <summary> /// Depict a single molecule. /// </summary> /// <param name="mol">molecule</param> /// <param name="highlight">highlight the provided set of atoms and bonds in the depiction in the specified color</param> /// <returns>depiction instance</returns> /// <exception cref="CDKException">a depiction could not be generated</exception> public Depiction Depict(IAtomContainer mol, IReadOnlyDictionary <IChemObject, Color> highlight = null) { return(Depict(new[] { mol }, 1, 1, highlight)); }
public MonoTypeContext(TypeReference type, IReadOnlyDictionary <GenericParameter, TypeReference> arguments) { Type = type; Arguments = arguments; }
public abstract Task<IContainSagaData> Find(IServiceProvider builder, SagaFinderDefinition finderDefinition, SynchronizedStorageSession storageSession, ContextBag context, object message, IReadOnlyDictionary<string, string> messageHeaders, CancellationToken cancellationToken);
// Creates and returns the processor used to create the file rename mapping for source based file renames. private static IProcessor SetupRenameProcessor(IEngineEnvironmentSettings environmentSettings, IReadOnlyDictionary <string, string> substringReplacementMap) { List <IOperationProvider> operations = new List <IOperationProvider>(); foreach (KeyValuePair <string, string> replacement in substringReplacementMap) { IOperationProvider replacementOperation = new Replacement(replacement.Key.TokenConfig(), replacement.Value, null, true); operations.Add(replacementOperation); } return(SetupProcessor(environmentSettings, operations)); }
public DictionaryWrapper(IReadOnlyDictionary <TKey, TValue> dictionary) { ValidationUtils.ArgumentNotNull(dictionary, "dictionary"); _readOnlyDictionary = dictionary; }
/// <summary> /// Returns an estimator. /// </summary> /// <param name="env">The host environment to use to create the estimator</param> /// <param name="toOutput">The columns that the object created by the reconciler should output</param> /// <param name="inputNames">The name mapping that maps dependencies of the output columns to their names</param> /// <param name="outputNames">The name mapping that maps the output column to their names</param> /// <param name="usedNames">While most estimators allow full control over the names of their outputs, a limited /// subset of estimator transforms do not allow this: they produce columns whose names are unconfigurable. For /// these, there is this collection which provides the names used by the analysis tool. If the estimator under /// construction must use one of the names here, then they are responsible for "saving" the column they will /// overwrite using applications of the <see cref="CopyColumnsEstimator"/>. Note that if the estimator under /// construction has complete control over what columns it produces, there is no need for it to pay this argument /// any attention.</param> /// <returns>Returns an estimator.</returns> public abstract IEstimator <ITransformer> Reconcile( IHostEnvironment env, PipelineColumn[] toOutput, IReadOnlyDictionary <PipelineColumn, string> inputNames, IReadOnlyDictionary <PipelineColumn, string> outputNames, IReadOnlyCollection <string> usedNames);
/// <summary> /// Returns a data-reader estimator. Note that there are no input names because the columns from a data-reader /// estimator should have no dependencies. /// </summary> /// <param name="env">The host environment to use to create the data-reader estimator</param> /// <param name="toOutput">The columns that the object created by the reconciler should output</param> /// <param name="outputNames">A map containing</param> /// <returns></returns> public abstract IDataReaderEstimator <TIn, IDataReader <TIn> > Reconcile( IHostEnvironment env, PipelineColumn[] toOutput, IReadOnlyDictionary <PipelineColumn, string> outputNames);
internal SearchResult(double score, IReadOnlyDictionary <string, IList <string> > highlights, IReadOnlyDictionary <string, object> additionalProperties) { Score = score; Highlights = highlights; AdditionalProperties = additionalProperties; }
private async Task <Tuple <MetadataItem, bool> > GetMetadataFromProjectLevelCacheAsync <T>( T input, IEnumerable <string> inputKey, Func <IncrementalCheck, Task <bool> > rebuildChecker, Func <T, Task <Compilation> > compilationProvider, Func <T, Task <IAssemblySymbol> > assemblyProvider, Func <T, IDictionary <string, List <string> > > containedFilesProvider, string outputFolder, bool preserveRawInlineComments, bool shouldSkipMarkup, string filterConfigFile, IReadOnlyDictionary <Compilation, IEnumerable <IMethodSymbol> > extensionMethods) { DateTime triggeredTime = DateTime.UtcNow; var projectLevelCache = ProjectLevelCache.Get(inputKey); var projectConfig = projectLevelCache.GetValidConfig(inputKey); var rebuildProject = true; if (projectConfig != null) { var projectCheck = new IncrementalCheck(projectConfig); rebuildProject = await rebuildChecker(projectCheck); } MetadataItem projectMetadata; if (!rebuildProject) { // Load from cache var cacheFile = Path.Combine(projectConfig.OutputFolder, projectConfig.RelatvieOutputFiles.First()); Logger.Log(LogLevel.Info, $"'{projectConfig.InputFilesKey}' keep up-to-date since '{projectConfig.TriggeredUtcTime.ToString()}', cached intermediate result '{cacheFile}' is used."); if (TryParseYamlMetadataFile(cacheFile, out projectMetadata)) { return(Tuple.Create(projectMetadata, rebuildProject)); } else { Logger.Log(LogLevel.Info, $"'{projectConfig.InputFilesKey}' is invalid, rebuild needed."); } } var compilation = await compilationProvider(input); var assembly = await assemblyProvider(input); projectMetadata = GenerateYamlMetadata(compilation, assembly, preserveRawInlineComments, filterConfigFile, extensionMethods); var file = Path.GetRandomFileName(); var cacheOutputFolder = projectLevelCache.OutputFolder; var path = Path.Combine(cacheOutputFolder, file); YamlUtility.Serialize(path, projectMetadata); Logger.Log(LogLevel.Verbose, $"Successfully generated metadata {cacheOutputFolder} for {projectMetadata.Name}"); IDictionary <string, List <string> > containedFiles = null; if (containedFilesProvider != null) { containedFiles = containedFilesProvider(input); } // Save to cache projectLevelCache.SaveToCache(inputKey, containedFiles, triggeredTime, cacheOutputFolder, new List <string>() { file }, shouldSkipMarkup, _msbuildProperties); return(Tuple.Create(projectMetadata, rebuildProject)); }
public RouteValueDictionaryWrapper(IReadOnlyDictionary <string, object> routeValueDictionary) { RouteValueDictionary = routeValueDictionary; }
private Task <Tuple <MetadataItem, bool> > GetAssemblyMetadataFromCacheAsync(IEnumerable <string> files, Compilation compilation, IAssemblySymbol assembly, string outputFolder, bool forceRebuild, string filterConfigFile, IReadOnlyDictionary <Compilation, IEnumerable <IMethodSymbol> > extensionMethods) { if (files == null || !files.Any()) { return(null); } return(GetMetadataFromProjectLevelCacheAsync( files, files.Concat(new string[] { filterConfigFile }), s => Task.FromResult(forceRebuild || s.AreFilesModified(files.Concat(new string[] { filterConfigFile }))), s => Task.FromResult(compilation), s => Task.FromResult(assembly), s => null, outputFolder, false, false, filterConfigFile, extensionMethods)); }
public static async ValueTask <(int exitCode, MemoryStreamWriter stdOut, MemoryStreamWriter stdErr)> BuildAndRunTestAsync(this CliApplicationBuilder applicationBuilder, ITestOutputHelper testOutput, string commandLine, IReadOnlyDictionary <string, string> environmentVariables, bool containsExecutable = false, bool isInputRedirected = true) { var(console, stdOut, stdErr) = VirtualConsole.CreateBuffered(isInputRedirected: isInputRedirected); CliApplication application = applicationBuilder.UseConsole(console) .Build(); int exitCode = await application.RunAsync(commandLine, environmentVariables, containsExecutable); testOutput.WriteLine("Exit Code: {0}", exitCode); testOutput.Print(stdOut, stdErr); return(exitCode, stdOut, stdErr); }
internal static MetadataItem GenerateYamlMetadata(Compilation compilation, IAssemblySymbol assembly = null, bool preserveRawInlineComments = false, string filterConfigFile = null, IReadOnlyDictionary <Compilation, IEnumerable <IMethodSymbol> > extensionMethods = null) { if (compilation == null) { return(null); } object visitorContext = new object(); SymbolVisitorAdapter visitor; if (compilation.Language == "Visual Basic") { visitor = new SymbolVisitorAdapter(new CSYamlModelGenerator() + new VBYamlModelGenerator(), SyntaxLanguage.VB, compilation, preserveRawInlineComments, filterConfigFile, extensionMethods); } else if (compilation.Language == "C#") { visitor = new SymbolVisitorAdapter(new CSYamlModelGenerator() + new VBYamlModelGenerator(), SyntaxLanguage.CSharp, compilation, preserveRawInlineComments, filterConfigFile, extensionMethods); } else { Debug.Assert(false, "Language not supported: " + compilation.Language); Logger.Log(LogLevel.Error, "Language not supported: " + compilation.Language); return(null); } assembly = assembly ?? compilation.Assembly; MetadataItem item = assembly.Accept(visitor); return(item); }
private Task <Tuple <MetadataItem, bool> > GetFileMetadataFromCacheAsync(IEnumerable <string> files, Compilation compilation, string outputFolder, bool forceRebuild, bool shouldSkipMarkup, bool preserveRawInlineComments, string filterConfigFile, IReadOnlyDictionary <Compilation, IEnumerable <IMethodSymbol> > extensionMethods) { if (files == null || !files.Any()) { return(null); } return(GetMetadataFromProjectLevelCacheAsync( files, files.Concat(new string[] { filterConfigFile }), s => Task.FromResult(forceRebuild || s.AreFilesModified(files.Concat(new string[] { filterConfigFile })) || s.MSBuildPropertiesUpdated(_msbuildProperties)), s => Task.FromResult(compilation), s => Task.FromResult(compilation.Assembly), s => null, outputFolder, preserveRawInlineComments, shouldSkipMarkup, filterConfigFile, extensionMethods)); }
public IEntitySyncState <TAtypeEntityId, TAtypeEntityVersion, TAtypeEntity, TBtypeEntityId, TBtypeEntityVersion, TBtypeEntity> FetchRequiredEntities(IReadOnlyDictionary <TAtypeEntityId, TAtypeEntity> aEntities, IReadOnlyDictionary <TBtypeEntityId, TBtypeEntity> bEntites) { return(this); }
private Task <Tuple <MetadataItem, bool> > GetProjectMetadataFromCacheAsync(Project project, Compilation compilation, string outputFolder, ProjectDocumentCache documentCache, bool forceRebuild, bool shouldSkipMarkup, bool preserveRawInlineComments, string filterConfigFile, IReadOnlyDictionary <Compilation, IEnumerable <IMethodSymbol> > extensionMethods, bool isReferencedProjectRebuilt) { var projectFilePath = project.FilePath; var k = documentCache.GetDocuments(projectFilePath); return(GetMetadataFromProjectLevelCacheAsync( project, new[] { projectFilePath, filterConfigFile }, s => Task.FromResult(forceRebuild || s.AreFilesModified(k.Concat(new string[] { filterConfigFile })) || isReferencedProjectRebuilt || s.MSBuildPropertiesUpdated(_msbuildProperties)), s => Task.FromResult(compilation), s => Task.FromResult(compilation.Assembly), s => { return new Dictionary <string, List <string> > { { StringExtension.ToNormalizedFullPath(s.FilePath), k.ToList() } }; }, outputFolder, preserveRawInlineComments, shouldSkipMarkup, filterConfigFile, extensionMethods)); }
public static U UnsafeGetValue <T, U>(this IReadOnlyDictionary <T, U> dict, T key, U defaultValue = default(U)) { return(dict.TryGetValue(key, out var value) ? value : defaultValue); }
public ResultRow(IReadOnlyDictionary <string, object> fields) { Fields = fields; }
/// <summary> /// 1) Bind input and output features /// 2) Run evaluation of the model /// 3) Report the result /// </summary> /// <param name="inputVideoFrame"></param> /// <returns></returns> private async Task EvaluateVideoFrameAsync(VideoFrame inputVideoFrame) { Debug.WriteLine("EvaluateVideoFrameAsync"); LearningModelSession session = null; bool isReadyForEval = false; bool showInitialImageAndProgress = true; bool proceedWithEval = false; _evaluationLock.Wait(); { session = m_session; isReadyForEval = _isReadyForEval; _isReadyForEval = false; showInitialImageAndProgress = _showInitialImageAndProgress; proceedWithEval = _proceedWithEval; } _evaluationLock.Release(); if ((inputVideoFrame != null) && (inputVideoFrame.SoftwareBitmap != null || inputVideoFrame.Direct3DSurface != null) && isReadyForEval && (session != null) && proceedWithEval) { try { _perfStopwatch.Restart(); NotifyUser("Processing...", NotifyType.StatusMessage); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { if (showInitialImageAndProgress) { UIProcessingProgressRing.IsActive = true; UIProcessingProgressRing.Visibility = Visibility.Visible; UIButtonSaveImage.IsEnabled = false; } }); // Crop the input image to communicate appropriately to the user what is being evaluated _inputFrame = await ImageHelper.CenterCropImageAsync(inputVideoFrame, m_inWidth, m_inHeight); _perfStopwatch.Stop(); Int64 cropTime = _perfStopwatch.ElapsedMilliseconds; Debug.WriteLine($"Image handling: {cropTime}ms"); // Bind and Eval if (_inputFrame != null) { _evaluationLock.Wait(); try { _perfStopwatch.Restart(); // create bindings for the input and output buffers // ###### BUG 4794 - Reusing the same binding object currently fails to update output on 2nd+ eval call as of 07/17/2018 //if (m_binding == null) { m_binding = new LearningModelBinding(session); ImageFeatureValue outputImageFeatureValue = ImageFeatureValue.CreateFromVideoFrame(_outputFrame); m_binding.Bind(m_outName, outputImageFeatureValue); } ImageFeatureValue inputImageFeatureValue = ImageFeatureValue.CreateFromVideoFrame(_inputFrame); m_binding.Bind(m_inName, inputImageFeatureValue); Int64 bindTime = _perfStopwatch.ElapsedMilliseconds; Debug.WriteLine($"Binding: {bindTime}ms"); // render the input frame if (showInitialImageAndProgress) { await ImageHelper.RenderFrameAsync(_inputFrameRenderer, _inputFrame); } // Process the frame with the model _perfStopwatch.Restart(); var results = m_session.Evaluate(m_binding, "test"); _perfStopwatch.Stop(); Int64 evalTime = _perfStopwatch.ElapsedMilliseconds; Debug.WriteLine($"Eval: {evalTime}ms"); // Parse result IReadOnlyDictionary <string, object> outputs = results.Outputs; foreach (var output in outputs) { Debug.WriteLine($"{output.Key} : {output.Value} -> {output.Value.GetType()}"); } // Display result //ImageFeatureValue outputImage = (results.Outputs[m_outputTensorDescription.Name] as ImageFeatureValue); //if(outputImage != null) //{ // _outputFrame = outputImage.VideoFrame; //} await ImageHelper.RenderFrameAsync(_resultframeRenderer, _outputFrame); } catch (Exception ex) { NotifyUser(ex.Message, NotifyType.ErrorMessage); Debug.WriteLine(ex.ToString()); } finally { _evaluationLock.Release(); } if (showInitialImageAndProgress) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { UIProcessingProgressRing.IsActive = false; UIProcessingProgressRing.Visibility = Visibility.Collapsed; UIButtonSaveImage.IsEnabled = true; }); } NotifyUser("Done!", NotifyType.StatusMessage); } else { Debug.WriteLine("Skipped eval, null input frame"); } } catch (Exception ex) { NotifyUser(ex.Message, NotifyType.ErrorMessage); Debug.WriteLine(ex.ToString()); } _evaluationLock.Wait(); { _isReadyForEval = true; } _evaluationLock.Release(); _perfStopwatch.Reset(); } }
public override async Task <IContainSagaData> Find(IServiceProvider builder, SagaFinderDefinition finderDefinition, SynchronizedStorageSession storageSession, ContextBag context, object message, IReadOnlyDictionary <string, string> messageHeaders, CancellationToken cancellationToken = default) { var propertyAccessor = (Func <object, object>)finderDefinition.Properties["property-accessor"]; var propertyValue = propertyAccessor(message); var sagaPropertyName = (string)finderDefinition.Properties["saga-property-name"]; var lookupValues = context.GetOrCreate <SagaLookupValues>(); lookupValues.Add <TSagaData>(sagaPropertyName, propertyValue); if (propertyValue == null) { var saga = context.Get <ActiveSagaInstance>(); var sagaEntityName = saga.Metadata.Name; var messageName = finderDefinition.MessageTypeName; throw new Exception($"Message {messageName} mapped to saga {sagaEntityName} has attempted to assign null to the correlation property {sagaPropertyName}. Correlation properties cannot be assigned null."); } if (sagaPropertyName.ToLower() == "id") { return(await sagaPersister.Get <TSagaData>((Guid)propertyValue, storageSession, context, cancellationToken).ConfigureAwait(false)); } return(await sagaPersister.Get <TSagaData>(sagaPropertyName, propertyValue, storageSession, context, cancellationToken).ConfigureAwait(false)); }
public VersionCookie(IDictionary <int, BufferVersion> versions) { Versions = new SortedDictionary <int, BufferVersion>(versions); }
private void GenerateMapCacheIniFile(string path, IReadOnlyDictionary <string, MapCache> mapCacheEntries) { using (var writer = new StreamWriter(File.Create(path))) { writer.WriteLine($"; FILE: {path} /////////////////////////////////////////////////////////////"); writer.WriteLine("; This INI file is auto-generated - do not modify"); writer.WriteLine("; /////////////////////////////////////////////////////////////////////////////"); foreach (var entry in mapCacheEntries) { var mapCache = entry.Value; writer.WriteLine(); writer.Write("MapCache "); WriteEncodedPath(entry.Key); Write("fileSize", mapCache.FileSize); Write("fileCRC", mapCache.FileCrc); Write("timestampLo", mapCache.TimestampLo); Write("timestampHi", mapCache.TimestampHi); WriteBoolean("isOfficial", mapCache.IsOfficial); WriteBoolean("isMultiplayer", mapCache.IsMultiplayer); Write("numPlayers", mapCache.NumPlayers); WriteVector("extentMin", mapCache.ExtentMin); WriteVector("extentMax", mapCache.ExtentMax); Write("nameLookupTag", mapCache.NameLookupTag); WriteVector("InitialCameraPosition", mapCache.InitialCameraPosition); if (mapCache.Player1Start != Vector3.Zero) { WriteVector("Player_1_Start", mapCache.Player1Start); } if (mapCache.Player2Start != Vector3.Zero) { WriteVector("Player_2_Start", mapCache.Player2Start); } if (mapCache.Player3Start != Vector3.Zero) { WriteVector("Player_3_Start", mapCache.Player3Start); } if (mapCache.Player4Start != Vector3.Zero) { WriteVector("Player_4_Start", mapCache.Player4Start); } if (mapCache.Player5Start != Vector3.Zero) { WriteVector("Player_5_Start", mapCache.Player5Start); } if (mapCache.Player6Start != Vector3.Zero) { WriteVector("Player_6_Start", mapCache.Player6Start); } if (mapCache.Player7Start != Vector3.Zero) { WriteVector("Player_7_Start", mapCache.Player7Start); } if (mapCache.Player8Start != Vector3.Zero) { WriteVector("Player_8_Start", mapCache.Player8Start); } foreach (var techPosition in mapCache.TechPositions) { WriteVector("techPosition", techPosition); } foreach (var supplyPosition in mapCache.SupplyPositions) { WriteVector("supplyPosition", supplyPosition); } writer.WriteLine("END"); writer.WriteLine(); } void WriteEncodedPath(string path) { for (int i = 0; i < path.Length; i++) { switch (path[i]) { case char l when l >= 'a' && l <= 'z': case char u when u >= 'A' && u <= 'Z': case char d when d >= '0' && d <= '9': writer.Write(path[i]); break; default: writer.Write('_'); writer.Write(((short)path[i]).ToString("X2")); break; } } writer.WriteLine(); } void Write(string key, object value) { writer.Write(" "); writer.Write(key); writer.Write(" = "); writer.WriteLine(value); } void WriteVector(string key, in Vector3 vector) { Write(key, $"X:{vector.X:F2} Y:{vector.Y:F2} Z:{vector.Z:F2}"); } void WriteBoolean(string key, bool value) { Write(key, value ? "yes" : "no"); } } }
/// <summary> /// Depict a reaction. /// </summary> /// <param name="rxn">reaction instance</param> /// <returns>depiction</returns> /// <exception cref="CDKException">a depiction could not be generated</exception> public Depiction Depict(IReaction rxn, IReadOnlyDictionary <IChemObject, Color> highlight = null) { if (highlight == null) { highlight = Dictionaries.Empty <IChemObject, Color>(); } Ensure2DLayout(rxn); // can reorder components! var fgcol = templateModel.GetAtomColorer().GetAtomColor(rxn.Builder.NewAtom("C")); var reactants = rxn.Reactants.ToList(); var products = rxn.Products.ToList(); var agents = rxn.Agents.ToList(); List <LayoutBackup> layoutBackups = new List <LayoutBackup>(); // set ids for tagging elements int molId = 0; foreach (var mol in reactants) { SetIfMissing(mol, MarkedElement.IdKey, "mol" + ++molId); SetIfMissing(mol, MarkedElement.ClassKey, "reactant"); layoutBackups.Add(new LayoutBackup(mol)); } foreach (var mol in products) { SetIfMissing(mol, MarkedElement.IdKey, "mol" + ++molId); SetIfMissing(mol, MarkedElement.ClassKey, "product"); layoutBackups.Add(new LayoutBackup(mol)); } foreach (var mol in agents) { SetIfMissing(mol, MarkedElement.IdKey, "mol" + ++molId); SetIfMissing(mol, MarkedElement.ClassKey, "agent"); layoutBackups.Add(new LayoutBackup(mol)); } var myHighlight = new Dictionary <IChemObject, Color>(); if (atomMapColors != null) { foreach (var e in MakeHighlightAtomMap(reactants, products)) { myHighlight[e.Key] = e.Value; } } // user highlight buffer pushes out the atom-map highlight if provided foreach (var e in highlight) { myHighlight[e.Key] = e.Value; } PrepareCoords(reactants); PrepareCoords(products); PrepareCoords(agents); // highlight parts foreach (var e in myHighlight) { e.Key.SetProperty(StandardGenerator.HighlightColorKey, e.Value); } // setup the model scale based on bond length var scale = this.CaclModelScale(rxn); var model = CreateModel(); model.SetScale(scale); // reactant/product/agent element generation, we number the reactants, then products then agents var reactantBounds = Generate(reactants, model, 1); var productBounds = Generate(rxn.Products.ToList(), model, rxn.Reactants.Count); var agentBounds = Generate(rxn.Agents.ToList(), model, rxn.Reactants.Count + rxn.Products.Count); // remove current highlight buffer foreach (var obj in myHighlight.Keys) { obj.RemoveProperty(StandardGenerator.HighlightColorKey); } // generate a 'plus' element var plus = GeneratePlusSymbol(scale, fgcol); // reset the coordinates to how they were before we invoked depict foreach (LayoutBackup backup in layoutBackups) { backup.Reset(); } var emptyBounds = new Bounds(); var title = model.GetShowReactionTitle() ? GenerateTitle(model, rxn, scale) : emptyBounds; var reactantTitles = new List <Bounds>(); var productTitles = new List <Bounds>(); if (model.GetShowMoleculeTitle()) { foreach (IAtomContainer reactant in reactants) { reactantTitles.Add(GenerateTitle(model, reactant, scale)); } foreach (IAtomContainer product in products) { productTitles.Add(GenerateTitle(model, product, scale)); } } Bounds conditions = GenerateReactionConditions(rxn, fgcol, model.GetScale()); return(new ReactionDepiction(model, reactantBounds, productBounds, agentBounds, plus, rxn.Direction, dimensions, reactantTitles, productTitles, title, conditions, fgcol)); }
internal Workspace(string id, string name, string type, string location, IReadOnlyDictionary <string, string> tags, string eTag, WorkspaceIdentity identity, string provisioningState, DateTimeOffset?createTime, string version, LinkedServiceReference defaultStorage, LinkedServiceReference defaultSqlServer, IReadOnlyDictionary <string, object> additionalProperties) : base(id, name, type, location, tags, eTag) { Identity = identity; ProvisioningState = provisioningState; CreateTime = createTime; Version = version; DefaultStorage = defaultStorage; DefaultSqlServer = defaultSqlServer; AdditionalProperties = additionalProperties ?? new Dictionary <string, object>(); }
public DbContextOptions( [NotNull] IReadOnlyDictionary <Type, IDbContextOptionsExtension> extensions) : base(extensions) { }
public VersionCookie(int version) { Versions = new Dictionary <int, BufferVersion> { [0] = new BufferVersion(version, null, null) }; }
public ExecuteResult(int executionCount, string source = null, IReadOnlyDictionary <string, object> data = null, IReadOnlyDictionary <string, object> metaData = null, IReadOnlyDictionary <string, object> transient = null) : base(source, data, metaData, transient) { ExecutionCount = executionCount; }
/// <summary> /// Depict a set of molecules, they will be depicted in a grid with the /// specified number of rows and columns. Rows are filled first and then /// columns. /// </summary> /// <param name="mols">molecules</param> /// <param name="nrow">number of rows</param> /// <param name="ncol">number of columns</param> /// <returns>depiction</returns> /// <exception cref="CDKException">a depiction could not be generated</exception> public Depiction Depict(IEnumerable <IAtomContainer> mols, int nrow, int ncol, IReadOnlyDictionary <IChemObject, Color> highlight = null) { if (highlight == null) { highlight = Dictionaries.Empty <IChemObject, Color>(); } var layoutBackups = new List <LayoutBackup>(); int molId = 0; foreach (var mol in mols) { SetIfMissing(mol, MarkedElement.IdKey, "mol" + ++molId); layoutBackups.Add(new LayoutBackup(mol)); } // ensure we have coordinates, generate them if not // we also rescale the molecules such that all bond // lengths are the same. PrepareCoords(mols); // highlight parts foreach (var e in highlight) { e.Key.SetProperty(StandardGenerator.HighlightColorKey, e.Value); } // generate bound rendering elements var model = CreateModel(); // setup the model scale var molList = mols.ToList(); model.SetScale(CaclModelScale(molList)); var molElems = Generate(molList, model, 1); // reset molecule coordinates foreach (LayoutBackup backup in layoutBackups) { backup.Reset(); } // generate titles (if enabled) var titles = new List <Bounds>(); if (model.GetShowMoleculeTitle()) { foreach (var mol in mols) { titles.Add(GenerateTitle(model, mol, model.GetScale())); } } // remove current highlight buffer foreach (var obj in highlight.Keys) { obj.RemoveProperty(StandardGenerator.HighlightColorKey); } return(new MolGridDepiction(model, molElems, titles, dimensions, nrow, ncol)); }
internal MockRawConfigSnapshot(IReadOnlyDictionary <string, string> dictionary) => _dictionary = dictionary;
public RuntimeDescription(string runtimeIdentifier, IEnumerable <string> inheritedRuntimes, IEnumerable <RuntimeDependencySet> runtimeDependencySets) { RuntimeIdentifier = runtimeIdentifier; InheritedRuntimes = inheritedRuntimes.ToList().AsReadOnly(); RuntimeDependencySets = runtimeDependencySets.ToDictionary(d => d.Id, StringComparer.OrdinalIgnoreCase); }
/// common functionality public void connect(IMethodResult oResult) { Logger.Write("connect call"); IReadOnlyDictionary<string, string> options = new IReadOnlyDictionary<string, string>(); connectWithOptions(options, oResult); }