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);
		}
Example #5
0
        /// <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);
            }

        }
Example #7
0
        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);
            }
        }
		/// <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);
		}
Example #9
0
        /// <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)));
                }
            }
        }
Example #10
0
        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));
        }
Example #11
0
        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));
        }
Example #12
0
    /// <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;
    }
Example #13
0
 public void IsSupersetOfEqualsSetsTest()
 {
     var set = new HashSet<int>();
     var arr = Enumerable.Range(0, 10).ToArray();
     set.UnionWith(arr);
     Assert.IsTrue(set.IsSupersetOf(arr));
 }
Example #14
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;
            }
        }
Example #15
0
        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;
        }
Example #16
0
		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
		}
 private bool CheckDependenciesExist(DependencyNode node)
 {
     HashSet<string> effectiveExistingObjectNames = new HashSet<string>(existingObjectNames, existingObjectNames.Comparer);
     effectiveExistingObjectNames.ExceptWith(dependencies.Keys);
     return effectiveExistingObjectNames.IsSupersetOf(node.Edges);
 }
        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));
        }
Example #19
0
    /// <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 );
    }
Example #20
0
 /// <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);
 }
        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);
            }
        }
        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);
        }
Example #23
0
        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);
            }
        }
Example #24
0
 public void IsSupersetOfEmptyCollectionTest()
 {
     var set = new HashSet<int>(Enumerable.Range(0,10));
     Assert.IsTrue(set.IsSupersetOf(Enumerable.Range(0,0)));
 }
Example #25
0
        /// <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;
        }
Example #26
0
        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));
        }