示例#1
0
        static int makingAnagrams(string s1, string s2)
        {
            HashSet <char> hashset = new HashSet <char>();

            foreach (char c in s1)
            {
                hashset.Add(c);
            }
            foreach (char c in s2)
            {
                hashset.Add(c);
            }

            Dictionary <char, int> fs = hashset.Distinct().ToDictionary(x => x, x => 0);

            foreach (var c in s1.ToArray())
            {
                fs[c]++;
            }
            Dictionary <char, int> ss = hashset.Distinct().ToDictionary(x => x, x => 0);

            foreach (var c in s2.ToArray())
            {
                ss[c]++;
            }

            int res = 0;

            foreach (char c in hashset)
            {
                res += Math.Abs(fs[c] - ss[c]);
            }
            return(res);
        }
        // Inefficient way of calculating GCD of array of numbers
        public static void GcdOfArray(int length, int[] array)
        {
            Array.Sort(array);

            var hash = new HashSet <int>(array);

            var gcds  = new HashSet <int>();
            var count = gcds.Distinct().Count();

            while (count != 1)
            {
                var startNum = hash.ElementAt(0);
                for (int i = 1; i < hash.Count(); i++)
                {
                    var gcd = Utility.GetGcd(startNum, hash.ElementAt(i));
                    gcds.Add(gcd);
                }

                hash.Clear();

                for (int i = 0; i < gcds.Count(); i++)
                {
                    hash.Add(gcds.ElementAt(i));
                }
                count = gcds.Distinct().Count();
                gcds.Clear();
            }

            IEnumerable <int> list = hash.Distinct();

            Utility.PrintPlainElements(list);
            return;
        }
示例#3
0
        /// <summary>
        /// will use Shuffle if you want many of the items, as it will be more efficient
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <param name="count"></param>
        /// <param name="rand"></param>
        /// <returns></returns>
        public static List <T> SampleAtRandomWithoutReplacement <T>(this IList <T> list, int count, Random rand)
        {
            Helper.CheckCondition(count <= list.Count, "Can't sample without replacement more items that there are");
            if (count > list.Count / 4)
            {
                list.Shuffle(rand).Take(count).ToList();
            }

            //first sample the indexes, and make sure there are no duplicates:
            HashSet <int> sampledIndexes = new HashSet <int>();

            while (sampledIndexes.Count < count)
            {
                int nxtIndex = rand.Next(list.Count);

                if (!sampledIndexes.Contains(nxtIndex))
                {
                    sampledIndexes.Add(nxtIndex);
                }
            }
            Helper.CheckCondition(sampledIndexes.Distinct().Count() == count, "something went wrong--bug");

            List <T> results = list.SubList(sampledIndexes.ToList());

            return(results);
        }
示例#4
0
        internal static int GetNumProcessedPhotosByGuest(Event ev, string name, string created)
        {
            Func <GuestPhoto, Boolean> func;

            if (string.IsNullOrEmpty(created))
            {
                func = gp => (gp.Photo.Event.EventId == ev.EventId) && (gp.Photo.Status == (byte)PhotoStatus.Submitted || gp.Photo.Status == (byte)PhotoStatus.PendingPublish || gp.Photo.Status == (byte)PhotoStatus.Published);
            }
            else
            {
                created = DateTime.Parse(created).ToShortDateString();
                func    = gp => (gp.Photo.Event.EventId == ev.EventId) && gp.Photo.Created.ToShortDateString().Equals(created, StringComparison.InvariantCultureIgnoreCase) && (gp.Photo.Status == (byte)PhotoStatus.Submitted || gp.Photo.Status == (byte)PhotoStatus.PendingPublish || gp.Photo.Status == (byte)PhotoStatus.Published);
            }
            IEnumerable <Guest> guests = ev.Guests.Where(g => (g.FirstName + " " + g.LastName + " " + g.MiddleInitial).Contains(name, StringComparison.InvariantCultureIgnoreCase));
            HashSet <PhotoTDO>  photos = new HashSet <PhotoTDO>();

            foreach (Guest guest in guests)
            {
                IEnumerable <PhotoTDO> ps = guest.GuestPhotos.Where(func).Select(gp => new PhotoTDO {
                    PhotoId  = gp.Photo.PhotoId,
                    Filename = gp.Photo.Filename,
                    Created  = gp.Photo.Created
                });
                if (ps.Any())
                {
                    photos.UnionWith(ps);
                }
            }

            return(photos.Distinct(new PhotoComparer <PhotoTDO>()).Count());
        }
        /// <summary>
        /// selects all values that matches the wildcard expressions. Only one wild card can be given per expression
        /// </summary>
        /// <param name="variable"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public static PCAxis.Paxiom.Selection SelectAll(Variable variable, Query query)
        {
            PCAxis.Paxiom.Selection s = new PCAxis.Paxiom.Selection(query.Code);
            var values = new HashSet <string>();

            foreach (var value in query.Selection.Values)
            {
                if (value.StartsWith("*"))
                {
                    var variableValues = variable.Values.Where(v => v.Code.EndsWith(value.Substring(1))).Select(v => v.Code);
                    foreach (var variableValue in variableValues)
                    {
                        values.Add(variableValue);
                    }
                }
                else if (value.EndsWith("*"))
                {
                    var variableValues = variable.Values.Where(v => v.Code.StartsWith(value.Substring(0, value.Length - 1))).Select(v => v.Code);
                    foreach (var variableValue in variableValues)
                    {
                        values.Add(variableValue);
                    }
                }
                else
                {
                    throw new Exception("Invalid value supplied to ALL-filter");
                }
            }

            //Remove duplicates
            s.ValueCodes.AddRange(values.Distinct().ToArray());
            return(s);
        }
示例#6
0
        public override SourceCode GenerateModelCode()
        {
            var code = new SourceCode();

            if (ValueType == TypeEnum.DATA_ENUM)
            {
                code.BracketStart("enum {0}", EnumTypeName);
                foreach (var value in Values.Distinct())
                {
                    code.Append("{0},", value.Substring(1).ToEnumName()); // remove leading _ char
                }
                code.BracketEnd(";");
            }
            code.Append("{0} {1};", TypeString, CanonicalName);
            return(code);
        }
        public BenchmarkSettings(TestMode testMode, RunMode runMode, int numberOfIterations, int runTimeMilliseconds,
            IEnumerable<GcBenchmarkSetting> gcBenchmarks,
            IEnumerable<MemoryBenchmarkSetting> memoryBenchmarks,
            IEnumerable<CounterBenchmarkSetting> counterBenchmarks, string description, string skip)
        {
            TestMode = testMode;
            RunMode = runMode;
            NumberOfIterations = numberOfIterations;
            RunTime = TimeSpan.FromMilliseconds(runTimeMilliseconds == 0 ? DefaultRuntimeMilliseconds : runTimeMilliseconds);
            Description = description;
            Skip = skip;

            // Strip out any duplicates here
            // TODO: is it better to move that responsibility outside of the BenchmarkSettings class?

            GcBenchmarks = new HashSet<GcBenchmarkSetting>(gcBenchmarks).ToList();
            MemoryBenchmarks = new HashSet<MemoryBenchmarkSetting>(memoryBenchmarks).ToList();
            CounterBenchmarks = new HashSet<CounterBenchmarkSetting>(counterBenchmarks).ToList();

            DistinctGcBenchmarks =
                GcBenchmarks.Distinct(GcBenchmarkSetting.GcBenchmarkDistinctComparer.Instance).ToList();

            DistinctCounterBenchmarks =
                CounterBenchmarks.Distinct(CounterBenchmarkSetting.CounterBenchmarkDistinctComparer.Instance).ToList();

            DistinctMemoryBenchmarks =
                MemoryBenchmarks.Distinct(MemoryBenchmarkSetting.MemoryBenchmarkDistinctComparer.Instance).ToList();
        }
        /// <summary>
        /// Initializes app configuration.
        /// </summary>
        private async Task InitializeBootstrap()
        {
            /*
             * GR Bootstrap Initializers Common Order Recommendations:
             *
             * ... - -1    Setup No-dependency Initializer Preparers.
             * 0           Global Configuration
             * 1           Main Specific Configuration
             * 2 - 10      Setup Config dependent Initializer Preparers
             * 11 - 20     Important Configuration
             * 21 - 100    Normal Priority Configuration
             * 101 - ...   Low Priority Initializers.
             */

            //Order Bootstrap Initializers.
            var bootstrapInitializers = BootstrapInitializers
                                        .Distinct()
                                        .OrderBy(init => init.Order)
                                        .ThenBy(init => init.InitializerName)
                                        .ToList();

            foreach (var bootstrapInitializer in bootstrapInitializers)
            {
                OnInitializerStatusChanged?.Invoke($"Running: {bootstrapInitializer.InitializerName}");
                await bootstrapInitializer.DoInitialize();
            }

            OnInitializerStatusChanged?.Invoke("Bootstrap Done!");
        }
示例#9
0
        private static XElement CreatePropertiesElement(TestCase result)
        {
            var propertyElements = new HashSet <XElement>(result.Traits.Select(CreatePropertyElement));

#pragma warning disable CS0618 // Type or member is obsolete

            // Required since TestCase.Properties is a superset of TestCase.Traits
            // Unfortunately not all NUnit properties are available as traits
            var traitProperties = result.Properties.Where(t => t.Attributes.HasFlag(TestPropertyAttributes.Trait));

#pragma warning restore CS0618 // Type or member is obsolete

            foreach (var p in traitProperties)
            {
                var propValue = result.GetPropertyValue(p);

                if (p.Id == "NUnit.TestCategory")
                {
                    var elements = CreatePropertyElement("Category", (string[])propValue);

                    foreach (var element in elements)
                    {
                        propertyElements.Add(element);
                    }
                }
            }

            return(propertyElements.Any()
                ? new XElement("properties", propertyElements.Distinct())
                : null);
        }
    protected override object GetDataFromSource()
    {
        var gateways          = PaymentAccountDetails.AllGateways;
        var availableGateways = new HashSet <PaymentProcessor>();

        foreach (var gateway in gateways)
        {
            if (gateway.IsActive && (gateway.Cashflow == GatewayCashflowDirection.ToGate || gateway.Cashflow == GatewayCashflowDirection.Both))
            {
                availableGateways.Add(gateway.GetProcessorType());
            }
        }

        var cryptocurrencies = CryptocurrencyFactory.GetAllAvailable();

        foreach (var crypto in cryptocurrencies)
        {
            if (crypto.DepositApiProcessor != 0 && CryptocurrencyApiFactory.Get(crypto.DepositApiProcessor).AllowToUsePaymentButtons())
            {
                if (crypto.DepositApiProcessor == CryptocurrencyAPIProvider.CoinPayments)
                {
                    availableGateways.Add(PaymentProcessor.CoinPayments);
                }
                if (crypto.DepositApiProcessor == CryptocurrencyAPIProvider.Coinbase)
                {
                    availableGateways.Add(PaymentProcessor.Coinbase);
                }
            }
        }

        return(availableGateways.Distinct().ToList());
    }
示例#11
0
        static TypingGenInfo ToTypingGenInfo(IEnumerable <Type> types)
        {
            HashSet <Type> genTypeSet = new HashSet <Type>();

            HashSet <Type> refTypes = new HashSet <Type>();

            foreach (var type in types)
            {
                AddRefType(refTypes, type);
                var defType = type.IsGenericType ? type.GetGenericTypeDefinition() : type;
                if (!genTypeSet.Contains(defType))
                {
                    genTypeSet.Add(defType);
                }
                foreach (var field in type.GetFields(Flags))
                {
                    AddRefType(refTypes, field.FieldType);
                }

                foreach (var method in type.GetMethods(Flags))
                {
                    AddRefType(refTypes, method.ReturnType);
                    foreach (var pinfo in method.GetParameters())
                    {
                        AddRefType(refTypes, pinfo.ParameterType);
                    }
                }
                foreach (var constructor in type.GetConstructors())
                {
                    foreach (var pinfo in constructor.GetParameters())
                    {
                        AddRefType(refTypes, pinfo.ParameterType);
                    }
                }

                var baseType = type.BaseType;
                while (baseType != null)
                {
                    AddRefType(refTypes, baseType);
                    baseType = baseType.BaseType;
                }
            }

            return(new TypingGenInfo()
            {
                NamespaceInfos = refTypes.Distinct().Select(t => ToTsTypeGenInfo(t, genTypeSet)).GroupBy(t => t.Namespace)
                                 .Select(g => new TsNamespaceGenInfo()
                {
                    Name = g.Key,
                    Types = g.ToArray()
                }).ToArray(),
#if CSHARP_7_3_OR_NEWER
                TaskDef = refTypes.Contains(typeof(System.Threading.Tasks.Task <>)) ?
                          "type $Task<T> = System.Threading.Tasks.Task$1<T>"
                        : "interface $Task<T> {}",
#else
                TaskDef = "interface $Task<T> {}",
#endif
            });
        }
示例#12
0
        private static IEnumerable <PhotoTDO> GetPhotosByGuest(Event ev, string name, PhotoStatus status, int page, int pageSize, FotoShoutDbContext db)
        {
            IEnumerable <Guest> guests = ev.Guests.Where(g => (g.FirstName + " " + g.LastName + " " + g.MiddleInitial).Contains(name, StringComparison.InvariantCultureIgnoreCase));
            HashSet <PhotoTDO>  photos = new HashSet <PhotoTDO>();

            foreach (Guest guest in guests)
            {
                IEnumerable <PhotoTDO> ps = guest.GuestPhotos.Where(gp => gp.Photo.Event.EventId == ev.EventId && gp.Photo.Status == (byte)status).Select(gp => new PhotoTDO {
                    PhotoId     = gp.Photo.PhotoId,
                    Filename    = gp.Photo.Filename,
                    Folder      = gp.Photo.Folder,
                    Status      = gp.Photo.Status,
                    Submitted   = gp.Photo.Submitted,
                    SubmittedBy = gp.Photo.SubmittedBy,
                    Thumbnail   = AppConfigs.VirtualRoot + gp.Photo.Thumbnail,
                    Created     = gp.Photo.Created,
                    Image       = AppConfigs.VirtualRoot + ev.EventVirtualPath + "/" + Constants.STR_PROCESSED + "/" + gp.Photo.Filename,
                    Rating      = gp.Photo.Rating
                });
                photos.UnionWith(ps);
            }

            return((page > 0 && pageSize > 0 && (photos.Count() > pageSize)) ?
                   photos.Distinct(new PhotoComparer <PhotoTDO>()).Skip((page - 1) * pageSize).Take(pageSize) : photos.Distinct(new PhotoComparer <PhotoTDO>()));
        }
示例#13
0
        public BenchmarkSettings(TestMode testMode, RunMode runMode, int numberOfIterations, int runTimeMilliseconds,
                                 IEnumerable <GcBenchmarkSetting> gcBenchmarks,
                                 IEnumerable <MemoryBenchmarkSetting> memoryBenchmarks,
                                 IEnumerable <CounterBenchmarkSetting> counterBenchmarks, string description, string skip)
        {
            TestMode           = testMode;
            RunMode            = runMode;
            NumberOfIterations = numberOfIterations;
            RunTime            = TimeSpan.FromMilliseconds(runTimeMilliseconds == 0 ? DefaultRuntimeMilliseconds : runTimeMilliseconds);
            Description        = description;
            Skip = skip;

            // Strip out any duplicates here
            // TODO: is it better to move that responsibility outside of the BenchmarkSettings class?

            GcBenchmarks      = new HashSet <GcBenchmarkSetting>(gcBenchmarks).ToList();
            MemoryBenchmarks  = new HashSet <MemoryBenchmarkSetting>(memoryBenchmarks).ToList();
            CounterBenchmarks = new HashSet <CounterBenchmarkSetting>(counterBenchmarks).ToList();

            DistinctGcBenchmarks =
                GcBenchmarks.Distinct(GcBenchmarkSetting.GcBenchmarkDistinctComparer.Instance).ToList();

            DistinctCounterBenchmarks =
                CounterBenchmarks.Distinct(CounterBenchmarkSetting.CounterBenchmarkDistinctComparer.Instance).ToList();

            DistinctMemoryBenchmarks =
                MemoryBenchmarks.Distinct(MemoryBenchmarkSetting.MemoryBenchmarkDistinctComparer.Instance).ToList();
        }
示例#14
0
        private static BaseManager[] Find()
        {
            var usageStorage = (int)QPatch.UseStorage.GetValue(QPatch.EasyCraftSettingsInstance);

            HashSet <BaseManager> list = new HashSet <BaseManager>();

            if (usageStorage != 0)
            {
                if (usageStorage == 1 && Player.main.IsInside())
                {
                    if (Player.main.IsInSub())
                    {
                        list.Add(BaseManager.FindManager(Player.main.currentSub));
                    }
                }
                else if (usageStorage == 2)
                {
                    foreach (SubRoot subRoot in GameObject.FindObjectsOfType <SubRoot>())
                    {
                        Vector3  position = Player.main.transform.position;
                        BaseRoot baseRoot;
                        if ((subRoot.isCyclops && (position - subRoot.GetWorldCenterOfMass()).sqrMagnitude < 10000f) || (subRoot.isBase && (baseRoot = (subRoot as BaseRoot)) != null && baseRoot.GetDistanceToPlayer() < 100f))
                        {
                            list.Add(BaseManager.FindManager(subRoot));
                        }
                    }
                }

                return((from x in list.Distinct <BaseManager>()
                        orderby(Player.main.transform.position - x.Habitat.transform.position).sqrMagnitude
                        select x).ToArray <BaseManager>());
            }
            return(list.ToArray());
        }
示例#15
0
        static void Main(string[] args)
        {
            SortedSet <Person> sortedSet = new SortedSet <Person>();
            HashSet <Person>   hashSet   = new HashSet <Person>();

            int n = int.Parse(Console.ReadLine());

            for (int i = 0; i < n; i++)
            {
                string[] data = Console.ReadLine().Split().ToArray();

                Person person = new Person(data[0], int.Parse(data[1]));

                sortedSet.Add(person);
                hashSet.Add(person);
            }

            sortedSet = new SortedSet <Person>(sortedSet.Distinct());
            hashSet   = new HashSet <Person>(hashSet.Distinct());

            Console.WriteLine(sortedSet.Count);
            Console.WriteLine(hashSet.Count); // :(

            //TODO: Да проуча и оправя GetHashCode
        }
示例#16
0
        private IEnumerable <string> GetSolution(string vertex, IEnumerable <string[]> graphEdges)
        {
            var verticesSolution = new HashSet <string>();

            verticesSolution.Add(vertex);

            var excludedVertices = new HashSet <string>(new[] { vertex });
            var excludedEdges    = new HashSet <string[]>();

            var currentEdges    = graphEdges.Where(e => e.Any(edge => edge.Contains(vertex)));
            var edgeBuffer      = graphEdges;
            var currentVertices = Enumerable.Empty <string>().Add(new[] { vertex });

            while (edgeBuffer.Any())
            {
                excludedEdges.UnionWith(GetEdgesFromVertices(currentVertices, ref edgeBuffer, ref currentEdges));
                if (!edgeBuffer.Any())
                {
                    break;
                }
                currentVertices = currentEdges.SelectMany(edge => edge).Distinct().RemoveValues(currentVertices);
                excludedVertices.UnionWith(currentVertices);
                excludedEdges.UnionWith(GetEdgesFromVertices(currentVertices, ref edgeBuffer, ref currentEdges));
                currentVertices = currentEdges.SelectMany(edge => edge).Distinct().RemoveValues(currentVertices);
                verticesSolution.UnionWith(currentVertices);
                //verticesSolution.AddRange(currentVertices);
            }

            return(verticesSolution.Distinct());
        }
示例#17
0
        public IFeatureInfoList GetFeatureDependencies(string featureId)
        {
            var features = GetExtensions().Features;

            var feature = features.FirstOrDefault(x => x.Id == featureId);

            if (feature == null)
            {
                return(EmptyFeatureInfoList.Singleton);
            }

            var dependencies = new HashSet <IFeatureInfo>()
            {
                feature
            };
            var stack = new Stack <IFeatureInfo[]>();

            stack.Push(features.Where(x => feature.DependencyOn(x)).ToArray());

            while (stack.Count > 0)
            {
                var next = stack.Pop();
                foreach (var dependency in next.Where(dependency => !dependencies.Contains(dependency)))
                {
                    dependencies.Add(dependency);
                    stack.Push(features.Where(x => dependency.DependencyOn(x)).ToArray());
                }
            }

            return(new FeatureInfoList(dependencies.Distinct().ToArray()));
        }
        public static IDictionary<IPAddress, IPAddress> ExtractContiguousRanges(IEnumerable<IPAddress> IPs)
        {
            Logger logger = LogManager.GetCurrentClassLogger();
            IDictionary<IPAddress, IPAddress> ranges = new Dictionary<IPAddress, IPAddress>();
            HashSet<uint> IPNumbers = new HashSet<uint>();
            foreach (IPAddress address in IPs)
            {
                IPNumbers.Add(address.ToUint());
            }
            IEnumerable<IEnumerable<uint>> IPNumberGroups = IPNumbers.Distinct()
                .GroupBy(num => NumberUtils.Range(num, uint.MaxValue - num + 1)
                .TakeWhile(IPNumbers.Contains).Last())
                .Where(seq => seq.Count() >= 3)
                .Select(seq => seq.OrderBy(num => num));

            foreach (IEnumerable<uint> group in IPNumberGroups)
            {
                uint low = group.Min();
                uint high = group.Max();
                IPAddress rangeLow = parseUint(low);
                IPAddress rangeHigh = parseUint(high);
                logger.Debug("Selected for exclusion: " + rangeLow + " to " + rangeHigh);
                ranges.Add(rangeLow, rangeHigh);
            }
            return ranges;
        }
        static void Main(string[] args)
        {
            var input = Console.ReadLine().Split().Select(x => int.Parse(x)).ToArray();
            var n     = input[0];
            var m     = input[1];

            var setN = new HashSet <int>();
            var setM = new HashSet <int>();

            for (int i = 0; i < n + m; i++)
            {
                if (i < n)
                {
                    var number = int.Parse(Console.ReadLine());
                    setN.Add(number);
                }
                else
                {
                    var number = int.Parse(Console.ReadLine());
                    setM.Add(number);
                }
            }

            setN.IntersectWith(setM);

            Console.WriteLine(String.Join(" ", setN.Distinct()));
        }
示例#20
0
        public static int Star2(string[] rules)
        {
            var counter      = 0;
            var groupCounter = new HashSet <char>();
            var groupInnerId = 0;

            foreach (var line in rules)
            {
                if (line.Trim().Length == 0)
                {
                    counter     += groupCounter.Distinct().Count();
                    groupCounter = new HashSet <char>();
                    groupInnerId = 0;
                    continue;
                }
                if (groupInnerId == 0)
                {
                    groupCounter = line.Trim().ToHashSet();
                }
                else
                {
                    groupCounter = groupCounter.Intersect(line.Trim().AsEnumerable()).ToHashSet();
                }
                groupInnerId++;
            }
            counter += groupCounter.Distinct().Count();
            return(counter);
        }
示例#21
0
        protected override int[] GetSkipFrames(AVSValue args, ScriptEnvironment env)
        {
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
            string filename = args[1].AsString();
            HashSet<int> f = new HashSet<int>();
            int lineNo = 0;
            string line = "xx";
            try
            {
                using (StreamReader sr = new StreamReader(filename))
                {
                    while ((line = sr.ReadLine()) != null)
                    {
                        lineNo++;
                        f.Add(int.Parse(line));
                    }
                }
            }
            catch (Exception ex)
            {
                env.ThrowError(string.Format("line: {0:4} | {1} {2}\n", lineNo, ex.Message, line));
            }

            return f.Distinct().OrderBy(key => key).ToArray<int>();
        }
示例#22
0
        public IEnumerable <IFeatureInfo> GetFeatureDependencies(string featureId)
        {
            return(_featureDependencies.GetOrAdd(featureId,
                                                 new Lazy <IEnumerable <IFeatureInfo> >(() =>
            {
                var unorderedFeatures = GetAllUnorderedFeatures();

                var feature = unorderedFeatures.FirstOrDefault(x => x.Id == featureId);
                if (feature == null)
                {
                    return Enumerable.Empty <IFeatureInfo>();
                }

                var dependencies = new HashSet <IFeatureInfo>()
                {
                    feature
                };
                var stack = new Stack <IFeatureInfo[]>();

                stack.Push(unorderedFeatures.Where(subject => feature.Dependencies.Any(x => x == subject.Id)).ToArray());

                while (stack.Count > 0)
                {
                    var next = stack.Pop();
                    foreach (var dependency in next.Where(dependency => !dependencies.Contains(dependency)))
                    {
                        dependencies.Add(dependency);
                        stack.Push(unorderedFeatures.Where(subject => feature.Dependencies.Any(x => x == subject.Id)).ToArray());
                    }
                }

                return dependencies.Distinct();
            })).Value);
        }
        private XElement CreateFixturePropertiesElement(Type testFixtureType)
        {
            if (testFixtureType == null)
            {
                return(null);
            }

            var propertyElements = new HashSet <XElement>();

            var attributes = testFixtureType.GetCustomAttributes(false)
                             .Cast <Attribute>();

            var description = ReflectionUtility.GetDescription(attributes);

            if (description != null)
            {
                var propertyElement = CreatePropertyElement("Description", description).Single();
                propertyElements.Add(propertyElement);
            }

            var categories = ReflectionUtility.GetCategories(attributes);

            propertyElements.UnionWith(CreatePropertyElement("Category", categories));

            return(propertyElements.Any()
                ? new XElement("properties", propertyElements.Distinct())
                : null);
        }
示例#24
0
        public static IList <string> GetDistinctPhysicalPipingSystemTypeNames(Document doc)
        {
            FilteredElementCollector   collector         = new FilteredElementCollector(doc);
            HashSet <PipingSystem>     pipingSystems     = collector.OfClass(typeof(PipingSystem)).Cast <PipingSystem>().ToHashSet();
            HashSet <PipingSystemType> pipingSystemTypes = pipingSystems.Select(ps => doc.GetElement(ps.GetTypeId())).Cast <PipingSystemType>().ToHashSet();
            HashSet <string>           abbreviations     = pipingSystemTypes.Select(pst => pst.Abbreviation).ToHashSet();

            return(abbreviations.Distinct().ToList());
        }
示例#25
0
        private async Task HandleUpdatedTransactions()
        {
            await _transactionRepository.UpdateTransactionsAsync(_updatedTransactions.Distinct());

            foreach (var updatedTransaction in _updatedTransactions)
            {
                OnTransactionConfirmationUpdated(updatedTransaction);
            }
        }
示例#26
0
        public void AssertFieldsUnique()
        {
            var unique = fields.Distinct(new FieldComparer()).Count().Equals(fields.Count);

            if (unique == false)
            {
                throw new InvalidOperationException("Усі поля мають бути унікальні за назвою та порядковим номером.");
            }
        }
示例#27
0
        public async static Task <IEnumerable <object> > GetAutpocompletionFor(string code, int position)
        {
            //e:\dev\roslyn\omnisharp-roslyn\src\omnisharp.roslyn.csharp\services\intellisense\intellisenseservice.cs

            code     = @"class Script
{
    static void Main()
    {
        var test = ""ttt"";
        System.Console.WriteLine($""Hello World!{test.Ends";
            position = 103;
            position = 128 + 4;

            var completions = new HashSet <string>();

            var workspace = new AdhocWorkspace();
            //var workspace1 = new AdhocWorkspace();
            //InitWorkspace(workspace, code, position);

            string projName     = "NewProject";
            var    projectId    = ProjectId.CreateNewId();
            var    versionStamp = VersionStamp.Create();
            var    mscorlib     = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
            var    systemCore   = MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location);
            var    references   = new[] { mscorlib, systemCore };
            var    projectInfo  = ProjectInfo.Create(projectId, versionStamp, projName, projName, LanguageNames.CSharp, metadataReferences: references);
            var    newProject   = workspace.AddProject(projectInfo);
            var    sourceText   = SourceText.From(code);
            var    newDocument  = workspace.AddDocument(newProject.Id, "NewFile7.cs", sourceText);

            foreach (var project in workspace.CurrentSolution.Projects)
            {
                foreach (var document in project.Documents)
                {
                    var model = document.GetSemanticModelAsync().Result;

                    var symbols = Recommender.GetRecommendedSymbolsAtPosition(model, position, workspace).ToArray();
                    foreach (var symbol in symbols.Where(s => s.Name.StartsWith("", StringComparison.OrdinalIgnoreCase)))
                    {
                        completions.Add(symbol.Name);
                    }
                }
            }

            var result = completions.Distinct().OrderBy(x => x.ToLower());

            result.ToList().ForEach(x => System.Console.WriteLine(x));
            return(result);
            //return completions
            //    .OrderByDescending(c => c.CompletionText.IsValidCompletionStartsWithExactCase(wordToComplete))
            //    .ThenByDescending(c => c.CompletionText.IsValidCompletionStartsWithIgnoreCase(wordToComplete))
            //    .ThenByDescending(c => c.CompletionText.IsCamelCaseMatch(wordToComplete))
            //    .ThenByDescending(c => c.CompletionText.IsSubsequenceMatch(wordToComplete))
            //    .ThenBy(c => c.CompletionText);
        }
示例#28
0
        internal static IEnumerable <PhotoTDO> GetProcessedPhotosByGuest(Event ev, string name, string created, int page, int pageSize, FotoShoutDbContext db)
        {
            Func <GuestPhoto, Boolean> func;

            if (string.IsNullOrEmpty(created))
            {
                func = gp => (gp.Photo.Event.EventId == ev.EventId) && (gp.Photo.Status == (byte)PhotoStatus.Submitted || gp.Photo.Status == (byte)PhotoStatus.PendingPublish || gp.Photo.Status == (byte)PhotoStatus.Published);
            }
            else
            {
                created = DateTime.Parse(created).ToShortDateString();
                func    = gp => (gp.Photo.Event.EventId == ev.EventId) && gp.Photo.Created.ToShortDateString().Equals(created, StringComparison.InvariantCultureIgnoreCase) && (gp.Photo.Status == (byte)PhotoStatus.Submitted || gp.Photo.Status == (byte)PhotoStatus.PendingPublish || gp.Photo.Status == (byte)PhotoStatus.Published);
            }
            IEnumerable <Guest> guests = ev.Guests.Where(g => (g.FirstName + " " + g.LastName + " " + g.MiddleInitial).Contains(name, StringComparison.InvariantCultureIgnoreCase));
            HashSet <PhotoTDO>  photos = new HashSet <PhotoTDO>();

            foreach (Guest guest in guests)
            {
                IEnumerable <PhotoTDO> ps = guest.GuestPhotos.Where(func).Select(gp => new PhotoTDO {
                    PhotoId     = gp.Photo.PhotoId,
                    Filename    = gp.Photo.Filename,
                    Folder      = gp.Photo.Folder,
                    Status      = gp.Photo.Status,
                    Submitted   = gp.Photo.Submitted,
                    SubmittedBy = gp.Photo.SubmittedBy,
                    Thumbnail   = AppConfigs.VirtualRoot + gp.Photo.Thumbnail,
                    Created     = gp.Photo.Created,
                    Image       = AppConfigs.VirtualRoot + ev.EventVirtualPath + "/" + Constants.STR_PROCESSED + "/" + gp.Photo.Filename,
                    Rating      = gp.Photo.Rating
                });
                if (ps.Any())
                {
                    photos.UnionWith(ps);
                }
            }

            IEnumerable <PhotoTDO> ret = (page > 0 && pageSize > 0 && (photos.Count() > pageSize)) ?
                                         photos.Distinct(new PhotoComparer <PhotoTDO>()).OrderBy(p => p.Created).Skip((page - 1) * pageSize).Take(pageSize) :
                                         photos.Distinct(new PhotoComparer <PhotoTDO>()).OrderBy(p => p.Created);

            return(ret);
        }
示例#29
0
        public void TimeGeneratingOneMillionGuids()
        {
            var set = new HashSet<Guid>();
            for (var i = 0; i < _oneMillion; i++)
            {
                set.Add(Guid.NewGuid());
            }

            set.Count.Should().Be(_oneMillion);
            set.Distinct().Count().Should().Be(_oneMillion);
        }
示例#30
0
        public int GetConnectedComponentsCount()
        {
            HashSet <V[]> connectedGraphs = new HashSet <V[]>(new NodeArrayComparer());

            foreach (V node in Edges.Keys)
            {
                connectedGraphs.Add(GetNodesConnectedTo(node).OrderBy(n => n).ToArray());
            }

            return(connectedGraphs.Distinct().Count());
        }
示例#31
0
 internal void NormaliseFlags()
 {
     foreach (string f in BoolFlags.Distinct().ToArray())
     {
         if (f.EndsWith("#"))
         {
             IntFlags.Add(f.Substring(0, f.Length - 1));
             BoolFlags.Remove(f);
         }
     }
 }
示例#32
0
        public static IDataSource BuildMockDataSource(this IEnumerable <TextReplacementTemplate> textReplacements)
        {
            DataTable table = new DataTable();

            Dictionary <string, Group> groups  = new Dictionary <string, Group>();
            HashSet <string>           columns = new HashSet <string>();

            foreach (var textReplacement in textReplacements)
            {
                columns.Add(textReplacement.Key);
                foreach (var group in textReplacement.Groups)
                {
                    groups[group.Key] = group;
                }
            }

            table.Columns.Add("Id", typeof(Guid));
            table.Columns["Id"].Unique = true;

            // The ID of the main report item
            table.Columns.Add("MainReportItemId", typeof(Guid));

            foreach (var group in groups.Distinct().OrderBy(x => x.Key).ThenBy(x => x.Value))
            {
                table.Columns.Add(group.Key, typeof(string));
                table.Columns[group.Key].ExtendedProperties["ColType"] = "Group";
            }

            foreach (var column in columns.Distinct().OrderBy(x => x))
            {
                table.Columns.Add(column.Trim('{', '}'), typeof(string));
            }

            // Fill with mock data
            Guid    mainItemID = Guid.NewGuid();
            DataRow newRow     = table.NewRow();

            newRow["Id"] = Guid.NewGuid();
            newRow["MainReportItemID"] = mainItemID;
            newRow["group1"]           = "g1";
            newRow["group2"]           = "g2 value 0";
            newRow["Column_D"]         = "D0";
            table.Rows.Add(newRow);

            table.Rows.Add(Guid.NewGuid(), mainItemID, "g1", "g2 value 1", "g3 v1", "A1", "B1", "C1", "D1", "E2");
            table.Rows.Add(Guid.NewGuid(), mainItemID, "g1", "g2 value 1", "g3 v2", "A1", "B1", "C1", "D1", "E2");
            table.Rows.Add(Guid.NewGuid(), mainItemID, "g1", "g2 value 1", "g3 v3", "A1", "B1", "C1", "D1", "E2");

            table.Rows.Add(Guid.NewGuid(), mainItemID, "g1", "g2 value 2", "g3", "A2", "B2", "C2", "D2", "E2 value");
            table.Rows.Add(Guid.NewGuid(), mainItemID, "g1a", "g2 value 2", "g3", "A2", "B2", "C2", "D2", "E2 value");
            table.Rows.Add(Guid.NewGuid(), mainItemID, "g1a", "g2 value 3", "g3", "A2", "B2", "C2", "D2", "E2 value");

            return(new DataTableDataSource(table));
        }
        public async Task Process(TRequest request, CancellationToken cancellationToken)
        {
            foreach (var requirement in _requirements.Distinct())
            {
                var result = await _sender.Send(requirement, cancellationToken);

                if (!result.IsAuthorized)
                {
                    throw new UnauthorizedAccessException(result.FailureMessage);
                }
            }
        }
        public static IEnumerable<string> CollectTabs(this EditorResult editorResult) {
            var set = new HashSet<ShapePosition>();

            foreach (var editor in editorResult.Editors) {
                var positionText = editor.Metadata.Position;

                if (!String.IsNullOrWhiteSpace(positionText)) {
                    var position = ShapePosition.Parse(positionText);
                    set.Add(position);
                }
            }
            return set.Distinct(new ShapePositionDistinctComparer()).OrderBy(x => x.Position).Select(x => x.Name);
        }
示例#35
0
        private static IEnumerable<string> PossibleWords(string word, int level = 1)
        {
            var words = new HashSet<string>();
            Matcher(word, _list).ToList().ForEach(w => words.Add(w));

            if (level < 3)
            {
                var toAdd = new List<string>();
                foreach (var item in words)
                    toAdd.AddRange(PossibleWords(item, level + 1));

                toAdd.ForEach(w => words.Add(w));
            }

            return words.Distinct();
        }
示例#36
0
 public HashSet<Timetable> getUniques(HashSet<Timetable> tables)
 {
     return new HashSet<Timetable>(tables.Distinct(new TimetableBookedTimeEquality()).Select(t => t.RemoveAllFreeTime()).OrderBy(x => x.ToString()));
 }
示例#37
0
        public void When_running_the_order_is_random()
        {
            var last = "";
            var runs = new HashSet<string>();

            var ex = Experiment
                .On(() => last = "control")
                .Try(() => last = "try");

            for (int i = 0; i < 1000; i++)
            {
                ex.Run();
                runs.Add(last);
            }

            runs.Distinct().Count().ShouldBeGreaterThan(1);
        }
示例#38
0
        public static string DisplayResults()
        {
            string scope = HostingEnvironment.MapPath("~");

            Regex regex = new Regex(@"([a-fA-F0-9]{64})");
            string connectionString = "Provider=Search.CollatorDSO;Extended Properties=\"Application=Windows\"";
            HashSet<string> imgExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
                {
                    ".jpg", ".jpeg", ".jpe", ".gif", ".png", ".tiff", ".tif", ".svg", ".svgz", ".xbm", ".bmp", ".ico"
                };

            OleDbConnection connection = new OleDbConnection(connectionString);

            string query = @"SELECT TOP 100 System.ItemFolderPathDisplay FROM SystemIndex WHERE scope ='file:" + scope + "' AND System.FileName = 'index.htm' ORDER BY System.DateModified DESC";
            OleDbCommand command = new OleDbCommand(query, connection);
            connection.Open();
            HashSet<string> result = new HashSet<string>();
            OleDbDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                string searchString = reader.GetString(0);
                Match match = regex.Match(searchString);
                if (match.Success)
                {
                    result.Add(match.Value);
                }
            }
            connection.Close();
            if (result.Count > 0)
            {
                string searchHTML = "";
                var uniqueResults = result.Distinct();
                foreach (string s in uniqueResults)
                {
                    var signature = "";
                    var img = "";
                    //var file = "";
                    var msg = "";
                    var date = "";
                    var blockchain = "";
                    var profiles = "";
                    var doc = new HtmlAgilityPack.HtmlDocument();
                    try
                    {
                        doc.Load(scope + s + "\\index.htm");
                    }
                    catch { break; }


                    try
                    {
                        img = doc.GetElementbyId("img0").InnerText;
                        searchHTML = searchHTML + "<div class=\"item\"><div class=\"content\"><table><tr><th rowspan=\"6\"><a href=\"" + s + "/index.htm\"><img src=\"" + s + "/" + img + "\" /></a></th><th></th></tr>";
                    }
                    catch { searchHTML = searchHTML + "<div class=\"item\"><div class=\"content\"><table><tr><th rowspan=\"6\"></th><th></th></tr>"; }
                    try { signature = doc.GetElementbyId("signature").InnerText; }
                    catch { }
                    try { blockchain = doc.GetElementbyId("blockchain").InnerText; }
                    catch { }
                    searchHTML = searchHTML + "<tr><td>" + blockchain + " - " + signature + "</td></tr>";
                    try { date = doc.GetElementbyId("block-date").InnerText; }
                    catch { }
                    try { msg = doc.GetElementbyId("msg1").InnerText; }
                    catch { }
                    try { profiles = doc.GetElementbyId("profiles").InnerHtml; }
                    catch { }
                    searchHTML = searchHTML + "<tr><td><a href=\"" + s + "/index.htm\">" + msg.PadRight(50).Substring(0, 49) + "</a></td></tr>";

                    if (msg.Length > 500)
                    { searchHTML = searchHTML + "<tr><td>" + date + " : " + msg.Substring(0, 499) + "...</td></tr>"; }
                    else { searchHTML = searchHTML + "<tr><td>" + date + " : " + msg + "</td></tr>"; }

                    if (profiles.Length > 0)
                    {
                        searchHTML = searchHTML + "<tr><td>" + profiles + "</td></tr>";
                    }
                    searchHTML = searchHTML + "<tr><td><a href=\"" + s + "/index.htm\"><font size=\"1\">" + s + "</font></a></td></tr></table></div></div>";

                }
                return searchHTML;

            }
            else
            { return "<div class=\"item\"><div class=\"content\">Nothing found</div></div>"; }
        
        }
示例#39
0
        public string GetBinaryPath()
        {
            if (null == assemblies)
               {
               throw new Exception("No mapping assembly specified");
               }
               HashSet<string> paths = new HashSet<string>();
               foreach (MSBuild.BuildItem it in assemblies)
               {
               paths.Add(Path.GetDirectoryName(it.Include).ToLower());
               }
               if (paths.Count == 0)
               {
               throw new Exception("No mapping assembly specified");
               }

               if (paths.Count > 1)
               {
               throw new Exception("Mapping assemblies does not share the same directory.");
               }

               return paths.Distinct().First();
        }
示例#40
0
        public ActionResult Ship(String id, Guid shipID, Guid newID, Guid? parentID, String portName)
        {
            try
            {
                HoloTableController._lockMap[id] = HoloTableController._lockMap.GetValue(id, new Object());

                lock (HoloTableController._lockMap[id])
                {
                    var model = new DetailModel(id, shipID);

                    // Parents being equipped
                    var parentItems = model.Player.Items.Where(i => i.ID == parentID).ToArray();

                    // Ports being equipped
                    var newShipPorts = model.Player.Ships.Where(s => s.ID == shipID).Where(s => s.Ports != null).Where(s => s.Ports.Items != null).SelectMany(s => s.Ports.Items).Where(p => p.PortName == portName).ToArray();
                    var newItemPorts = model.Player.Items.Where(i => i.ID == parentID).Where(i => i.Ports != null).Where(i => i.Ports.Items != null).SelectMany(i => i.Ports.Items).Where(p => p.PortName == portName).ToArray();
                    var newPorts = newShipPorts.Concat(newItemPorts).ToArray();

                    // Item IDs being replaced
                    var oldItemIDs = new HashSet<Guid>(newPorts.Select(p => p.ItemID));

                    // Items being replaced
                    var oldItems = model.Player.Items.Where(i => oldItemIDs.Contains(i.ID)).ToArray();
                    var oldIDs = new HashSet<Guid>(oldItems.SelectMany(i => this.FlattenIDs(model, i)));

                    // Inventory being moved
                    var oldHangarInventory = model.Player.Inventory.Items.Where(i => oldIDs.Contains(i.ID));
                    var oldShipInventory = model.Player.Ships.Where(s => s.Inventory != null).Where(s => s.Inventory.Items != null).SelectMany(s => s.Inventory.Items.Where(i => oldIDs.Contains(i.ID)));
                    var oldInventory = oldShipInventory.Union(oldHangarInventory).ToArray();

                    // Items being equipped
                    var newItems = model.Player.Items.Where(i => i.ID == newID).ToArray();
                    var newIDs = new HashSet<Guid>(newItems.SelectMany(i => this.FlattenIDs(model, i)));

                    // Inventory being moved
                    var newHangarInventory = model.Player.Inventory.Items.Where(i => newIDs.Contains(i.ID));
                    var newShipInventory = model.Player.Ships.Where(s => s.Inventory != null).Where(s => s.Inventory.Items != null).SelectMany(s => s.Inventory.Items.Where(i => newIDs.Contains(i.ID)));
                    var newInventory = newShipInventory.Union(newHangarInventory).ToArray();

                    // Old ports
                    var oldShipPorts = model.Player.Ships.Where(s => s.Ports != null).Where(s => s.Ports.Items != null).SelectMany(s => s.Ports.Items).Where(p => p.ItemID == newID).Where(p => p.ItemID != Guid.Empty).ToArray();
                    var oldItemPorts = model.Player.Items.Where(i => i.Ports != null).Where(i => i.Ports.Items != null).SelectMany(i => i.Ports.Items).Where(p => p.ItemID == newID).Where(p => p.ItemID != Guid.Empty).ToArray();
                    var oldPorts = oldItemPorts.Concat(oldShipPorts).ToArray();

                    // Configure Ship inventory
                    foreach (var ship in model.Player.Ships.Where(s => s.Inventory != null).Where(s => s.Inventory.Items != null))
                    {
                        ship.Inventory.Items = ship.Inventory.Items.Where(i => !oldIDs.Contains(i.ID)).Where(i => !newIDs.Contains(i.ID)).ToArray();

                        if (ship.ID == shipID)
                        {
                            ship.Inventory.Items = ship.Inventory.Items.Union(newInventory).ToArray();
                        }
                    }

                    // Configure Player inventory
                    var shipItemIDs = new HashSet<Guid>(model.Player.Ships.Where(s => s.Inventory != null).Where(s => s.Inventory.Items != null).SelectMany(s => s.Inventory.Items).Select(i => i.ID));

                    model.Player.Inventory = new Inventory.Inventory
                    {
                        Items = model.Player.Items.Where(i => !shipItemIDs.Contains(i.ID)).Select(i => new Inventory.InventoryItem { ID = i.ID }).ToArray()
                    };

                    var oldPort = oldPorts.SingleOrDefault();

                    if (oldPort != null)
                    {
                        oldPort.ItemID = oldItemIDs.Distinct().SingleOrDefault();
                    }

                    var newPort = newPorts.SingleOrDefault();

                    if (newPort != null)
                    {
                        newPort.ItemID = newID;
                    }

                    foreach (var item in newItems)
                    {
                        if (item.Ports.Items == null) continue;
                        var gameItem = model.GameData_ItemMap[newID];
                        if (gameItem.Ports.Items == null) continue;
                        var itemPorts = item.Ports.Items.ToList();
                        var missingPorts = gameItem.Ports.Items.Where(p => !item.Ports.Items.Select(i => i.PortName).Distinct().Contains(p.Name));

                        foreach (var port in missingPorts)
                        {
                            itemPorts.Add(new Port
                            {
                                ItemID = Guid.Empty,
                                PortName = port.Name,
                            });
                        }

                        item.Ports.Items = itemPorts.ToArray();
                    }

                    // TODO: Validate parts - can't because CIG breaks the rules

                    // Set current ship (Optional)
                    model.Player.VehicleID = shipID;

                    model.Save();

                    ViewBag.ID = id;

                    return View(model);
                }
            }
            catch (FileNotFoundException)
            {
                this.Response.StatusCode = 500;
                this.Response.TrySkipIisCustomErrors = true;

                return new JsonResult
                {
                    Data = new
                    {
                        Reason = "Hangar Removed"
                    }
                };
            }
            catch (Exception ex)
            {
                Elmah.ErrorLog.GetDefault(System.Web.HttpContext.Current).Log(new Elmah.Error(ex));

                this.Response.StatusCode = 500;
                this.Response.TrySkipIisCustomErrors = true;

                return new JsonResult
                {
                    Data = new
                    {
                        Reason = "System Error"
                    }
                };
            }
        }
示例#41
0
文件: Program.cs 项目: jamiees2/Euler
        static void Main(string[] args)
        {
            List<List<int>> possibles = new List<List<int>>();
            for (int a = 1000; a < 10000; a++)
            {
                if (IsValid(a))
                {
                    int[] digits = a.Digits().ToArray();
                    int startA = GetCycleStart(a);
                    if (startA < 1000) continue;
                    for (int b = startA; b < startA + 100; b++)
                    {
                        if (IsValid(b))
                        {
                            int startB = GetCycleStart(b);
                            if (startB < 1000) continue;
                            for (int c = startB; c < startB + 100; c++)
                            {
                                if (IsValid(c))
                                {
                                    int startC = GetCycleStart(c);
                                    if (startC < 1000) continue;
                                    for (int d = startC; d < startC + 100; d++)
                                    {
                                        if (IsValid(d))
                                        {
                                            int startD = GetCycleStart(d);
                                            if (startD < 1000) continue;
                                            for (int e = startD; e < startD + 100; e++)
                                            {
                                                if (IsValid(e))
                                                {
                                                    int startE = GetCycleStart(e);
                                                    if (startE < 1000) continue;
                                                    for (int k = startE; k < startE + 100; k++)
                                                    {
                                                        List<int> sequence = new List<int>();
                                                        if (IsValid(k))
                                                        {
                                                            sequence.Add(a);
                                                            sequence.Add(b);
                                                            sequence.Add(c);
                                                            sequence.Add(d);
                                                            sequence.Add(e);
                                                            sequence.Add(k);
                                                            int[] kDigits = k.Digits().ToArray();
                                                            if (digits[0] == kDigits[2] && digits[1] == kDigits[3])
                                                            {

                                                                if (IsValidSequence(sequence))
                                                                {
                                                                    possibles.Add(sequence);
                                                                    /*
                                                                    Console.WriteLine(a + "  " + b + "  " + c + "  " + d + "  " + e + "  " + k);
                                                                    Console.WriteLine(a + b + c + d + e + k);*/
                                                                }

                                                                //Console.WriteLine(a + "  " + b + "  " + c + "  " + d + "  " + e + "  " + k);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                        }
                    }
                }
            }
            HashSet<int> sums = new HashSet<int>();
            foreach (var sequence in possibles)
            {
                if (!sums.Contains(sequence.Sum()))
                {
                    sums.Add(sequence.Sum());
                    Console.WriteLine(sequence.ToStringPretty());
                }

                //Console.WriteLine(sequence.ToStringPretty());
                /*
                if (IsOrdered(sequence))
                {
                    Console.WriteLine(sequence.ToStringPretty());
                    Console.WriteLine(sequence.Sum());
                }*/
            }
            //The answer is the 4th index in this, don't ask me why
            Console.WriteLine(sums.Distinct().ToStringPretty());
            Console.ReadKey();
        }
            public void UpdateNotifications(Domain.Entity.Mill.Pipe pipeSavingState)
            {
                if (isProperlyCreated)
                {
                    //* What can happen at Save Pipe: (NRO - non required inspection operation)
                    //* - pipe is new and have no previous state (to update: NROs from current size type(new))
                    if (initialPipeSizeTypeId == Guid.Empty)
                    {
                        AddPipe(pipeSavingState.PipeTestResult);
                        ProcessOperationForPipeSizeType(pipeSavingState.Type.Id);
                    }

                    //* - pipe is existing and pipe size type changed (to update: NROs from previous size type(remove), NROs from current size type(new))
                    else if (pipeSavingState.Type == null || initialPipeSizeTypeId != pipeSavingState.Type.Id)
                    {
                        RemoveAndUpdatePipe(initialSelectivePipeTestResult);
                        AddAndUpdate(pipeSavingState.PipeTestResult);

                    }

                    //* - pipe is existing and operations were edited (to update: NROs from current size type(track changes))
                    else if (initialPipeSizeTypeId == pipeSavingState.Type.Id)
                    {
                        HashSet<TestResultInfo> savingState = new HashSet<TestResultInfo>(GetTestResultInfoListFromPipeTestResultList(pipeSavingState.PipeTestResult));
                        HashSet<TestResultInfo> initialState = new HashSet<TestResultInfo>(initialSelectiveInfo);

                        savingState.ExceptWith(initialState);

                        foreach (TestResultInfo result in savingState.Distinct())
                        {
                            manager.cache.RemovePipeAmount(result.OperationId);
                            manager.cache.AddPipeAmount(result.OperationId);

                            UpdateNotification(result.OperationId);
                        }
                    }

                    //* - pipe deactivation (to update: NRO (remove))
                    else if (!pipeSavingState.IsActive)
                    {
                        RemoveAndUpdatePipe(pipeSavingState.PipeTestResult);
                    }
                }

                NotificationService.Instance.NotifyInterested();
                SavePipeState(pipeSavingState);
            }
示例#43
0
        protected virtual int[] GetSkipFrames(AVSValue args, ScriptEnvironment env)
        {
            int n = args[1].ArraySize();
            HashSet<int> f = new HashSet<int>();
            int max = vi.num_frames;
            for (int i = 0; i < n; ++i)
            {
                int skipFrm = args[1][i].AsInt();
                if (vi.num_frames > skipFrm)
                {
                    f.Add(skipFrm);
                }
            }

            return f.Distinct().OrderBy(key => key).ToArray<int>();
        }
示例#44
0
 // Set of search methods, each for a different ocassion.
 public void Search(List<List<string>> listOfSearchValues, List<SearchFunction> searchFunctions)
 {
     /* 1. Complex search method.
      * This method receives a list of lists of strings and a list of SearchFunction (delegate)
      * The reason for the use of list of lists is to keep generality and keep the code short.
      * Regarding complexity, this theoretically can reach O(n^2), but is most unlikely.
      * The method runs the appropriate search function for the appropriate set of values.
      * The use of the hashset is to handle duplicate entries in collection.
      */
     HashSet<AbstractItem> results = null;
     for (int i = 0; i < searchFunctions.Count; i++)
     {
         List<AbstractItem> funcResults = new List<AbstractItem>();
         foreach (string value in listOfSearchValues[i])
         {
             List<AbstractItem> lastSearchResults = results != null ? results.ToList() : new List<AbstractItem>();
             funcResults.AddRange(searchFunctions[i](value, lastSearchResults));
         }
         results = new HashSet<AbstractItem>();
         results.UnionWith(funcResults);
     }
     if (onSearchComplete != null)
     {
         onSearchComplete(results.Distinct().ToList());
     }
 }
示例#45
0
 public void Search()
 {
     /* 2. All items search method.
      * This method simply returns all the items in the collection, without duplicates.
      */
     HashSet<AbstractItem> results = new HashSet<AbstractItem>(coll);
     if (onSearchComplete != null)
     {
         onSearchComplete(results.Distinct().ToList());
     }
 }
示例#46
0
 static IEnumerable<string> filesFromDpl(string dplUrl, Langs[] langs) {
   var dplPath = pathFromUrl(dplUrl);
   var cfg = Newtonsoft.Json.JsonConvert.DeserializeObject<deplyConfig>(File.ReadAllText(dplPath));
   HashSet<string> res = new HashSet<string>();
   var relDir = dplUrl.Substring(0, dplUrl.LastIndexOf('/'));
   Func<string, string> fullUrl = url => (url.StartsWith("/") ? url : relDir + "/" + url).ToLower();
   if (dplUrl.IndexOf("{loc}") > 0) {
     foreach (var inc in cfg.includes) foreach (var lng in langs) res.Add(string.Format(fullUrl(inc), swLang(lng)));
   } else {
     //** includes x excludes x regExs
     if (cfg.includes != null)
       foreach (var inc in cfg.includes) {
         if (inc.StartsWith("@")) {
           var regEx = inc.Substring(1);
           var urls = Directory.GetFiles(commonDir, "*.*", SearchOption.AllDirectories).Select(f => urlFromPath(f)).ToArray();
           var rx = new Regex(regEx, RegexOptions.IgnoreCase);
           foreach (var url in urls) if (rx.IsMatch(url)) res.Add(url);
         } else if (inc.EndsWith(".json")) res.UnionWith(filesFromDpl(fullUrl(inc), langs));
         else if (inc.StartsWith("!")) res.Remove(fullUrl(inc));
         else res.Add(fullUrl(inc));
       }
   }
   return res.Distinct();
 }