public void Parsing_Of_Sc_Query_Output() { string output = Resources.ScQueryOutput; HashSet<ServiceItem> expected = new HashSet<ServiceItem> { new ServiceItem { ServiceName = "TermService", DisplayName = "Terminal Services" }, new ServiceItem { ServiceName = "Themes", DisplayName = "Themes" }, new ServiceItem { ServiceName = "UNS", DisplayName = "Intel(R) Management and Security Application User Notification Service" } }; HashSet<ServiceItem> actual = ServiceHelper_Accessor.ParseServicesOutput(output); Assert.IsTrue(expected.IsSubsetOf(actual)); Assert.IsTrue(expected.IsSupersetOf(actual)); }
static void Main(string[] args) { var ukCities = new HashSet<string> { "Ripon", "Manchester", "Sheffield", "Truro" }; var bigUKCities = new HashSet<string> { "Sheffield", "Manchester" }; var bigCitiesArray = new HashSet<string> { "New York", "Manchester", "Sheffield", "Paris" }; //bool ukIsSubset = bigUKCities.IsSubsetOf(ukCities); bool ukIsSuperset = ukCities.IsSupersetOf(bigUKCities); Console.WriteLine(ukIsSuperset); // bool bigUKIsSubset = bigUKCities.IsSubsetOf(bigCitiesArray); bool bigUKIsSuperset = bigCitiesArray.IsSupersetOf(bigUKCities); Console.WriteLine(bigUKIsSuperset); }
public void TestSubSetSuperSet () { var aSet = new HashSet<int> { 1, 2 }; var bSet = new HashSet<int> { 1 }; Assert.IsTrue (aSet.IsSubsetOf (aSet)); Assert.IsTrue (bSet.IsSubsetOf (aSet)); Assert.IsTrue (bSet.IsProperSubsetOf (aSet)); Assert.IsFalse (aSet.IsProperSubsetOf (aSet)); Assert.IsTrue (aSet.IsSupersetOf (aSet)); Assert.IsTrue (aSet.IsSupersetOf (bSet)); Assert.IsTrue (aSet.IsProperSupersetOf (bSet)); Assert.IsFalse (aSet.IsProperSupersetOf (aSet)); }
private IEnumerableEx<Level1ChangeMessage> GetMessages() { var types = new HashSet<Level1Fields>(Level1FieldsCtrl.SelectedFields); var messages = StorageRegistry .GetLevel1MessageStorage(SelectedSecurity, Drive, StorageFormat) .Load(From, To + TimeHelper.LessOneDay); return messages .Where(m => types.IsSupersetOf(m.Changes.Keys)) .ToEx(messages.Count); }
/// <summary> /// Gets the instance of the created command object. /// </summary> /// <param name="tokens">Command line arguments to initialize command with.</param> /// <exception cref="Exception{OptionsValidationExceptionArgs}"> /// Indicates that at least one required option was not specified. /// </exception> internal object CreateInstance(IDictionary<string, OptionValue> tokens) { HashSet<string> availableOptions = new HashSet<string>(tokens.Select(t => t.Key.ToLowerInvariant())); OptionMetadata[] targetMetadata = null; // Find options set that matches our tokens collection. foreach (var usage in _metadata.Options) { HashSet<string> requiredOptions = new HashSet<string>(usage.Where(o => o.Required).Select(o => o.Name.ToLowerInvariant())); HashSet<string> allOptions = new HashSet<string>(usage.Select(o => o.Name.ToLowerInvariant())); if (requiredOptions.IsSubsetOf(availableOptions) && allOptions.IsSupersetOf(availableOptions)) { targetMetadata = usage; break; } } if (null == targetMetadata) { var args = new OptionsValidationExceptionArgs("Invalid command arguments provided."); throw new Exception<OptionsValidationExceptionArgs>(args); } try { return CreateInstanceInternal(targetMetadata, tokens); } catch (TargetInvocationException ex) { var argumentError = ex.InnerException as ArgumentException; if (null == argumentError) throw; string msg = string.Format("Invalid value for option '{0}'. {1}", argumentError.ParamName, argumentError.Message); var args = new OptionsValidationExceptionArgs(msg); throw new Exception<OptionsValidationExceptionArgs>(args); } catch (MissingMethodException) { var args = new OptionsValidationExceptionArgs("Invalid command arguments provided."); throw new Exception<OptionsValidationExceptionArgs>(args); } }
static void Main() { var companyTeams = new HashSet<string>() { "Ferrari", "McLaren", "Mercedes" }; var traditionalTeams = new HashSet<string>() { "Ferrari", "McLaren" }; var privateTeams = new HashSet<string>() { "Red Bull", "Lotus", "Toro Rosso", "Force India", "Sauber" }; if (privateTeams.Add("Williams")) WriteLine("Williams added"); if (!companyTeams.Add("McLaren")) WriteLine("McLaren was already in this set"); if (traditionalTeams.IsSubsetOf(companyTeams)) { WriteLine("traditionalTeams is subset of companyTeams"); } if (companyTeams.IsSupersetOf(traditionalTeams)) { WriteLine("companyTeams is a superset of traditionalTeams"); } traditionalTeams.Add("Williams"); if (privateTeams.Overlaps(traditionalTeams)) { WriteLine("At least one team is the same with traditional and private teams"); } var allTeams = new SortedSet<string>(companyTeams); allTeams.UnionWith(privateTeams); allTeams.UnionWith(traditionalTeams); WriteLine(); WriteLine("all teams"); foreach (var team in allTeams) { WriteLine(team); } allTeams.ExceptWith(privateTeams); WriteLine(); WriteLine("no private team left"); foreach (var team in allTeams) { WriteLine(team); } }
public static void Cozy() { Console.WriteLine("\n-----------------------------------------------"); Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName); Console.WriteLine("-----------------------------------------------"); //HashSet<T>和List<T>差不多的,但HashSet<T>只能包含不重复的元素 var hashSet = new HashSet<int>(); //Add()会返回一个bool值,添加成功返回true,集合内有相同的元素,则添加失败返回false Console.WriteLine(hashSet.Add(1)); //output True Console.WriteLine(hashSet.Add(1)); //output False Console.WriteLine(hashSet.Add(2)); Console.WriteLine(hashSet.Add(3)); var array = new[] {1, 2, 3, 4, 5}; Console.WriteLine(hashSet.IsSubsetOf(array)); //output True Console.WriteLine(hashSet.IsSupersetOf(array)); //output False //增加array集合的元素 hashSet.UnionWith(array); foreach (var i in hashSet) { Console.WriteLine(i); } //移除array集合的元素 hashSet.ExceptWith(array); foreach (var i in hashSet) { Console.WriteLine(i); } }
public bool IsSupersetOf(IEnumerable <string> other) => Flags.IsSupersetOf(other);
/// <summary> /// Is superset of /// </summary> /// <param name="other">Other</param> /// <returns>"true" if it is a superset of other, otherwise "false"</returns> public bool IsSupersetOf(IEnumerable <Regex> other) => patterns.IsSupersetOf(other);
internal void HandleMessage(Message msg) { if (msg == null) { return; } //List<Connection> recipients = new List<Connection> (); HashSet <Connection> recipients = new HashSet <Connection> (); //HashSet<Connection> recipientsAll = new HashSet<Connection> (Connections); object fieldValue = msg.Header[FieldCode.Destination]; if (fieldValue != null) { string destination = (string)fieldValue; Connection destConn; if (Names.TryGetValue(destination, out destConn)) { recipients.Add(destConn); } else if (destination != DBusBusName && !destination.StartsWith(":") && (msg.Header.Flags & HeaderFlag.NoAutoStart) != HeaderFlag.NoAutoStart) { // Attempt activation StartProcessNamed(destination); //Thread.Sleep (5000); // TODO: Route the message to the newly activated service! activationMessages[destination] = msg; //if (Names.TryGetValue (destination, out destConn)) // recipients.Add (destConn); //else // Console.Error.WriteLine ("Couldn't route message to activated service"); } else if (destination != DBusBusName) { // Send an error when there's no hope of getting the requested reply if (msg.ReplyExpected) { // Error org.freedesktop.DBus.Error.ServiceUnknown: The name {0} was not provided by any .service files Message rmsg = MessageHelper.CreateUnknownMethodError(new MethodCall(msg)); if (rmsg != null) { //Caller.Send (rmsg); Caller.SendReal(rmsg); return; } } } } HashSet <Connection> recipientsMatchingHeader = new HashSet <Connection> (); HashSet <ArgMatchTest> a = new HashSet <ArgMatchTest> (); foreach (KeyValuePair <MatchRule, List <Connection> > pair in Rules) { if (recipients.IsSupersetOf(pair.Value)) { continue; } if (pair.Key.MatchesHeader(msg)) { a.UnionWith(pair.Key.Args); recipientsMatchingHeader.UnionWith(pair.Value); } } MatchRule.Test(a, msg); foreach (KeyValuePair <MatchRule, List <Connection> > pair in Rules) { if (recipients.IsSupersetOf(pair.Value)) { continue; } if (!recipientsMatchingHeader.IsSupersetOf(pair.Value)) { continue; } if (a.IsSupersetOf(pair.Key.Args)) { recipients.UnionWith(pair.Value); } } foreach (Connection conn in recipients) { // TODO: rewrite/don't header fields //conn.Send (msg); // TODO: Zero the Serial or not? //msg.Header.Serial = 0; ((ServerConnection)conn).SendReal(msg); } }
void ProcessDependencyGraph(StreamWriter writer) { #if false // The parallelized building isn't much faster, and tests don't all work right. // ---------------------------------------------------------------------------- // Filter dependencies for those that are actually built. // Also collect all projects that don't depend on any other built projects. Dictionary <string, List <string> > mapProjInternalDepends = new Dictionary <string, List <string> >(); List <HashSet <string> > groupDependencies = new List <HashSet <string> >(); groupDependencies.Add(new HashSet <string>()); int cProjects = 0; foreach (var project in m_mapProjFile.Keys) { if (project.StartsWith("SharpViews") || // These projects are experimental. project == "FxtExe" || // These projects weren't built by nant normally. project == "FixFwData" || project.StartsWith("LinuxSmokeTest")) { continue; } var dependencies = new List <string>(); foreach (var dep in m_mapProjDepends[project]) { if (m_mapProjFile.ContainsKey(dep)) { dependencies.Add(dep); } } if (project == "xWorksTests" && !dependencies.Contains("XCoreAdapterSilSidePane")) { dependencies.Add("XCoreAdapterSilSidePane"); } if (dependencies.Count == 0) { groupDependencies[0].Add(project); } dependencies.Sort(); mapProjInternalDepends.Add(project, dependencies); ++cProjects; } if (groupDependencies[0].Count == 0) { return; } int num = 1; HashSet <string> total = new HashSet <string>(groupDependencies[0]); // Work through all the dependencies, collecting sets of projects that can be // built in parallel. while (total.Count < cProjects) { groupDependencies.Add(new HashSet <string>()); foreach (var project in mapProjInternalDepends.Keys) { bool fAlready = false; for (int i = 0; i < groupDependencies.Count - 1; ++i) { if (groupDependencies[i].Contains(project)) { fAlready = true; break; } } if (fAlready) { continue; } var dependencies = mapProjInternalDepends[project]; if (total.IsSupersetOf(dependencies)) { groupDependencies[num].Add(project); } } if (groupDependencies[num].Count == 0) { break; } foreach (var x in groupDependencies[num]) { total.Add(x); } ++num; } writer.WriteLine("<!--"); writer.WriteLine("\tUsing this parallelization gains only 15% for building FieldWorks,"); writer.WriteLine("\tand possibly nothing for running tests. (Although trials have shown"); writer.WriteLine("\t1600+ new test failures when trying this parallelized setup!)"); writer.WriteLine(); for (int i = 0; i < groupDependencies.Count; ++i) { var targName = string.Format("cs{0:d03}", i + 1); writer.Write("\t<Target Name=\"{0}\"", targName); var depends = String.Format("cs{0:d03}", i); if (i == 0) { depends = "Initialize"; } if (groupDependencies[i].Contains("COMInterfaces")) { depends = "mktlbs;" + depends; } writer.WriteLine(" DependsOnTargets=\"{0}\">", depends); bool fIncludesTests = false; int count = 0; writer.Write("\t\t<MSBuild Projects=\""); foreach (var targ in groupDependencies[i]) { if (count > 0) { writer.Write(";"); } writer.Write(m_mapProjFile[targ].Replace(m_fwroot, "$(fwrt)")); ++count; if (targ.EndsWith("Tests") || targ == "TestManager" || targ == "ProjectUnpacker") { fIncludesTests = true; } } writer.WriteLine("\""); writer.WriteLine("\t\t Targets=\"$(msbuild-target)\""); writer.WriteLine("\t\t Properties=\"$(msbuild-props)\""); writer.WriteLine("\t\t BuildInParallel=\"true\""); writer.WriteLine("\t\t ToolsVersion=\"4.0\"/>"); if (fIncludesTests) { writer.WriteLine("\t\t<NUnit Condition=\"'$(action)'=='test'\""); writer.Write("\t\t Assemblies=\""); count = 0; int timeout = 0; foreach (var targ in groupDependencies[i]) { if (targ.EndsWith("Tests") || targ == "TestManager" || targ == "ProjectUnpacker") { if (count > 0) { writer.Write(";"); } writer.Write("$(dir-outputBase)/{0}.dll", targ); ++count; timeout += TimeoutForProject(targ); } } writer.WriteLine("\""); writer.WriteLine("\t\t ToolPath=\"$(fwrt)/Bin/NUnit/bin\""); writer.WriteLine("\t\t WorkingDirectory=\"$(dir-outputBase)\""); writer.WriteLine("\t\t OutputXmlFile=\"$(dir-outputBase)/cs{0:d03}.dll-nunit-output.xml\"", i + 1); writer.WriteLine("\t\t Force32Bit=\"$(useNUnit-x86)\""); writer.WriteLine("\t\t ExcludeCategory=\"$(excludedCategories)\""); writer.WriteLine("\t\t Timeout=\"{0}\"", timeout); writer.WriteLine("\t\t ContinueOnError=\"true\" />"); } writer.WriteLine("\t</Target>"); writer.WriteLine(); } writer.WriteLine("\t<Target Name=\"csAll\" DependsOnTargets=\"cs{0:d03}\"/>", groupDependencies.Count); writer.WriteLine("-->"); writer.WriteLine(); #endif }
public void IsSupersetOfTest() { var set = new HashSet<int>(); var arr = Enumerable.Range(0, 10).ToArray(); for (int i = 0; i < 50; i++) { set.Add(i -25); } Assert.IsTrue(set.IsSupersetOf(arr)); }
/// <summary> /// 获取路由值 /// </summary> /// <param name="virtualPath">当前请求的虚拟路径</param> /// <param name="queryString">当前请求的查询数据</param> /// <returns></returns> public IDictionary<string, string> GetRouteValues( string virtualPath, NameValueCollection queryString ) { if ( virtualPath == null ) throw new ArgumentNullException( "virtualPath" ); if ( !VirtualPathUtility.IsAppRelative( virtualPath ) ) throw new ArgumentException( "virtualPath 只能使用应用程序根相对路径,即以 \"~/\" 开头的路径,调用 VirtualPathUtility.ToAppRelative 方法或使用 HttpRequest.AppRelativeCurrentExecutionFilePath 属性获取", "virtualPath" ); var queryKeySet = new HashSet<string>( _queryKeys, StringComparer.OrdinalIgnoreCase ); var requestQueryKeySet = new HashSet<string>( queryString.AllKeys, StringComparer.OrdinalIgnoreCase ); if ( LimitedQueries && !queryKeySet.IsSupersetOf( requestQueryKeySet ) )//如果限制了查询键并且查询键集合没有完全涵盖所有传进来的QueryString键的话,即存在有一个QueryString键不在查询键集合中,则这条规则不适用。 return null; virtualPath = multipleSlashRegex.Replace( virtualPath, "/" );//将连续的/替换成单独的/ var extensionLength = VirtualPathUtility.GetExtension( virtualPath ).Length; if ( extensionLength > 0 ) virtualPath = virtualPath.Remove( virtualPath.Length - extensionLength );//去除扩展名 virtualPath = virtualPath.Substring( 2 ); virtualPath = VirtualPathUtility.RemoveTrailingSlash( virtualPath ) ?? "";//在虚拟路径最后移除 / ,使得 xxx/ 与 xxx 被视为同一路径。 var pathParagraphs = virtualPath.Split( '/' ); if ( virtualPath == "" ) pathParagraphs = new string[0]; if ( pathParagraphs.Length != Paragraphes.Length )//路径段长度不一致,规则不适用 return null; var values = new Dictionary<string, string>( StringComparer.OrdinalIgnoreCase ); foreach ( var pair in _staticValues ) values.Add( pair.Key, pair.Value ); for ( int i = 0; i < pathParagraphs.Length; i++ ) { var paragraph = Paragraphes[i]; if ( !paragraph.StartsWith( "{" ) ) { if ( !pathParagraphs[i].EqualsIgnoreCase( paragraph ) )//静态路径段不符,规则不适用 return null; } else { var name = paragraph.Substring( 1, paragraph.Length - 2 ); values.Add( name, pathParagraphs[i] ); } } if ( !LimitedQueries )//如果没有限制查询键,但传进来的查询键与现有路由键有任何冲突,则这条规则不适用。 { //因为如果限制了查询键,则上面会确保查询键不超出限制的范围,且查询键的范围与路由键范围不可能重合(构造函数限定),也就不可能存在冲突。 requestQueryKeySet.IntersectWith( _routeKeys ); if ( requestQueryKeySet.Any() ) return null; } foreach ( var key in queryString.AllKeys ) { if ( key == null ) continue;//因某些未知原因会导致 AllKeys 包含空键值。 var v = queryString[key]; if ( v != null ) values.Add( key, v ); } return values; }
///<inheritdoc/> public bool IsSupersetOf(IEnumerable <TKey> other) { lock (_syncLock) return(_hashSet.IsSupersetOf(other)); }
/// <summary> /// Checks whether the granted scope is a superset of the required scope. /// </summary> /// <param name="requiredScope">The set of strings that the resource server demands in an access token's scope in order to complete some operation.</param> /// <param name="grantedScope">The set of strings that define the scope within an access token that the client is authorized to.</param> /// <returns><c>true</c> if <paramref name="grantedScope"/> is a superset of <paramref name="requiredScope"/> to allow the request to proceed; <c>false</c> otherwise.</returns> /// <remarks> /// The default reasonable implementation of this is: /// <code> /// return <paramref name="grantedScope"/>.IsSupersetOf(<paramref name="requiredScope"/>); /// </code> /// <para>In some advanced cases it may not be so simple. One case is that there may be a string that aggregates the capabilities of several others /// in order to simplify common scenarios. For example, the scope "ReadAll" may represent the same authorization as "ReadProfile", "ReadEmail", and /// "ReadFriends". /// </para> /// <para>Great care should be taken in implementing this method as this is a critical security module for the authorization and resource servers.</para> /// </remarks> public bool IsScopeSatisfied(HashSet<string> requiredScope, HashSet<string> grantedScope) { Requires.NotNull(requiredScope, "requiredScope"); Requires.NotNull(grantedScope, "grantedScope"); return grantedScope.IsSupersetOf(requiredScope); }
public bool IsSupersetOf(CompletedSuit other) { return(piecesHashSet.IsSupersetOf(other.piecesHashSet)); }
/// <summary> /// 尝试从路由值创建虚拟路径 /// </summary> /// <param name="requestContext">当前请求上下文</param> /// <param name="values">路由值</param> /// <returns>虚拟路径信息</returns> public override VirtualPathData GetVirtualPath( RequestContext requestContext, RouteValueDictionary values ) { var cache = requestContext.HttpContext.Cache; var _values = values.ToDictionary( pair => pair.Key, pair => pair.Value == null ? null : pair.Value.ToString(), StringComparer.OrdinalIgnoreCase ); var cacheKey = CreateCacheKey( _values ); var virtualPath = cache.Get( cacheKey ) as string; if ( virtualPath != null ) return new VirtualPathData( this, virtualPath ); var keySet = new HashSet<string>( _values.Keys, StringComparer.OrdinalIgnoreCase ); var candidateRules = _rules .Where( r => !r.Oneway ) //不是单向路由规则 .Where( r => keySet.IsSupersetOf( r.RouteKeys ) ) //所有路由键都必须匹配 .Where( r => keySet.IsSubsetOf( r.AllKeys ) || !r.LimitedQueries ) //所有路由键和查询字符串键必须能涵盖要设置的键。 .Where( r => r.IsMatch( _values ) ) //必须满足路由规则所定义的路由数据。 .ToArray(); if ( !candidateRules.Any() ) return null; var bestRule = BestRule( candidateRules ); virtualPath = bestRule.CreateVirtualPath( _values ); if ( IsIgnoredPath( virtualPath ) )//如果产生的虚拟路径是被忽略的,则返回 null { if ( DebugMode ) Trace( string.Format( "名为 \"{0}\" 路由表的 \"{1}\" 路由规则产生的虚拟路径 {2} 被该路由表忽略", Name, bestRule.Name, virtualPath ), TraceLevel.Warning ); else return null; } if ( MvcCompatible ) virtualPath = virtualPath.Substring( 2 ); cache.Insert( cacheKey, virtualPath, CacheItemPriority.AboveNormal ); return CreateVirtualPathData( virtualPath, bestRule ); }
public bool IsSupersetOf(IEnumerable <IVariant> other) => _hashSet.IsSupersetOf(other);
//for each of the tables make owl:Class with fields as owl:ObjectProperty or owl:DataProperty public IGraph GenerateOntologyFromDB(string dbName, string dbNamespace, string ontologyName, bool includeViews = false) { DBLoader dbLoader = new DBLoader(connString); List <string> tableNames = dbLoader.GetTableNames(includeViews); List <string> nmTableNames = new List <string>(); //referenced tables = ObjectProperty (FK fields) //other fields = DataProperty //for each table create owl:Class OntologyGraph g = new OntologyGraph(); string ns = dbNamespace; //RdfXmlWriter writer = new RdfXmlWriter(); //writer.PrettyPrintMode = true; //writer.Save(g, PathWrapper.Combine(Environment.CurrentDirectory, "LMS.owl")); ////header was printed OWLWriter owlWriter = new OWLWriter(); owlWriter.AddNamespace(ns); StringBuilder sb = new StringBuilder(); owlWriter.WriteHeader(sb); string globalUri = MatchUri(ns); foreach (string tableName in tableNames) { //check, if it's not a n:m mapping table HashSet <string> PKs = new HashSet <string>(GetPrimaryKeys(dbName, tableName)); if (PKs.Count >= 2) { HashSet <string> FKs = new HashSet <string>(GetReferencingTableColumns(dbName, tableName)); //if all PK columns are FKs at the same time -> probably, we have n:m relation if (FKs.IsSupersetOf(PKs)) //is ProperSubset maybe ??? { nmTableNames.Add(tableName); continue; //go to next table } } string tableUri = ComposeTableUri(globalUri, tableName);//globalUri.Remove(globalUri.LastIndexOf('"')) + tableName; //OntologyClass newClass = g.CreateOntologyClass(new Uri(tableUri)); owlWriter.EmitSimpleOWLClass(sb, tableUri); List <string> tableColumns = dbLoader.GetColumnNames(tableName); //now distinguish between DataProperty and ObjectProperty columns List <string> dataColumns = new List <string>(), objectColumns = GetReferencingTableColumns(dbName, tableName); //referenced via Foreign Key dataColumns = (from column in tableColumns select column).Except(objectColumns).ToList(); //seek to the end of file (till the </rdf:RDF> foreach (string dataColumn in dataColumns) { //newClass.AddLiteralProperty($"{tableUri}/{dataColumn}", g.CreateLiteralNode(dataColumn), true); string xsdType = ConvertNativeToXsdDataType(GetTableAttributeDataType(dbName, tableName, dataColumn)); owlWriter.EmitSimpleDataTypeProp(sb, $"{tableUri}#{dataColumn}", tableUri, xsdType); } foreach (string objectColumn in objectColumns) { string referencedTable = GetReferencedTableName(dbName, tableName, objectColumn); string refTableUri = ComposeTableUri(globalUri, referencedTable);//globalUri.Remove(globalUri.LastIndexOf('"')) + referencedTable; owlWriter.EmitSimpleObjectProp(sb, $"{tableUri}#{objectColumn}", tableUri, refTableUri); } //foreach(string objectColumn in objectColumns) //{ // IUriNode uriNode = g.Create //} } //process n:m tables //all n:m tables we should present as Object Properties, where domain='PK1 table' and range='PK2 table' foreach (var tableName in nmTableNames) { //string tableUri = ComposeTableUri(globalUri, tableName); List <string> PKs = GetPrimaryKeys(dbName, tableName); string tableN = GetReferencedTableName(dbName, tableName, PKs[0]); string tableM = GetReferencedTableName(dbName, tableName, PKs[1]); string tableUri = $"{ComposeTableUri(globalUri, tableN)}#{tableName}"; //where tableN - domain table //table N = domain (or vice versa) //table M = range (or vice versa) owlWriter.EmitSimpleObjectProp(sb, tableUri, ComposeTableUri(globalUri, tableN), ComposeTableUri(globalUri, tableM)); } owlWriter.WriteFooter(sb); File.WriteAllText(Path.Combine(Environment.CurrentDirectory, ontologyName), sb.ToString()); g.LoadFromString(sb.ToString(), new VDS.RDF.Parsing.RdfXmlParser()); return(g); }
public bool IsSupersetOf(IEnumerable <TElement> other) => backingSet.IsSupersetOf(other);
public bool IsSupersetOf(IEnumerable <T> other) { return(set.IsSupersetOf(other)); }
public void AssertMessageContainsAllWordsCaseSensitive(int messageIndex, string[] words, char[] splitter = null) { Assert.IsTrue(this.outputStrings.Count > messageIndex, "Message not found for specified index {0}", messageIndex); var allWords = new HashSet<string>(this.outputStrings[messageIndex].Split(splitter, StringSplitOptions.RemoveEmptyEntries)); Assert.IsTrue(allWords.IsSupersetOf(words), "Not all words found. Missing: {0}.\nAll words: {1}", string.Join(", ", words.Except(allWords)), string.Join(" ", allWords)); }
private int GetMaxStateId(IEnumerable<TreeRule> rules) { HashSet<Expr> states = new HashSet<Expr>(); HashSet<Expr> botStates = new HashSet<Expr>(); int res = -1; foreach (var rule in rules) { int k = tt.Z.GetNumeralInt(rule.state); states.Add(rule.state); if (k > res) res = k; for (int i=0; i < rule.Rank; i++) foreach (var s in rule.Lookahead(i)) botStates.Add(s); } if (!states.IsSupersetOf(botStates)) throw new AutomataException(AutomataExceptionKind.TreeTransducer_UndefinedState); return res; }
/// <summary> /// Determines whether the hash set is a superset of the specified collection. /// </summary> /// <param name="other"> The collection to compare to the current hash set. </param> /// <returns> /// True if the hash set is a superset of other; otherwise, false. /// </returns> public virtual bool IsSupersetOf(IEnumerable <T> other) { return(_set.IsSupersetOf(other)); }
public void IsSupersetOfEqualsSetsTest() { var set = new HashSet<int>(); var arr = Enumerable.Range(0, 10).ToArray(); set.UnionWith(arr); Assert.IsTrue(set.IsSupersetOf(arr)); }
public static bool SetEquals <T>(this HashSet <T> me, IEnumerable <T> other) { return(me.IsSubsetOf(other) && me.IsSupersetOf(other)); }
/// <summary> /// The method returns a list of TikzParseItems all of whose coordinates objects are contained in the selection. /// </summary> /// <param name="?"></param> /// <returns></returns> public static List <TikzParseItem> GetFullSelection2(IEnumerable <TikzParseItem> ItemList) { List <TikzParseItem> ret = new List <TikzParseItem>(); if (ItemList == null || ItemList.Count() == 0) { return(ret); } // find all ancestors for each Item. Theese are candidates to be selected (or not) var AncestorList = ItemList.Select(l => FindAncestorsInPicture(l)).ToList(); HashSet <TikzParseItem> candidates = new HashSet <TikzParseItem>(); foreach (var l in AncestorList) { foreach (var ll in l) { candidates.Add(ll); } } // add all items contained in selected container items HashSet <TikzParseItem> selWithDesc = new HashSet <TikzParseItem>(ItemList); foreach (var tpi in ItemList) { foreach (var ll in SelectDescendants(tpi, t => !(t is Tikz_Something))) { selWithDesc.Add(ll); } } // scan through all elements in the candidate lists and determine wheter all its node descendants are selected HashSet <TikzParseItem> ret2 = new HashSet <TikzParseItem>(); foreach (var tpi in candidates) { var mustbeselected = SelectDescendants(tpi, t => !(t is Tikz_Something)); if (selWithDesc.IsSupersetOf(mustbeselected)) { ret2.Add(tpi); } } // remove descendants from the list of selected items foreach (var tpi in ret2) { if (!ret2.Any(t => IsAncestorOf(t, tpi))) { ret.Add(tpi); } } // sort items ret.Sort((a, b) => a.StartPosition() - b.StartPosition()); return(ret); // Now the last elements of all lists are ancestors on one "level" of the tree. Find the smallest and largest in the horizontal ordering /* var elements = AncestorList.Select(l => l.Last()); * TikzContainerParseItem commonparent = elements.First().parent; * * int firstind = elements.Min(t => commonparent.Children.IndexOf(t)); * int lastind = elements.Max(t => commonparent.Children.IndexOf(t)); * * // Handle a special case: if the items are all coordinates in a single Tikz_Path, * // that (other than those items) contains only Tikz_Somethings, then return the whole path * if (commonparent is Tikz_Path) * { * if (commonparent.Children.FindIndex(tpi => !(tpi is Tikz_Something)) >= firstind * && commonparent.Children.FindLastIndex(tpi => !(tpi is Tikz_Something)) <= lastind) * { * ret.Add(commonparent); * return ret; * } * } * * return commonparent.Children.GetRange(firstind, lastind - firstind + 1).ToList(); */ }
/// <summary> /// Used for Linq queries to determines whether an element is a superset of the specified collection /// </summary> /// <typeparam name="T"></typeparam> /// <param name="enumerable"></param> /// <param name="items"></param> /// <returns></returns> public static bool IsSupersetOf <T>(this IEnumerable <T> enumerable, IEnumerable <T> items) { var hashSet = new HashSet <T>(enumerable); return(hashSet.IsSupersetOf(items)); }
public bool IsSupersetOf(IEnumerable <T> set) => content.IsSupersetOf(set);
public bool IsSupersetOf(IEnumerable <T> other) { bool isSupersetOf = hashSet.IsSupersetOf(other); return(isSupersetOf); }
/// <summary> /// Checks if the left items set is the superset of right items set /// </summary> /// <typeparam name="T">Type of items</typeparam> /// <param name="left">Left items set</param> /// <param name="right">Right items set</param> /// <returns>True if the left has all items of right</returns> public static bool IsSuperSetOf <T>(this IEnumerable <T> left, IEnumerable <T> right) { HashSet <T> lHashSet = new HashSet <T>(left); return(lHashSet.IsSupersetOf(right)); }
public static bool IsSupersetOf <T>(IEnumerable <T> set1, IEnumerable <T> set2) { var newSet = new HashSet <T>(set1); return(newSet.IsSupersetOf(set2)); }
public bool IsSupersetOf(IEnumerable <TVal> other) => hashSet.IsSupersetOf(other);
public bool IsSupersetOf(IEnumerable <T> other) => items.IsSupersetOf(other);
public bool IsSupersetOf(IEnumerable <T> other) { return(_wrapped.IsSupersetOf(other)); }
public void Properly_expose_IsSupersetOf() { var originalSet = new HashSet <Card>() { Card.Parse("QC"), Card.Parse("TS") }; var byValueSet = new SetByValue <Card>(originalSet); Check.That(byValueSet.IsSupersetOf(new[] { Card.Parse("QC") })).IsEqualTo(originalSet.IsSupersetOf(new[] { Card.Parse("QC") })); }
public bool IsSupersetOf(IEnumerable <string> other) { return(_hashset.IsSupersetOf(other)); }
public bool IsSupersetOf(IEnumerable <T> other) { return(collection.IsSupersetOf(other)); }
private bool CheckDependenciesExist(DependencyNode node) { HashSet<string> effectiveExistingObjectNames = new HashSet<string>(existingObjectNames, existingObjectNames.Comparer); effectiveExistingObjectNames.ExceptWith(dependencies.Keys); return effectiveExistingObjectNames.IsSupersetOf(node.Edges); }
/// <summary> /// Verifies that the streams selected for playback exist in the file and are capable of being played on the service /// </summary> /// <param name="client">KStudioClient which is connected to the Kinect service</param> /// <param name="filePath">Path to file that will be played back</param> /// <param name="playbackStreams">Collection of streams which have been selected for playback</param> private static void VerifyStreamsForPlayback(KStudioClient client, string filePath, IEnumerable<Guid> playbackStreams) { if (client == null) { throw new ArgumentNullException("client"); } if (!client.IsServiceConnected) { throw new InvalidOperationException(Strings.ErrorNotConnected); } if (string.IsNullOrEmpty(filePath)) { throw new ArgumentNullException("filePath"); } if (playbackStreams == null) { throw new ArgumentNullException("playbackStreams"); } // verify stream exists in the file using (KStudioEventFile file = client.OpenEventFile(filePath)) { HashSet<Guid> fileStreams = new HashSet<Guid>(); foreach (KStudioEventStream stream in file.EventStreams) { fileStreams.Add(stream.DataTypeId); } if (!fileStreams.IsSupersetOf(playbackStreams)) { Guid invalidStream = playbackStreams.First(x => !fileStreams.Contains(x)); throw new InvalidOperationException(string.Format(Strings.ErrorPlaybackStreamNotInFile, StreamSupport.ConvertStreamGuidToString(invalidStream))); } } // verify stream is supported for playback by the Kinect sensor foreach (Guid stream in playbackStreams) { KStudioEventStream eventStream = client.GetEventStream(stream, KStudioEventStreamSemanticIds.KinectDefaultSensorConsumer); if (!eventStream.IsPlaybackable) { throw new InvalidOperationException(string.Format(Strings.ErrorPlaybackStreamNotSupported, StreamSupport.ConvertStreamGuidToString(stream))); } } }
private static bool HasAllProperties(NuGetArtifactGroup group, IEnumerable<KeyValuePair<string, string>> properties) { HashSet<KeyValuePair<string, string>> groupProperties = new HashSet<KeyValuePair<string, string>>(group.Properties); HashSet<KeyValuePair<string, string>> checkProperties = new HashSet<KeyValuePair<string, string>>(properties); return groupProperties.IsSupersetOf(checkProperties); }
void ProcessDependencyGraph(StreamWriter writer) { #if false // The parallelized building isn't much faster, and tests don't all work right. // ---------------------------------------------------------------------------- // Filter dependencies for those that are actually built. // Also collect all projects that don't depend on any other built projects. Dictionary<string, List<string>> mapProjInternalDepends = new Dictionary<string, List<string>>(); List<HashSet<string>> groupDependencies = new List<HashSet<string>>(); groupDependencies.Add(new HashSet<string>()); int cProjects = 0; foreach (var project in m_mapProjFile.Keys) { if (project.StartsWith("SharpViews") || // These projects are experimental. project == "FxtExe" || // These projects weren't built by nant normally. project == "FixFwData" || project.StartsWith("LinuxSmokeTest")) { continue; } var dependencies = new List<string>(); foreach (var dep in m_mapProjDepends[project]) { if (m_mapProjFile.ContainsKey(dep)) dependencies.Add(dep); } if (project == "xWorksTests" && !dependencies.Contains("XCoreAdapterSilSidePane")) dependencies.Add("XCoreAdapterSilSidePane"); if (dependencies.Count == 0) groupDependencies[0].Add(project); dependencies.Sort(); mapProjInternalDepends.Add(project, dependencies); ++cProjects; } if (groupDependencies[0].Count == 0) return; int num = 1; HashSet<string> total = new HashSet<string>(groupDependencies[0]); // Work through all the dependencies, collecting sets of projects that can be // built in parallel. while (total.Count < cProjects) { groupDependencies.Add(new HashSet<string>()); foreach (var project in mapProjInternalDepends.Keys) { bool fAlready = false; for (int i = 0; i < groupDependencies.Count - 1; ++i) { if (groupDependencies[i].Contains(project)) { fAlready = true; break; } } if (fAlready) continue; var dependencies = mapProjInternalDepends[project]; if (total.IsSupersetOf(dependencies)) groupDependencies[num].Add(project); } if (groupDependencies[num].Count == 0) break; foreach (var x in groupDependencies[num]) total.Add(x); ++num; } writer.WriteLine("<!--"); writer.WriteLine("\tUsing this parallelization gains only 15% for building FieldWorks,"); writer.WriteLine("\tand possibly nothing for running tests. (Although trials have shown"); writer.WriteLine("\t1600+ new test failures when trying this parallelized setup!)"); writer.WriteLine(); for (int i = 0; i < groupDependencies.Count; ++i) { var targName = string.Format("cs{0:d03}", i+1); writer.Write("\t<Target Name=\"{0}\"", targName); var depends = String.Format("cs{0:d03}", i); if (i == 0) depends = "Initialize"; if (groupDependencies[i].Contains("COMInterfaces")) depends = "mktlbs;" + depends; writer.WriteLine(" DependsOnTargets=\"{0}\">", depends); bool fIncludesTests = false; int count = 0; writer.Write("\t\t<MSBuild Projects=\""); foreach (var targ in groupDependencies[i]) { if (count > 0) writer.Write(";"); writer.Write(m_mapProjFile[targ].Replace(m_fwroot, "$(fwrt)")); ++count; if (targ.EndsWith("Tests") || targ == "TestManager" || targ == "ProjectUnpacker") { fIncludesTests = true; } } writer.WriteLine("\""); writer.WriteLine("\t\t Targets=\"$(msbuild-target)\""); writer.WriteLine("\t\t Properties=\"$(msbuild-props)\""); writer.WriteLine("\t\t BuildInParallel=\"true\""); writer.WriteLine("\t\t ToolsVersion=\"4.0\"/>"); if (fIncludesTests) { writer.WriteLine("\t\t<NUnit Condition=\"'$(action)'=='test'\""); writer.Write("\t\t Assemblies=\""); count = 0; int timeout = 0; foreach (var targ in groupDependencies[i]) { if (targ.EndsWith("Tests") || targ == "TestManager" || targ == "ProjectUnpacker") { if (count > 0) writer.Write(";"); writer.Write("$(dir-outputBase)/{0}.dll", targ); ++count; timeout += TimeoutForProject(targ); } } writer.WriteLine("\""); writer.WriteLine("\t\t ToolPath=\"$(fwrt)/Bin/NUnit/bin\""); writer.WriteLine("\t\t WorkingDirectory=\"$(dir-outputBase)\""); writer.WriteLine("\t\t OutputXmlFile=\"$(dir-outputBase)/cs{0:d03}.dll-nunit-output.xml\"", i+1); writer.WriteLine("\t\t Force32Bit=\"$(useNUnit-x86)\""); writer.WriteLine("\t\t ExcludeCategory=\"$(excludedCategories)\""); writer.WriteLine("\t\t Timeout=\"{0}\"", timeout); writer.WriteLine("\t\t ContinueOnError=\"true\" />"); } writer.WriteLine("\t</Target>"); writer.WriteLine(); } writer.WriteLine("\t<Target Name=\"csAll\" DependsOnTargets=\"cs{0:d03}\"/>", groupDependencies.Count); writer.WriteLine("-->"); writer.WriteLine(); #endif }
public void IsSupersetOfEmptyCollectionTest() { var set = new HashSet<int>(Enumerable.Range(0,10)); Assert.IsTrue(set.IsSupersetOf(Enumerable.Range(0,0))); }
/// <summary> /// Finds and returns all modules that could not exist without the listed modules installed, including themselves. /// Acts recursively. /// </summary> internal static HashSet<string> FindReverseDependencies(IEnumerable<string> modules_to_remove, IEnumerable<Module> orig_installed, IEnumerable<string> dlls) { while (true) { // Make our hypothetical install, and remove the listed modules from it. HashSet<Module> hypothetical = new HashSet<Module>(orig_installed); // Clone because we alter hypothetical. hypothetical.RemoveWhere(mod => modules_to_remove.Contains(mod.identifier)); log.DebugFormat("Started with {0}, removing {1}, and keeping {2}; our dlls are {3}", string.Join(", ", orig_installed), string.Join(", ", modules_to_remove), string.Join(", ", hypothetical), string.Join(", ", dlls)); // Find what would break with this configuration. // The Values.SelectMany() flattens our list of broken mods. var broken = new HashSet<string>(SanityChecker.FindUnmetDependencies(hypothetical, dlls) .Values.SelectMany(x => x).Select(x => x.identifier)); // If nothing else would break, it's just the list of modules we're removing. HashSet<string> to_remove = new HashSet<string>(modules_to_remove); if (to_remove.IsSupersetOf(broken)) { log.DebugFormat("{0} is a superset of {1}, work done", string.Join(", ", to_remove), string.Join(", ", broken)); return to_remove; } // Otherwise, remove our broken modules as well, and recurse. broken.UnionWith(to_remove); modules_to_remove = broken; } }
public void IsSupersetOfFailureTest() { var set = new HashSet<int>(); var arr = Enumerable.Range(0, 10).ToArray(); for (int i = 0; i < 5; i++) { set.Add(i); } Assert.IsFalse(set.IsSupersetOf(arr)); }
/// <summary> /// True if the entity has all of these properties. This is assuming the proper vocabs are used. /// </summary> public bool? HasProperties(IEnumerable<string> desiredProperties) { var jsonProps = new HashSet<string>(_entityJson.Properties().Select(p => p.Name)); return jsonProps.IsSupersetOf(desiredProperties); }
/// <summary> /// 尝试从路由值创建虚拟路径 /// </summary> /// <param name="requestContext">当前请求上下文</param> /// <param name="values">路由值</param> /// <returns>虚拟路径信息</returns> public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) { var cache = requestContext.HttpContext.Cache; var _values = values.ToDictionary(pair => pair.Key, pair => pair.Value == null ? null : pair.Value.ToString(), StringComparer.OrdinalIgnoreCase); var cacheKey = CreateCacheKey(_values); var virtualPath = cache.Get(cacheKey) as string; if (virtualPath != null) { return(new VirtualPathData(this, virtualPath)); } var keySet = new HashSet <string>(_values.Keys, StringComparer.OrdinalIgnoreCase); var candidateRules = _rules .Where(r => !r.Oneway) //不是单向路由规则 .Where(r => keySet.IsSupersetOf(r.RouteKeys)) //所有路由键都必须匹配 .Where(r => keySet.IsSubsetOf(r.AllKeys) || !r.LimitedQueries) //所有路由键和查询字符串键必须能涵盖要设置的键。 .Where(r => r.IsMatch(_values)) //必须满足路由规则所定义的路由数据。 .ToArray(); if (!candidateRules.Any()) { return(null); } var bestRule = BestRule(candidateRules); virtualPath = bestRule.CreateVirtualPath(_values); if (IsIgnoredPath(virtualPath))//如果产生的虚拟路径是被忽略的,则返回 null { if (DebugMode) { Trace(string.Format("名为 \"{0}\" 路由表的 \"{1}\" 路由规则产生的虚拟路径 {2} 被该路由表忽略", Name, bestRule.Name, virtualPath), TraceLevel.Warning); } else { return(null); } } if (MvcCompatible) { virtualPath = virtualPath.Substring(2); } cache.Insert(cacheKey, virtualPath, CacheItemPriority.AboveNormal); return(CreateVirtualPathData(virtualPath, bestRule)); }
/// <summary> /// Determines whether the hash set is a superset of the specified collection. /// </summary> /// <param name="other"> The collection to compare to the current hash set. </param> /// <returns> /// <see langword="true" /> if the hash set is a superset of other; otherwise, <see langword="false" />. /// </returns> public virtual bool IsSupersetOf(IEnumerable <T> other) => _set.IsSupersetOf(other);
/// <summary> /// 获取路由值 /// </summary> /// <param name="virtualPath">当前请求的虚拟路径</param> /// <param name="queryString">当前请求的查询数据</param> /// <returns></returns> public virtual IDictionary <string, string> GetRouteValues(string virtualPath, NameValueCollection queryString) { if (virtualPath == null) { throw new ArgumentNullException("virtualPath"); } if (!VirtualPathUtility.IsAppRelative(virtualPath)) { throw new ArgumentException("virtualPath 只能使用应用程序根相对路径,即以 \"~/\" 开头的路径,调用 VirtualPathUtility.ToAppRelative 方法或使用 HttpRequest.AppRelativeCurrentExecutionFilePath 属性获取", "virtualPath"); } var queryKeySet = new HashSet <string>(_queryKeys, StringComparer.OrdinalIgnoreCase); var requestQueryKeySet = new HashSet <string>(queryString.AllKeys, StringComparer.OrdinalIgnoreCase); if (LimitedQueries && !queryKeySet.IsSupersetOf(requestQueryKeySet))//如果限制了查询键并且查询键集合没有完全涵盖所有传进来的QueryString键的话,即存在有一个QueryString键不在查询键集合中,则这条规则不适用。 { return(null); } virtualPath = multipleSlashRegex.Replace(virtualPath, "/");//将连续的/替换成单独的/ virtualPath = virtualPath.Substring(2); var pathParagraphs = virtualPath.Split('/'); if (virtualPath == "") { pathParagraphs = new string[0]; } if (pathParagraphs.Length != Paragraphes.Length) { return(null); } var values = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); foreach (var pair in _staticValues) { values.Add(pair.Key, pair.Value); } for (int i = 0; i < pathParagraphs.Length; i++) { var paragraph = Paragraphes[i]; if (!paragraph.StartsWith("{")) { if (!pathParagraphs[i].EqualsIgnoreCase(paragraph)) { return(null); } } else { var name = paragraph.Substring(1, paragraph.Length - 2); values.Add(name, pathParagraphs[i]); } } if (!LimitedQueries) //如果没有限制查询键,但传进来的查询键与现有路由键有任何冲突,则这条规则不适用。 { //因为如果限制了查询键,则上面会确保路由键不超出限制的范围,也就不可能存在冲突。 requestQueryKeySet.IntersectWith(_routeKeys); if (requestQueryKeySet.Any()) { return(null); } } foreach (var key in queryString.AllKeys) { if (key == null) { continue;//因某些未知原因会导致 AllKeys 包含空键值。 } var v = queryString[key]; if (v != null) { values.Add(key, v); } } return(values); }
/// <summary> /// Finds and returns all modules that could not exist without the listed modules installed, including themselves. /// Acts recursively and lazily. /// </summary> /// <param name="modulesToRemove">Modules that are about to be removed.</param> /// <param name="modulesToInstall">Optional list of modules that are about to be installed.</param> /// <param name="origInstalled">Modules that are already installed</param> /// <param name="dlls">Installed DLLs</param> /// <param name="dlc">Installed DLCs</param> /// <returns>List of modules whose dependencies are about to be or already removed.</returns> internal static IEnumerable <string> FindReverseDependencies( IEnumerable <string> modulesToRemove, IEnumerable <CkanModule> modulesToInstall, IEnumerable <CkanModule> origInstalled, IEnumerable <string> dlls, IDictionary <string, UnmanagedModuleVersion> dlc ) { modulesToRemove = modulesToRemove.Memoize(); origInstalled = origInstalled.Memoize(); var dllSet = dlls.ToHashSet(); // The empty list has no reverse dependencies // (Don't remove broken modules if we're only installing) if (modulesToRemove.Any()) { // All modules in the input are included in the output foreach (string starter in modulesToRemove) { yield return(starter); } while (true) { // Make our hypothetical install, and remove the listed modules from it. HashSet <CkanModule> hypothetical = new HashSet <CkanModule>(origInstalled); // Clone because we alter hypothetical. if (modulesToInstall != null) { // Pretend the mods we are going to install are already installed, so that dependencies that will be // satisfied by a mod that is going to be installed count as satisfied. hypothetical = hypothetical.Concat(modulesToInstall).ToHashSet(); } hypothetical.RemoveWhere(mod => modulesToRemove.Contains(mod.identifier)); log.DebugFormat("Started with {0}, removing {1}, and keeping {2}; our dlls are {3}", string.Join(", ", origInstalled), string.Join(", ", modulesToRemove), string.Join(", ", hypothetical), string.Join(", ", dllSet)); // Find what would break with this configuration. var broken = SanityChecker.FindUnsatisfiedDepends(hypothetical, dllSet, dlc) .Select(x => x.Key.identifier).ToHashSet(); if (modulesToInstall != null) { // Make sure to only report modules as broken if they are actually currently installed. // This is mainly to remove the modulesToInstall again which we added // earlier to the hypothetical list. broken.IntersectWith(origInstalled.Select(m => m.identifier)); } // Lazily return each newly found rev dep foreach (string newFound in broken.Except(modulesToRemove)) { yield return(newFound); } // If nothing else would break, it's just the list of modules we're removing. HashSet <string> to_remove = new HashSet <string>(modulesToRemove); if (to_remove.IsSupersetOf(broken)) { log.DebugFormat("{0} is a superset of {1}, work done", string.Join(", ", to_remove), string.Join(", ", broken)); break; } // Otherwise, remove our broken modules as well, and recurse. broken.UnionWith(to_remove); modulesToRemove = broken; } } }
public void TestEnvironmentOfChildProcess() { const string ItemSeparator = "CAFF9451396B4EEF8A5155A15BDC2080"; // random string that shouldn't be in any env vars; used instead of newline to separate env var strings const string ExtraEnvVar = "TestEnvironmentOfChildProcess_SpecialStuff"; Environment.SetEnvironmentVariable(ExtraEnvVar, "\x1234" + Environment.NewLine + "\x5678"); // ensure some Unicode characters and newlines are in the output try { // Schedule a process to see what env vars it gets. Have it write out those variables // to its output stream so we can read them. Process p = CreateProcess(() => { Console.Write(string.Join(ItemSeparator, Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().Select(e => e.Key + "=" + e.Value))); return SuccessExitCode; }); p.StartInfo.StandardOutputEncoding = Encoding.UTF8; p.StartInfo.RedirectStandardOutput = true; p.Start(); string output = p.StandardOutput.ReadToEnd(); Assert.True(p.WaitForExit(WaitInMS)); // Parse the env vars from the child process var actualEnv = new HashSet<string>(output.Split(new[] { ItemSeparator }, StringSplitOptions.None)); // Validate against StartInfo.Environment. var startInfoEnv = new HashSet<string>(p.StartInfo.Environment.Select(e => e.Key + "=" + e.Value)); Assert.True(startInfoEnv.SetEquals(actualEnv), string.Format("Expected: {0}{1}Actual: {2}", string.Join(", ", startInfoEnv.Except(actualEnv)), Environment.NewLine, string.Join(", ", actualEnv.Except(startInfoEnv)))); // Validate against current process. (Profilers / code coverage tools can add own environment variables // but we start child process without them. Thus the set of variables from the child process could // be a subset of variables from current process.) var envEnv = new HashSet<string>(Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().Select(e => e.Key + "=" + e.Value)); Assert.True(envEnv.IsSupersetOf(actualEnv), string.Format("Expected: {0}{1}Actual: {2}", string.Join(", ", envEnv.Except(actualEnv)), Environment.NewLine, string.Join(", ", actualEnv.Except(envEnv)))); } finally { Environment.SetEnvironmentVariable(ExtraEnvVar, null); } }
//-------------------------------------------------------------------------------------------------------------------------------- public bool IsSupersetOf(EnumHashSet <T> other) { return(Raw.IsSupersetOf(other.Raw)); }
internal void HandleMessage(Message msg) { if (msg == null) return; //List<Connection> recipients = new List<Connection> (); HashSet<Connection> recipients = new HashSet<Connection>(); //HashSet<Connection> recipientsAll = new HashSet<Connection> (Connections); object fieldValue = msg.Header[FieldCode.Destination]; if (fieldValue != null) { string destination = (string)fieldValue; Connection destConn; if (Names.TryGetValue(destination, out destConn)) recipients.Add(destConn); else if (destination != DBusBusName && !destination.StartsWith(":") && (msg.Header.Flags & HeaderFlag.NoAutoStart) != HeaderFlag.NoAutoStart) { // Attempt activation StartProcessNamed(destination); //Thread.Sleep (5000); // TODO: Route the message to the newly activated service! activationMessages[destination] = msg; //if (Names.TryGetValue (destination, out destConn)) // recipients.Add (destConn); //else // Console.Error.WriteLine ("Couldn't route message to activated service"); } else if (destination != DBusBusName) { // Send an error when there's no hope of getting the requested reply if (msg.ReplyExpected) { // Error org.freedesktop.DBus.Error.ServiceUnknown: The name {0} was not provided by any .service files Message rmsg = MessageHelper.CreateUnknownMethodError(new MethodCall(msg)); if (rmsg != null) { //Caller.Send (rmsg); Caller.SendReal(rmsg); return; } } } } HashSet<Connection> recipientsMatchingHeader = new HashSet<Connection>(); HashSet<ArgMatchTest> a = new HashSet<ArgMatchTest>(); foreach (KeyValuePair<MatchRule, List<Connection>> pair in Rules) { if (recipients.IsSupersetOf(pair.Value)) continue; if (pair.Key.MatchesHeader(msg)) { a.UnionWith(pair.Key.Args); recipientsMatchingHeader.UnionWith(pair.Value); } } MatchRule.Test(a, msg); foreach (KeyValuePair<MatchRule, List<Connection>> pair in Rules) { if (recipients.IsSupersetOf(pair.Value)) continue; if (!recipientsMatchingHeader.IsSupersetOf(pair.Value)) continue; if (a.IsSupersetOf(pair.Key.Args)) recipients.UnionWith(pair.Value); } foreach (Connection conn in recipients) { // TODO: rewrite/don't header fields //conn.Send (msg); // TODO: Zero the Serial or not? //msg.Header.Serial = 0; ((ServerConnection)conn).SendReal(msg); } }
public static bool IsSupersetOf <T>(HashSet <T> hashSet, IEnumerable <T> other) { (hashSet as Mock <T>)?.CheckDataRace(false); return(hashSet.IsSupersetOf(other)); }
/// <summary> /// 尝试从路由值创建虚拟路径 /// </summary> /// <param name="requestContext">当前请求上下文</param> /// <param name="values">路由值</param> /// <returns>虚拟路径信息</returns> public override VirtualPathData GetVirtualPath( RequestContext requestContext, RouteValueDictionary values ) { var cache = requestContext.HttpContext.Cache; var _values = values.ToDictionary( pair => pair.Key, pair => pair.Value == null ? null : pair.Value.ToString(), StringComparer.OrdinalIgnoreCase ); var cacheKey = CreateCacheKey( _values ); var virtualPath = cache.Get( cacheKey ) as string; if ( virtualPath != null ) return new VirtualPathData( this, virtualPath ); var keySet = new HashSet<string>( _values.Keys, StringComparer.OrdinalIgnoreCase ); var candidateRules = _rules .Where( r => !r.Oneway ) //不是单向路由规则 .Where( r => keySet.IsSupersetOf( r.RouteKeys ) ) //所有路由键都必须匹配 .Where( r => keySet.IsSubsetOf( r.AllKeys ) || !r.LimitedQueries ) //所有路由键和查询字符串键必须能涵盖要设置的键。 .Where( r => r.IsMatch( _values ) ) //必须满足路由规则所定义的路由数据。 .ToArray(); if ( !candidateRules.Any() ) return null; var bestRule = BestRule( candidateRules ); virtualPath = bestRule.CreateVirtualPath( _values ); if ( MvcCompatible ) virtualPath = virtualPath.Substring( 2 ); cache.Insert( cacheKey, virtualPath, CacheItemPriority.AboveNormal ); var data = new VirtualPathData( this, virtualPath ); foreach ( var pair in bestRule.DataTokens ) data.DataTokens.Add( pair.Key, pair.Value ); data.DataTokens["RoutingRuleName"] = bestRule.Name; return data; }
public void SubsetsAndSupersets() { var set0 = new HashSet<int>(); var set1 = new HashSet<int>(new[] { 0, 1, 2, 3 }); var set2 = new HashSet<int>(new[] { 0, 1, 2, 3 }); var set3 = new HashSet<int>(new[] { 0, 1, 2, 3, 4 }); var set4 = new HashSet<int>(new[] { 0, 1, 2, 3, 5 }); Assert.That(() => { set1.IsProperSubsetOf(null); }, Throws.TypeOf(typeof(ArgumentNullException))); Assert.That(() => { set1.IsProperSupersetOf(null); }, Throws.TypeOf(typeof(ArgumentNullException))); Assert.That(() => { set1.IsSubsetOf(null); }, Throws.TypeOf(typeof(ArgumentNullException))); Assert.That(() => { set1.IsSupersetOf(null); }, Throws.TypeOf(typeof(ArgumentNullException))); Assert.IsTrue(set1.IsSubsetOf(set1)); Assert.IsTrue(set1.IsSubsetOf(set2)); Assert.IsTrue(set1.IsSubsetOf(set3)); Assert.IsFalse(set3.IsSubsetOf(set4)); Assert.IsFalse(set1.IsProperSubsetOf(set1)); Assert.IsFalse(set1.IsProperSubsetOf(set2)); Assert.IsTrue(set1.IsProperSubsetOf(set3)); Assert.IsFalse(set3.IsProperSubsetOf(set4)); Assert.IsFalse(set3.IsSubsetOf(set2)); Assert.IsFalse(set3.IsProperSubsetOf(set2)); Assert.IsTrue(set3.IsSupersetOf(set3)); Assert.IsTrue(set3.IsSupersetOf(set2)); Assert.IsFalse(set3.IsSupersetOf(set4)); Assert.IsFalse(set3.IsProperSupersetOf(set3)); Assert.IsTrue(set3.IsProperSupersetOf(set2)); Assert.IsFalse(set3.IsProperSupersetOf(set4)); // Empty set. Assert.IsTrue(set0.IsSubsetOf(set0)); Assert.IsTrue(set0.IsSubsetOf(set1)); Assert.IsFalse(set0.IsProperSubsetOf(set0)); Assert.IsTrue(set0.IsProperSubsetOf(set1)); Assert.IsTrue(set0.IsSupersetOf(set0)); Assert.IsFalse(set0.IsProperSupersetOf(set0)); Assert.IsFalse(set0.IsSupersetOf(set1)); Assert.IsTrue(set0.IsProperSubsetOf(set1)); Assert.IsFalse(set1.IsSubsetOf(set0)); Assert.IsFalse(set1.IsProperSubsetOf(set0)); Assert.IsTrue(set1.IsSupersetOf(set0)); Assert.IsTrue(set1.IsProperSupersetOf(set0)); }