Пример #1
0
        public void TestWords()
        {
            var input = new List <KeyValuePair <string, int> >
            {
                new KeyValuePair <string, int>("a", 1),
                new KeyValuePair <string, int>("n", 2),
                new KeyValuePair <string, int>("d", 3),
                new KeyValuePair <string, int>("k", 4),
                new KeyValuePair <string, int>("n", 5),
                new KeyValuePair <string, int>("n", 6),
                new KeyValuePair <string, int>("a", 7),
                new KeyValuePair <string, int>("a", 8),
                new KeyValuePair <string, int>("t", 9),
                new KeyValuePair <string, int>("r", 10)
            };
            var find    = "and";
            var results = new List <List <KeyValuePair <string, int> > >();

            foreach (var letter in find)
            {
                var letterResult = new List <KeyValuePair <string, int> >();
                foreach (var found in input.Where(s => s.Key == letter.ToString()))
                {
                    letterResult.Add(found);
                }
                results.Add(letterResult);
            }
            Assert.IsNotNull(results);

            var super = results.CartesianProduct();
        }
        private IEnumerable <IEnumerable <GeneratedMethodParameter> > getParamaterCombinations(bool includeParameterCombinations, bool includeCodeBranchCombinations)
        {
            var result = new List <List <GeneratedMethodParameter> >();

            var workingParameterInfos = GetWorkingParameterInfos();
            var methodParameters      = workingParameterInfos.Select(w => w.GetMethodParameter()).ToList();


            foreach (var item in methodParameters)
            {
                //generate a default method call
                List <GeneratedMethodParameter> generatedParameter = new List <GeneratedMethodParameter>();
                generatedParameter.Add(new GeneratedMethodParameter {
                    MethodDeclarationText = item.Symbol.Name + item.DefaultDeclaration.Key, MethodSyntax = item.DefaultDeclaration.Value, ParameterName = item.Symbol.Name
                });

                //then if combinations generates a combinations of parameters values
                if (includeParameterCombinations)
                {
                    generatedParameter.AddRange(item.CommonDeclarations.Select(c => new GeneratedMethodParameter {
                        MethodDeclarationText = item.Symbol.Name + c.Key, MethodSyntax = c.Value, ParameterName = item.Symbol.Name
                    }).ToList());
                }

                result.Add(generatedParameter);
            }

            //if code banch then read the model and add extra comibations if not in dico.
            if (includeCodeBranchCombinations)
            {
                throw new NotImplementedException();
            }

            return(result.CartesianProduct().ToList());
        }
Пример #3
0
        private List <DifferentialCharacteristic> GetPossibleSubstitutionOutcomes(int inputDifference, Dictionary <int, List <SubstitutionBoxOutput> > sBoxOutputs, double previosProbability = 1)
        {
            List <List <SubstitutionBoxOutput> > allOutputs = sBoxOutputs.Select(k => k.Value).ToList();
            IEnumerable <IEnumerable <SubstitutionBoxOutput> > possibleOutcomes = allOutputs.CartesianProduct();

            List <DifferentialCharacteristic> outcomes = new List <DifferentialCharacteristic>();

            foreach (IEnumerable <SubstitutionBoxOutput> possibleOutcome in possibleOutcomes)
            {
                List <int> sBoxIndexes = sBoxOutputs.Keys.ToList();
                int        currentIndex = 0, output = 0;
                double     probability = previosProbability;
                foreach (SubstitutionBoxOutput sBoxOutput in possibleOutcome)
                {
                    output      |= (sBoxOutput.Output << ((_spn.SubstitutionBoxCount - 1 - sBoxIndexes[currentIndex++]) * Substitution.InputLength));
                    probability *= sBoxOutput.Bias;
                }

                if (probability > LOWER_BOUND_PROBABILITY)
                {
                    DifferentialCharacteristic characteristic = new DifferentialCharacteristic(inputDifference, output, probability);
                    characteristic.AddUsedSubstitionBoxForRound(possibleOutcome.ToList());

                    outcomes.Add(characteristic);
                }
            }

            return(outcomes);
        }
Пример #4
0
        public void TestCartesianProduct()
        {
            var test = new List <int[]> {
                new[] { 0, 1, 2 }, new[] { 2, 3 }
            };
            var expected = new List <int[]> {
                new[] { 0, 2 }, new[] { 0, 3 },
                new[] { 1, 2 }, new[] { 1, 3 },
                new[] { 2, 2 }, new[] { 2, 3 }
            };

            Assert.That(test.CartesianProduct().ToList(), Is.EqualTo(expected));
            Assert.That(new List <int[]>().CartesianProduct(), Is.EqualTo(new List <int[]>()));
            Assert.That(new List <int[]> {
                new[] { 0 }
            }.CartesianProduct(),
                        Is.EqualTo(new List <int[]> {
                new[] { 0 }
            }));
            Assert.That(new List <int[]> {
                new[] { 0, 1 }
            }.CartesianProduct(),
                        Is.EqualTo(new List <int[]> {
                new[] { 0 }, new[] { 1 }
            }));
        }
Пример #5
0
        public async Task <ILoadedReport> LoadAsync(Guid competitionId, int classificationWeight, int categoryLength, int?differenceDistance, Guid[] distanceIdentifiers,
                                                    bool groupByDistanceCombinations, OptionalReportColumns optionalColumns)
        {
            var book = new ReportBook();

            using (var workflow = racesWorkflowFactory())
            {
                var competition = await workflow.Competitions.Include(c => c.Venue).Include(c => c.ReportTemplate.Logos).FirstOrDefaultAsync(c => c.Id == competitionId);

                if (competition == null)
                {
                    return(null);
                }

                var distances = await workflow.Distances.Include(d => d.Combinations).Where(d => d.CompetitionId == competitionId && distanceIdentifiers.Contains(d.Id))
                                .OrderBy(d => d.Number).ToArrayAsync();

                book.DocumentName = string.Format(Resources.ClassificationTitle, competition.Name,
                                                  groupByDistanceCombinations
                        ? Resources.DistanceCombinations
                        : string.Join("-", distances.Select(d => d.Value)));

                var selectorSets = new List <IRaceSelector[]>();
                if (groupByDistanceCombinations)
                {
                    var distanceCombinations = distances.SelectMany(d => d.Combinations).Distinct();
                    selectorSets.Add(distanceCombinations.Select(dc => (IRaceSelector) new RaceDistanceCombinationSelector(dc)).ToArray());
                }
                else
                {
                    selectorSets.Add(new IRaceSelector[] { new RaceDistancesSelector(distances) });
                }

                foreach (var selectors in selectorSets.CartesianProduct().Select(p => p.ToArray()))
                {
                    var classifications = await workflow.GetClassificationAsync(competitionId, classificationWeight, categoryLength, differenceDistance, selectors);

                    foreach (var classification in classifications)
                    {
                        if (classification.Distances.Count == 0)
                        {
                            continue;
                        }

                        var filters = selectors.Select(s => s.ToString());
                        if (classification.Category != string.Empty)
                        {
                            filters = filters.Concat(new[] { classification.Category });
                        }

                        var report = CreateReport(classification, differenceDistance, optionalColumns);
                        report.SetParameters(competition);
                        report.ReportParameters.Add("Filters", ReportParameterType.String, string.Join(" ", filters));
                        book.Reports.Add(report);
                    }
                }
            }

            return(book.Reports.Count != 0 ? new TelerikLoadedReport(book) : null);
        }
        public void GivenEmptyOuterCollection_ReturnsEmptyCollection()
        {
            var collection = new List <List <object> >();

            var result = collection.CartesianProduct();

            Assert.Empty(result);
        }
Пример #7
0
        private static List <string> getSecondaryColumns(ConcurrentDictionary <string, List <string> > pivotValues, List <ColumnVO> valueColumns)
        {
            List <IEnumerable <KeyValuePair <string, string> > > pivotPairs = pivotValues.Select(e => e.Value.ToList().Select(pivotValue => new KeyValuePair <string, string>(e.Key, pivotValue))).ToList();

            return(pivotPairs.CartesianProduct().ToList().SelectMany(pairs => {
                string pivotCol = string.Join("_", pairs.Select(pair => pair.Value));
                return valueColumns.Select(valueCol => pivotCol + "_" + valueCol.Field);
            }).ToList());
        }
Пример #8
0
        /// <summary>
        /// Constructor.
        ///
        /// Generates a list of list of windings for the design.
        ///
        /// Taking in a list of base windings that contain no wires; a lists of wires that satisfy the conditions of each section in the windings as generated.
        ///
        /// Note: As the sections do not 'know' if they are to be used on an EI or UI style lamination and do not 'know' if they would be connected in series or parallel in the case of a UI lamination.
        /// The wires are found always using the full section current. Meaning that current density ranges for parallel windings would have to be half of the desired range.
        /// If using both series/EI and parallel the current density range may become too large to operate over in a resonable amount of time.
        ///
        /// If not wires are found meeting a sections' conditions a <see cref="Exceptions.Exceptions.NoWiresFound"/> is thrown.
        ///
        /// For each wire combination with a winding, a new winding object is created and put into a list with the other windings corresponding to a design.
        /// Once all windings and the respective lists are generated, the collection can be permutated to create more combinations.
        /// Permutations will keep the same section order within the winding, but allow the winding order to change.
        ///
        /// Note: Permutations are on the order of N^2, be careful of large combinations of windings.
        ///
        /// Example: Base Windings - A, B
        ///          Wires - A1, A2, B1, C1, C2
        ///
        ///          Winding Combinations - {A.A1, B.B1}, {A.A2, B.B1}
        ///          Permutations - {A.A1, B.B1}, {B.B1, A.A1}, {A.A2, B.B1}, {B.B1, A.A2}
        ///
        /// </summary>
        /// <param name="baseWindings">A list of windings to be the base for each generated winding.</param>
        /// <param name="usePermutations">Whether or not windings should be permutated in order to find possibly better designs.</param>
        /// <param name="func">Optional parameter, a function delegate that returns a boolean, and takes two integer inputs. As of 03/15/2019 only used with <see cref="Optimizer.IncrementCurrentProcessProgress(int, int)"/>.</param>
        protected internal WindingFactory(List <Winding> baseWindings, bool usePermutations, Func <int, int, bool> func)
        {
            Windings = new List <List <Winding> >();
            List <List <Winding> > indexedWindings = new List <List <Winding> >();
            List <Section>         sections        = new List <Section>();

            foreach (var w in baseWindings)
            {
                foreach (var s in w.Sections)
                {
                    s.Wires = Wires.GetWires(s.IterateWireMaterial, s.IterateWireShapes, s.BifilarRange, s.SectionCurrent / s.CurrentDensityMaximum, s.SectionCurrent / s.CurrentDensityMinimum, s);
                    sections.Add(s);
                    if (s.Wires.Count == 0)
                    {
                        throw new NoWiresFound("Not all sections have a wire combination. Failure Section: " + s.Name);
                    }
                }
            }

            sections = sections.OrderBy(s => s.SectionOrder).ToList();
            List <List <Section> > indexSections = new List <List <Section> >();

            foreach (var s in sections)
            {
                List <Section> newSections = new List <Section>();
                foreach (var wire in s.Wires)
                {
                    newSections.Add(new Section(s, wire));
                }
                indexSections.Add(newSections);
            }
            IEnumerable <IEnumerable <Section> > completedSections = indexSections.CartesianProduct();

            foreach (IEnumerable <Section> section in completedSections)
            {
                List <Base.Winding> toAddWindings = new List <Base.Winding>();
                foreach (var w in baseWindings)
                {
                    Base.Winding winding = new Base.Winding(w);
                    winding.Sections = section.GetSectionsForWinding(winding).ToList();
                    winding.SetSectionsToSelf();
                    toAddWindings.Add(winding);
                }
                indexedWindings.Add(toAddWindings);
            }

            if (usePermutations)
            {
                Windings = GetPermutations(indexedWindings, baseWindings.Count, func);
            }
            else
            {
                Windings = indexedWindings;
            }
        }
Пример #9
0
        public SparseFacetedSearcher(IndexReader reader, params string[] groupByFields)
        {
            this.reader = reader;

            var fieldValuesBitSets = new List <FieldValuesDocIDs>();

            //STEP 1
            //f1 = A, B
            //f2 = I, J
            //f3 = 1, 2, 3
            int maxFacets = 1;
            var inputToCP = new List <List <string> >();

            foreach (string field in groupByFields)
            {
                var f = new FieldValuesDocIDs(reader, field);
                maxFacets *= f.FieldValueDocIDsPair.Count;
                if (maxFacets > MAX_FACETS)
                {
                    throw new Exception("Facet count exceeded " + MAX_FACETS);
                }
                fieldValuesBitSets.Add(f);
                inputToCP.Add(f.FieldValueDocIDsPair.Keys.ToList());
            }

            //STEP 2
            // comb1: A I 1
            // comb2: A I 2 etc.
            var cp = inputToCP.CartesianProduct();

            //SETP 3
            //create a single BitSet for each combination
            //BitSet1: A AND I AND 1
            //BitSet2: A AND I AND 2 etc.
            //and remove impossible comb's (for ex, B J 3) from list.
            Parallel.ForEach(cp, combinations =>
            {
                var comb = combinations.ToList();

                var bitSet = fieldValuesBitSets[0].FieldValueDocIDsPair[comb[0]];
                for (int j = 1; j < comb.Count; j++)
                {
                    bitSet = bitSet.WalkingIntersect(fieldValuesBitSets[j].FieldValueDocIDsPair[comb[j]]).ToList();
                }

                //STEP 3
                if (bitSet.Any())
                {
                    lock (groups)
                        groups.Add(Tuple.Create(new FacetName(comb), bitSet));
                }
            });

            //Now groups has 7 rows (as <List<string>, BitSet> pairs)
        }
Пример #10
0
        public SimpleFacetedSearch(IndexReader reader, string[] groupByFields)
        {
            this._Reader = reader;

            List<FieldValuesBitSets> fieldValuesBitSets = new List<FieldValuesBitSets>();

            //STEP 1
            //f1 = A, B
            //f2 = I, J
            //f3 = 1, 2, 3
            int maxFacets = 1;
            IList<IList<string>> inputToCP = new List<IList<string>>();
            foreach (string field in groupByFields)
            {
                FieldValuesBitSets f = new FieldValuesBitSets(reader, field);
                maxFacets *= f.FieldValueBitSetPair.Count;
                if (maxFacets > MAX_FACETS) throw new Exception("Facet count exceeded " + MAX_FACETS);
                fieldValuesBitSets.Add(f);
                inputToCP.Add(f.FieldValueBitSetPair.Keys.ToList());
            }

            //STEP 2
            // comb1: A I 1
            // comb2: A I 2 etc.
            var cp = inputToCP.CartesianProduct();

            //SETP 3
            //create a single BitSet for each combination
            //BitSet1: A AND I AND 1
            //BitSet2: A AND I AND 2 etc.
            //and remove impossible comb's (for ex, B J 3) from list.
#if !NET35
            Parallel.ForEach(cp, combinations =>
#else
            foreach(var combinations in cp)
#endif
            {
                OpenBitSetDISI bitSet = new OpenBitSetDISI(_Reader.MaxDoc);
                bitSet.Set(0, bitSet.Size());
                List<string> comb = combinations.ToList();

                for (int j = 0; j < comb.Count; j++)
                {
                    bitSet.And(fieldValuesBitSets[j].FieldValueBitSetPair[comb[j]]);
                }

                //STEP 3
                if (bitSet.Cardinality() > 0)
                {
                    lock(_Groups)
                        _Groups.Add(new KeyValuePair<List<string>, OpenBitSetDISI>(comb, bitSet));
                }
            }
Пример #11
0
        /// <summary>
        /// Creates all possible combinations for truth-table
        /// </summary>
        /// <param name="numberOfVariables"></param>
        /// <returns>List of lists of combinations</returns>
        private dynamic BitFluctuation(int numberOfVariables)
        {
            const string  set       = "01";
            List <char[]> setOfSets = new List <char[]>();

            for (int i = 0; i < numberOfVariables; i++)
            {
                setOfSets.Add(set.ToArray());
            }
            var result = setOfSets.CartesianProduct();

            return(result);
        }
Пример #12
0
        public void CartesianProduct_NullParameter_ThrowsArgumentException()
        {
            //----------- Arrange -----------------------------
            List <bool> set1 = null;
            List <int>  set2 = new List <int>();

            //----------- Act ---------------------------------
            var          pairs     = set1.CartesianProduct(set2);
            TestDelegate enumerate = () => pairs.Any();

            //----------- Assert-------------------------------
            Assert.Throws <ArgumentException>(enumerate);
        }
Пример #13
0
        public void CartesianProduct_EmptyInput_EmptyResult()
        {
            // ----------------------- Arrange -----------------------
            List <bool> set1 = new List <bool>()
            {
                false, true, false
            };
            List <int> set2 = new List <int>();

            // -----------------------   Act   -----------------------
            var pairs = set1.CartesianProduct(set2).ToList();

            // -----------------------  Assert -----------------------
            Assert.True(pairs.Count == set1.Count * set2.Count);
        }
Пример #14
0
        public IEnumerable <PremSpec <I, E> > FlatMap <E>(Func <I, O, List <E> > mapper)
        {
            var keys     = new List <I>();
            var elements = new List <List <E> >();

            foreach (var p in MapOutputs(mapper))
            {
                keys.Add(p.Key);
                elements.Add(p.Value);
            }

            foreach (var group in elements.CartesianProduct())
            {
                yield return(From(keys, group));
            }
        }
Пример #15
0
        private List <string> GeneratePatternsFromWord(string word)
        {
            var combos = new List <List <char> >();

            foreach (var c in word)
            {
                combos.Add(!_charsMapping.ContainsKey(c) ? new List <char>()
                {
                    c
                } : _charsMapping[c]);
            }

            var product = combos.CartesianProduct();

            return(product.Select(combo => string.Join("", combo)).ToList());
        }
Пример #16
0
        private static IEnumerable <IEnumerable <bool> > DigitReplacementCombinations(int n)
        {
            var boolList = new List <List <bool> >();

            for (int i = 0; i < n.DigitLength(); i++)
            {
                boolList.Add(new List <bool> {
                    false, true
                });
            }

            var digitReplacementCombinations = boolList.CartesianProduct().ToList();

            digitReplacementCombinations.RemoveAt(0);
            digitReplacementCombinations.RemoveAt(digitReplacementCombinations.Count - 1);

            return(digitReplacementCombinations);
        }
Пример #17
0
        private static List <List <object> > GetEvaluationParameterGrid(List <Parameter> _parameters)
        {
            List <object[]> evaluationParameterArray = new List <object[]>();

            foreach (var parameter in _parameters)
            {
                var variableType = parameter.selectedVariableTypeString;
                if (variableType == typeof(int).ToString())
                {
                    evaluationParameterArray.Add(ParseVariableSettingsAsString <int>(parameter, false, 0));
                }
                else if (variableType == typeof(float).ToString())
                {
                    evaluationParameterArray.Add(ParseVariableSettingsAsString <float>(parameter, false, 0));
                }
                else if (variableType == typeof(bool).ToString())
                {
                    evaluationParameterArray.Add(new string[] { "True", "False" });
                }
                else if (variableType == typeof(int[]).ToString())
                {
                    string[][] arrayVariableSettings = new string[parameter.selectedVariableSize][];
                    for (int i = 0; i < parameter.selectedVariableSize; i++)
                    {
                        arrayVariableSettings[i] = ParseVariableSettingsAsString <int>(parameter, true, i);
                    }
                    evaluationParameterArray.Add(arrayVariableSettings.CartesianProduct().ToArray());
                }
                else if (variableType == typeof(float[]).ToString())
                {
                    string[][] arrayVariableSettings = new string[parameter.selectedVariableSize][];
                    for (int i = 0; i < parameter.selectedVariableSize; i++)
                    {
                        arrayVariableSettings[i] = ParseVariableSettingsAsString <float>(parameter, true, i);
                    }
                    evaluationParameterArray.Add(arrayVariableSettings.CartesianProduct().ToArray());
                }
            }
            return(evaluationParameterArray.CartesianProduct());
        }
        public void CartesianProductTest()
        {
            var list1 = new List <string>()
            {
                "a", "b", "c"
            };
            var list2 = new List <int>()
            {
                1, 2, 3, 4
            };

            var result = list1.CartesianProduct(list2);

            int resultCount = 0;

            foreach (var element in result)
            {
                ++resultCount;
            }

            Assert.AreEqual(list1.Count * list2.Count, resultCount);
        }
Пример #19
0
        public void CartesianProduct_ExpectedInput_ComputesAllCombinations()
        {
            // ----------------------- Arrange -----------------------
            List <bool> set1 = new List <bool>()
            {
                false, true
            };
            List <int> set2 = new List <int>()
            {
                0, 1, 2, int.MinValue
            };

            // -----------------------   Act   -----------------------
            var pairs = set1.CartesianProduct(set2).ToList();

            // -----------------------  Assert -----------------------
            Assert.True(pairs.Count == set1.Count * set2.Count);
            int item2  = set2.Skip(1).First();
            var subset = pairs.Where(t => t.Item2 == item2).ToList();

            Assert.True(subset.Count == set1.Count);
            Assert.True(subset.Count(t => set1.Contains(t.Item1)) == subset.Count());
        }
Пример #20
0
        private static void Main(string[] args)
        {
            // order doesnt matter
            // no duplicates
            var kShirts         = int.Parse(Console.ReadLine());
            var skirtLetters    = Console.ReadLine();
            var distinctLetters = skirtLetters.Distinct().ToArray();
            var people          = int.Parse(Console.ReadLine());

            for (var i = 0; i < people; i++)
            {
                PossibleCombinations.Add(new List <string>());
                foreach (var ch in distinctLetters)
                {
                    for (var k = 0; k < kShirts; k++)
                    {
                        PossibleCombinations[i].Add(k + ch.ToString());
                    }
                }

                PossibleCombinations[i] = PossibleCombinations[i].OrderBy(x => x).ToList();
            }

            var a = PossibleCombinations.CartesianProduct();

            foreach (var vara in a)
            {
                //Console.WriteLine(string.Join("-", vara));
                results.Add(string.Join("-", vara));
            }

            Console.WriteLine(a.ToArray().Length);
            foreach (var result in results)
            {
                Console.WriteLine(result);
            }
        }
Пример #21
0
        public override void Evaluate(FSharpList <Value> args, Dictionary <PortData, Value> outPuts)
        {
            //if this element maintains a collcection of references
            //then clear the collection
            if (this is IClearable)
            {
                (this as IClearable).ClearReferences();
            }

            List <FSharpList <Value> > argSets = new List <FSharpList <Value> >();

            //create a zip of the incoming args and the port data
            //to be used for type comparison
            var portComparison       = args.Zip(InPortData, (first, second) => new Tuple <Type, Type>(first.GetType(), second.PortType));
            var listOfListComparison = args.Zip(InPortData, (first, second) => new Tuple <bool, Type>(Utils.IsListOfLists(first), second.PortType));

            //there are more than zero arguments
            //and there is either an argument which does not match its expections
            //OR an argument which requires a list and gets a list of lists
            //AND argument lacing is not disabled
            if (args.Count() > 0 &&
                (portComparison.Any(x => x.Item1 == typeof(Value.List) && x.Item2 != typeof(Value.List)) ||
                 listOfListComparison.Any(x => x.Item1 == true && x.Item2 == typeof(Value.List))) &&
                this.ArgumentLacing != LacingStrategy.Disabled)
            {
                //if the argument is of the expected type, then
                //leave it alone otherwise, wrap it in a list
                int j = 0;
                foreach (var arg in args)
                {
                    //incoming value is list and expecting single
                    if (portComparison.ElementAt(j).Item1 == typeof(Value.List) &&
                        portComparison.ElementAt(j).Item2 != typeof(Value.List))
                    {
                        //leave as list
                        argSets.Add(((Value.List)arg).Item);
                    }
                    //incoming value is list and expecting list
                    else
                    {
                        //check if we have a list of lists, if so, then don't wrap
                        if (Utils.IsListOfLists(arg))
                        {
                            //leave as list
                            argSets.Add(((Value.List)arg).Item);
                        }
                        else
                        {
                            //wrap in list
                            argSets.Add(Utils.MakeFSharpList(arg));
                        }
                    }
                    j++;
                }

                IEnumerable <IEnumerable <Value> > lacedArgs = null;
                switch (this.ArgumentLacing)
                {
                case LacingStrategy.First:
                    lacedArgs = argSets.SingleSet();
                    break;

                case LacingStrategy.Shortest:
                    lacedArgs = argSets.ShortestSet();
                    break;

                case LacingStrategy.Longest:
                    lacedArgs = argSets.LongestSet();
                    break;

                case LacingStrategy.CrossProduct:
                    lacedArgs = argSets.CartesianProduct();
                    break;
                }

                //setup a list to hold the results
                //each output will have its own results collection
                List <FSharpList <Value> > results = new List <FSharpList <FScheme.Value> >();
                for (int i = 0; i < OutPortData.Count(); i++)
                {
                    results.Add(FSharpList <Value> .Empty);
                }
                //FSharpList<Value> result = FSharpList<Value>.Empty;

                //run the evaluate method for each set of
                //arguments in the la result. do these
                //in reverse order so our cons comes out the right
                //way around
                for (int i = lacedArgs.Count() - 1; i >= 0; i--)
                {
                    var evalResult = Evaluate(Utils.MakeFSharpList(lacedArgs.ElementAt(i).ToArray()));

                    //if the list does not have the same number of items
                    //as the number of output ports, then throw a wobbly
                    if (!evalResult.IsList)
                    {
                        throw new Exception("Output value of the node is not a list.");
                    }

                    for (int k = 0; k < OutPortData.Count(); k++)
                    {
                        FSharpList <Value> lst = ((Value.List)evalResult).Item;
                        results[k] = FSharpList <Value> .Cons(lst[k], results[k]);
                    }
                    runCount++;
                }

                //the result of evaluation will be a list. we split that result
                //and send the results to the outputs
                for (int i = 0; i < OutPortData.Count(); i++)
                {
                    outPuts[OutPortData[i]] = Value.NewList(results[i]);
                }
            }
            else
            {
                Value evalResult = Evaluate(args);

                runCount++;

                if (!evalResult.IsList)
                {
                    throw new Exception("Output value of the node is not a list.");
                }

                FSharpList <Value> lst = ((Value.List)evalResult).Item;

                //the result of evaluation will be a list. we split that result
                //and send the results to the outputs
                for (int i = 0; i < OutPortData.Count(); i++)
                {
                    outPuts[OutPortData[i]] = lst[i];
                }
            }

            ValidateConnections();
        }
Пример #22
0
        public override void Evaluate(FSharpList <Value> args, Dictionary <PortData, Value> outPuts)
        {
            //THE OLD WAY
            //outPuts[OutPortData[0]] = Evaluate(args);

            //THE NEW WAY
            //if this element maintains a collcection of references
            //then clear the collection
            if (this is IClearable)
            {
                (this as IClearable).ClearReferences();
            }

            List <FSharpList <Value> > argSets = new List <FSharpList <Value> >();

            //create a zip of the incoming args and the port data
            //to be used for type comparison
            var portComparison       = args.Zip(InPortData, (first, second) => new Tuple <Type, Type>(first.GetType(), second.PortType));
            var listOfListComparison = args.Zip(InPortData, (first, second) => new Tuple <bool, Type>(Utils.IsListOfLists(first), second.PortType));

            //there are more than zero arguments
            //and there is either an argument which does not match its expections
            //OR an argument which requires a list and gets a list of lists
            //AND argument lacing is not disabled
            if (args.Count() > 0 &&
                (portComparison.Any(x => x.Item1 == typeof(Value.List) && x.Item2 != typeof(Value.List)) ||
                 listOfListComparison.Any(x => x.Item1 == true && x.Item2 == typeof(Value.List))) &&
                this.ArgumentLacing != LacingStrategy.Disabled)
            {
                //if the argument is of the expected type, then
                //leave it alone otherwise, wrap it in a list
                int j = 0;
                foreach (var arg in args)
                {
                    var portAtThis = portComparison.ElementAt(j);

                    //incoming value is list and expecting single
                    if (portAtThis.Item1 == typeof(Value.List) &&
                        portAtThis.Item2 != typeof(Value.List))
                    {
                        //leave as list
                        argSets.Add(((Value.List)arg).Item);
                    }
                    //incoming value is list and expecting list
                    else
                    {
                        //check if we have a list of lists, if so, then don't wrap
                        if (Utils.IsListOfLists(arg) && !acceptsListOfLists(arg))
                        {
                            //leave as list
                            argSets.Add(((Value.List)arg).Item);
                        }
                        else
                        {
                            //wrap in list
                            argSets.Add(Utils.MakeFSharpList(arg));
                        }
                    }
                    j++;
                }

                IEnumerable <IEnumerable <Value> > lacedArgs = null;
                switch (this.ArgumentLacing)
                {
                case LacingStrategy.First:
                    lacedArgs = argSets.SingleSet();
                    break;

                case LacingStrategy.Shortest:
                    lacedArgs = argSets.ShortestSet();
                    break;

                case LacingStrategy.Longest:
                    lacedArgs = argSets.LongestSet();
                    break;

                case LacingStrategy.CrossProduct:
                    lacedArgs = argSets.CartesianProduct();
                    break;
                }

                //setup an empty list to hold results
                FSharpList <Value> result = FSharpList <Value> .Empty;

                //run the evaluate method for each set of
                //arguments in the cartesian result. do these
                //in reverse order so our cons comes out the right
                //way around
                for (int i = lacedArgs.Count() - 1; i >= 0; i--)
                {
                    var evalResult = Evaluate(Utils.MakeFSharpList(lacedArgs.ElementAt(i).ToArray()));
                    result = FSharpList <Value> .Cons(evalResult, result);

                    runCount++;
                }

                outPuts[OutPortData[0]] = Value.NewList(result);
            }
            else
            {
                outPuts[OutPortData[0]] = Evaluate(args);
                runCount++;
            }
        }
        public SparseFacetedSearcher(IndexReader reader, params string[] groupByFields)
        {
            this.reader = reader;

            var fieldValuesBitSets = new List<FieldValuesDocIDs>();

            //STEP 1
            //f1 = A, B
            //f2 = I, J
            //f3 = 1, 2, 3
            int maxFacets = 1;
            var inputToCP = new List<List<string>>();
            foreach (string field in groupByFields)
            {
                var f = new FieldValuesDocIDs(reader, field);
                maxFacets *= f.FieldValueDocIDsPair.Count;
                if (maxFacets > MAX_FACETS) throw new Exception("Facet count exceeded " + MAX_FACETS);
                fieldValuesBitSets.Add(f);
                inputToCP.Add(f.FieldValueDocIDsPair.Keys.ToList());
            }

            //STEP 2
            // comb1: A I 1
            // comb2: A I 2 etc.
            var cp = inputToCP.CartesianProduct();

            //SETP 3
            //create a single BitSet for each combination
            //BitSet1: A AND I AND 1
            //BitSet2: A AND I AND 2 etc.
            //and remove impossible comb's (for ex, B J 3) from list.
            Parallel.ForEach(cp, combinations =>
            {
                var comb = combinations.ToList();

                var bitSet = fieldValuesBitSets[0].FieldValueDocIDsPair[comb[0]];
                for (int j = 1; j < comb.Count; j++)
                    bitSet = bitSet.WalkingIntersect(fieldValuesBitSets[j].FieldValueDocIDsPair[comb[j]]).ToList();

                //STEP 3
                if (bitSet.Any())
                {
                    lock (groups)
                        groups.Add(Tuple.Create(new FacetName(comb), bitSet));
                }
            });

            //Now groups has 7 rows (as <List<string>, BitSet> pairs)
        }
Пример #24
0
        private void finishLoad(TestScene newTest, Action onCompletion)
        {
            if (CurrentTest != newTest)
            {
                // There could have been multiple loads fired after us. In such a case we want to silently remove ourselves.
                testContentContainer.Remove(newTest.Parent);
                return;
            }

            updateButtons();

            bool hadTestAttributeTest = false;

            foreach (var m in newTest.GetType().GetMethods())
            {
                var name = m.Name;

                if (name == nameof(TestScene.TestConstructor) || m.GetCustomAttribute(typeof(IgnoreAttribute), false) != null)
                {
                    continue;
                }

                if (name.StartsWith("Test", StringComparison.Ordinal))
                {
                    name = name.Substring(4);
                }

                int runCount = 1;

                if (m.GetCustomAttribute(typeof(RepeatAttribute), false) != null)
                {
                    var count = m.GetCustomAttributesData().Single(a => a.AttributeType == typeof(RepeatAttribute)).ConstructorArguments.Single().Value;
                    Debug.Assert(count != null);

                    runCount += (int)count;
                }

                for (int i = 0; i < runCount; i++)
                {
                    string repeatSuffix = i > 0 ? $" ({i + 1})" : string.Empty;

                    var methodWrapper = new MethodWrapper(m.GetType(), m);

                    if (methodWrapper.GetCustomAttributes <TestAttribute>(false).SingleOrDefault() != null)
                    {
                        var parameters = m.GetParameters();

                        if (parameters.Length > 0)
                        {
                            var valueMatrix = new List <List <object> >();

                            foreach (var p in methodWrapper.GetParameters())
                            {
                                var valueAttrib = p.GetCustomAttributes <ValuesAttribute>(false).SingleOrDefault();
                                if (valueAttrib == null)
                                {
                                    throw new ArgumentException($"Parameter is present on a {nameof(TestAttribute)} method without values specification.", p.ParameterInfo.Name);
                                }

                                List <object> choices = new List <object>();

                                foreach (var choice in valueAttrib.GetData(p))
                                {
                                    choices.Add(choice);
                                }

                                valueMatrix.Add(choices);
                            }

                            foreach (var combination in valueMatrix.CartesianProduct())
                            {
                                hadTestAttributeTest = true;
                                CurrentTest.AddLabel($"{name}({string.Join(", ", combination)}){repeatSuffix}");
                                handleTestMethod(m, combination.ToArray());
                            }
                        }
                        else
                        {
                            hadTestAttributeTest = true;
                            CurrentTest.AddLabel($"{name}{repeatSuffix}");
                            handleTestMethod(m);
                        }
                    }

                    foreach (var tc in m.GetCustomAttributes(typeof(TestCaseAttribute), false).OfType <TestCaseAttribute>())
                    {
                        hadTestAttributeTest = true;
                        CurrentTest.AddLabel($"{name}({string.Join(", ", tc.Arguments)}){repeatSuffix}");

                        handleTestMethod(m, tc.Arguments);
                    }
                }
            }

            // even if no [Test] or [TestCase] methods were found, [SetUp] steps should be added.
            if (!hadTestAttributeTest)
            {
                addSetUpSteps();
            }

            backgroundCompiler?.SetRecompilationTarget(CurrentTest);
            runTests(onCompletion);
            updateButtons();

            void addSetUpSteps()
            {
                var setUpMethods = Reflect.GetMethodsWithAttribute(newTest.GetType(), typeof(SetUpAttribute), true)
                                   .Where(m => m.Name != nameof(TestScene.SetUpTestForNUnit));

                if (setUpMethods.Any())
                {
                    CurrentTest.AddStep(new SingleStepButton(true)
                    {
                        Text        = "[SetUp]",
                        LightColour = Color4.Teal,
                        Action      = () => setUpMethods.ForEach(s => s.Invoke(CurrentTest, null))
                    });
                }

                CurrentTest.RunSetUpSteps();
            }

            void handleTestMethod(MethodInfo methodInfo, object[] arguments = null)
            {
                addSetUpSteps();
                methodInfo.Invoke(CurrentTest, arguments);
                CurrentTest.RunTearDownSteps();
            }
        }
Пример #25
0
        /// <summary>
        /// Checks if the specified tiles form a complete hand (four combinations of three tiles and a pair).
        /// "Kokushi musou" and "Chiitoitsu" must be checked separately.
        /// </summary>
        /// <param name="concealedTiles">List of concealed tiles.</param>
        /// <param name="declaredCombinations">List of declared combinations.</param>
        /// <returns>A list of every valid sequences of combinations.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="concealedTiles"/> is <c>Null</c>.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="declaredCombinations"/> is <c>Null</c>.</exception>
        /// <exception cref="ArgumentException"><see cref="Messages.InvalidHandTilesCount"/></exception>
        public static List <List <TileComboPivot> > IsCompleteBasic(List <TilePivot> concealedTiles, List <TileComboPivot> declaredCombinations)
        {
            if (declaredCombinations == null)
            {
                throw new ArgumentNullException(nameof(declaredCombinations));
            }

            if (concealedTiles == null)
            {
                throw new ArgumentNullException(nameof(concealedTiles));
            }

            if (declaredCombinations.Count * 3 + concealedTiles.Count != 14)
            {
                throw new ArgumentException(Messages.InvalidHandTilesCount, nameof(concealedTiles));
            }

            var combinationsSequences = new List <List <TileComboPivot> >();

            // Every combinations are declared.
            if (declaredCombinations.Count == 4)
            {
                // The last two should form a pair.
                if (concealedTiles[0] == concealedTiles[1])
                {
                    combinationsSequences.Add(
                        new List <TileComboPivot>(declaredCombinations)
                    {
                        new TileComboPivot(concealedTiles)
                    });
                }
                return(combinationsSequences);
            }

            // Creates a group for each family
            IEnumerable <IGrouping <FamilyPivot, TilePivot> > familyGroups = concealedTiles.GroupBy(t => t.Family);

            // The first case is not possible because its implies a single tile or several pairs.
            // The second case is not possible more than once because its implies a pair.
            if (familyGroups.Any(fg => new[] { 1, 4, 7, 10 }.Contains(fg.Count())) ||
                familyGroups.Count(fg => new[] { 2, 5, 8, 11 }.Contains(fg.Count())) > 1)
            {
                // Empty list.
                return(combinationsSequences);
            }

            foreach (IGrouping <FamilyPivot, TilePivot> familyGroup in familyGroups)
            {
                switch (familyGroup.Key)
                {
                case FamilyPivot.Dragon:
                    CheckHonorsForCombinations(familyGroup, k => k.Dragon.Value, combinationsSequences);
                    break;

                case FamilyPivot.Wind:
                    CheckHonorsForCombinations(familyGroup, t => t.Wind.Value, combinationsSequences);
                    break;

                default:
                    List <List <TileComboPivot> > temporaryCombinationsSequences = GetCombinationSequencesRecursive(familyGroup);
                    // Cartesian product of existant sequences and temporary list.
                    combinationsSequences = combinationsSequences.Count > 0 ?
                                            combinationsSequences.CartesianProduct(temporaryCombinationsSequences) : temporaryCombinationsSequences;
                    break;
                }
            }

            // Adds the declared combinations to each sequence of combinations.
            foreach (List <TileComboPivot> combinationsSequence in combinationsSequences)
            {
                combinationsSequence.AddRange(declaredCombinations);
            }

            // Filters invalid sequences :
            // - Doesn't contain exactly 5 combinations.
            // - Doesn't contain a pair.
            // - Contains more than one pair.
            combinationsSequences.RemoveAll(cs => cs.Count() != 5 || cs.Count(c => c.IsPair) != 1);

            // Filters duplicates sequences
            combinationsSequences.RemoveAll(cs1 =>
                                            combinationsSequences.Exists(cs2 =>
                                                                         combinationsSequences.IndexOf(cs2) < combinationsSequences.IndexOf(cs1) &&
                                                                         cs1.IsBijection(cs2)));

            return(combinationsSequences);
        }
Пример #26
0
        private void btnCombinatorialTheory_Click(object sender, EventArgs e)
        {
            //List<string> _list = new List<string>() { "a", "b", "c", "d" };
            //List<List<string>> _answer = _list.CombinationsWithoutRepetition(3);

            //List<test1> _list = new List<test1>() { new test1() { propertyA = null, propertyB = 1 }, new test1() { propertyA = null, propertyB = 2 }, new test1() { propertyA = null, propertyB = 3 } };
            //List<List<test1>> _answer = _list.PermutationsWithoutRepetition();
            //List<List<test1>> _answer = _list.CombinationsWithoutRepetition(2);
            //_answer.First()[0].propertyA  = 18;

            /*
            List<string> _source = new List<string>() { "1", "2" };
            List<string> _other = new List<string>() { "a", "b" };
            List<List<string>> _answer = _source.CartesianProduct(_other);
            */

            /*
            List<string> _source = new List<string>() { "1", "2" };
            List<List<string>> _other = new List<List<string>>() { new List<string>() { "a", "b" }, new List<string>() { "c", "d" } };
            List<List<string>> _answer = _source.CartesianProduct(_other);
            */

            List<string> _other = new List<string>() { "1", "2" };
            List<List<string>> _source = new List<List<string>>() { new List<string>() { "a", "b" }, new List<string>() { "c", "d" } };
            List<List<string>> _answer = _source.CartesianProduct(_other);

        }
        private void ExecuteTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (selectedMethod == null)
            {
                return;
            }
            isExecuting  = true;
            this.Message = "I am running";

            // Get the data
            List <List <object> > datas  = new List <List <object> >();
            List <object>         inputs = new List <object>();

            int m = 0;

            for (int i = 0; i < selectedMethod.inputs.Count; i++)
            {
                if (i < Params.Input.Count)
                {
                    var           myParam = Params.Input[i];
                    List <object> data    = new List <object>();
                    foreach (object o in myParam.VolatileData.AllData(false))
                    {
                        data.Add(o);
                    }
                    // remove gh bs
                    data = data.Select(obj => obj.GetType().GetProperty("Value").GetValue(obj)).ToList();

                    if (myParam.Name.Contains("(List)"))
                    {
                        datas.Add(PrimeParam(new List <object>()
                        {
                            data
                        }, i));
                    }
                    else
                    {
                        datas.Add(PrimeParam(data, i));
                    }
                }
                else
                {
                    datas.Add(new List <object>()
                    {
                        null
                    });
                }
            }


            var calls = datas.CartesianProduct().ToList();
            List <List <object> > theCalls = new List <List <object> >();

            calls.ForEach(obj =>
            {
                List <object> myList = new List <object>();
                foreach (var ob in obj)
                {
                    myList.Add(ob);
                }
                theCalls.Add(myList);
            });

            var clsz = theCalls;
            // bust some balls

            var jsonSerializerSettings = new JsonSerializerSettings()
            {
                TypeNameHandling = TypeNameHandling.All
            };
            var jsonString = JsonConvert.SerializeObject(theCalls, jsonSerializerSettings);

            var Client     = new HttpClient();
            var TheRequest = new HttpRequestMessage(HttpMethod.Post, selectedMethod.url);

            TheRequest.Content = new System.Net.Http.StringContent(jsonString);
            TheRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
            TheRequest.Method = new System.Net.Http.HttpMethod("POST");
            TheRequest.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            TheRequest.Headers.AcceptEncoding.Add(new System.Net.Http.Headers.StringWithQualityHeaderValue("gzip"));

            TheRequest.Content = new GzipContent(TheRequest.Content);

            var response = Client.SendAsync(TheRequest).Result;


            string responseData;
            var    bytes = response.Content.ReadAsByteArrayAsync().Result;

            using (var compressedStream = new MemoryStream(bytes))
                using (var zipStream = new System.IO.Compression.GZipStream(compressedStream, System.IO.Compression.CompressionMode.Decompress))
                    using (var resultStream = new MemoryStream())
                    {
                        zipStream.CopyTo(resultStream);
                        var xx = System.Text.Encoding.UTF8.GetString(resultStream.ToArray());
                        responseData = xx;
                    }

            AllResults = JsonConvert.DeserializeObject(responseData, jsonSerializerSettings) as List <List <object> >;

            justSetResults = true;
            Action expire = () => this.ExpireSolution(true);

            Rhino.RhinoApp.MainApplicationWindow.Invoke(expire);

            isExecuting  = false;
            this.Message = "I am slacking";
        }
Пример #28
0
        public static List <CurrencyArbitrageLog> CalculateCurrencyArbitrage(List <CurrencyExchangeRates> paramCurrencyExchangeRates, string paramDate, string paramBaseCurrencyCode, string paramTargetCurrencyCode, int paramDegree = 1)
        {
            List <CurrencyArbitrageLog> CurrencyArbitrageLogList          = new List <CurrencyArbitrageLog>();
            List <CurrencyArbitrageLog> CurrencyArbitrageLogList_Distinct = new List <CurrencyArbitrageLog>();

            try
            {
                #region Calculate Currency Arbitrage Values

                if (paramCurrencyExchangeRates != null && paramCurrencyExchangeRates.Count() > 0)
                {
                    if (paramDegree > 0)
                    {
                        decimal actualValue = paramCurrencyExchangeRates
                                              .Where(type => type.Date == paramDate &&
                                                     type.BaseCurrencyCode == paramBaseCurrencyCode &&
                                                     type.TargetCurrencyCode == paramTargetCurrencyCode)
                                              .Select(type => type.ExchangeRate)
                                              .FirstOrDefault();

                        if (paramBaseCurrencyCode.Equals(paramTargetCurrencyCode))
                        {
                            actualValue = 1;
                        }

                        paramCurrencyExchangeRates = paramCurrencyExchangeRates.Where(type => type.Date == paramDate).ToList();
                        List <string> distinctIntermediateCurrencyCodes = paramCurrencyExchangeRates
                                                                          .Where(type => type.BaseCurrencyCode.Equals(paramBaseCurrencyCode) == false &&
                                                                                 type.BaseCurrencyCode.Equals(paramTargetCurrencyCode) == false)
                                                                          .Select(type => type.BaseCurrencyCode)
                                                                          .Distinct()
                                                                          .OrderBy(type => type)
                                                                          .ToList();

                        List <List <string> > listIntermediateCurrencyCodes = new List <List <string> >();
                        for (int i = 1; i <= paramDegree; i++) //Create The Dynamic List/Array Of CurrencyCodes Based On The Degree Value
                        {
                            listIntermediateCurrencyCodes.Add(distinctIntermediateCurrencyCodes);
                        }

                        //Create Cartesian Product Of CurrencyCodes Present In The Dynamic List/Array Of CurrencyCodes
                        List <string> listIntermediateCurrencyCodesCartesianList = listIntermediateCurrencyCodes
                                                                                   .CartesianProduct()
                                                                                   .Select(tuple => $"{string.Join(" ", tuple)}")
                                                                                   .ToList();

                        foreach (string eachCartesianList in listIntermediateCurrencyCodesCartesianList)
                        {
                            if (eachCartesianList.Split(' ').Count() == eachCartesianList.Split(' ').Distinct().Count()) //Perform Currency Arbitrage Calculation ONLY For Distinct CurrencyCodes In IntermediateCurrencyCodesCartesianList
                            {
                                CurrencyArbitrageLogList.Add(new CurrencyArbitrageLog()
                                {
                                    Date                      = paramDate,
                                    BaseCurrencyCode          = paramBaseCurrencyCode,
                                    TargetCurrencyCode        = paramTargetCurrencyCode,
                                    IntermediateCurrencyCodes = eachCartesianList,
                                    Degree                    = paramDegree,
                                    ImpliedValue              = 0,
                                    ActualValue               = actualValue
                                });
                            }
                        }

                        //Calculate Implied Value For Each Combination Of IntermediateCurrencyCodes
                        foreach (CurrencyArbitrageLog eachCurrencyArbitrage in CurrencyArbitrageLogList)
                        {
                            string  sourceCurrency = eachCurrencyArbitrage.BaseCurrencyCode;
                            decimal impliedValue   = 1;

                            foreach (string eachIntermediateCurrencyCode in eachCurrencyArbitrage.IntermediateCurrencyCodes.Split(' ').ToList())
                            {
                                string destinationCurrency = eachIntermediateCurrencyCode;

                                impliedValue = paramCurrencyExchangeRates
                                               .Where(type => type.Date == paramDate &&
                                                      type.BaseCurrencyCode == sourceCurrency &&
                                                      type.TargetCurrencyCode == destinationCurrency)
                                               .Select(type => type.ExchangeRate * impliedValue)
                                               .FirstOrDefault();

                                sourceCurrency = eachIntermediateCurrencyCode;
                            }

                            impliedValue = paramCurrencyExchangeRates
                                           .Where(type => type.Date == paramDate &&
                                                  type.BaseCurrencyCode == sourceCurrency &&
                                                  type.TargetCurrencyCode == eachCurrencyArbitrage.TargetCurrencyCode)
                                           .Select(type => type.ExchangeRate * impliedValue)
                                           .FirstOrDefault();

                            eachCurrencyArbitrage.ImpliedValue = impliedValue;
                        }
                    }
                    else //Degree Value Set To Zero (0)
                    {
                        CurrencyArbitrageLog currencyArbitrageLog = paramCurrencyExchangeRates
                                                                    .Where(type => type.Date == paramDate &&
                                                                           type.BaseCurrencyCode == paramBaseCurrencyCode &&
                                                                           type.TargetCurrencyCode == paramTargetCurrencyCode)
                                                                    .Select(type => new CurrencyArbitrageLog()
                        {
                            Date                      = type.Date,
                            BaseCurrencyCode          = type.BaseCurrencyCode,
                            TargetCurrencyCode        = type.TargetCurrencyCode,
                            IntermediateCurrencyCodes = null,
                            Degree                    = 0,
                            ImpliedValue              = type.ExchangeRate,
                            ActualValue               = type.ExchangeRate
                        })
                                                                    .FirstOrDefault();
                        if (currencyArbitrageLog != null)
                        {
                            CurrencyArbitrageLogList.Add(currencyArbitrageLog);
                        }
                    }
                }

                #endregion Calculate Currency Arbitrage Values

                #region Remove Duplicates & Return ONLY Profitable Currency Arbitrage Values

                foreach (var eachCurrencyArbitrageLog in CurrencyArbitrageLogList.Where(type => type.ImpliedValue > type.ActualValue).ToList())
                {
                    if (CurrencyArbitrageLogList_Distinct
                        .Where(type => type.Date == eachCurrencyArbitrageLog.Date &&
                               type.BaseCurrencyCode == eachCurrencyArbitrageLog.BaseCurrencyCode &&
                               type.IntermediateCurrencyCodes == eachCurrencyArbitrageLog.IntermediateCurrencyCodes &&
                               type.TargetCurrencyCode == eachCurrencyArbitrageLog.TargetCurrencyCode &&
                               type.Degree == eachCurrencyArbitrageLog.Degree &&
                               type.ImpliedValue == eachCurrencyArbitrageLog.ImpliedValue &&
                               type.ActualValue == eachCurrencyArbitrageLog.ActualValue)
                        .Any() == false)
                    {
                        CurrencyArbitrageLogList_Distinct.Add(eachCurrencyArbitrageLog);
                    }
                }

                //Sort / OrderBy The Results Based On The Most Profitable Arbitrage Transactions On The Top
                CurrencyArbitrageLogList_Distinct = CurrencyArbitrageLogList_Distinct.OrderByDescending(type => type.ImpliedValue).ToList();

                #endregion Remove Duplicates & Return ONLY Profitable Currency Arbitrage Values
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(CurrencyArbitrageLogList_Distinct);
        }
Пример #29
0
        private void ExecuteTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (selectedMethod == null)
            {
                return;
            }
            isExecuting  = true;
            this.Message = "I am running";

            // Get the data
            List <List <object> > datas  = new List <List <object> >();
            List <object>         inputs = new List <object>();

            int m = 0;

            for (int i = 0; i < selectedMethod.inputs.Count; i++)
            {
                if (i < Params.Input.Count)
                {
                    var           myParam = Params.Input[i];
                    List <object> data    = new List <object>();
                    foreach (object o in myParam.VolatileData.AllData(false))
                    {
                        data.Add(o);
                    }
                    // remove gh bs
                    data = data.Select(obj => obj.GetType().GetProperty("Value").GetValue(obj)).ToList();

                    if (myParam.Name.Contains("(List)"))
                    {
                        datas.Add(PrimeParam(new List <object>()
                        {
                            data
                        }, i));
                    }
                    else
                    {
                        datas.Add(PrimeParam(data, i));
                    }
                }
                else
                {
                    datas.Add(new List <object>()
                    {
                        null
                    });
                }
            }


            var calls = datas.CartesianProduct().ToList();

            AllResults = new List <List <object> >();

            foreach (var call in calls)
            {
                object invokeResult = null;
                inputs = call.ToList();
                object[] invokeInputs = call.ToArray();

                if (!selectedMethod.isCtor && !selectedMethod.isStatic)
                {
                    object self      = null;
                    bool   foundSelf = false;
                    for (int k = selectedMethod.inputs.Count - 1; k >= 0 && !foundSelf; k--)
                    {
                        var inp = selectedMethod.inputs[k];
                        if (inp.isSelf)
                        {
                            self = inputs[k];
                            inputs.RemoveAt(k);
                            foundSelf = true;
                        }
                    }
                    invokeInputs = inputs.ToArray();
                    invokeResult = selectedMethod.methodBase.Invoke(self, invokeInputs);
                }
                else if (selectedMethod.isStatic)
                {
                    invokeResult = selectedMethod.methodBase.Invoke(null, invokeInputs);
                }
                else if (selectedMethod.isCtor)
                {
                    invokeResult = (( ConstructorInfo )selectedMethod.methodBase).Invoke(invokeInputs);
                }

                List <object> results = new List <object>();

                int j = 0;
                foreach (var inp in selectedMethod.methodBase.GetParameters())
                {
                    if (inp.ParameterType.IsByRef)
                    {
                        results.Add(invokeInputs[j]);
                    }
                    j++;
                }

                results.Add(invokeResult);
                AllResults.Add(results);
            }


            justSetResults = true;

            Action expire = () => this.ExpireSolution(true);

            Rhino.RhinoApp.MainApplicationWindow.Invoke(expire);

            isExecuting  = false;
            this.Message = "I am slacking";
        }
Пример #30
0
        private static IEnumerable <Type> ParameterizeType(Type type, Dictionary <Type, List <Type> > typesImplementations)
        {
            List <Type> possibleTypes = new List <Type>();

            List <SerializationValuesAttribute> attributes = type.GetCustomAttributes(typeof(SerializationValuesAttribute), false)
                                                             .Cast <SerializationValuesAttribute>().ToList();

            List <List <Type> > groupingTypes = new List <List <Type> >();

            foreach (Type parameterType in ((System.Reflection.TypeInfo)type).GenericTypeParameters)
            {
                SerializationValuesAttribute attribute = attributes.FirstOrDefault(a => a.GenericParameterName == parameterType.Name);
                if (attribute == null)
                {
                    throw new Exception($"The parameter {parameterType.Name} of type {type.FullName} does not have its corresponding class attribute for serialization: {typeof(SerializationValuesAttribute).FullName}");
                }

                // Implementation for current parameter
                List <Type> currentTypeImplementations = new List <Type>();

                foreach (Type possibleType in attribute.PossibleTypes)
                {
                    if (typesImplementations.Keys.Contains(possibleType))
                    {
                        // Cache
                        currentTypeImplementations.AddRange(typesImplementations[possibleType]);
                    }
                    else
                    {
                        if (possibleType.IsClass && possibleType.IsAbstract)
                        {
                            List <Type> inheritedTypes = typeof(BaseFormula).Assembly.GetTypes()
                                                         .Where(t => t.IsSubclassOf(possibleType) && !t.IsAbstract && t.IsClass).ToList();
                            // Add to cache
                            typesImplementations.Add(possibleType, inheritedTypes);
                            // Add to implementations
                            currentTypeImplementations.AddRange(inheritedTypes.Except(currentTypeImplementations));
                        }
                        else if (possibleType.IsInterface)
                        {
                            List <Type> interfaceTypes = typeof(BaseFormula).Assembly.GetTypes()
                                                         .Where(t => possibleType.IsAssignableFrom(t) && !t.IsAbstract && t.IsClass).ToList();
                            // Add to cache
                            typesImplementations.Add(possibleType, interfaceTypes);
                            // Add to implementations
                            currentTypeImplementations.AddRange(interfaceTypes.Except(currentTypeImplementations));
                        }
                        else
                        {
                            if (!currentTypeImplementations.Contains(possibleType))
                            {
                                currentTypeImplementations.Add(possibleType);
                            }
                        }
                    }
                }

                groupingTypes.Add(currentTypeImplementations);
            }

            IEnumerable <IEnumerable <Type> > combinations = groupingTypes.CartesianProduct();

            foreach (IEnumerable <Type> parameterTypes in combinations)
            {
                try
                {
                    possibleTypes.Add(type.MakeGenericType(parameterTypes.ToArray()));
                }
                catch (ArgumentException)
                {
                    // Not all combinations have to be valid due to the internal restrictions of type
                    // Ignore situation
                }
            }

            return(possibleTypes);
        }
        public SimpleFacetedSearch(IndexReader reader, string[] groupByFields)
        {
            this._Reader = reader;

            List<FieldValuesBitSets> fieldValuesBitSets = new List<FieldValuesBitSets>();

            //STEP 1
            //f1 = A, B
            //f2 = I, J
            //f3 = 1, 2, 3
            int maxFacets = 1;
            List<List<string>> inputToCP = new List<List<string>>();
            foreach (string field in groupByFields)
            {
                FieldValuesBitSets f = new FieldValuesBitSets(reader, field);
                maxFacets *= f.FieldValueBitSetPair.Count;
                if (maxFacets > MAX_FACETS) throw new Exception("Facet count exceeded " + MAX_FACETS);
                fieldValuesBitSets.Add(f);
                inputToCP.Add(f.FieldValueBitSetPair.Keys.ToList());
            }

            //STEP 2
            // comb1: A I 1
            // comb2: A I 2 etc.
            var cp = inputToCP.CartesianProduct();

            //SETP 3
            //create a single BitSet for each combination
            //BitSet1: A AND I AND 1
            //BitSet2: A AND I AND 2 etc.
            //and remove impossible comb's (for ex, B J 3) from list.
            Parallel.ForEach(cp, combinations =>
            {
                OpenBitSetDISI bitSet = new OpenBitSetDISI(_Reader.MaxDoc());
                bitSet.Set(0, bitSet.Size());

                List<string> comb = combinations.ToList();

                for (int j = 0; j < comb.Count; j++)
                {
                    bitSet.And(fieldValuesBitSets[j].FieldValueBitSetPair[comb[j]]);
                }

                //STEP 3
                if (bitSet.Cardinality() > 0)
                {
                    lock(_Groups)
                        _Groups.Add(new KeyValuePair<List<string>, OpenBitSetDISI>(comb, bitSet));
                }
            });

            //Now _Groups has 7 rows (as <List<string>, BitSet> pairs) 
        }
Пример #32
0
        static void Main(string[] args)
        {
            IEnumerable <string> list = new List <string> {
                "varoitus", "koulualue", "rajoitus", "tyhjä", "tyhjäpieni"
            };
            var alist = GetCombinations(list, 3);

            foreach (var lista in alist)
            {
                Console.WriteLine(String.Join(" ", lista));
            }

            Console.WriteLine("\n --------------- \n");
            List <string[]> lists = new List <string[]>()
            {
                new[] { "tyhjä", "varoitus", "mainos" },
                new[] { "tyhjäpieni", "koulualue", "mainos" },
                new[] { "tyhjä", "rajoitus" },
            };



            Console.WriteLine("\n ------- Foreach ------- \n");
            var listaCartesiani = new List <string[]>();

            Stopwatch sw = new Stopwatch();

            sw.Start();
            foreach (var item in lists[0])
            {
                foreach (var item1 in lists[1])
                {
                    foreach (var item2 in lists[2])
                    {
                        var itemLista = new string[] { item.ToString(), item1.ToString(), item2.ToString() };
                        //Console.WriteLine(item.ToString() + " " + item1.ToString() + " " + item2.ToString() + " ");
                        listaCartesiani.Add(itemLista);
                    }
                }
            }

            foreach (var item in listaCartesiani)
            {
                Console.WriteLine(String.Join(" ", item));
            }
            sw.Stop();
            Console.WriteLine("Loop time -> " + sw.Elapsed);
            Console.WriteLine("\n ------- LINQ ------- \n");

            sw.Restart();
            var cp = lists.CartesianProduct();


            foreach (var line in cp)
            {
                Console.WriteLine(String.Join(" ", line));
            }
            sw.Stop();
            Console.WriteLine("Loop time -> " + sw.Elapsed);
            Console.ReadKey();
        }
Пример #33
0
    /// <summary>
    /// Pivots the DataTable based on provided RowField, DataField, Aggregate Function and ColumnFields.//
    /// </summary>
    /// <param name="rowField">The column name of the Source Table which you want to spread into rows</param>
    /// <param name="dataField">The column name of the Source Table which you want to spread into Data Part</param>
    /// <param name="aggregate">The Aggregate function which you want to apply in case matching data found more than once</param>
    /// <param name="columnFields">The List of column names which you want to spread as columns</param>
    /// <returns>A DataTable containing the Pivoted Data</returns>
    public DataTable PivotData(string rowField, string dataField, AggregateFunction aggregate, Dictionary <int, string> departments, Dictionary <int, string> heads, IEnumerable <string> columnFields)
    {
        DataTable     dt        = new DataTable();
        string        Separator = ".";
        List <string> rowList   = _Source.Select(x => x[rowField].ToString()).Distinct().ToList();

        if (rowList.Contains(""))
        {
            rowList.Remove("");
        }
        List <List <string> > columnsLists = new List <List <string> >();

        foreach (var columnField in columnFields)
        {
            List <string> cList = new List <string>();
            cList = _Source.Select(x => x[columnField].ToString()).Distinct().ToList();
            if (cList.Contains(""))
            {
                cList.Remove("");
            }
            // columnsLists.Add(cList);
            var modifiedCList = cList
                                .Select(s => s.Replace(".", ""))
                                .ToArray()
            ;

            columnsLists.Add(modifiedCList.ToList());
        }

        var resultZip = columnsLists.CartesianProduct().Select(x => string.Join(".", x.Cast <object>()))
                        .OrderBy(x => x);

        var resultZipped = resultZip.ToList();

        //List<string> colList = _Source.Select(x => columnFields.Aggregate((a, b) => x[a].ToString() + Separator + x[b].ToString())).Distinct().OrderBy(m => m).ToList();



        // Gets the list of columns .(dot) separated.
        //var colList = _Source.Select(x => (columnFields.Select(n => x[n]).Aggregate((a, b) => a += Separator + b.ToString())).ToString()).Distinct().OrderBy(c => c);

        dt.Columns.Add(rowField);

        //var columnsList = colList.ToList();
        //columnsList.RemoveAt(0);
        //columnsList.RemoveAt(0);
        foreach (var colName in resultZipped)
        {
            // var column = departments[Convert.ToInt32(colName)];
            dt.Columns.Add(colName);  // Cretes the result columns.//
        }

        // var columnRowTotal = dt.Columns.Add("rowTotal");


        //columnsList.RemoveAt(0);
        //columnsList.RemoveAt(0);

        foreach (string rowName in rowList)
        {
            DataRow row = dt.NewRow();
            row[rowField] = rowName;

            float allColumnsTotal = 0;
            foreach (string colName in resultZipped)
            {
                int      i            = 0;
                string   strFilter    = rowField + " = '" + rowName + "'";
                string[] strColValues = colName.Split(Separator.ToCharArray(), StringSplitOptions.None);
                foreach (var columnField in columnFields)
                {
                    strFilter += " and " + columnField + " = '" + strColValues[i] + "'";
                    i++;
                }
                row[colName] = GetData(strFilter, dataField, aggregate);
                var columnsTotal = row[colName];
                //allColumnsTotal += (float)columnsTotal;
            }
            // row[columnRowTotal] = allColumnsTotal;
            dt.Rows.Add(row);
        }

        //DataRow totalRow = dt.NewRow();

        //dt.Rows.Add(totalRow);

        //foreach (DataColumn column in dt.Columns)
        //{
        //    int rowTotal = 0;
        //    foreach (DataRow row in dt.Rows)
        //    {
        //        try
        //        {
        //            int columnValue = Convert.ToInt32(row[column]);
        //            rowTotal = rowTotal += columnValue;
        //        }
        //        catch (Exception)
        //        { }
        //    }
        //    totalRow[column] = rowTotal;
        //}
        //totalRow[rowField] = "TotalColumn";
        foreach (var colName in resultZipped)
        {
            var column = departments[Convert.ToInt32(colName)];
            dt.Columns[colName].ColumnName = column;  // Cretes the result columns.//
        }

        foreach (DataRow row in dt.Rows)
        {
            row[rowField] = heads[Convert.ToInt32(row[rowField])];
        }

        return(dt);
    }