public void TestOverlaps ()
		{
			var aSet = new HashSet<int> { 1, 2 };  
			var bSet = new HashSet<int> { 1 };  

			Assert.IsTrue (aSet.Overlaps (bSet));
		}
    public virtual List<AbstracteEffect> getEffectListByKey(HashSet<EffectActionTypes> keys)
    {
        List<AbstracteEffect> returnedList = new List<AbstracteEffect> ();

        foreach (AbstracteEffect effect in effects.Values) {
            if (keys.Overlaps(effect.getEffectActionList())) {
                returnedList.Add(effect);
            }
        }
        return returnedList;
    }
Example #3
0
        static void Main(string[] args)
        {
            var myHash = new HashSet<String>();

            myHash.Add("hello");
            myHash.Add("hello");

            String[] s = new String[] { "hello" };

            Console.WriteLine(myHash.Count);
            Console.WriteLine(myHash.Overlaps(s));
        }
    public override List<AbstracteEffect> getEffectListByKey(HashSet<EffectActionTypes> keys)
    {
        List<AbstracteEffect> returnedList = base.getEffectListByKey (keys);

        for (int i = currentLifeIndex; i < healthPoints.Length; i++) {
            if ((healthPoints [i].effect != null) &&
                (keys.Overlaps(healthPoints [i].effect.getEffectActionList()))
            ) {
                returnedList.Add(healthPoints [i].effect);
            }
        }

        return returnedList;
    }
        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);
            }

        }
		int GetDisplayedBountyValue(Actor self, HashSet<string> deathTypes, string bountyType)
		{
			var bounty = GetBountyValue(self);
			if (cargo == null)
				return bounty;

			foreach (var a in cargo.Passengers)
			{
				var givesProximityBounty = a.TraitsImplementing<GivesProximityBounty>().Where(gpb => deathTypes.Overlaps(gpb.info.DeathTypes)
					&& (gpb.info.BountyTypes.Count == 0 || gpb.info.BountyTypes.Contains(bountyType)));
				foreach (var gpb in givesProximityBounty)
					bounty += gpb.GetDisplayedBountyValue(a, deathTypes, bountyType);
			}

			return bounty;
		}
		private static HashSet<string> GetRequiredStrippableModules(HashSet<string> nativeClasses)
		{
			HashSet<string> hashSet = new HashSet<string>();
			string[] moduleNames = ModuleMetadata.GetModuleNames();
			for (int i = 0; i < moduleNames.Length; i++)
			{
				string text = moduleNames[i];
				if (ModuleMetadata.GetModuleStrippable(text))
				{
					HashSet<string> classNames = CodeStrippingUtils.GetClassNames(ModuleMetadata.GetModuleClasses(text));
					if (nativeClasses.Overlaps(classNames))
					{
						hashSet.Add(text);
					}
				}
			}
			return hashSet;
		}
        /// <summary>
        /// Append the result of this dependency graph to the end of the given sorting solution
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <returns></returns>
        public TopologicalSort CalculateSort(TopologicalSort instance)
        {
            HashSet<OrderedProcess> unused = new HashSet<OrderedProcess>(_processes);

            do
            {
                HashSet<OrderedProcess> set = new HashSet<OrderedProcess>(
                    unused.Where(p => !unused.Overlaps(p.Predecessors)) //select processes which have no predecessors in the unused set, which means that all their predecessors must either be used, or not exist, either way is fine
                );

                if (set.Count == 0)
                    throw new InvalidOperationException("Cannot order this set of processes");

                unused.ExceptWith(set);

                foreach (var subset in SolveResourceDependencies(set))
                    instance.Append(subset);
            }
            while (unused.Count > 0);

            return instance;
        }
 private static HashSet<string> GetRequiredStrippableModules(HashSet<string> nativeClasses)
 {
   HashSet<string> stringSet = new HashSet<string>();
   foreach (string moduleName in ModuleMetadata.GetModuleNames())
   {
     if (ModuleMetadata.GetModuleStrippable(moduleName))
     {
       HashSet<string> classNames = CodeStrippingUtils.GetClassNames((IEnumerable<int>) ModuleMetadata.GetModuleClasses(moduleName));
       if (nativeClasses.Overlaps((IEnumerable<string>) classNames))
         stringSet.Add(moduleName);
     }
   }
   return stringSet;
 }
Example #10
0
 public static bool LocationsAreUniqueOnRoute(INetworkCoverage source, Route route)
 {
     //find all locations and checks for doubles.
     var locationsSet = new HashSet<INetworkLocation>();
     foreach (var segment in route.Segments.Values)
     {
         IEnumerable<INetworkLocation> locations = GetLocationsForSegment(segment, source, false);
         
         if (locationsSet.Overlaps(locations))
             return false;
         foreach (var location in locations)
         {
             locationsSet.Add(location);
         }
     }
     return true;
 }
        /// <summary>
        /// Verifies that no circular exception will be created and then sends CHANGE request to server.
        /// </summary>
        /// <param name="name">The cell to be changed</param>
        /// <param name="content">The candidate contents of the cell</param>
        public void Change(string name, string content)
        {
            // If we're waiting for a change to be confirmed by the server, don't take a new change.
            if (_currentChangeCell != null)
            {
                return;
            }
            var normalizedName = Normalize(name);

            // Check if content is null.
            if (content == null)
            {
                throw new ArgumentNullException();
            }
            // Check if name is null or invalid.
            if (normalizedName == null || !_validCellNameRegex.IsMatch(normalizedName) || !IsValid(normalizedName))
            {
                throw new InvalidNameException();
            }
            if (content.StartsWith("="))
            {
                Formula formula = new Formula(content.Substring(1), IsValid, Normalize);

                // The HashSet dependents contains name and all of name's direct and indirect dependents.
                var dependents = new HashSet<string>(GetCellsToRecalculate(normalizedName));

                // Variables contains name's new dependees.
                var variables = formula.GetVariables();

                // Checking if any of name's new dependees are already its dependents
                // or if name is its own new dependee.
                if (dependents.Overlaps(variables))
                {
                    throw new CircularException();
                }
            }
            _currentChangeCell = normalizedName;
            _currentChangeContent = content;
            _socket.BeginSend("CHANGE\n" + _name + "\n" + _version + "\nCell:" + normalizedName + "\nLength:" + content.Length.ToString() + "\n" + content + "\n", (e, o) => { }, null);
        }
Example #12
0
 private static void ExcludeModuleManagers(ref HashSet<string> nativeClasses)
 {
     string[] moduleNames = ModuleMetadata.GetModuleNames();
     int derivedFromClassID = BaseObjectTools.StringToClassID("GlobalGameManager");
     foreach (string str in moduleNames)
     {
         if (ModuleMetadata.GetModuleStrippable(str))
         {
             int[] moduleClasses = ModuleMetadata.GetModuleClasses(str);
             HashSet<int> set = new HashSet<int>();
             HashSet<string> other = new HashSet<string>();
             foreach (int num3 in moduleClasses)
             {
                 if (BaseObjectTools.IsDerivedFromClassID(num3, derivedFromClassID))
                 {
                     set.Add(num3);
                 }
                 else
                 {
                     other.Add(BaseObjectTools.ClassIDToString(num3));
                 }
             }
             if ((other.Count != 0) && !nativeClasses.Overlaps(other))
             {
                 foreach (int num5 in set)
                 {
                     nativeClasses.Remove(BaseObjectTools.ClassIDToString(num5));
                 }
             }
         }
     }
 }
Example #13
0
        // Adds an output adapter to the dependency chain.
        private void AddOutputAdapter(IOutputAdapter adapter, ISet<IAdapter> dependencyChain, IInputAdapter[] inputAdapterCollection, IActionAdapter[] actionAdapterCollection, IOutputAdapter[] outputAdapterCollection)
        {
            HashSet<MeasurementKey> inputMeasurementKeys = new HashSet<MeasurementKey>(adapter.InputMeasurementKeys());

            // Adds the adapter to the chain
            dependencyChain.Add(adapter);

            if ((object)inputAdapterCollection != null)
            {
                // Checks all input adapters to determine whether they also need to be
                // added to the chain as a result of this adapter being added to the chain
                foreach (IInputAdapter inputAdapter in inputAdapterCollection)
                {
                    if (!dependencyChain.Contains(inputAdapter) && inputMeasurementKeys.Overlaps(inputAdapter.OutputMeasurementKeys()))
                        AddInputAdapter(inputAdapter, dependencyChain, inputAdapterCollection, actionAdapterCollection, outputAdapterCollection);
                }
            }

            if ((object)actionAdapterCollection != null)
            {
                // Checks all action adapters to determine whether they also need to be
                // added to the chain as a result of this adapter being added to the chain
                foreach (IActionAdapter actionAdapter in actionAdapterCollection)
                {
                    if (actionAdapter.RespectOutputDemands && !dependencyChain.Contains(actionAdapter) && inputMeasurementKeys.Overlaps(actionAdapter.OutputMeasurementKeys()))
                        AddActionAdapter(actionAdapter, dependencyChain, inputAdapterCollection, actionAdapterCollection, outputAdapterCollection);
                }
            }
        }
        /// <summary>
        /// temporarily flips joints to remove cycles
        /// </summary>
        private void RemoveGraphCycles()
        {
            HashSet<GraphNode> tempGraph = new HashSet<GraphNode>(RobotNodes.Values.ToArray());
            while (tempGraph.Count > 0)
            {
                bool hasFinished = false;
                while (!hasFinished)//remove all sources from tempGraph. A source is a node with no parents
                {
                    hasFinished = true;
                    GraphNode tempNode;

                    for (int i = 0; i < tempGraph.Count;i++ )
                    {
                        tempNode = tempGraph.ElementAt(i);
                        if(!tempGraph.Overlaps(tempNode.ParentNodes))
                        {
                            tempGraph.Remove(tempNode);
                            hasFinished = false;
                            i--;
                        }
                    }
                }
                hasFinished = false;
                while (!hasFinished)//remove all sinks from the graph. A sink is a node with no children
                {
                    hasFinished = true;
                    GraphNode tempNode;
                    for (int i = 0; i < tempGraph.Count; i++)
                    {
                        tempNode = tempGraph.ElementAt(i);
                        if(!tempGraph.Overlaps(tempNode.ChildNodes))
                        {
                            tempGraph.Remove(tempNode);
                            hasFinished = false;
                            i--;
                        }
                    }
                }

                if (tempGraph.Count > 0) //If nodes are left, they must be in a cycle, so flip joints to fix
                {
                    foreach (GraphNode tempNode in tempGraph)
                    {
                        if (tempNode.Equals(RobotNodes[0]) || tempNode.ParentNodes.Count > 1)
                        {
                            List<GraphNode> tempList = tempNode.ParentNodes.ToList();
                            foreach (GraphNode g in tempList)
                            {
                                if (tempGraph.Contains(g))
                                {
                                    tempNode.FlipJoint(g);
                                }

                            }
                            break;
                        }

                    }
                }

            }
        }
Example #15
0
        //GL
        public HashSet<MDPStateStat> CollectPminZeroStates()
        {
            bool done = false;
            HashSet<MDPStateStat> target = new HashSet<MDPStateStat>(TargetStates);
            HashSet<MDPStateStat> reached = new HashSet<MDPStateStat>();
            reached.UnionWith(target);
            HashSet<MDPStateStat> copyTarget = new HashSet<MDPStateStat>(); //updated

            while (done == false)
            {

                HashSet<MDPStateStat> postreached = MDPStateStat.cloneHashSet(reached);
                List<MDPStateStat> preTarget = new List<MDPStateStat>();
                HashSet<MDPStateStat> intsPre = null;

                foreach (MDPStateStat state in reached)  //updated
                {
                    if (copyTarget.Contains(state)) { continue; }  //updated
                    preTarget = state.Pre;
                    if (intsPre == null)
                    {
                        intsPre = new HashSet<MDPStateStat>(preTarget);
                    }
                    else
                    {
                        //intsPre.IntersectWith(preTarget);
                        intsPre.UnionWith(preTarget);
                    }
                }

                // intsPre2 = this.ListStateFromHashset(intsPre);
                if (intsPre == null) { done = true; break; }  //updated
                HashSet<MDPStateStat> enLargeTarget = MDPStateStat.cloneHashSet(intsPre);

                foreach (MDPStateStat st in intsPre)
                {
                    foreach (DistributionStat ds in st.Distributions)
                    {
                        // HashSet<MDPStateStat> nextStates = new HashSet<KeyValuePair> (ds.States);
                        HashSet<MDPStateStat> endStates = new HashSet<MDPStateStat>();
                        endStates = ds.getEndStates();
                        if (!reached.Overlaps(endStates))  //updated
                        {
                            enLargeTarget.Remove(st);
                            goto firstforloop;
                        }
                    }
                firstforloop: ;
                }
                copyTarget = MDPStateStat.cloneHashSet(reached);  //updated
                postreached.UnionWith(enLargeTarget);
                if (reached.SetEquals(postreached)) done = true;
                reached = postreached;
            }
            return reached;
        }
        /// <summary>
        /// NOTE: Relies on the results from CombineMCPComicsData
        /// </summary>
        /// <param name="pathDataDir"></param>
        private static void AssembleMCPCharacterCharacters(string pathDataDir)
        {
            Console.WriteLine("Starting character-characters data assembling . . .");

            int countProcessedCharacter = 0;
            int totalNumCharacters = FileManager.GetNumLinesInCSV(FileManager.GetPathResultCharComics(pathDataDir));

            using (StreamWriter writer = new StreamWriter(FileManager.GetPathResultCharChars(pathDataDir), false))
            {
                string pathCharComics = FileManager.GetPathResultCharComics(pathDataDir);
                FileStream outerFileStream = new FileStream(pathCharComics, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read);
                using (StreamReader outerReader = new StreamReader(outerFileStream))
                {
                    while (!outerReader.EndOfStream)
                    {
                        string outerInput = outerReader.ReadLine();

                        if (!outerReader.Equals(String.Empty))
                        {
                            Console.WriteLine(String.Format("Processing character #{0} of {1}", countProcessedCharacter, totalNumCharacters));
                            ++countProcessedCharacter;

                            string[] testCharData = outerInput.Split(',');
                            string testCharId = testCharData[0];
                            HashSet<string> testCharComics = new HashSet<string>();
                            for (int i = 1; i < testCharData.Length; ++i)
                            {
                                testCharComics.Add(testCharData[i]);
                            }

                            writer.Write(testCharId);

                            // Check overlapping with all characters
                            FileStream innerFileStream = new FileStream(pathCharComics, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read);
                            using (StreamReader innerReader = new StreamReader(innerFileStream))
                            {
                                while (!innerReader.EndOfStream)
                                {
                                    string innerInput = innerReader.ReadLine();

                                    if (!innerInput.Equals(String.Empty))
                                    {
                                        string[] nextCharData = innerInput.Split(',');
                                        string nextCharId = nextCharData[0];

                                        if (!nextCharId.Equals(testCharId))
                                        {
                                            HashSet<string> nextCharComics = new HashSet<string>();
                                            for (int i = 1; i < nextCharData.Length; ++i)
                                            {
                                                nextCharComics.Add(nextCharData[i]);
                                            }

                                            if (testCharComics.Overlaps(nextCharComics))
                                            {
                                                writer.Write(String.Format(",{0}", nextCharId));
                                            }
                                        }
                                    }
                                }
                            }

                            writer.WriteLine();
                        }
                    }
                }
            }

            Console.WriteLine("Finished character-characters data assembling.");
        }
Example #17
0
 public void OverlapsFailureTest()
 {
     var set = new HashSet<int>();
     var arr = Enumerable.Range(0, 10);
     set.UnionWith(Enumerable.Range(11, 20));
     Assert.IsFalse(set.Overlaps(arr));
 }
        static OverloadGroupEquivalenceInfo GetOverloadGroupEquivalence(Dictionary<string, List<RuntimeArgument>> groupDefinitions)
        {
            OverloadGroupEquivalenceInfo overloadGroupsInfo = new OverloadGroupEquivalenceInfo();

            if (!groupDefinitions.IsNullOrEmpty())
            {
                string[] groupNames = new string[groupDefinitions.Count];
                groupDefinitions.Keys.CopyTo(groupNames, 0);

                for (int i = 0; i < groupNames.Length; i++)
                {
                    string group1 = groupNames[i];
                    HashSet<RuntimeArgument> group1Args = new HashSet<RuntimeArgument>(groupDefinitions[group1]);
                    for (int j = i + 1; j < groupNames.Length; j++)
                    {
                        string group2 = groupNames[j];
                        HashSet<RuntimeArgument> group2Args = new HashSet<RuntimeArgument>(groupDefinitions[group2]);

                        if (group1Args.IsProperSupersetOf(group2Args))
                        {
                            overloadGroupsInfo.SetAsSuperset(group1, group2);
                        }
                        else if (group1Args.IsProperSubsetOf(group2Args))
                        {
                            overloadGroupsInfo.SetAsSuperset(group2, group1);
                        }
                        else if (group1Args.SetEquals(group2Args))
                        {
                            overloadGroupsInfo.SetAsEquivalent(group1, group2);
                        }
                        else if (group1Args.Overlaps(group2Args))
                        {
                            overloadGroupsInfo.SetAsOverlapping(group1, group2);
                        }
                        else // the groups are disjoint.
                        {
                            overloadGroupsInfo.SetAsDisjoint(group1, group2);
                        }
                    }
                }
            }

            return overloadGroupsInfo;
        }
Example #19
0
    /// <summary>
    /// Checks the second transition in a 2-transition jump and sees if we can
    /// perform the collapse (there's no overlap, etc.)
    /// </summary>
    /// <param name="beginning">The first expanded node (beginning, middle, 
    /// end)</param>
    /// <param name="jump1">The first edge (beginning-middle)</param>
    /// <param name="jump1Events">The events in the first edge</param>
    /// <param name="involvedInFirst">The objects involved in jump1</param>
    /// <param name="edgesToAdd">(out) A list in which we write the edges to
    /// add to the graph</param>
    private static void AnalyzeEndpoints(
        ExplorationNode beginning,
        ExplorationEdge jump1,
        IEnumerable<TransitionEvent> jump1Events,
        HashSet<uint> involvedInFirst,
        IList<ExplorationEdge> edgesToAdd)
    {
        // Get all of the final endpoint jumps (middle-end)
        foreach (ExplorationEdge jump2 in jump1.Target.Outgoing)
        {
            ExplorationNode end = jump2.Target;
            List<TransitionEvent> jump2Events =
                new List<TransitionEvent>(jump2.Events);

            // All the objects in jump2 
            HashSet<uint> involvedSecond = new HashSet<uint>();
            GetInvolved(jump2Events).ForEach(
                (uint id) =>
                {
                    DebugUtil.Assert(involvedSecond.Contains(id) == false);
                    involvedSecond.Add(id);
                });

            // There's no overlap
            if (involvedInFirst.Overlaps(involvedSecond) == false)
            {
                List<TransitionEvent> combined = new List<TransitionEvent>();
                combined.AddRange(
                    jump1Events.Convert(s => new TransitionEvent(s)));
                combined.AddRange(
                    jump2Events.Convert(s => new TransitionEvent(s)));
                edgesToAdd.Add(
                    new ExplorationEdge(beginning, end, combined.ToArray()));
            }
        }
    }
Example #20
0
 private bool EvaluateTags(HashSet<string> allcats)
 {
     return !allcats.Overlaps(HideTags);
 }
		private static void ExcludeModuleManagers(ref HashSet<string> nativeClasses)
		{
			string[] moduleNames = ModuleMetadata.GetModuleNames();
			int derivedFromClassID = BaseObjectTools.StringToClassID("GlobalGameManager");
			string[] array = moduleNames;
			for (int i = 0; i < array.Length; i++)
			{
				string moduleName = array[i];
				if (ModuleMetadata.GetModuleStrippable(moduleName))
				{
					int[] moduleClasses = ModuleMetadata.GetModuleClasses(moduleName);
					HashSet<int> hashSet = new HashSet<int>();
					HashSet<string> hashSet2 = new HashSet<string>();
					int[] array2 = moduleClasses;
					for (int j = 0; j < array2.Length; j++)
					{
						int num = array2[j];
						if (BaseObjectTools.IsDerivedFromClassID(num, derivedFromClassID))
						{
							hashSet.Add(num);
						}
						else
						{
							hashSet2.Add(BaseObjectTools.ClassIDToString(num));
						}
					}
					if (hashSet2.Count != 0)
					{
						if (!nativeClasses.Overlaps(hashSet2))
						{
							foreach (int current in hashSet)
							{
								nativeClasses.Remove(BaseObjectTools.ClassIDToString(current));
							}
						}
					}
				}
			}
		}
Example #22
0
 private static HashSet<string> GetRequiredStrippableModules(HashSet<string> nativeClasses)
 {
     HashSet<string> set = new HashSet<string>();
     foreach (string str in ModuleMetadata.GetModuleNames())
     {
         if (ModuleMetadata.GetModuleStrippable(str))
         {
             HashSet<string> classNames = GetClassNames(ModuleMetadata.GetModuleClasses(str));
             if (nativeClasses.Overlaps(classNames))
             {
                 set.Add(str);
             }
         }
     }
     return set;
 }
 private static void ExcludeModuleManagers(ref HashSet<string> nativeClasses)
 {
   string[] moduleNames = ModuleMetadata.GetModuleNames();
   int classId = BaseObjectTools.StringToClassID("GlobalGameManager");
   foreach (string moduleName in moduleNames)
   {
     if (ModuleMetadata.GetModuleStrippable(moduleName))
     {
       int[] moduleClasses = ModuleMetadata.GetModuleClasses(moduleName);
       HashSet<int> intSet = new HashSet<int>();
       HashSet<string> stringSet = new HashSet<string>();
       foreach (int num in moduleClasses)
       {
         if (BaseObjectTools.IsDerivedFromClassID(num, classId))
           intSet.Add(num);
         else
           stringSet.Add(BaseObjectTools.ClassIDToString(num));
       }
       if (stringSet.Count != 0 && !nativeClasses.Overlaps((IEnumerable<string>) stringSet))
       {
         using (HashSet<int>.Enumerator enumerator = intSet.GetEnumerator())
         {
           while (enumerator.MoveNext())
           {
             int current = enumerator.Current;
             nativeClasses.Remove(BaseObjectTools.ClassIDToString(current));
           }
         }
       }
     }
   }
 }
Example #24
0
 public void OverlapsTest()
 {
     var set=new HashSet<int>();
     var arr = Enumerable.Range(0, 10);
     set.UnionWith(Enumerable.Range(8, 10));
     Assert.IsTrue(set.Overlaps(arr));
 }
    public void OnEnable()
    {
        editorSettings = JointEditorSettings.Singleton;

        if (editorSettings == null) {
            return;
        }

        var defaultNames = new HashSet<string> {"slider", "lock", "offset"};
        var childControlNames = GetControlNames();

        if (defaultNames.Overlaps(childControlNames)) {
            Debug.LogError("Reserved control names: " +
                           String.Join(",", defaultNames.Intersect(childControlNames)
                                                        .ToArray()) + ".");
        }
        controlNames = new HashSet<string>(defaultNames.Union(childControlNames));

        if (EditorHelpers.AllowMultiObjectAccess) {
            var allSettings =
                targets.Cast<Joint2D>()
                       .Select(joint2D => SettingsHelper.GetOrCreate(joint2D))
                       .Where(jointSettings => jointSettings != null)
                       .Cast<Object>()
                       .ToList();

            if (allSettings.Count > 0) {
                serializedSettings = new SerializedObject(allSettings.ToArray());
            } else {
                serializedSettings = null;
            }
        } else {
            if (target) {
                serializedSettings = new SerializedObject(new Object[] {SettingsHelper.GetOrCreate(target as Joint2D)});
            } else {
                serializedSettings = null;
            }
        }
    }
Example #26
0
 public void Test_Overlaps()
 {
     hs = new HashSet<int> { 1, 6, 7, 8};
     HashSet<int> hs1 = new HashSet<int> { 1, 2, 3, 4, 5, 6, 7, 8};
     Assert.That(hs.Overlaps(hs1), Is.True);
 }
 private static OverloadGroupEquivalenceInfo GetOverloadGroupEquivalence(Dictionary<string, List<RuntimeArgument>> groupDefinitions)
 {
     OverloadGroupEquivalenceInfo info = new OverloadGroupEquivalenceInfo();
     if (!groupDefinitions.IsNullOrEmpty())
     {
         string[] array = new string[groupDefinitions.Count];
         groupDefinitions.Keys.CopyTo(array, 0);
         for (int i = 0; i < array.Length; i++)
         {
             string str = array[i];
             HashSet<RuntimeArgument> set = new HashSet<RuntimeArgument>(groupDefinitions[str]);
             for (int j = i + 1; j < array.Length; j++)
             {
                 string str2 = array[j];
                 HashSet<RuntimeArgument> other = new HashSet<RuntimeArgument>(groupDefinitions[str2]);
                 if (set.IsProperSupersetOf(other))
                 {
                     info.SetAsSuperset(str, str2);
                 }
                 else if (set.IsProperSubsetOf(other))
                 {
                     info.SetAsSuperset(str2, str);
                 }
                 else if (set.SetEquals(other))
                 {
                     info.SetAsEquivalent(str, str2);
                 }
                 else if (set.Overlaps(other))
                 {
                     info.SetAsOverlapping(str, str2);
                 }
                 else
                 {
                     info.SetAsDisjoint(str, str2);
                 }
             }
         }
     }
     return info;
 }
Example #28
0
        public override void PostUpdateBySync(HashSet<SyncableProperties.Type> updatedProperties)
        {
            SceneObjectPart sop = (SceneObjectPart)SceneThing;
            UUID uuid = sop.UUID;

            // All updated properties are in the set of TerseUpdateProperites
            bool allTerseUpdates = updatedProperties.IsSubsetOf(SyncableProperties.TerseUpdateProperties);

            // Any updated properties are in the set of GroupProperties
            bool hasGroupUpdates = updatedProperties.Overlaps(SyncableProperties.GroupProperties);

            if (!hasGroupUpdates || sop.ParentGroup == null)
            {
                if (allTerseUpdates)
                    sop.ScheduleTerseUpdate();
                else
                    sop.ScheduleFullUpdate();
            }
            else
            {
                if (allTerseUpdates)
                    sop.ParentGroup.ScheduleGroupForTerseUpdate();
                else
                    sop.ParentGroup.ScheduleGroupForFullUpdate();
            }

            /*
            string props = "";
            foreach (SyncableProperties.Type t in updatedProperties)
                props += t.ToString() + ",";
            DebugLog.WarnFormat("{0}: PostUpdateBySync: uuid={1}, allterse={2}, groupupates={3}, props={4}", LogHeader, uuid, allTerseUpdates, hasGroupUpdates, props);
            */
        }
Example #29
0
        public void Overlaps()
        {
            var set = new HashSet<int>();

              Assert.That(() => { set.Overlaps(null); }, Throws.TypeOf(typeof(ArgumentNullException)));
              Assert.IsFalse(set.Overlaps(new[] { 3, 9, 11 }));

              set.AddRange(Enumerable.Range(0, 10));
              Assert.IsTrue(set.Overlaps(set));
              Assert.IsTrue(set.Overlaps(new[] { 3, 9, 11 }));
              Assert.IsTrue(set.Overlaps(new HashSet<int>(new[] { 3, 9, 11 })));
              Assert.IsFalse(set.Overlaps(new[] { 11 }));
              Assert.IsFalse(set.Overlaps(new HashSet<int>(new[] { 11 })));
        }
        /// <summary>
        /// Loads hidden field state. We use this instead of LoadViewState because the latter doesn't get called during post backs on which the page structure
        /// changes.
        /// </summary>
        protected override sealed object LoadPageStateFromPersistenceMedium()
        {
            string formValueHash = null;
            string lastPostBackFailingDmId = null;
            try {
                // Based on our implementation of SavePageStateToPersistenceMedium, the base implementation of LoadPageStateFromPersistenceMedium will return a Pair
                // with no First object.
                var pair = base.LoadPageStateFromPersistenceMedium() as Pair;

                var savedState = PageState.CreateFromViewState( (object[])pair.Second );
                AppRequestState.Instance.EwfPageRequestState = new EwfPageRequestState(
                    savedState.Item1,
                    Request.Form[ "__SCROLLPOSITIONX" ],
                    Request.Form[ "__SCROLLPOSITIONY" ] );
                formValueHash = (string)savedState.Item2[ 0 ];
                lastPostBackFailingDmId = (string)savedState.Item2[ 1 ];
            }
            catch {
                // Set a 400 status code if there are any problems loading hidden field state. We're assuming these problems are never the developers' fault.
                if( AppRequestState.Instance.EwfPageRequestState == null )
                    AppRequestState.Instance.EwfPageRequestState = new EwfPageRequestState( PageState.CreateForNewPage(), null, null );
                Response.StatusCode = 400;
                Response.TrySkipIisCustomErrors = true;
                AppRequestState.Instance.EwfPageRequestState.TopModificationErrors =
                    Translation.ApplicationHasBeenUpdatedAndWeCouldNotInterpretAction.ToSingleElementArray();
                resetPage();
            }

            onLoadData();

            var requestState = AppRequestState.Instance.EwfPageRequestState;
            ResourceInfo redirectInfo = null;
            FullResponse fullSecondaryResponse = null;
            executeWithDataModificationExceptionHandling(
                () => {
                    validateFormSubmission( formValueHash );

                    // Get the post-back object and, if necessary, the last post-back's failing data modification.
                    var postBackId = Request.Form[ postBackHiddenFieldName ]; // returns null if field missing
                    var postBack = postBackId != null ? GetPostBack( postBackId ) : null;
                    if( postBack == null )
                        throw new DataModificationException( Translation.AnotherUserHasModifiedPageAndWeCouldNotInterpretAction );
                    var lastPostBackFailingDm = postBack.IsIntermediate && lastPostBackFailingDmId != null
                                                    ? lastPostBackFailingDmId.Any() ? GetPostBack( lastPostBackFailingDmId ) as DataModification : dataUpdate
                                                    : null;
                    if( postBack.IsIntermediate && lastPostBackFailingDmId != null && lastPostBackFailingDm == null )
                        throw new DataModificationException( Translation.AnotherUserHasModifiedPageAndWeCouldNotInterpretAction );

                    // Execute the page's data update.
                    var dmExecuted = false;
                    if( !postBack.IsIntermediate ) {
                        try {
                            dmExecuted |= dataUpdate.Execute(
                                !postBack.ForcePageDataUpdate,
                                formValues.Any( i => i.ValueChangedOnPostBack( requestState.PostBackValues ) ),
                                handleValidationErrors );
                        }
                        catch {
                            AppRequestState.Instance.EwfPageRequestState.DmIdAndSecondaryOp = Tuple.Create( "", SecondaryPostBackOperation.NoOperation );
                            throw;
                        }
                    }

                    // Execute the post-back.
                    var actionPostBack = postBack as ActionPostBack;
                    if( actionPostBack != null ) {
                        var formValuesChanged =
                            GetDescendants( contentContainer )
                                .OfType<FormControl>()
                                .Any( i => i.FormValue != null && i.FormValue.ValueChangedOnPostBack( requestState.PostBackValues ) );
                        try {
                            dmExecuted |= actionPostBack.Execute(
                                formValuesChanged,
                                handleValidationErrors,
                                postBackAction => {
                                    if( postBackAction == null )
                                        return;
                                    redirectInfo = postBackAction.Resource;
                                    if( postBackAction.SecondaryResponse != null )
                                        fullSecondaryResponse = postBackAction.SecondaryResponse.GetFullResponse();
                                } );
                        }
                        catch {
                            AppRequestState.Instance.EwfPageRequestState.DmIdAndSecondaryOp = Tuple.Create( actionPostBack.Id, SecondaryPostBackOperation.NoOperation );
                            throw;
                        }
                    }

                    if( dmExecuted ) {
                        AppRequestState.AddNonTransactionalModificationMethod( () => StandardLibrarySessionState.Instance.StatusMessages.AddRange( statusMessages ) );
                        try {
                            AppRequestState.Instance.CommitDatabaseTransactionsAndExecuteNonTransactionalModificationMethods();
                        }
                        finally {
                            DataAccessState.Current.ResetCache();
                        }
                    }

                    if( postBack.IsIntermediate ) {
                        var regionSets = new HashSet<UpdateRegionSet>( actionPostBack.UpdateRegions );
                        var preModRegions =
                            updateRegionLinkers.SelectMany(
                                i => i.PreModificationRegions,
                                ( linker, region ) => new { region.Sets, region.ControlGetter, linker.Key, region.ArgumentGetter } )
                                .Where( i => regionSets.Overlaps( i.Sets ) )
                                .ToArray();
                        var staticRegionContents = getStaticRegionContents( preModRegions.SelectMany( i => i.ControlGetter() ) );

                        requestState.PostBackValues.RemoveExcept( staticRegionContents.Item2.Select( i => i.GetPostBackValueKey() ) );
                        requestState.DmIdAndSecondaryOp = Tuple.Create(
                            actionPostBack.ValidationDm == dataUpdate ? "" : ( (ActionPostBack)actionPostBack.ValidationDm ).Id,
                            actionPostBack.ValidationDm == lastPostBackFailingDm ? SecondaryPostBackOperation.Validate : SecondaryPostBackOperation.ValidateChangesOnly );
                        requestState.SetStaticAndUpdateRegionState( staticRegionContents.Item1, preModRegions.Select( i => Tuple.Create( i.Key, i.ArgumentGetter() ) ).ToArray() );
                    }
                    else
                        requestState.PostBackValues = null;
                } );

            navigate( redirectInfo, requestState.ModificationErrorsExist ? null : fullSecondaryResponse );
            return null;
        }