Exemple #1
0
    public static void Main()
    {
        System.Collections.Concurrent.ConcurrentBag <int> bag = new System.Collections.Concurrent.ConcurrentBag <int>();
        // Test Bag Parallel
        Stopwatch t = Stopwatch.StartNew();

        System.Threading.Tasks.Parallel.For(0, 500000, index =>
        {
            bag.Add(index);
        });
        t.Stop();
        Console.WriteLine("Parallel Bag test completed in " + t.ElapsedTicks.ToString());
        // Test Bag Incremental
        bag = new System.Collections.Concurrent.ConcurrentBag <int>();
        t   = Stopwatch.StartNew();
        for (int index = 0; index <= 500000; index += 1)
        {
            bag.Add(index);
        }
        t.Stop();
        Console.WriteLine("Incremental Bag test completed in " + t.ElapsedTicks.ToString());
        bag = null;
        // Test List Incremental
        t = Stopwatch.StartNew();
        System.Collections.Generic.List <int> lst = new System.Collections.Generic.List <int>();
        t = Stopwatch.StartNew();
        for (int index = 0; index <= 500000; index += 1)
        {
            lst.Add(index);
        }
        t.Stop();
        Console.WriteLine("Incremental list test completed in " + t.ElapsedTicks.ToString());
    }
    /// <summary>
    /// Uses Monte Carlo search to suggest the number column to play in.
    /// </summary>
    /// <param name="game"></param>
    /// <param name="playerID"></param>
    /// <returns></returns>
    internal int SuggestMove(Game game, Guid playerID)
    {
        var playerIsYellow = game.YellowPlayerID == playerID;

        // Start with the current state of the board.
        var currentState = new Node()
        {
            NumberOfWins = 0, PlayCount = 0, Game = game, Parent = null
        };

        // Work out which is the best out of the available moves.
        var availableMoves = game.GetAvailableMoves();

        //Score, ColumnNumber
        var scores = new System.Collections.Concurrent.ConcurrentBag <Tuple <decimal, int> >();

        Parallel.For(0, availableMoves.Count, columnToPlay =>
        {
            // Have we just won,  in which case we are done!
            if (game.IsWinningMove(columnToPlay, playerIsYellow))
            {
                scores.Add(new Tuple <decimal, int>(decimal.MaxValue, columnToPlay));
            }
            else
            {
                // Get the game after applying the move
                var childGame = game.EffectOfMakingMove(playerIsYellow, columnToPlay);
                var childNode = new Node()
                {
                    NumberOfWins = 0, PlayCount = 0, Game = childGame, Parent = null
                };

                // How successfully were we playing down from here?
                PlayToDepth(1, childNode, !playerIsYellow, playerIsYellow);

                if (childNode.PlayCount > 0)
                {
                    decimal score = (decimal)childNode.NumberOfWins / childNode.PlayCount;
                    scores.Add(new Tuple <decimal, int>(score, columnToPlay));
                }
            }
        });

        // Find the highest scoring column
        var bestScore  = decimal.MinValue;
        var bestColumn = -1;

        foreach (var result in scores)
        {
            if (result.Item1 > bestScore)
            {
                bestScore  = result.Item1;
                bestColumn = result.Item2;
            }
        }

        return(bestColumn);
    }
Exemple #3
0
    public static void Init()
    {
        drivers = new System.Collections.Concurrent.ConcurrentBag <IDriver>();
        drivers.Add(new USBHIDDriver());
        //drivers.Add(new BootloaderHidDriver());
        simdriver = new SIMDriver();
        drivers.Add(simdriver);

        System.Threading.Thread t = new System.Threading.Thread(() =>
        {
            while (bexit == false)
            {
                System.Threading.Thread.Sleep(1000);
                _Check();
            }
        }
                                                                );
        bexit = false;
        t.Start();
        _Check();
    }
Exemple #4
0
    public void Populate()
    {
        #region Types of Keywords

        FieldPublicDynamic = new { PropPublic1 = "A", PropPublic2 = 1, PropPublic3 = "B", PropPublic4 = "B", PropPublic5 = "B", PropPublic6 = "B", PropPublic7 = "B", PropPublic8 = "B", PropPublic9 = "B", PropPublic10 = "B", PropPublic11 = "B", PropPublic12 = new { PropSubPublic1 = 0, PropSubPublic2 = 1, PropSubPublic3 = 2 } };
        FieldPublicObject  = new StringBuilder("Object - StringBuilder");
        FieldPublicInt32   = int.MaxValue;
        FieldPublicInt64   = long.MaxValue;
        FieldPublicULong   = ulong.MaxValue;
        FieldPublicUInt    = uint.MaxValue;
        FieldPublicDecimal = 100000.999999m;
        FieldPublicDouble  = 100000.999999d;
        FieldPublicChar    = 'A';
        FieldPublicByte    = byte.MaxValue;
        FieldPublicBoolean = true;
        FieldPublicSByte   = sbyte.MaxValue;
        FieldPublicShort   = short.MaxValue;
        FieldPublicUShort  = ushort.MaxValue;
        FieldPublicFloat   = 100000.675555f;

        FieldPublicInt32Nullable   = int.MaxValue;
        FieldPublicInt64Nullable   = 2;
        FieldPublicULongNullable   = ulong.MaxValue;
        FieldPublicUIntNullable    = uint.MaxValue;
        FieldPublicDecimalNullable = 100000.999999m;
        FieldPublicDoubleNullable  = 100000.999999d;
        FieldPublicCharNullable    = 'A';
        FieldPublicByteNullable    = byte.MaxValue;
        FieldPublicBooleanNullable = true;
        FieldPublicSByteNullable   = sbyte.MaxValue;
        FieldPublicShortNullable   = short.MaxValue;
        FieldPublicUShortNullable  = ushort.MaxValue;
        FieldPublicFloatNullable   = 100000.675555f;

        #endregion

        #region System

        FieldPublicDateTime         = new DateTime(2000, 1, 1, 1, 1, 1);
        FieldPublicTimeSpan         = new TimeSpan(1, 10, 40);
        FieldPublicEnumDateTimeKind = DateTimeKind.Local;

        // Instantiate date and time using Persian calendar with years,
        // months, days, hours, minutes, seconds, and milliseconds
        FieldPublicDateTimeOffset = new DateTimeOffset(1387, 2, 12, 8, 6, 32, 545,
                                                       new System.Globalization.PersianCalendar(),
                                                       new TimeSpan(1, 0, 0));

        FieldPublicIntPtr         = new IntPtr(100);
        FieldPublicTimeZone       = TimeZone.CurrentTimeZone;
        FieldPublicTimeZoneInfo   = TimeZoneInfo.Utc;
        FieldPublicTuple          = Tuple.Create <string, int, decimal>("T-string\"", 1, 1.1m);
        FieldPublicType           = typeof(object);
        FieldPublicUIntPtr        = new UIntPtr(100);
        FieldPublicUri            = new Uri("http://www.site.com");
        FieldPublicVersion        = new Version(1, 0, 100, 1);
        FieldPublicGuid           = new Guid("d5010f5b-0cd1-44ca-aacb-5678b9947e6c");
        FieldPublicSingle         = Single.MaxValue;
        FieldPublicException      = new Exception("Test error", new Exception("inner exception"));
        FieldPublicEnumNonGeneric = EnumTest.ValueA;
        FieldPublicAction         = () => true.Equals(true);
        FieldPublicAction2        = (a, b) => true.Equals(true);
        FieldPublicFunc           = () => true;
        FieldPublicFunc2          = (a, b) => true;

        #endregion

        #region Arrays and Collections

        FieldPublicArrayUni    = new string[2];
        FieldPublicArrayUni[0] = "[0]";
        FieldPublicArrayUni[1] = "[1]";

        FieldPublicArrayTwo       = new string[2, 2];
        FieldPublicArrayTwo[0, 0] = "[0, 0]";
        FieldPublicArrayTwo[0, 1] = "[0, 1]";
        FieldPublicArrayTwo[1, 0] = "[1, 0]";
        FieldPublicArrayTwo[1, 1] = "[1, 1]";

        FieldPublicArrayThree          = new string[1, 1, 2];
        FieldPublicArrayThree[0, 0, 0] = "[0, 0, 0]";
        FieldPublicArrayThree[0, 0, 1] = "[0, 0, 1]";

        FieldPublicJaggedArrayTwo    = new string[2][];
        FieldPublicJaggedArrayTwo[0] = new string[5] {
            "a", "b", "c", "d", "e"
        };
        FieldPublicJaggedArrayTwo[1] = new string[4] {
            "a1", "b1", "c1", "d1"
        };

        FieldPublicJaggedArrayThree          = new string[1][][];
        FieldPublicJaggedArrayThree[0]       = new string[1][];
        FieldPublicJaggedArrayThree[0][0]    = new string[2];
        FieldPublicJaggedArrayThree[0][0][0] = "[0][0][0]";
        FieldPublicJaggedArrayThree[0][0][1] = "[0][0][1]";

        FieldPublicMixedArrayAndJagged = new int[3][, ]
        {
            new int[, ] {
                { 1, 3 }, { 5, 7 }
            },
            new int[, ] {
                { 0, 2 }, { 4, 6 }, { 8, 10 }
            },
            new int[, ] {
                { 11, 22 }, { 99, 88 }, { 0, 9 }
            }
        };

        FieldPublicDictionary = new System.Collections.Generic.Dictionary <string, string>();
        FieldPublicDictionary.Add("Key1", "Value1");
        FieldPublicDictionary.Add("Key2", "Value2");
        FieldPublicDictionary.Add("Key3", "Value3");
        FieldPublicDictionary.Add("Key4", "Value4");

        FieldPublicList = new System.Collections.Generic.List <int>();
        FieldPublicList.Add(0);
        FieldPublicList.Add(1);
        FieldPublicList.Add(2);

        FieldPublicQueue = new System.Collections.Generic.Queue <int>();
        FieldPublicQueue.Enqueue(10);
        FieldPublicQueue.Enqueue(11);
        FieldPublicQueue.Enqueue(12);

        FieldPublicHashSet = new System.Collections.Generic.HashSet <string>();
        FieldPublicHashSet.Add("HashSet1");
        FieldPublicHashSet.Add("HashSet2");

        FieldPublicSortedSet = new System.Collections.Generic.SortedSet <string>();
        FieldPublicSortedSet.Add("SortedSet1");
        FieldPublicSortedSet.Add("SortedSet2");
        FieldPublicSortedSet.Add("SortedSet3");

        FieldPublicStack = new System.Collections.Generic.Stack <string>();
        FieldPublicStack.Push("Stack1");
        FieldPublicStack.Push("Stack2");
        FieldPublicStack.Push("Stack3");

        FieldPublicLinkedList = new System.Collections.Generic.LinkedList <string>();
        FieldPublicLinkedList.AddFirst("LinkedList1");
        FieldPublicLinkedList.AddLast("LinkedList2");
        FieldPublicLinkedList.AddAfter(FieldPublicLinkedList.Find("LinkedList1"), "LinkedList1.1");

        FieldPublicObservableCollection = new System.Collections.ObjectModel.ObservableCollection <string>();
        FieldPublicObservableCollection.Add("ObservableCollection1");
        FieldPublicObservableCollection.Add("ObservableCollection2");

        FieldPublicKeyedCollection = new MyDataKeyedCollection();
        FieldPublicKeyedCollection.Add(new MyData()
        {
            Data = "data1", Id = 0
        });
        FieldPublicKeyedCollection.Add(new MyData()
        {
            Data = "data2", Id = 1
        });

        var list = new List <string>();
        list.Add("list1");
        list.Add("list2");
        list.Add("list3");

        FieldPublicReadOnlyCollection = new ReadOnlyCollection <string>(list);

        FieldPublicReadOnlyDictionary           = new ReadOnlyDictionary <string, string>(FieldPublicDictionary);
        FieldPublicReadOnlyObservableCollection = new ReadOnlyObservableCollection <string>(FieldPublicObservableCollection);
        FieldPublicCollection = new Collection <string>();
        FieldPublicCollection.Add("collection1");
        FieldPublicCollection.Add("collection2");
        FieldPublicCollection.Add("collection3");

        FieldPublicArrayListNonGeneric = new System.Collections.ArrayList();
        FieldPublicArrayListNonGeneric.Add(1);
        FieldPublicArrayListNonGeneric.Add("a");
        FieldPublicArrayListNonGeneric.Add(10.0m);
        FieldPublicArrayListNonGeneric.Add(new DateTime(2000, 01, 01));

        FieldPublicBitArray    = new System.Collections.BitArray(3);
        FieldPublicBitArray[2] = true;

        FieldPublicSortedList = new System.Collections.SortedList();
        FieldPublicSortedList.Add("key1", 1);
        FieldPublicSortedList.Add("key2", 2);
        FieldPublicSortedList.Add("key3", 3);
        FieldPublicSortedList.Add("key4", 4);

        FieldPublicHashtableNonGeneric = new System.Collections.Hashtable();
        FieldPublicHashtableNonGeneric.Add("key1", 1);
        FieldPublicHashtableNonGeneric.Add("key2", 2);
        FieldPublicHashtableNonGeneric.Add("key3", 3);
        FieldPublicHashtableNonGeneric.Add("key4", 4);

        FieldPublicQueueNonGeneric = new System.Collections.Queue();
        FieldPublicQueueNonGeneric.Enqueue("QueueNonGeneric1");
        FieldPublicQueueNonGeneric.Enqueue("QueueNonGeneric2");
        FieldPublicQueueNonGeneric.Enqueue("QueueNonGeneric3");

        FieldPublicStackNonGeneric = new System.Collections.Stack();
        FieldPublicStackNonGeneric.Push("StackNonGeneric1");
        FieldPublicStackNonGeneric.Push("StackNonGeneric2");

        FieldPublicIEnumerable = FieldPublicSortedList;

        FieldPublicBlockingCollection = new System.Collections.Concurrent.BlockingCollection <string>();
        FieldPublicBlockingCollection.Add("BlockingCollection1");
        FieldPublicBlockingCollection.Add("BlockingCollection2");

        FieldPublicConcurrentBag = new System.Collections.Concurrent.ConcurrentBag <string>();
        FieldPublicConcurrentBag.Add("ConcurrentBag1");
        FieldPublicConcurrentBag.Add("ConcurrentBag2");
        FieldPublicConcurrentBag.Add("ConcurrentBag3");

        FieldPublicConcurrentDictionary = new System.Collections.Concurrent.ConcurrentDictionary <string, int>();
        FieldPublicConcurrentDictionary.GetOrAdd("ConcurrentDictionary1", 0);
        FieldPublicConcurrentDictionary.GetOrAdd("ConcurrentDictionary2", 0);

        FieldPublicConcurrentQueue = new System.Collections.Concurrent.ConcurrentQueue <string>();
        FieldPublicConcurrentQueue.Enqueue("ConcurrentQueue1");
        FieldPublicConcurrentQueue.Enqueue("ConcurrentQueue2");

        FieldPublicConcurrentStack = new System.Collections.Concurrent.ConcurrentStack <string>();
        FieldPublicConcurrentStack.Push("ConcurrentStack1");
        FieldPublicConcurrentStack.Push("ConcurrentStack2");

        // FieldPublicOrderablePartitioner = new OrderablePartitioner();
        // FieldPublicPartitioner;
        // FieldPublicPartitionerNonGeneric;

        FieldPublicHybridDictionary = new System.Collections.Specialized.HybridDictionary();
        FieldPublicHybridDictionary.Add("HybridDictionaryKey1", "HybridDictionary1");
        FieldPublicHybridDictionary.Add("HybridDictionaryKey2", "HybridDictionary2");

        FieldPublicListDictionary = new System.Collections.Specialized.ListDictionary();
        FieldPublicListDictionary.Add("ListDictionaryKey1", "ListDictionary1");
        FieldPublicListDictionary.Add("ListDictionaryKey2", "ListDictionary2");
        FieldPublicNameValueCollection = new System.Collections.Specialized.NameValueCollection();
        FieldPublicNameValueCollection.Add("Key1", "Value1");
        FieldPublicNameValueCollection.Add("Key2", "Value2");

        FieldPublicOrderedDictionary = new System.Collections.Specialized.OrderedDictionary();
        FieldPublicOrderedDictionary.Add(1, "OrderedDictionary1");
        FieldPublicOrderedDictionary.Add(2, "OrderedDictionary1");
        FieldPublicOrderedDictionary.Add("OrderedDictionaryKey2", "OrderedDictionary2");

        FieldPublicStringCollection = new System.Collections.Specialized.StringCollection();
        FieldPublicStringCollection.Add("StringCollection1");
        FieldPublicStringCollection.Add("StringCollection2");

        #endregion

        #region Several

        PropXmlDocument = new XmlDocument();
        PropXmlDocument.LoadXml("<xml>something</xml>");

        var tr = new StringReader("<Root>Content</Root>");
        PropXDocument         = XDocument.Load(tr);
        PropStream            = GenerateStreamFromString("Stream");
        PropBigInteger        = new System.Numerics.BigInteger(100);
        PropStringBuilder     = new StringBuilder("StringBuilder");
        FieldPublicIQueryable = new List <string>()
        {
            "IQueryable"
        }.AsQueryable();

        #endregion

        #region Custom

        FieldPublicMyCollectionPublicGetEnumerator           = new MyCollectionPublicGetEnumerator("a b c", new char[] { ' ' });
        FieldPublicMyCollectionInheritsPublicGetEnumerator   = new MyCollectionInheritsPublicGetEnumerator("a b c", new char[] { ' ' });
        FieldPublicMyCollectionExplicitGetEnumerator         = new MyCollectionExplicitGetEnumerator("a b c", new char[] { ' ' });
        FieldPublicMyCollectionInheritsExplicitGetEnumerator = new MyCollectionInheritsExplicitGetEnumerator("a b c", new char[] { ' ' });
        FieldPublicMyCollectionInheritsTooIEnumerable        = new MyCollectionInheritsTooIEnumerable("a b c", new char[] { ' ' });

        FieldPublicEnumSpecific = EnumTest.ValueB;
        MyDelegate            = MethodDelegate;
        EmptyClass            = new EmptyClass();
        StructGeneric         = new ThreeTuple <int>(0, 1, 2);
        StructGenericNullable = new ThreeTuple <int>(0, 1, 2);
        FieldPublicNullable   = new Nullable <ThreeTuple <int> >(StructGeneric);

        #endregion
    }
Exemple #5
0
    public static void ImplementBamlInit(Builder builder)
    {
        if (builder.ResourceNames == null)
        {
            return;
        }

        var xamlList = builder.ResourceNames.Where(x => x.EndsWith(".baml")).Select(x => x.Replace(".baml", ".xaml")).ToArray();

        builder.Log(LogTypes.Info, "Checking for xaml/baml resources without initializers.");

        var resourceDictionary = new __ResourceDictionary();

        builder.Log(LogTypes.Info, "Implementing XAML initializer for baml resources.");

        // First we have to find every InitializeComponent method so that we can remove bamls that are already initialized.
        var allInitializeComponentMethods = builder.FindMethodsByName(SearchContext.Module, "InitializeComponent", 0).Where(x => !x.IsAbstract);
        var ldStrs = new System.Collections.Concurrent.ConcurrentBag <string>();

        System.Threading.Tasks.Parallel.ForEach(allInitializeComponentMethods, methods =>
        {
            foreach (var str in methods.GetLoadStrings())
            {
                ldStrs.Add(str);
            }
        });

        var xamlWithInitializers         = ldStrs.Select(x => x.Substring(x.IndexOf("component/") + "component/".Length)).ToArray();
        var xamlThatRequiredInitializers = xamlList
                                           .Where(x => !xamlWithInitializers.Contains(x))
                                           .Select(x =>
        {
            var index = uint.MaxValue;
            if (x.IndexOf('-') > 0)
            {
                var dashPosition  = x.LastIndexOf('-') + 1;
                var pointPosition = x.IndexOf('.', dashPosition);

                uint result;
                if (uint.TryParse(x.Substring(dashPosition, pointPosition > dashPosition ? pointPosition - dashPosition : x.Length - dashPosition), out result))
                {
                    index = result;
                }
            }

            return(new { Index = index, Item = x });
        })
                                           .OrderBy(x => x.Index)
                                           .ThenBy(x => x.Item)
                                           .ToArray();

        var resourceDictionaryMergerClass = builder.CreateType("XamlGeneratedNamespace", TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Sealed, "<>_generated_resourceDictionary_Loader");

        resourceDictionaryMergerClass.CustomAttributes.Add(BuilderTypes.ComponentAttribute.BuilderType, __ResourceDictionary.Type.Fullname);
        resourceDictionaryMergerClass.CustomAttributes.AddEditorBrowsableAttribute(EditorBrowsableState.Never);
        resourceDictionaryMergerClass.CustomAttributes.AddCompilerGeneratedAttribute();

        //var method = resourceDictionaryMergerClass.CreateMethod(Modifiers.Private, "AddToDictionary", typeof(string));
        resourceDictionaryMergerClass.CreateConstructor().NewCoder().Context(context =>
        {
            var resourceDick = context.AssociatedMethod.GetOrCreateVariable(BuilderTypes.ICollection1.BuilderType.MakeGeneric(__ResourceDictionary.Type));
            context
            .SetValue(resourceDick, x =>
                      x.Call(BuilderTypes.Application.GetMethod_get_Current())
                      .Call(BuilderTypes.Application.GetMethod_get_Resources())
                      .Call(resourceDictionary.MergedDictionaries));

            var resourceDictionaryInstance = context.AssociatedMethod.GetOrCreateVariable(__ResourceDictionary.Type);

            foreach (var item in xamlThatRequiredInitializers)
            {
                builder.Log(LogTypes.Info, $"- Adding XAML '{item.Item}' with index '{item.Index}' to the Application's MergeDictionary");
                context.SetValue(resourceDictionaryInstance, x => x.NewObj(resourceDictionary.Ctor));
                context.Load(resourceDictionaryInstance)
                .Call(resourceDictionary.SetSource,
                      x => x.NewObj(BuilderTypes.Uri.GetMethod_ctor(), $"pack://application:,,,/{Path.GetFileNameWithoutExtension(builder.Name)};component/{item.Item}"));
                context.Load(resourceDick)
                .Call(BuilderTypes.ICollection1.GetMethod_Add().MakeGeneric(__ResourceDictionary.Type), resourceDictionaryInstance);
            }

            return(context);
        })
        .Return()
        .Replace();

        // Let us look for ResourceDictionaries without a InitializeComponent in their ctor
        // TODO

        resourceDictionaryMergerClass.ParameterlessContructor.CustomAttributes.AddEditorBrowsableAttribute(EditorBrowsableState.Never);
        resourceDictionaryMergerClass.ParameterlessContructor.CustomAttributes.Add(BuilderTypes.ComponentConstructorAttribute.BuilderType);
    }