Пример #1
0
        public static List<GeneradorDeNumero> GenerarComplementos(List<int> excluidos)
        {
            var posibles = digitos.Except(excluidos);

            var variaciones = new Variations<int>(posibles, 4);
            return variaciones.Select(variacion => new GeneradorDeNumero(variacion[0], variacion[1], variacion[2], variacion[3], excluidos.Union(variacion).ToList())).ToList();
        }
Пример #2
0
 static void Main()
 {
     int N = GetValidInput("Enter the upper margin for the number list ( 1 to N ): ", 2);
     //build the array
     List<int> numbers = new List<int>();
     for (int i = 1; i <= N; i++)
     {
         numbers.Add(i);
     }
     //get the number of ellements to be combined
     int K = GetValidInput("Enter the number of elements to ne combined :", 1);
     //generate a variations collection
     Variations<int> variations = new Variations<int>(numbers,K,GenerateOption.WithRepetition);
     //print the elements in the collection
     foreach (IList<int> p in variations)
     {
         foreach (var item in p)
         {
             Console.Write(item+" ");
         }
         Console.WriteLine();
     }
 }
Пример #3
0
 internal Base(BuilderService service) : base(service.Algorithm)
 {
     this.digestAlg = service.Digest;
     this.variation = service.Variation;
 }
Пример #4
0
 internal BuilderService(FipsAlgorithm algorithm, FipsDigestAlgorithm digestAlgorithm) : base(algorithm)
 {
     this.digestAlg = digestAlgorithm;
     this.variation = Variations.NONE;
 }
Пример #5
0
 internal BuilderService(FipsAlgorithm algorithm, Variations variation) : base(algorithm)
 {
     this.digestAlg = null;
     this.variation = variation;
 }
Пример #6
0
 /// <summary>
 /// Construct a enumerator with the parent object.
 /// </summary>
 /// <param name="source">The source Variations object.</param>
 public EnumeratorWithoutRepetition(Variations <T> source)
 {
     myParent = source;
     myPermutationsEnumerator = (Permutations <int> .Enumerator)myParent.myPermutations.GetEnumerator();
 }
Пример #7
0
        ///////////////////////////////////////////////
        private void verificationRelations_Click(object sender, EventArgs e)
        {
            if (calc.modulsAfterVerification.Count != 0)
            {
                relationsWithM_Click(sender, e);

                List<List<string>> temp = new List<List<string>>();
                temp.AddRange(calc.modulsAfterVerification);
                //temp.Remove(findFirstAndLast()[0]);
                //temp.Remove(findFirstAndLast()[1]);

                //Всі перестановки
                var permutationsP = new Variations<List<string>>(temp, temp.Count);//Всі перестановки

                int feedback = 1000;
                List<List<string>> permutatiOptimal = new List<List<string>>();
                List<List<string>> permutation = new List<List<string>>();

                foreach (var p in permutationsP)
                {
                    //permutation.Add(findFirstAndLast()[0]);
                    permutation.AddRange(p);
                    //permutation.Add(findFirstAndLast()[1]);

                    if (createEdgesAndFindMinFeedBack(permutation) < feedback)
                    {
                        feedback = createEdgesAndFindMinFeedBack(permutation);
                        permutatiOptimal.Clear();
                        permutatiOptimal.AddRange(permutation);
                    }
                    permutation.Clear();
                }
                /////////////////////
                createEdgesAndFindMinFeedBack(permutatiOptimal);
                outVModulsFrom(permutatiOptimal);
                textBox2.Text += "\r\nКількість зворотніх зв'язків: " + feedback;
                _gArea.RelayoutGraph();
            }
        }
Пример #8
0
        private static void Main(string[] args)
        {
            Console.Write("Enter the folder path to save the file: ");
            string folder = Console.ReadLine();

            Console.WriteLine("The generated file will be generated with number unique name");

StartTheProcess:
            int file = 0;

            Console.WriteLine("The longer you input, the longer the list");
            Console.Write(
                "Enter seed words with space (for example 'tran van tuan dep trai nguyen le an phuong xau xi'): ");
            string fullName = Console.ReadLine();

            string[] input = fullName.Split(' ');
            ObservableCollection <string> result = new ObservableCollection <string>();

            for (int i = 2; i <= input.Length; i++)
            {
                Variations <string> variations = new Variations <string>(input, i);
                foreach (IList <string> c in variations)
                {
                    string temp = "";

                    bool notAvaiName = false;

                    //Write first name
                    for (int index = 0; index < c.Count; index++)
                    {
                        string s = c[index];
                        int    n;
                        bool   isNumeric = int.TryParse(s, out n);

                        if (index == 0 && isNumeric)
                        {
                            notAvaiName = true;
                        }

                        if (!isNumeric && temp.Split('|').Count() < 3)
                        {
                            temp = temp + s + "|";
                        }
                    }

                    temp = temp + c.Aggregate("", (current, s) => current + s);
                    if (!notAvaiName)
                    {
                        result.Add(temp);
                        Console.WriteLine(temp);
                    }
                }
            }

            System.IO.File.WriteAllLines(folder + "\\result" + file + ".txt", result);
            file++;

            Console.WriteLine("You can continue generating another list with numberical file name");

            goto StartTheProcess;

            //Combinations<char> combinations = new Combinations<char>(inputSet, 3);
            //string cformat = "Combinations of {{A B C D}} choose 3: size = {0}";
            //Console.WriteLine(String.Format(cformat, combinations.Count));
            //foreach (IList<char> c in combinations)
            //{
            //    Console.WriteLine(String.Format("{{{0} {1} {2}}}", c[0], c[1], c[2]));
            //}

            //Variations<char> variations = new Variations<char>(inputSet, 2);
            //string vformat = "Variations of {{A B C D}} choose 2: size = {0}";
            //Console.WriteLine(String.Format(vformat, variations.Count));
            //foreach (IList<char> v in variations)
            //{
            //    Console.WriteLine(String.Format("{{{0} {1}}}", v[0], v[1]));
            //}
        }
Пример #9
0
        static void Main()
        {
            string seq = "cggtagagctggtgatgcggatgacagatgcgatgcagtttacataacgt";

            Console.WriteLine(seq + "\n");

            MonoDiCalc dinucCalc = new MonoDiCalc();
            var        dinuc     = dinucCalc.DiCalcReturn(seq);

            List <DinucDiff> dinucDiff = new List <DinucDiff>();

            foreach (var item in dinuc)
            {
                dinucDiff.Add(new DinucDiff {
                    dinucleotide = item.Item1, dinucleotideDiff = item.Item2 - item.Item3
                });
            }

            foreach (var item in dinucDiff)
            {
                Console.Write(item.dinucleotide + "\t");
            }
            Console.WriteLine();
            foreach (var item in dinucDiff)
            {
                Console.Write(item.dinucleotideDiff + "\t");
            }
            Console.WriteLine("\n\n");

            //dinucDiff = dinucDiff.OrderBy(x => x.dinucleotideDiff).ToList();
            dinucDiff = dinucDiff.OrderByDescending(x => x.dinucleotideDiff).ToList();
            foreach (var item in dinucDiff)
            {
                if (item.dinucleotideDiff != 0)
                {
                    Console.Write(item.dinucleotide + "\t");
                }
            }
            Console.WriteLine();
            foreach (var item in dinucDiff)
            {
                if (item.dinucleotideDiff != 0)
                {
                    Console.Write(item.dinucleotideDiff + "\t");
                }
            }

            List <string> dinucList = new List <string>();

            foreach (var item in dinucDiff)
            {
                if (item.dinucleotideDiff < 0)
                {
                    dinucList.Add(item.dinucleotide);
                }
            }
            Console.WriteLine();

            var permutateDinuc = new Variations <string>(dinucList, 2, GenerateOption.WithRepetition);

            foreach (var item in permutateDinuc)
            {
                Console.WriteLine(string.Join("", item));
            }

            EndRun.End();
        }
Пример #10
0
        private List<int[]> Combinations(int[] list, int Length)
        {
            List<int[]> pleaseOrder = new List<int[]>();
            Variations<int> comb = new Variations<int>(list, Length);
            decimal progress = (100 / (decimal)comb.Count);
            decimal progressCount = progress;


            pleaseOrder.Add(new int[Length]);
            int previousRounded = 0;
            foreach (List<int> inte in comb)
            {
                progressCount = progress + progressCount;

                int rounded = (int)Math.Round(progressCount);
                if (rounded > previousRounded)
                {
                    previousRounded = rounded;
                    progressBar1.Step = 1;
                    progressBar1.Increment(1);
                }
                bool add = true;
                inte.Sort();
                for (int tes = 0; tes < pleaseOrder.Count; tes++)
                {
                    int sameCount = 0;
                    for (int x = 0; x < pleaseOrder[tes].Length; x++)
                    {

                        var po = pleaseOrder[tes].ToArray<int>();
                        var intee = inte.ToArray<int>();
                        if (po[x] == intee[x])
                        {
                            sameCount++;
                        }

                    }
                    if (sameCount == Length)
                        add = false;
                }
                if (add)
                    pleaseOrder.Add(inte.ToArray<int>());


            }
            pleaseOrder.Remove(pleaseOrder[0]);
            if (progressBar1.Value == progressBar1.Maximum)
            {
                btnNext.Location = new Point(336, 177);
            }
            return pleaseOrder;
        }
Пример #11
0
        private Variation GenerateAllWordsVariations()
        {
            var variationModel = new Variation()
            {
                MaxVariations  = VariationModel.MaxVariations,
                MinVariations  = VariationModel.MinVariations,
                GenerateOption = VariationModel.GenerateOption,
            };

            if (VariationsGroups.Any())
            {
                variationModel.Variations = new HashSet <string>(VariationModel.Variations);
                Sender.GenericMessageBoxDuringBruteForce("Bruteforce info", $"Found {VariationsGroups.Count} groups to generate variations!");
                var forceBreakPreventOutMemory = false;
                Variations <string> variations;
                var lastWordGenerated = string.Empty;
                foreach (var wordVariation in VariationsGroups)
                {
                    for (int variationsCount = wordVariation.MinVariations; variationsCount <= wordVariation.MaxVariations; variationsCount++)
                    {
                        variations = new Variations <string>(wordVariation.Variations, variationsCount, wordVariation.GenerateOption);
                        foreach (var variation in variations)
                        {
                            if (GC.GetTotalMemory(false) >= 1_500_000_000)
                            {
                                lastWordGenerated = string.Join("", variation);
                                variationModel.Variations.Add(lastWordGenerated);
                                forceBreakPreventOutMemory = true;
                                break;
                            }
                            variationModel.Variations.Add(string.Join("", variation));
                        }

                        if (forceBreakPreventOutMemory)
                        {
                            break;
                        }
                    }

                    if (forceBreakPreventOutMemory)
                    {
                        break;
                    }
                }

                if (forceBreakPreventOutMemory)
                {
                    Sender.GenericMessageBoxDuringBruteForce("Bruteforce info", $"Not all variations were generated. Generations stopped to prevent out of memory exception." +
                                                             $"{Environment.NewLine}Hashes identified: {Hashes.Count}" +
                                                             $"{Environment.NewLine}Last word generated: {lastWordGenerated}" +
                                                             $"{Environment.NewLine}Total of strings to choose from: {variationModel.Variations.Count}");
                }
                else
                {
                    Sender.GenericMessageBoxDuringBruteForce("Bruteforce info", $"Generated all variations from groups!" +
                                                             $"{Environment.NewLine}Hashes identified: {Hashes.Count}" +
                                                             $"{Environment.NewLine}Total of strings to choose from: {variationModel.Variations.Count}");
                }
            }
            else
            {
                variationModel.Variations = new List <string>(VariationModel.Variations);
                Sender.GenericMessageBoxDuringBruteForce("Bruteforce info", $"No groups found to generate variations!" +
                                                         $"{Environment.NewLine}Hashes identified: {Hashes.Count}" +
                                                         $"{Environment.NewLine}Total of strings to choose from: {variationModel.Variations.Count}");
            }

            return(variationModel);
        }
        public virtual void TryInheritFrom(IEntity parent)
        {
            if (parent is IHasProperties hasProperties)
            {
                //Properties inheritance
                foreach (var parentProperty in hasProperties.Properties)
                {
                    var existProperty = Properties.FirstOrDefault(x => x.IsSame(parentProperty, PropertyType.Product, PropertyType.Variation));
                    if (existProperty != null)
                    {
                        existProperty.TryInheritFrom(parentProperty);
                        existProperty.ActualizeValues();
                    }
                    else
                    {
                        Properties.Add(parentProperty);
                    }
                }
            }

            if (parent is IHasTaxType hasTaxType)
            {
                //TODO: prevent saving the inherited simple values
                //TaxType  inheritance
                if (TaxType == null)
                {
                    TaxType = hasTaxType.TaxType;
                }
            }

            if (parent is CatalogProduct parentProduct)
            {
                var isVariation = GetType().IsAssignableFrom(typeof(Variation));
                //Inherit images from parent product (if its not set)
                if (Images.IsNullOrEmpty() && !parentProduct.Images.IsNullOrEmpty())
                {
                    Images = new List <Image>();
                    foreach (var parentImage in parentProduct.Images)
                    {
                        var image = AbstractTypeFactory <Image> .TryCreateInstance();

                        image.TryInheritFrom(parentImage);
                        Images.Add(image);
                    }
                }

                //Inherit assets from parent product (if its not set)
                if (Assets.IsNullOrEmpty() && !parentProduct.Assets.IsNullOrEmpty())
                {
                    Assets = new List <Asset>();
                    foreach (var parentAsset in parentProduct.Assets)
                    {
                        var asset = AbstractTypeFactory <Asset> .TryCreateInstance();

                        asset.TryInheritFrom(parentAsset);
                        Assets.Add(asset);
                    }
                }

                //inherit editorial reviews from main product and do not inherit if variation loaded within product
                if (!isVariation && Reviews.IsNullOrEmpty() && parentProduct.Reviews != null)
                {
                    Reviews = new List <EditorialReview>();
                    foreach (var parentReview in parentProduct.Reviews)
                    {
                        var review = AbstractTypeFactory <EditorialReview> .TryCreateInstance();

                        review.TryInheritFrom(parentReview);
                        Reviews.Add(review);
                    }
                }
                //inherit not overridden property values from main product
                foreach (var parentProductProperty in parentProduct.Properties)
                {
                    var existProperty = Properties.FirstOrDefault(x => x.IsSame(parentProductProperty, PropertyType.Product, PropertyType.Variation));
                    if (existProperty == null)
                    {
                        var property = AbstractTypeFactory <Property> .TryCreateInstance();

                        property.TryInheritFrom(parentProductProperty);
                        Properties.Add(parentProductProperty);
                    }
                }
                //TODO: prevent saving the inherited simple values
                Width       = Width ?? parentProduct.MainProduct.Width;
                Height      = Height ?? parentProduct.MainProduct.Height;
                Length      = Length ?? parentProduct.MainProduct.Length;
                MeasureUnit = MeasureUnit ?? parentProduct.MainProduct.MeasureUnit;
                Weight      = Weight ?? parentProduct.MainProduct.Weight;
                WeightUnit  = WeightUnit ?? parentProduct.MainProduct.WeightUnit;
                PackageType = PackageType ?? parentProduct.MainProduct.PackageType;

                if (!Variations.IsNullOrEmpty())
                {
                    foreach (var variation in Variations)
                    {
                        variation.TryInheritFrom(this);
                    }
                }
            }
        }
Пример #13
0
 public bool IsFavoriteButNotVariation(Variation variation)
 {
     return(Favorites.Contains(variation) && !Variations.Contains(variation));
 }
Пример #14
0
        /// <param name="generations">Number of generations to run the network for</param>
        /// <param name="links">Number of links between nodes when creating random network</param>
        /// <param name="nodes">Number of nodes to add when creating random network</param>
        /// <param name="stateFile">Saved SystemState file to re-run</param>
        static void Main(int generations = 100, int links = 4, int nodes = 20, FileInfo stateFile = null)
        {
            List <Node>      networkNodes;
            GenerationMatrix matrix;
            Guid             systemStateId;
            var nodeLinker     = new NodeLinker();
            var outputRenderer = new OutputRenderer();

            if (stateFile == null || !stateFile.Exists)
            {
                var nodeLabels  = Enumerable.Range(0, nodes).ToList();
                var combs       = new Variations <int>(nodeLabels, links);
                var nodeBuilder = new NodeBuilder(combs);
                matrix = new GenerationMatrix(links);

                networkNodes = nodeLabels.Select(label => nodeBuilder.CreateNode(label)).ToList();

                var systemState = new SystemState <GenerationMatrix, Node> {
                    MatrixState = matrix, NodeStates = networkNodes
                };
                systemStateId = systemState.StateId;
                File.WriteAllText(
                    $"state_{systemState.StateId}.json",
                    JsonSerializer.Serialize(systemState, new JsonSerializerOptions {
                    WriteIndented = true
                }));
            }
            else
            {
                using var streamReader = stateFile.OpenText();
                var json = streamReader.ReadToEnd();

                var systemState = JsonSerializer.Deserialize <SystemState <MatrixState, NodeState> >(json);
                systemStateId = systemState.StateId;

                matrix       = new GenerationMatrix(systemState.MatrixState);
                networkNodes = systemState.NodeStates.Select(ns => new Node(ns)).ToList();
            }


            nodeLinker.Link(networkNodes);
            var nodeIterator = new NodeIterator(networkNodes);

            List <string> output = new List <string>();

            for (int i = 0; i < generations; i++)
            {
                var states = new List <string>();
                nodeIterator.Execute(n => states.Add(n.ToString()));
                output.Add(string.Join(' ', states));

                nodeIterator.Execute(n => n.PrepareState(matrix));
                nodeIterator.Execute(n => n.UpdateState());
            }

            outputRenderer.Render(output);
            Console.WriteLine($"State Id: {systemStateId}");

            Console.WriteLine("\nDo you want to keep this system state? [y/n]");
            var input = Console.ReadLine();

            if ((stateFile == null && input.ToLower() != "y") || input.ToLower() == "n")
            {
                File.Delete($"state_{systemStateId}.json");
            }
        }
Пример #15
0
 public void VaryComponentUniform()
 {
     m_setCallback(Variations.VectorComponentUniform(m_lowScale, m_highScale),
                   Variations.VectorComponentUniform(m_lowRotation, m_highRotation),
                   Variations.VectorComponentUniform(m_lowTranslation, m_highTranslation));
 }
Пример #16
0
        public IList<GeneradorDeNumero> ObtenerPosibles(IEnumerable<GeneradorDeNumero> noPermitidos)
        {
            var posiblesValores = digitos.Except(DigitosExcluidos).ToList();
            var todoBien = posiblesValores.Count >= CantidadDeNulls;
            IList<GeneradorDeNumero> posibles = new List<GeneradorDeNumero>();
            if (todoBien)
            {
                var variaciones = new Variations<int>(posiblesValores, CantidadDeNulls);
                var todos = variaciones.Select(GenerarNumero).ToList();
                posibles = todos.Except(noPermitidos).ToList();
            }

            return posibles;
        }
Пример #17
0
 public void VaryComponentBellApproximation()
 {
     m_setCallback(Variations.VectorComponentBellApproximation(m_lowScale, m_highScale, 10),
                   Variations.VectorComponentBellApproximation(m_lowRotation, m_highRotation, 10),
                   Variations.VectorComponentBellApproximation(m_lowTranslation, m_highTranslation, 10));
 }
Пример #18
0
        private RouteInternal GetOptimizedPickupVariation
                 (IEnumerable<MatrixEntry> matrixDescendingDistanceFromDestination, int destinationId, int carCapacity)
        {
            //origin as the farest point from destination
            var originId = matrixDescendingDistanceFromDestination.First().OriginId;

            //selecting only ids from an ordered list of addresses to be used as feed to variations service
            var variationInput = matrixDescendingDistanceFromDestination.Select(a => a.OriginId).ToList();

            //must include all selected addresses to be able to pick to optimal variation
            Variations<int> variations = new Variations<int>(variationInput, carCapacity);

            //selecting only variations contains the origin address
            //the first seat plan had chance to have less pickups - thus, it is the best to include the farest point 
            var variationsIncludesOriginOnly = variations
                .Where(c => c.Contains(originId)).ToList();

            var alternatives = new List<RouteInternal>();

            foreach (var variation in variationsIncludesOriginOnly)
            {
                var variationResults = new RouteInternal();

                variationResults.Duration = 0;
                variationResults.PickupCount = carCapacity;

                for (int i = 0; i < variation.Count() - 1; i++)
                {
                    var leg = new LegInternal()
                    {
                        StartAddressId = variation[i],
                        EndAddressId = variation[i + 1],
                    };

                    leg.LegDuration = matrixDescendingDistanceFromDestination
                    .FirstOrDefault(mc => mc.OriginId == leg.StartAddressId
                                    && mc.DestinationId == leg.EndAddressId)
                                    .Value;

                    variationResults.Legs.Add(leg);
                    variationResults.Duration += leg.LegDuration;
                }

                //Add duration from end point of combo to destination
                var variationEndToDestination = matrixDescendingDistanceFromDestination
                    .First(a => a.OriginId == variation.Last());

                var legToDestination = new LegInternal()
                {
                    StartAddressId = variationEndToDestination.OriginId,
                    //EF circular cascade delete constraint forced to define this as nullable 
                    EndAddressId = variationEndToDestination.DestinationId,
                    LegDuration = variationEndToDestination.Value
                };

                variationResults.Legs.Add(legToDestination);
                variationResults.Duration += legToDestination.LegDuration;

                alternatives.Add(variationResults);
            }

            var optimalVariation = alternatives
                .First(o => o.Duration == alternatives.Min(op => op.Duration));

            optimalVariation.DestinationId = destinationId;
            return optimalVariation;
        }
Пример #19
0
        public virtual void TryInheritFrom(IEntity parent)
        {
            if (parent is IHasProperties hasProperties)
            {
                //Properties inheritance
                foreach (var parentProperty in hasProperties.Properties ?? Array.Empty <Property>())
                {
                    if (Properties == null)
                    {
                        Properties = new List <Property>();
                    }
                    var existProperty = Properties.FirstOrDefault(x => x.IsSame(parentProperty, PropertyType.Product, PropertyType.Variation));
                    if (existProperty == null)
                    {
                        existProperty = AbstractTypeFactory <Property> .TryCreateInstance();

                        Properties.Add(existProperty);
                    }
                    existProperty.TryInheritFrom(parentProperty);

                    existProperty.IsReadOnly = existProperty.Type != PropertyType.Variation && existProperty.Type != PropertyType.Product;
                }
                //Restore sorting order after changes
                if (Properties != null)
                {
                    Properties = Properties.OrderBy(x => x.Name).ToList();
                }
            }

            //TODO: prevent saving the inherited simple values
            //TaxType  inheritance
            if (parent is IHasTaxType hasTaxType && TaxType == null)
            {
                TaxType = hasTaxType.TaxType;
            }

            if (!Variations.IsNullOrEmpty())
            {
                foreach (var variation in Variations)
                {
                    variation.TryInheritFrom(this);
                }
            }

            if (parent is CatalogProduct parentProduct)
            {
                var isVariation = GetType().IsAssignableFrom(typeof(Variation));
                //Inherit images from parent product (if its not set)
                if (Images.IsNullOrEmpty() && !parentProduct.Images.IsNullOrEmpty())
                {
                    Images = new List <Image>();
                    foreach (var parentImage in parentProduct.Images)
                    {
                        var image = AbstractTypeFactory <Image> .TryCreateInstance();

                        image.TryInheritFrom(parentImage);
                        Images.Add(image);
                    }
                }

                //Inherit assets from parent product (if its not set)
                if (Assets.IsNullOrEmpty() && !parentProduct.Assets.IsNullOrEmpty())
                {
                    Assets = new List <Asset>();
                    foreach (var parentAsset in parentProduct.Assets)
                    {
                        var asset = AbstractTypeFactory <Asset> .TryCreateInstance();

                        asset.TryInheritFrom(parentAsset);
                        Assets.Add(asset);
                    }
                }

                //inherit editorial reviews from main product and do not inherit if variation loaded within product
                if (!isVariation && Reviews.IsNullOrEmpty() && parentProduct.Reviews != null)
                {
                    Reviews = new List <EditorialReview>();
                    foreach (var parentReview in parentProduct.Reviews)
                    {
                        var review = AbstractTypeFactory <EditorialReview> .TryCreateInstance();

                        review.TryInheritFrom(parentReview);
                        Reviews.Add(review);
                    }
                }
                //inherit not overridden property values from main product
                foreach (var parentProductProperty in parentProduct.Properties ?? Array.Empty <Property>())
                {
                    var existProperty = Properties.FirstOrDefault(x => x.IsSame(parentProductProperty, PropertyType.Product, PropertyType.Variation));
                    if (existProperty == null)
                    {
                        existProperty = AbstractTypeFactory <Property> .TryCreateInstance();

                        Properties.Add(existProperty);
                    }
                    existProperty.TryInheritFrom(parentProductProperty);
                    existProperty.IsReadOnly = existProperty.Type != PropertyType.Variation && existProperty.Type != PropertyType.Product;

                    //Inherit only parent Product properties  values if own values aren't set
                    if (parentProductProperty.Type == PropertyType.Product && existProperty.Values.IsNullOrEmpty() && !parentProductProperty.Values.IsNullOrEmpty())
                    {
                        existProperty.Values = new List <PropertyValue>();
                        foreach (var parentPropValue in parentProductProperty.Values)
                        {
                            var propValue = AbstractTypeFactory <PropertyValue> .TryCreateInstance();

                            propValue.TryInheritFrom(parentPropValue);
                            existProperty.Values.Add(propValue);
                        }
                    }
                }
                //TODO: prevent saving the inherited simple values
                Width       = parentProduct.Width ?? Width;
                Height      = parentProduct.Height ?? Height;
                Length      = parentProduct.Length ?? Length;
                MeasureUnit = parentProduct.MeasureUnit ?? MeasureUnit;
                Weight      = parentProduct.Weight ?? Weight;
                WeightUnit  = parentProduct.WeightUnit ?? WeightUnit;
                PackageType = parentProduct.PackageType ?? PackageType;
            }
        }
Пример #20
0
        public void Generate_Variations_of_3_With_Repetition_On_6_Input_Items_Should_Create_216_Output_Items()
        {
            var integers = new List<int> { 1, 2, 3, 4, 5, 6 };

            var v = new Variations<int>(integers, 3, GenerateOption.WithRepetition);

            foreach (var vv in v)
            {
                System.Diagnostics.Debug.WriteLine(string.Join(",", vv));
            }

            Assert.AreEqual(216, v.Count);
        }
Пример #21
0
        public string Cipher(string text, bool encrypt)
        {
            string result = "";

            var randomLenght = new Random(Random.Next());
            var randomLetter = new Random(Random.Next());

            var data = text.Split(':').ToList();

            data.RemoveAt(data.Count - 1);
            for (int i = 0; i < data.Count; i += 3)
            {
                Persons.Add(new Person(data[i], data[i + 1], data[i + 2]));
            }

            //Console.WriteLine("SELECT METHOD TO LOOK UP PASSWORDS:\n 1.Names with one big letter\n 2. 6-7 long random lower letters passwords\n 3. 4-5 long random lower/upper + numbers passwords");
            var num = "3";

            var tokenSource = new CancellationTokenSource();
            var token       = tokenSource.Token;

            switch (num)
            {
            case "1":
                var sr       = new StreamReader("..//..//..//test//updated_names.txt");
                var allNames = sr.ReadToEnd();
                var names    = allNames.Split('\n', StringSplitOptions.None).ToList();

                foreach (var person in Persons)
                {
                    var pom = names.FirstOrDefault(s => crypt(s, person.Salt) == person.Md5);
                    if (!string.IsNullOrEmpty(pom))
                    {
                        result += "User: "******" password is: " + pom + "\n";
                    }
                }
                break;

            case "2":
                var alphabet  = "abcdefghijklmnopqrstuvwxyz".ToList();
                var alphabet2 = alphabet.OrderByDescending(x => x).ToList();
                var alphabet3 = "mnopqrstuvwxyzabcdefghijkl".ToList();
                var alphabet4 = "lkjihgfedcbazyxwvutsrpqonm".ToList();

                var tasks = new Task <string> [alphabet.Count];
                for (int i = 0; i < alphabet.Count; i++)
                {
                    var cb = new Variations <char>(alphabet, 6, GenerateOption.WithRepetition);
                    var t  = Task.Factory.StartNew(() => BruteForce(cb, i), token);
                    tasks[i] = t;
                    alphabet = alphabet.ShiftLeft(1);
                }
                var ended = Task.WaitAny(tasks);
                result += tasks[ended].Result;
                tokenSource.Cancel();

                //var combs = new Variations<char>(alphabet, 6, GenerateOption.WithoutRepetition);
                //var combs2 = new Variations<char>(alphabet2, 6, GenerateOption.WithoutRepetition);
                //var combs3 = new Variations<char>(alphabet3, 6, GenerateOption.WithoutRepetition);
                //var combs4 = new Variations<char>(alphabet4, 6, GenerateOption.WithoutRepetition);
                //var tasks = new Task<string>[4];
                //var q = alphabet.Select(x => x.ToString());
                //int size = 7;
                //for (int i = 0; i < size - 1; i++)
                //    q = q.SelectMany(x => alphabet, (x, y) => x + y);
                //var cc = q.ToList();
                //var possiblePasswords = SplitList(cc, cc.Count / 10).ToList();


                //var task1 = Task.Factory.StartNew(() => BruteForce(persons, combs, 1), token);
                //tasks[0] = task1;
                //var task2 = Task.Factory.StartNew(() => BruteForce(persons, combs2, 2), token);
                //tasks[1] = task1;
                //var task3 = Task.Factory.StartNew(() => BruteForce(persons, combs3, 3), token);
                //tasks[2] = task1;
                //var task4 = Task.Factory.StartNew(() => BruteForce(persons, combs4, 4), token);
                //tasks[3] = task1;
                //var task5 = Task.Factory.StartNew(() => BruteForce(persons, possiblePasswords[4], 4));
                //var task6 = Task.Factory.StartNew(() => BruteForce(persons, possiblePasswords[5], 5));
                //var task7 = Task.Factory.StartNew(() => BruteForce(persons, possiblePasswords[6], 6));
                //var task8 = Task.Factory.StartNew(() => BruteForce(persons, possiblePasswords[7], 7));
                //var task9 = Task.Factory.StartNew(() => BruteForce(persons, possiblePasswords[8], 8));
                //var task10 = Task.Factory.StartNew(() => BruteForce(persons, possiblePasswords[9], 9));
                //Task.WaitAll(task1);


                //result += task1.Result + task2.Result + task3.Result + task4.Result + task5.Result + task6.Result +
                //          task7.Result + task8.Result + task9.Result + task10.Result;

                break;

            case "3":

                var a         = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789".ToList();
                var variation = new Variations <char>(a, 4, GenerateOption.WithRepetition);

                var tasks2 = new Task <string> [a.Count];
                for (int i = 0; i < a.Count; i++)
                {
                    var cb = new Variations <char>(a, 4, GenerateOption.WithRepetition);
                    var t  = Task.Factory.StartNew(() => BruteForce(cb, i), token);
                    tasks2[i] = t;
                    a         = a.ShiftLeft(1);
                }
                var e = Task.WaitAny(tasks2);
                result += tasks2[e].Result;
                tokenSource.Cancel();

                break;

            default:
                break;
            }

            var bw = new BinaryWriter(File.Open($"C:\\Users\\Marek\\Desktop\\heslaShadow{Shadow}.txt", FileMode.OpenOrCreate));

            bw.Write(result);
            Console.WriteLine($"SHADOW{Shadow} FOUND!!!");

            return(string.IsNullOrEmpty(result) ? "No results" : result);
        }
Пример #22
0
        private void BuildPermuations()
        {
            var permuations = new Variations<int>(Source, 4, GenerateOption.WithoutRepetition);

            _allCodes = new List<IReadOnlyList<int>>();
            foreach (var permuation in permuations)
            {
                _allCodes.Add(permuation.ToList().AsReadOnly());
            }
        }
Пример #23
0
 /// <summary>
 /// Construct a enumerator with the parent object.
 /// </summary>
 /// <param name="source">The source Variations object.</param>
 public EnumeratorWithRepetition(Variations <T> source)
 {
     myParent = source;
     Reset();
 }