public string Generate(Board _board, GameUnit _unit, GameUnit _finishUnit)
        {
            var stringBuilder = new StringBuilder();
            var words = MagicWordsStore.Words
                                       .Concat(SpecialWords)
                                       .ToArray();
            var usedUnits = new HashSet<GameUnit>();
            while (!_unit.Equals(_finishUnit))
            {
                if (TimeLimiter.NeedStop())
                    break;

                foreach (var powerWord in words.OrderByDescending(x => x.Length))
                {
                    if (TimeLimiter.NeedStop())
                        break;

                    var newlyUsedUnits = new HashSet<GameUnit>();
                    var currentUnit = _unit;
                    var fail = false;
                    for (var i = 0; i < powerWord.Length; ++i)
                    {
                        var command = powerWord[i];
                        newlyUsedUnits.Add(currentUnit);
                        var nextUnit = currentUnit.MakeStep(CommandConverter.Convert(command));
                        var locked = !_board.IsValid(nextUnit);
                        if (newlyUsedUnits.Contains(nextUnit) ||
                            usedUnits.Contains(nextUnit) ||
                            (locked && i < powerWord.Length - 1) ||
                            (locked && !nextUnit.Equals(_finishUnit)))
                        {
                            fail = true;
                            break;
                        }
                        if (!locked)
                        {
                            currentUnit = nextUnit;
                        }
                    }
                    var allUsedUnits = new HashSet<GameUnit>(usedUnits.Union(newlyUsedUnits));
                    if (!fail && ReachableStatesGetter.CanReach(_board, currentUnit, false, allUsedUnits, _finishUnit))
                    {
                        _unit = currentUnit;
                        usedUnits = allUsedUnits;
                        stringBuilder.Append(powerWord);
                        break;
                    }
                }
            }
            foreach (var command in Enum.GetValues(typeof(Command)).Cast<Command>().Except(new[] { Command.Empty }))
            {
                if (!_board.IsValid(_unit.MakeStep(command)))
                {
                    stringBuilder.Append(CommandConverter.CovertToAnyChar(command));
                    break;
                }
            }
            return stringBuilder.ToString();
        }
Example #2
0
        public static double simularity(HashSet<string> setA, HashSet<string> setB)
        {
            double interCount = setA.Intersect(setB).Count();
            if (interCount == 0) return 0;

            double unionCount = setA.Union(setB).Count();
            return interCount / unionCount;
        }
        private IEnumerable<string> GetTransitiveClosure(string state)
        {
            var result = new HashSet<string> { state };
            while (result.Union(result.SelectMany(s => GetTransitions(s, null))).Distinct().Count() != result.Count)
            {
                result.SelectMany(s => GetTransitions(s, null)).ToArray().ForEach(s => result.Add(s));
            }

            return result;
        }
        public static Type ResolveControllerType(string areaName, string controllerName)
        {
            // controller type to find and return
            Type controllerType;

            // is the type cached?
            var cacheKey = areaName + "_" + controllerName;
            if (cache.TryGetValue(cacheKey, out controllerType))
                return cache[cacheKey];

            lock (syncLock)
            {
                if (cache.TryGetValue(cacheKey, out controllerType))
                    return controllerType;

                // find controller details
                IEnumerable<string> areaNamespaces = FindNamespacesForArea(areaName, RouteTable.Routes);

                var area = areaName;
                var controller = controllerName;
                var controllerBuilder = ControllerBuilder.Current;

                // Find controller type
                HashSet<string> namespaces = null;
                if (areaNamespaces != null)
                {
                    areaNamespaces = (from ns in areaNamespaces
                                      where ns != "Elmah.Mvc"
                                      select ns).ToList();
                    if (areaNamespaces.Any())
                    {
                        namespaces = new HashSet<string>(areaNamespaces, StringComparer.OrdinalIgnoreCase);
                        if (string.IsNullOrEmpty(areaName))
                        {
                            namespaces = new HashSet<string>(
                                namespaces.Union(controllerBuilder.DefaultNamespaces, StringComparer.OrdinalIgnoreCase),
                                StringComparer.OrdinalIgnoreCase
                            );
                        }
                    }
                }
                else if (controllerBuilder.DefaultNamespaces.Count > 0)
                {
                    namespaces = controllerBuilder.DefaultNamespaces;
                }
                controllerType = GetControllerTypeWithinNamespaces(area, controller, namespaces);

                // Cache the result
                cache.Add(cacheKey, controllerType);

                // Return
                return controllerType;
            }
        }
        public static void Main(string[] args)
        {
            HashSet<int> first = new HashSet<int>();
            first.Add(1);
            first.Add(2);
            first.Add(3);

            Console.Write("First set: ");
            foreach (var item in first)
            {
                Console.Write(item.Key + " ");
            }

            Console.WriteLine();

            HashSet<int> second = new HashSet<int>();
            second.Add(4);
            second.Add(1);
            second.Remove(1);

            Console.Write("Second set: ");
            foreach (var item in second)
            {
                Console.Write(item.Key + " ");
            }

            Console.WriteLine();

            first.Union(second);

            Console.Write("Sets union: ");
            foreach (var item in first)
            {
                Console.Write(item.Key + " ");
            }

            Console.WriteLine();

            //second.Add(1);

            first.Intersect(second);

            Console.Write("Sets intersection: ");
            foreach (var item in first)
            {
                Console.Write(item.Key + " ");
            }

            Console.WriteLine();
        }
        public static void Main()
        {
            var firstSet = new HashSet<int>();
            var secondSet = new HashSet<int>();
            firstSet.Add(1);
            firstSet.Add(2);
            firstSet.Add(7);
            secondSet.Add(7);
            secondSet.Add(13);
            secondSet.Add(19);
            firstSet.Remove(2);

            var unionSet = firstSet.Union(secondSet);
            Console.WriteLine("Union set = {0}", unionSet);

            var intersectSet = firstSet.Intersect(secondSet);
            Console.WriteLine("Intersect set = {0}", intersectSet);
        }
        static void Main(string[] args)
        {
            HashSet<string> hashSet = new HashSet<string>();

            hashSet.Add("ooo");
            hashSet.Add("qqq");
            hashSet.Add("ppp");
            hashSet.Add("iii");

            foreach (var item in hashSet.Items)
            {
                Console.WriteLine(item);
            }

            hashSet.Remove("iii");
            Console.WriteLine("\nCount after removal: {0}", hashSet.Count);


            Console.WriteLine();
            Console.WriteLine(hashSet.Find("ppp"));


            HashSet<string> secondHashSet = new HashSet<string>();
            secondHashSet.Add("www");
            secondHashSet.Add("qqq");
            secondHashSet.Add("yyy");
            secondHashSet.Add("ooo");

            Console.WriteLine("\nUnion: ");
            HashSet<string> union = hashSet.Union(secondHashSet);
            foreach (var item in union.Items)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("\nIntersection: ");
            HashSet<string> intersection = hashSet.Intersect(secondHashSet);
            foreach (var item in intersection.Items)
            {
                Console.WriteLine(item);
            }
        }
Example #8
0
 // Needs sorted data!
 private static HashSet<List<int>> findSubsetIndices(int sum, int[] data)
 {
     HashSet<List<int>> results = new HashSet<List<int>>();
     int tsum = sum;
     List<int> indicies = new List<int>();
     for (int i = data.Length - 1; i >= 0; --i)
     {
         if (data[i] <= tsum)
         {
             tsum -= data[i];
             indicies.Add(i);
         }
         if (tsum == 0)
         {
             results = new HashSet<List<int>>(results.Union(findSubsetIndices(sum, data, indicies)));
             i = indicies.ElementAt(0);
             indicies = new List<int>();
             tsum = sum;
         }
     }
     return results;
 }
Example #9
0
        static void Main(string[] args)
        {
            int NewNumber = 10000000;

            int[] FirstArray = new int[NewNumber];

            int[] SecondArray = new int[NewNumber];

            int[] ThirdArray = new int[NewNumber];

            FirstArray[0] = 1;

            SecondArray[0] = 2;

            ThirdArray[0] = 2;

            for (int i = 1; i < NewNumber; i++)
            {
                FirstArray[i] = 2 * FirstArray[i - 1] + 3;
                SecondArray[i] = 3 * SecondArray[i - 1] + 1;
                ThirdArray[i] = 2 * ThirdArray[i - 1] - 1;
            }

            HashSet<int> hash1 = new HashSet<int>(FirstArray);

            HashSet<int> hash2 = new HashSet<int>(SecondArray);

            HashSet<int> hash3 = new HashSet<int>(ThirdArray);

            HashSet<int> Union1 = new HashSet<int>(hash1.Union(hash2));

            HashSet<int> Union2 = new HashSet<int>(hash2.Intersect(hash3));

            foreach (var item in Union2)
            {
                Console.WriteLine(item);
            }
        }
Example #10
0
        static void Main(string[] args)
        {
            int number = 100000;

           
            int[] arr1 = new int[number];
            int[] arr2 = new int[number];
            int[] arr3 = new int[number];

            arr1[0] = 1;
            arr2[0] = 2;
            arr3[0] = 2;

            for (int i = 1; i < number; i++)
            {
                arr1[i] = 2 * arr1[i - 1] + 3;
                arr2[i] = 3 * arr2[i - 1] + 1;
                arr3[i] = 2 * arr3[i - 1] - 1;
            }

            HashSet<int> hash1 = new HashSet<int>(arr1);
            HashSet<int> hash2 = new HashSet<int>(arr2);
            HashSet<int> hash3 = new HashSet<int>(arr3);
            HashSet<int> Union1 = new HashSet<int>(hash1.Union(hash2)); 
            HashSet<int> Union2 = new HashSet<int>(hash2.Intersect(hash3));


        

            foreach (var item in Union2)
            {
                Console.WriteLine(item);
            }


        }
        /// <summary>
        /// Resolves the type of the controller.
        /// </summary>
        /// <param name="areaName">Name of the area.</param>
        /// <param name="controllerName">Name of the controller.</param>
        /// <returns>Controller type</returns>
        public Type ResolveControllerType(string areaName, string controllerName)
        {
            // Is the type cached?
            string cacheKey = areaName + "_" + controllerName;
            if (Cache.ContainsKey(cacheKey))
            {
                return Cache[cacheKey];
            }

            // Find controller details
            IEnumerable<string> areaNamespaces = FindNamespacesForArea(areaName, this.routes);

            string area = areaName;
            string controller = controllerName;

            // Find controller type
            Type controllerType;
            HashSet<string> namespaces = null;
            if (areaNamespaces != null)
            {
                areaNamespaces = (from ns in areaNamespaces
                                  where ns != "Elmah.Mvc"
                                  where !this.areaNamespacesToIgnore.Contains(ns)
                                  select ns).ToList();
                if (areaNamespaces.Any())
                {
                    namespaces = new HashSet<string>(areaNamespaces, StringComparer.OrdinalIgnoreCase);
                    if (string.IsNullOrEmpty(areaName))
                    {
                        namespaces = new HashSet<string>(namespaces.Union(this.controllerBuilder.DefaultNamespaces, StringComparer.OrdinalIgnoreCase), StringComparer.OrdinalIgnoreCase);
                    }
                }
            }
            else if (this.controllerBuilder.DefaultNamespaces.Count > 0)
            {
                namespaces = this.controllerBuilder.DefaultNamespaces;
            }
            controllerType = GetControllerTypeWithinNamespaces(area, controller, namespaces);

            // Cache the result
            Cache.Add(cacheKey, controllerType);

            // Return
            return controllerType;
        }
Example #12
0
        private static ISet<Namespace> EvaluateSet(ExpressionEvaluator ee, Node node)
        {
            var n = (SetExpression)node;
            ISet<Namespace> result;
            if (!ee.GlobalScope.NodeVariables.TryGetValue(node, out result)) {
                var values = new HashSet<Namespace>();
                foreach (var x in n.Items) {
                    values.Union(ee.Evaluate(x));
                }

                result = new DictionaryInfo(values, values, ee.ProjectState, ee.GlobalScope.ShowClr).SelfSet;
                ee.GlobalScope.NodeVariables[node] = result;
            }
            return result;
        }
        static void Main(string[] args)
        {
            var BigCities = new HashSet<string>
            {
                "New York",
                "Manchester",
                "Sheffield",
                "Paris"
            };

            string[] citiesInUK =
            {
                "Sheffield",
                "Ripon",
                "Truro",
                "Manchester"
            };

            //// Generic code to find intersecting values.
            //BigCities.IntersectWith(citiesInUK);

            //foreach (string city in BigCities)
            //{
            //    Console.WriteLine(city);
            //}

            // Linq method
            // The linq method does create a new array.
            var IntersectCities = BigCities.Intersect(citiesInUK);
            foreach (string city in IntersectCities)
            {
                Console.WriteLine(city);
            }

            Console.WriteLine();

            // Union takes elements that are in either set and puts every element out once.
            var UnionCities = BigCities.Union(citiesInUK);
            foreach (string city in UnionCities)
            {
                Console.WriteLine(city);
            }

            Console.WriteLine();

            // Every element that is in the first set, but not in the second set.
            var ExceptCities = BigCities.Except(citiesInUK);
            foreach (string city in ExceptCities)
            {
                Console.WriteLine(city);
            }

            Console.WriteLine();

            // Which elements appear in either one but not in both collections.
            BigCities.SymmetricExceptWith(citiesInUK);
            foreach (string city in BigCities)
            {
                Console.WriteLine(city);
            }
        }
        public void HashSetShouldUnionElementCorrectly()
        {
            var set1 = new HashSet<int>();
            var set2 = new HashSet<int>();
            set1.Add(1);
            set1.Add(2);

            set2.Add(2);
            set2.Add(3);
            set2.Add(4);

            var union = set1.Union(set2);

            Assert.IsTrue(union.Find(1));
            Assert.IsTrue(union.Find(2));
            Assert.IsTrue(union.Find(3));
            Assert.IsTrue(union.Find(4));
            Assert.AreEqual(4, union.Count);
        }
Example #15
0
 private bool traversalHasLoop(AST.Address current_addr, Dictionary<AST.Address, AST.Address> visited, AST.Address from_addr)
 {
     // base case 1: loop check
     if (visited.ContainsKey(current_addr))
     {
         return true;
     }
     // base case 2: an input cell
     if (!_formulas.ContainsKey(current_addr))
     {
         return false;
     }
     // recursive case (it's a formula)
     // check both single inputs and the inputs of any vector inputs
     bool OK = true;
     HashSet<AST.Address> single_inputs = _f2i[current_addr];
     HashSet<AST.Address> vector_inputs = new HashSet<AST.Address>(_f2v[current_addr].SelectMany(addrs => addrs.Addresses()));
     foreach (AST.Address input_addr in vector_inputs.Union(single_inputs))
     {
         if (OK)
         {
             // new dict to mark visit
             var visited2 = new Dictionary<AST.Address, AST.Address>(visited);
             // mark visit
             visited2.Add(current_addr, from_addr);
             // recurse
             OK = OK && !traversalHasLoop(input_addr, visited2, from_addr);
         }
     }
     return !OK;
 }
        public IEnumerable<Pair<PDLPred,double>> SynthesizeUnderapproximationPDL(HashSet<char> alphabet, Automaton<BDD> dfa, CharSetSolver solver, StringBuilder sb, long timeout)
        {
            #region TestSets for equiv
            var mytests = DFAUtilities.MyHillTestGeneration(alphabet, dfa, solver);
            var posMN = mytests.First;
            var negMN = mytests.Second;
            var tests = DFAUtilities.GetTestSets(dfa, alphabet, solver);
            var positive = tests.First;
            var negative = tests.Second;
            foreach (var t in posMN)
                positive.Remove(t);
            foreach (var t in negMN)
                negative.Remove(t);
            #endregion

            #region Accessory variables
            bool checkNeeded = false;
            string hash = "";
            HashSet<string> visited = new HashSet<string>();
            HashSet<string> newNodes = new HashSet<string>();
            List<Pair<PDLPred, double>> subsetPhis = new List<Pair<PDLPred, double>>();
            timer = new Stopwatch();
            timer.Start();
            #endregion

            InitializeSearchParameters(alphabet, dfa, solver);


            for (maxWidth = 3; true; maxWidth++)
            {
                int limit = (int)(Math.Sqrt(maxWidth));
                int limitH = (int)(Math.Sqrt(maxWidth + 5));
                maxStrLength = Math.Min(dfa.StateCount + 1, limit + 2);
                highestNum = Math.Min(limitH, dfa.StateCount - 1);
                substrTot = limit;
                connectivesTot = limit;
                setCountTot = limit;
                maxEmptyString = Math.Max(1, limit - 1);

                newNodes = new HashSet<string>();

                foreach (var phi in EnumeratePDLpred(new HashSet<string>(), new HashSet<string>()))
                {
                    #region run for at most timeout
                    if (timer.ElapsedMilliseconds > timeout)
                    {
                        subsetPhis.Sort(ComparePairsPhiDoubleByDouble);
                        timer.Stop();
                        return subsetPhis;
                    }
                    #endregion

                    #region Check decider to avoid repetition
                    hash = string.Format(
                        "{0},{1},{2},{3},{4},{5},{6}",
                        maxWidthC, maxStrLengthC, highestNumC, substrTotC, connectivesTotC, setCountTotC, maxEmptyStringC);
                    checkNeeded = !(visited.Contains(hash));
                    #endregion

                    if (checkNeeded)
                    {
                        newNodes.Add(hash);

                        #region add it to set of results if it is a subset
                        if (CorrectOnNegSet(phi, negMN) && CorrectOnNegSet(phi, negative))
                        {
                            var phiDfa = phi.GetDFA(alphabet, solver);
                            if (!phiDfa.IsEmpty)
                                if (phiDfa.Minus(dfa, solver).IsEmpty)
                                    subsetPhis.Add(
                                        new Pair<PDLPred, double>(
                                            phi,
                                            (double)phi.GetFormulaSize() / DFADensity.GetDFARatio(dfa, phiDfa, alphabet, solver, true)
                                        )
                                    );
                        }
                        #endregion
                    }
                }
                visited = new HashSet<string>(visited.Union(newNodes));
            }

        }
Example #17
0
		void CheckForOtherOccurrences()
		{
			var allAnalysesCandidatesOfWordform = new List<IAnalysis>
													{
														m_srcwfiWordform
													};
			foreach (var anal in m_srcwfiWordform.AnalysesOC)
			{
				allAnalysesCandidatesOfWordform.Add(anal);
				foreach (var gloss in anal.MeaningsOC)
					allAnalysesCandidatesOfWordform.Add(gloss);
			}
			var allUsedSegments = new HashSet<ISegment>();
			foreach (var segment in m_cache.ServiceLocator.GetInstance<ISegmentRepository>().AllInstances().Where(
				segment => segment.AnalysesRS.Any(allAnalysesCandidatesOfWordform.Contains)))
			{
				allUsedSegments.Add(segment);
			}
			// There are 'other' occurrences if some of the real ones aren't in the displayed list.
			if (m_repoSeg == null)
				m_repoSeg = m_cache.ServiceLocator.GetInstance<ISegmentRepository>();
			var enabledSegments = new HashSet<ISegment>();
			foreach (int hvoFake in m_enabledItems)
			{
				int hvoSeg = m_specialSda.get_ObjectProp(hvoFake, ConcDecorator.kflidSegment);
				if (hvoSeg > 0)
					enabledSegments.Add(m_repoSeg.GetObject(hvoSeg));
			}
			m_fOtherOccurrencesExist = allUsedSegments.Union(enabledSegments).Count() != allUsedSegments.Count();
		}
Example #18
0
 /// <summary>
 /// Creates a new instance. The parameters are copied.
 /// </summary>
 public NodeStates(IEnumerable<GraphNode> searchSpace, IEnumerable<GraphNode> fixedTargetNodes, IEnumerable<GraphNode> variableTargetNodes)
 {
     _searchSpace = new List<GraphNode>(searchSpace);
     _fixedTargetNodes = new HashSet<GraphNode>(fixedTargetNodes);
     _variableTargetNodes = new HashSet<GraphNode>(variableTargetNodes);
     _allTargetNodes = new HashSet<GraphNode>(_variableTargetNodes.Union(_fixedTargetNodes));
     ComputeFields();
 }
Example #19
0
 /// <summary>
 /// Logic that handles selecting two groups of event stubs, and then executing a given action when
 /// both groups are selected and the Finish button is pressed.
 /// </summary>
 private void InitDualGroupSelection(Action<HashSet<EventStub>, HashSet<EventStub>> onSelectionEnd)
 {
     HashSet<EventStub> firstSet = new HashSet<EventStub>();
     HashSet<EventStub> secondSet = new HashSet<EventStub>();
     //all onClick actions
     Action<EventStub> highlightGreen = (EventStub evnt) => SetEventColor(evnt, Color.green);
     Action<EventStub> highlightMagenta = (EventStub evnt) => SetEventColor(evnt, Color.magenta);
     Action<EventStub> addToFirst = (EventStub e) => firstSet.Add(e);
     Action<EventStub> addToSecond = (EventStub e) => secondSet.Add(e);
     onEventLeftClick.Add(addToFirst);
     onEventLeftClick.Add(highlightGreen);
     ActionBar bar = new ActionBar(true);
     bar.AddButton("Cancel", () =>
     {
         onEventLeftClick.Remove(addToFirst);
         onEventLeftClick.Remove(addToSecond);
         onEventLeftClick.Remove(highlightGreen);
         onEventLeftClick.Remove(highlightMagenta);
         ResetEventColors(firstSet.Union(secondSet));
         parent.PopActionBar();
     });
     bar.AddButton("Next", () => 
         {
             onEventLeftClick.Remove(addToFirst);
             onEventLeftClick.Remove(highlightGreen);
             onEventLeftClick.Add(highlightMagenta);
             onEventLeftClick.Add(addToSecond);
             bar.RemoveButton("Next");
             bar.AddButton("Finish", () =>
             {
                 onEventLeftClick.Remove(addToSecond);
                 parent.PopActionBar();
                 onEventLeftClick.Remove(highlightMagenta);
                 ResetEventColors(firstSet.Union(secondSet));
                 onSelectionEnd.Invoke(firstSet, secondSet);
             });
         });
     parent.AddActionBar(bar);
 }
    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;
            }
        }
    }
        private static void ReportIssues(SymbolAnalysisContext context, HashSet<ISymbol> usedSymbols,
            HashSet<ISymbol> declaredPrivateSymbols, HashSet<ISymbol> emptyConstructors,
            BidirectionalDictionary<ISymbol, SyntaxNode> fieldLikeSymbols)
        {
            var unusedSymbols = declaredPrivateSymbols
                .Except(usedSymbols.Union(emptyConstructors))
                .ToList();

            var alreadyReportedFieldLikeSymbols = new HashSet<ISymbol>();

            var unusedSymbolSyntaxPairs = unusedSymbols
                .SelectMany(unusedSymbol => unusedSymbol.DeclaringSyntaxReferences
                    .Select(r =>
                        new
                        {
                            Syntax = r.GetSyntax(),
                            Symbol = unusedSymbol
                        }));

            foreach (var unused in unusedSymbolSyntaxPairs)
            {
                var location = unused.Syntax.GetLocation();

                var canBeFieldLike = unused.Symbol is IFieldSymbol || unused.Symbol is IEventSymbol;
                if (canBeFieldLike)
                {
                    if (alreadyReportedFieldLikeSymbols.Contains(unused.Symbol))
                    {
                        continue;
                    }

                    var variableDeclaration = GetVariableDeclaration(unused.Syntax);
                    if (variableDeclaration == null)
                    {
                        continue;
                    }

                    var declarations = variableDeclaration.Variables
                        .Select(v => fieldLikeSymbols.GetByB(v))
                        .ToList();

                    if (declarations.All(d => unusedSymbols.Contains(d)))
                    {
                        location = unused.Syntax.Parent.Parent.GetLocation();
                        alreadyReportedFieldLikeSymbols.UnionWith(declarations);
                    }
                }

                context.ReportDiagnosticIfNonGenerated(Diagnostic.Create(Rule, location), context.Compilation);
            }
        }
Example #22
0
        static void Main(string[] args)
        {
            IHashSet<int> sampleOne = new HashSet<int>();
           
            sampleOne.Add(1);
            sampleOne.Add(1);
            sampleOne.Add(2);
            sampleOne.Add(3);
            sampleOne.Add(4);
            sampleOne.Add(5);
            sampleOne.Add(6);
            sampleOne.Add(7);
            sampleOne.Add(8);
            sampleOne.Add(9);

             IHashSet<int> sampleTwo = new HashSet<int>();

            sampleTwo.Add(1);
            sampleTwo.Add(2);
            sampleTwo.Add(9);
            sampleTwo.Add(100);


            Console.WriteLine("sampleOne:");
            foreach (var item in sampleOne)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("sampleTwo:");
            foreach (var item in sampleTwo)
            {
                Console.WriteLine(item);
            }


            IHashSet<int> intersected = sampleOne.Intersect(sampleTwo);

            Console.WriteLine("Intesected of sampleOne and sampleTwo:");
            foreach (var item in intersected)
            {
                Console.WriteLine(item);
            }

            IHashSet<int> union = sampleOne.Union(sampleTwo);

            Console.WriteLine("Union of sampleOne and sampleTwo:");
            foreach (var item in union)
            {
                Console.WriteLine(item);
            }

            int founded = sampleOne.Find(1);
            Console.WriteLine("Look for '1':" + founded);

            Console.WriteLine("Count:" + sampleOne.Count);
            sampleOne.Remove(3);
            sampleOne.Clear();
            Console.WriteLine("Count after clear:" + sampleOne.Count);

        }
Example #23
0
        static void Main(string[] args)
        {
            Console.WriteLine("molq vavedete K ot klaviaturata:");
            int k = int.Parse(Console.ReadLine());
            if (k < 16)
            {
                int[] moni1 = new int[k];
                moni1[0] = 1;
                for (int i = 1; i < k; i++)
                {
                    moni1[i] = 2 * moni1[i - 1] + 3;
                }
                HashSet<int> example = new HashSet<int>(moni1);
                int[] moni2 = new int[k];
                moni2[0] = 2;
                for (int i = 1; i < k; i++)
                {
                    moni2[i] = 3 * moni1[i - 1] + 1;
                }
                HashSet<int> example1 = new HashSet<int>(moni2);
                int[] moni3 = new int[k];
                moni2[0] = 2;
                for (int i = 1; i < k; i++)
                {
                    moni2[i] = 2 * moni1[i - 1] - 1;
                }
                HashSet<int> example2 = new HashSet<int>(moni2);

                int[] intersectResult = example.Intersect(example1).ToArray();
                int[] intersectResult1 = example.Intersect(example2).ToArray();
                int[] intersectResult2 = example1.Intersect(example2).ToArray();
                int[] intersectResult3 = example.Intersect(example1.Intersect(example2)).ToArray();
                int[] unionResult = example.Union(example1).ToArray();
                int[] unionResult1 = example.Union(example2).ToArray();
                int[] unionResult2 = example1.Union(example2).ToArray();
                int[] unionResult3 = example.Union(example1.Union(example2)).ToArray();

                foreach (var item in intersectResult)
                {
                    Console.Write(item + " ");
                }
                Console.WriteLine();
                foreach (var item in intersectResult1)
                {
                    Console.Write(item + " ");
                }
                Console.WriteLine();
                foreach (var item in intersectResult2)
                {
                    Console.Write(item + " ");
                }
                Console.WriteLine();
                foreach (var item in intersectResult3)
                {
                    Console.Write(item + " ");
                }
                Console.WriteLine();
                foreach (var item in unionResult)
                {
                    Console.Write(item + " ");
                }
                Console.WriteLine();
                foreach (var item in unionResult1)
                {
                    Console.Write(item + " ");
                }
                Console.WriteLine();
                foreach (var item in unionResult2)
                {
                    Console.Write(item + " ");
                }
                Console.WriteLine();
                foreach (var item in unionResult3)
                {
                    Console.Write(item + " ");
                }

                Console.WriteLine();
            }
            else
            {
                Console.WriteLine("molq vavedete chislo po-malko ot 16");
            }
        }
Example #24
0
    public HashSet<Node> GetPossibleMoves(int player, GamePosition gamePosition)
    {
        Node currentLocation = gamePosition.Players[player].getLocation();
        HashSet<Node> possibleLocations = new HashSet<Node>();
        HashSet<Node> occupiedLocations = getAllOtherPlayerLocations(gamePosition.Players[player]);
        HashSet<Node> checkLocations;

        if(playerHasEnoughTickets(gamePosition.Players[player], TransportType.blackCard)){
            checkLocations = currentLocation.getAllEdges();
            checkLocations.ExceptWith(occupiedLocations);
            possibleLocations = new HashSet<Node>(possibleLocations.Union(checkLocations));
        } else {
            foreach(TransportType type in Enum.GetValues(typeof(TransportType))){
                if(playerHasEnoughTickets(gamePosition.Players[player], type)){
                    checkLocations = currentLocation.getEdges(type);
                    checkLocations.ExceptWith(occupiedLocations);
                    possibleLocations = new HashSet<Node>(possibleLocations.Union(checkLocations));
                }
            }
        }
        return possibleLocations;
    }
 private static bool IndirectlyDependsOnItself(Node target,Node current,ref HashSet<Node> traveledPath)
 {
     foreach (var dependency in current.SiblingDependencies)
     {
         if(traveledPath.Contains(dependency))
             continue;
         if (dependency == target)
             return true;
         var newPath = traveledPath.Union(new[]{dependency}).ToHashSet();
         if (IndirectlyDependsOnItself(target, dependency, ref newPath))
         {
             traveledPath = newPath;
             return true;
         }
     }
     return false;
 }
Example #26
0
        private void SynchronizeFiles(string leftRoot, string rightRoot)
        {
            var leftFiles =
                new HashSet<string>(Directory.GetFiles(leftRoot).Select(p => RelativePath(Left, p)));
            var rightFiles =
                new HashSet<string>(Directory.GetFiles(rightRoot).Select(p => RelativePath(Right, p)));
            var files = new HashSet<string>(leftFiles.Union(rightFiles));

            foreach (var file in files)
            {
                var left = Path.Combine(Left, file);
                var right = Path.Combine(Right, file);
                var leftExists = File.Exists(left);
                var rightExists = File.Exists(right);
                if (leftExists && rightExists)
                {
                    var diff = (File.GetLastWriteTime(left) - File.GetLastWriteTime(right)).Ticks;
                    if (diff > 0)
                    {
                        CopyWithEncrypt(left, right);
                    }
                    else if (diff < 0)
                    {
                        CopyWithDecrypt(right, left);
                    }
                }
                else if (leftExists && !rightExists)
                {
                    if (PreviousRightFiles.Contains(right))
                    {
                        File.Delete(left);
                    }
                    else
                    {
                        CopyWithEncrypt(left, right);
                    }
                }
                else if (!leftExists && rightExists)
                {
                    if (PreviousLeftFiles.Contains(left))
                    {
                        File.Delete(right);
                    }
                    else
                    {
                        CopyWithDecrypt(right, left);
                    }
                }
                else
                {
                    throw new InvalidOperationException();
                }
            }
        }
        protected override void DoAction()
        {
            var phrases = GetEntitiesToProcess();
            foreach (var phrase in phrases) {
                var domains = SpywordsQueryWrapper.GetDomainsForPhrase(phrase.Text);
                phrase.Datecollected = DateTime.UtcNow;

                var statsContainer = _phraseStatsContainer.Match(domains).Value;
                var resultRows = _containerSplitToTr.Matches(statsContainer);
                if (resultRows.Count == 3) {
                    phrase.Status = PhraseStatus.Collected;
                    var yandexRowResult = _extractTdResult.Matches(resultRows[1].Value);
                    var googleRowResult = _extractTdResult.Matches(resultRows[2].Value);
                    phrase.Showsgoogle =
                        StringParser.ToInt(googleRowResult[1].Groups["td"].Value.Trim().Replace(" ", string.Empty),
                            default(int));
                    phrase.Showsyandex =
                        StringParser.ToInt(yandexRowResult[1].Groups["td"].Value.Trim().Replace(" ", string.Empty),
                            default(int));
                    phrase.Advertisersgoogle =
                        StringParser.ToShort(googleRowResult[2].Groups["td"].Value.Trim().Replace(" ", string.Empty),
                            default(short));
                    phrase.Advertisersyandex =
                        StringParser.ToShort(yandexRowResult[2].Groups["td"].Value.Trim().Replace(" ", string.Empty),
                            default(short));

                    var domainsForPhraseYandex = SpywordsQueryWrapper.GetDomainsForPhraseYandex(phrase.Text);

                    var yandexDomains = GetDomains(_yandexDomainBlockRegex.Match(domains).Value);
                    var advancedYandexDomains =
                        GetDomains(_allDomainsListYandexContainer.Match(domainsForPhraseYandex).Value);
                    yandexDomains = new HashSet<string>(yandexDomains.Union(advancedYandexDomains).Distinct());

                    var googleDomains = GetDomains(_googleDomainBlockRegex.Match(domains).Value);
                    try {
                        TaskRunner.Instance.AddAction(() => {
                            var domainEntities = new List<DomainEntity>(yandexDomains.Union(googleDomains).Distinct().Select(GetDomainEntity));
                            foreach(var domainEntity in domainEntities) {
                                var seType = (
                                    (yandexDomains.Contains(domainEntity.Domain)
                                        ? SearchEngine.Yandex
                                        : SearchEngine.Default) |
                                    (googleDomains.Contains(domainEntity.Domain)
                                        ? SearchEngine.Google
                                        : SearchEngine.Default));

                                CreateOrUpdateDomainPhrase(domainEntity, phrase, seType, SourceType.Context);
                            }
                        });
                    }
                    catch (Exception ex) {
                        phrase.Status = PhraseStatus.Error;
                        Logger.Error(string.Format("PhraseID={0}\r\n{1}", phrase.ID, ex));
                    }
                } else {
                    phrase.Status = PhraseStatus.Error;
                    Logger.Error("Нет трёх строк в таблице статистики запроса для {0} ID={1}", phrase.Text, phrase.ID);
                }

                phrase.Save();
            }
        }
Example #28
0
        private void SynchronizeChildren(string leftRoot, string rightRoot)
        {
            var leftDirectories =
                new HashSet<string>(Directory.GetDirectories(leftRoot).Select(p => RelativePath(Left, p)));
            var rightDirectories =
                new HashSet<string>(Directory.GetDirectories(rightRoot).Select(p => RelativePath(Right, p)));
            var directories = new HashSet<string>(leftDirectories.Union(rightDirectories));

            foreach (var directory in directories)
            {
                var left = Path.Combine(Left, directory);
                var right = Path.Combine(Right, directory);
                var leftExists = Directory.Exists(left);
                var rightExists = Directory.Exists(right);
                if (leftExists && rightExists)
                {
                    SynchronizeDirectory(left, right);
                }
                else if (leftExists && !rightExists)
                {
                    if (PreviousRightDirectories.Contains(right))
                    {
                        Directory.Delete(left, true);
                    }
                    else
                    {
                        Directory.CreateDirectory(right);
                        SynchronizeDirectory(left, right);
                    }
                }
                else if (!leftExists && rightExists)
                {
                    if (PreviousLeftDirectories.Contains(left))
                    {
                        Directory.Delete(right, true);
                    }
                    else
                    {
                        Directory.CreateDirectory(left);
                        SynchronizeDirectory(left, right);
                    }
                }
                else
                {
                    throw new InvalidOperationException();
                }
            }
        }
Example #29
0
        static void Main(string[] args)
        {
            List<int> arr1 = new List<int>();
            List<int> arr3 = new List<int>();
            List<int> arr2 = new List<int>();
            int i = 0;
            arr1.Add(1);
            arr2.Add(2);
            arr3.Add(2);
            do
            {
                i++;
                arr1.Add(2 * arr1[i - 1] + 3);
                arr2.Add(3 * arr2[i - 1] + 1);
                arr3.Add(2 * arr3[i - 1] - 1);
            } while (arr3[i] < 100000);
            arr1.RemoveAll(item => item > 100000);
            arr2.RemoveAll(item => item > 100000);
            arr3.RemoveAt(i);

            HashSet<int> hesh1 = new HashSet<int>(arr1);
            HashSet<int> hesh2 = new HashSet<int>(arr2);
            HashSet<int> hesh3 = new HashSet<int>(arr3);

            int[] intersect1 = hesh1.Intersect(hesh2).ToArray();
            Console.WriteLine("arr1*arr2");
            foreach (var item in intersect1)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            intersect1 = null;
            intersect1 = hesh1.Intersect(hesh3).ToArray();
            Console.WriteLine("arr1*arr3");
            foreach (var item in intersect1)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            intersect1 = null;
            intersect1 = hesh2.Intersect(hesh3).ToArray();
            Console.WriteLine("arr2*arr3");
            foreach (var item in intersect1)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            intersect1 = null;
            intersect1 = hesh1.Intersect(hesh2).Intersect(hesh3).ToArray();
            Console.WriteLine("arr1*arr2*arr3");
            foreach (var item in intersect1)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            int[] union1 = hesh1.Union(hesh2).ToArray();
            Array.Sort(union1);
            Console.WriteLine("arr1+arr2");
            foreach (var item in union1)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            Console.WriteLine();
            union1 = null;
            union1 = hesh1.Union(hesh3).ToArray();
            Array.Sort(union1);
            Console.WriteLine("arr1+arr3");
            foreach (var item in union1)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            Console.WriteLine();
            union1 = null;
            union1 = hesh2.Union(hesh3).ToArray();
            Array.Sort(union1);
            Console.WriteLine("arr2+arr3");
            foreach (var item in union1)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            Console.WriteLine();
            union1 = null;
            union1 = hesh1.Union(hesh2).Union(hesh3).ToArray();
            Array.Sort(union1);
            Console.WriteLine("arr1+arr2+arr3");
            foreach (var item in union1)
            {
                Console.Write(item + " ");
            }
        }
Example #30
0
 // this is mostly for diagnostic purposes
 public int numberOfInputCells()
 {
     var v_cells = new HashSet<AST.Address>(_all_vectors.KeysT.SelectMany(rng => rng.Addresses()));
     var sc_cells = new HashSet<AST.Address>(_i2f.Values.SelectMany(addr => addr));
     var all = v_cells.Union(sc_cells);
     return all.Count();
 }