コード例 #1
1
        public static CompilerResults CompileFile(string input, string output, params string[] references)
        {
            CreateOutput(output);

            List<string> referencedAssemblies = new List<string>(references.Length + 3);

            referencedAssemblies.AddRange(references);
            referencedAssemblies.Add("System.dll");
            referencedAssemblies.Add(typeof(IModule).Assembly.CodeBase.Replace(@"file:///", ""));
            referencedAssemblies.Add(typeof(ModuleAttribute).Assembly.CodeBase.Replace(@"file:///", ""));

            CSharpCodeProvider codeProvider = new CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters(referencedAssemblies.ToArray(), output);

            using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(input))
            {
                if (stream == null)
                {
                    throw new ArgumentException("input");
                }

                StreamReader reader = new StreamReader(stream);
                string source = reader.ReadToEnd();
                CompilerResults results = codeProvider.CompileAssemblyFromSource(cp, source);
                ThrowIfCompilerError(results);
                return results;
            }
        }
コード例 #2
1
        private static IEnumerable<long> Eratostenes()
        {
            const int max = 2000000;
            var primes = new List<long>();
            var crossedOff = new HashSet<long>();

            long candidate = 1;

            while (candidate < max)
            {
                candidate++;

                if (crossedOff.Contains(candidate))
                {
                    continue;
                }

                primes.Add(candidate);

                // remove multiples of candidate
                for (var i = candidate; i < max + 1; i += candidate)
                {
                    crossedOff.Add(i);
                }
            }

            return primes.ToArray();
        }
コード例 #3
0
ファイル: HuffmanTreeTest.cs プロジェクト: rsgoheen/Compress
        public void TestEncodeDecodeWithCompression()
        {
            var input =
            "He paused for a moment, many recollections overpowering him. Then he went on telling her the history of his life, unfolding to her the story of his hopes and ambitions, describing to her the very home where he was born, and the dark-eyed sister whom he had loved, and with whom he had played over the daisied fields, and through the carpeted woods, and all among the richly tinted bracken. One day he was told she was dead, and that he must never speak her name; but he spoke it all the day and all the night, Beryl, nothing but Beryl, and he looked for her in the fields and in the woods and among the bracken. It seemed as if he had unlocked the casket of his heart, closed for so many years, and as if all the memories of the past and all the secrets of his life were rushing out, glad to be free once more, and grateful for the open air of sympathy.";

             var dict = CharacterFrequencyDictionary.CreateDictionary(input);

             var encodeTree = new HuffmanTree<char>(dict);

             var encode = encodeTree.Encode(input);

             var encodeAsByte = CompressUtil.ConvertToByteArray(encode);

             var secondDict = CharacterFrequencyDictionary.CreateDictionary(
            dict.GetKeysAsByteArray(), dict.GetValuesAsByteArray());

             var encodeAsByteArray = new List<byte>();
             foreach (var b in encodeAsByte)
            encodeAsByteArray.AddRange(CompressUtil.ConvertToBitArray(b));

             if (encode.Length < encodeAsByteArray.ToArray().Length)
            encodeAsByteArray.RemoveRange(encode.Length, encodeAsByteArray.ToArray().Length - encode.Length);

             CollectionAssert.AreEqual(dict, secondDict);
             CollectionAssert.AreEqual(encode, encodeAsByteArray.ToArray());

             var decodeTree = new HuffmanTree<char>(secondDict);
             var decode = decodeTree.Decode(encodeAsByteArray);

             Assert.AreEqual(input, decode);
        }
コード例 #4
0
        public void ArrayLiterals()
        {
            var array = new[] { 42 };
            Assert.AreEqual(typeof(int[]), array.GetType(), "You don't have to specify a type if the elements can be inferred");
            Assert.AreEqual(new int[] { 42 }, array, "These arrays are literally equal... But you won't see this string in the error message.");

            //Are arrays 0-based or 1-based?
            Assert.AreEqual(42, array[((int)FILL_ME_IN)], "Well, it's either 0 or 1.. you have a 110010-110010 chance of getting it right.");

            //This is important because...
            Assert.IsTrue(array.IsFixedSize, "...because Fixed Size arrays are not dynamic");

            //Begin RJG
            // Moved this Throws() call to a separate FixedSizeArraysCannotGrow() method below
            //...it means we can't do this: array[1] = 13;
            //Assert.Throws(typeof(FILL_ME_IN), delegate() { array[1] = 13; });
            //End RJG

            //This is because the array is fixed at length 1. You could write a function
            //which created a new array bigger than the last, copied the elements over, and
            //returned the new array. Or you could do this:
            var dynamicArray = new List<int>();
            dynamicArray.Add(42);
            CollectionAssert.AreEqual(array, dynamicArray.ToArray(), "Dynamic arrays can grow");

            dynamicArray.Add(13);
            CollectionAssert.AreEqual((new int[] { 42, (int)FILL_ME_IN }), dynamicArray.ToArray(), "Identify all of the elements in the array");
        }
コード例 #5
0
 public void AddAndGet()
 {
     var c = new SynchronizedCache();
     var lst = new List<Task>();
     for (var i = 0; i < 10; i++)
     {
         var i1 = i;
         var t = new Task(() => c.Add(i1, i1.ToString()));
         t.Start();
         lst.Add(t);
     }
     Task.WaitAll(lst.ToArray());
     Assert.AreEqual(c.Count, 10);
     lst.Clear();
     for (var i = 0; i < 10; i++)
     {
         var i1 = i;
         var t = new Task(() =>
         {
             var s = c.Read(i1);
             Assert.AreEqual(s, i1.ToString());
             c.Update(i1, "42");
         });
         t.Start();
         lst.Add(t);
     }
     Task.WaitAll(lst.ToArray());
     for (var i = 0; i < 10; i++)
     {
         var s = c.Read(i);
         Assert.AreEqual(s, "42");
     }
 }
コード例 #6
0
        public void addAllVerticalPointsToListTest()
        {
            List<Point> list = new List<Point>();
            List<Point> listExpected = new List<Point>();
            int miny = 0;
            int maxy = 4;
            int x = 1;
            listExpected.Add(new Point(x, 0));
            listExpected.Add(new Point(x, 1));
            listExpected.Add(new Point(x, 2));
            listExpected.Add(new Point(x, 3));
            listExpected.Add(new Point(x, 4));
            ArraySpaceUtilities.addAllVerticalPointsToList(ref list, miny, maxy, x, true);
            Assert.AreEqual(listExpected.Count, list.Count);
            Point[] listasarray = list.ToArray();
            Point[] expectedlistasarray = listExpected.ToArray();
            for (int i = 0; i < listasarray.Length; i++)
            {
                Assert.AreEqual(true, listasarray[i].Equals(expectedlistasarray[i]));
            }

            listExpected.Reverse();
            list.Clear();
            ArraySpaceUtilities.addAllVerticalPointsToList(ref list, miny, maxy, x, false);
            Assert.AreEqual(listExpected.Count, list.Count);

            listasarray = list.ToArray();
            expectedlistasarray = listExpected.ToArray();
            for (int i = 0; i < listasarray.Length; i++)
            {
                Assert.AreEqual(true, listasarray[i].Equals(expectedlistasarray[i]));
            }
        }
コード例 #7
0
ファイル: WpfTests.cs プロジェクト: MetalMynds/FlatGlass
        public void PetShopWindowWpfGuiTest()
        {
            Window window = application.FindWindow(FindBy.UiAutomationId("petShopWindow"));

            var petshopWindow = WindowFactory.Create<PetShopMainWindowWpf>(window.Element);

            List<String> rules = new List<string>();

            rules.Add("Special Environment");

            petshopWindow.RegisterAnimal("Foghorn Leghorn", "Large Bird", "Herbivorous", 69.68, rules.ToArray());

            petshopWindow.ShowHistory();

            petshopWindow.RegisterAnimal("Chickin Lic'in", "Small Bird", "Herbivorous", 666.99, rules.ToArray());

            petshopWindow.ShowHistory();

            rules.Clear();

            rules.Add("Dangerous");

            rules.Add("Sell In Pairs");

            petshopWindow.RegisterAnimal("Capistrano", "Cat", "Carnivorous", 9.99, rules.ToArray());

            petshopWindow.ShowHistory();
        }
コード例 #8
0
ファイル: JsonObjectTest.cs プロジェクト: nuxleus/WCFWeb
        public void AddRangeParamsTest()
        {
            string key1 = AnyInstance.AnyString;
            string key2 = AnyInstance.AnyString2;
            JsonValue value1 = AnyInstance.AnyJsonValue1;
            JsonValue value2 = AnyInstance.AnyJsonValue2;

            List<KeyValuePair<string, JsonValue>> items = new List<KeyValuePair<string, JsonValue>>()
            {
                new KeyValuePair<string, JsonValue>(key1, value1),
                new KeyValuePair<string, JsonValue>(key2, value2),
            };

            JsonObject target;

            target = new JsonObject();
            target.AddRange(items[0], items[1]);
            Assert.AreEqual(2, target.Count);
            ValidateJsonObjectItems(target, key1, value1, key2, value2);

            target = new JsonObject();
            target.AddRange(items.ToArray());
            Assert.AreEqual(2, target.Count);
            ValidateJsonObjectItems(target, key1, value1, key2, value2);

            ExceptionTestHelper.ExpectException<ArgumentNullException>(delegate { new JsonObject().AddRange((KeyValuePair<string, JsonValue>[])null); });
            ExceptionTestHelper.ExpectException<ArgumentNullException>(delegate { new JsonObject().AddRange((IEnumerable<KeyValuePair<string, JsonValue>>)null); });

            items[1] = new KeyValuePair<string, JsonValue>(key2, AnyInstance.DefaultJsonValue);
            ExceptionTestHelper.ExpectException<ArgumentException>(delegate { new JsonObject().AddRange(items.ToArray()); });
            ExceptionTestHelper.ExpectException<ArgumentException>(delegate { new JsonObject().AddRange(items[0], items[1]); });
        }
コード例 #9
0
 // interval: start, end
 // sample input: [[1,4],[1,5]] -- 2 interval, (1, 4) (1, 5)
 public int[][] Merge(int[][] intervals)
 {
     List<int[]> result = new List<int[]>();
     // order by start first
     var tuples = intervals.Select(i => Tuple.Create(i[0], i[1])).OrderBy(t => t.Item1).ToArray();
     if (tuples.Length == 0)
     {
         return result.ToArray();
     }
     int currentStart = tuples[0].Item1;
     int currentEnd = tuples[0].Item2;
     for (int i = 1; i < tuples.Length; i++)
     {
         var currentTuple = tuples[i];
         if (currentTuple.Item1 > currentEnd) // no overlap with previous
         {
             result.Add(new int[] { currentStart, currentEnd });
             currentStart = currentTuple.Item1;
             currentEnd = currentTuple.Item2;
         }
         else
         {
             currentEnd = Math.Max(currentEnd, currentTuple.Item2);
         }
     }
     result.Add(new int[] { currentStart, currentEnd });
     return result.ToArray();
 }
コード例 #10
0
        public void ComplexObject_Test()
        {
            ObjectConverter objectConverter = new ObjectConverter();
            objectConverter.RegisterConverter(1, new CreationDictionaryObjectConverter("xtype", new DomainTypeResolver(true)));

            Dictionary<string, object> Peter = new Dictionary<string, object>();
            Peter["Name"] = "Peter";

            List<object> pets = new List<object>();
            Dictionary<string, object> xcat = new Dictionary<string, object>();
            xcat["xtype"] = typeof(Cat).FullName;
            xcat["Name"] = "cat1";
            xcat["Age"] = 3;
            pets.Add(xcat);

            Dictionary<string, object> xdog = new Dictionary<string, object>();
            xdog["xtype"] = typeof(Dog).FullName;
            xdog["Name"] = "dog1";
            xdog["Age"] = 5;
            pets.Add(xdog);

            Peter["Pets"] = pets.ToArray();
            Peter["PetList"] = pets.ToArray();

            Person obj = new Person();
            objectConverter.MapObject(Peter, obj);

            Assert.IsNotNull(obj.Pets);
            Assert.AreEqual(2, obj.Pets.Length);

            var cat = obj.Pets[0] as Cat;
            Assert.IsNotNull(cat);
            Assert.AreEqual("cat1", cat.Name);
            Assert.AreEqual(3, cat.Age);

            var dot = obj.Pets[1] as Dog;
            Assert.IsNotNull(dot);
            Assert.AreEqual("dog1", dot.Name);
            Assert.AreEqual(5, dot.Age);

            // check list
            Assert.IsNotNull(obj.PetList);
            Assert.AreEqual(2, obj.PetList.Count);

            cat = obj.PetList[0] as Cat;
            Assert.IsNotNull(cat);
            Assert.AreEqual("cat1", cat.Name);
            Assert.AreEqual(3, cat.Age);

            dot = obj.PetList[1] as Dog;
            Assert.IsNotNull(dot);
            Assert.AreEqual("dog1", dot.Name);
            Assert.AreEqual(5, dot.Age);
        }
コード例 #11
0
ファイル: WinFormTests.cs プロジェクト: MetalMynds/FlatGlass
        public void PetShopWindowWinFormsGuiTest()
        {
            //try
            //{

                Window window = application.FindWindow(FindBy.UiAutomationId("FormMain"));

                var petshopWindow = WindowFactory.Create<PetShopMainWindowWinForm>(window.Element);

                ////var history = petshopWindow.historyTab.Control;

                ////history.Select();

                //var container = petshopWindow.container.Control;

                //var tabControl = petshopWindow.tabctrlAdmin.Control;

                ////var panel = petshopWindow.registrationTabContainer.Control;

                //var text = petshopWindow.name.Control;

                //text.Text = "Dave is legendery!";

                List<String> rules = new List<string>();

                rules.Add("Special Environment");

                petshopWindow.RegisterAnimal("Foghorn Leghorn", "Large Bird", "Herbivorous", 69.68, rules.ToArray());

                petshopWindow.ShowHistory();

                petshopWindow.RegisterAnimal("Chickin Lic'in", "Small Bird", "Herbivorous", 666.99, rules.ToArray());

                petshopWindow.ShowHistory();

                rules.Clear();

                rules.Add("Dangerous");

                rules.Add("Sell In Pairs");

                petshopWindow.RegisterAnimal("Capistrano", "Cat", "Carnivorous", 9.99, rules.ToArray());

                petshopWindow.ShowHistory();

            //}
            //catch (Exception ex)
            //{
            //    throw;
            //}
        }
コード例 #12
0
        public void MergeKLists()
        {
            var lists = new List<LeetCode.Code.MergeKSortedLists.ListNode>();
            var gap = 5;
            var eachCount = 10;
            var randomDifference = 3;
            var random = new Random(Guid.NewGuid().GetHashCode());
            var count = gap;
            for (var currentStart = 1
                ; currentStart <= gap
                ; currentStart++)
            {
                var firstNode = new LeetCode.Code.MergeKSortedLists.ListNode(currentStart);
                lists.Add(firstNode);

                for (var index = currentStart + gap
                    ; index <= gap * (eachCount + random.Next(-randomDifference, randomDifference))
                    ; index += gap)
                {
                    firstNode.next = new Code.MergeKSortedLists.ListNode(index);
                    firstNode = firstNode.next;
                    count++;
                }
            }

            this.AssertOrdered(mergeKSortedLists.MergeKLists(lists.ToArray()), count);

            lists = new List<MergeKSortedLists.ListNode>();
            var randomCount = 10000;
            for (var index = 0; index < randomCount; index++)
                lists.Add(new LeetCode.Code.MergeKSortedLists.ListNode(random.Next(int.MaxValue)));

            this.AssertOrdered(mergeKSortedLists.MergeKLists(lists.ToArray()), randomCount);
        }
コード例 #13
0
        public int[][] Insert(int[][] intervals, int[] newInterval)
        {
            bool inserted = false;
            List<int[]> resultList = new List<int[]>();
            for (int i = 0; i < intervals.Length; i++)
            {
                int[] interval = intervals[i];
                if (newInterval[0] > interval[1])
                {
                    resultList.Add(interval);
                    continue;
                }
                if (newInterval[1] < interval[0])
                {
                    if (!inserted)
                    {
                        resultList.Add(newInterval);
                        inserted = true;
                    }
                    resultList.Add(interval);
                    continue;
                }
                newInterval[0] = Math.Min(interval[0], newInterval[0]);
                newInterval[1] = Math.Max(interval[1], newInterval[1]);
            }

            if (!inserted)
                resultList.Add(newInterval);

            return resultList.ToArray();
        }
        /// <summary>
        /// Tests the scenario when the initial request contains a cookie (corresponding to user), in which case, the response should contain a similar cookie with the information
        /// replicated into the listener data.
        /// </summary>
        protected void ValidateUserIdWithRequestCookie(string requestPath, int testListenerTimeoutInMs, int testRequestTimeOutInMs, Cookie[] additionalCookies = null)
        {
            DateTimeOffset time = DateTimeOffset.UtcNow;
            List<Cookie> cookies = new List<Cookie>();
            int additionalCookiesLength = 0;
            if (null != additionalCookies)
            {
                cookies.AddRange(additionalCookies);
                additionalCookiesLength = additionalCookies.Length;
            }
            string userCookieStr = "userId|" + time.ToString("O");
            var cookie = new Cookie(CookieNames.UserCookie, userCookieStr);
            cookies.Add(cookie);

            var requestResponseContainer = new RequestResponseContainer(cookies.ToArray(), requestPath, this.Config.ApplicationUri, testListenerTimeoutInMs, testRequestTimeOutInMs);
            requestResponseContainer.SendRequest();

            var userCookie = requestResponseContainer.CookieCollection.ReceiveUserCookie();
            var item = Listener.ReceiveItemsOfType<TelemetryItem<RequestData>>(
                1,
                testListenerTimeoutInMs)[0];

            Assert.AreEqual("OK", requestResponseContainer.ResponseTask.Result.ReasonPhrase);
            Assert.AreEqual(2 + additionalCookiesLength, requestResponseContainer.CookieCollection.Count);
            Assert.AreEqual("userId", item.UserContext.Id);
            Assert.AreEqual(time, item.UserContext.AcquisitionDate.Value);
            Assert.AreEqual(userCookieStr, userCookie);
            Assert.AreEqual(userCookie, item.UserContext.Id + "|" + item.UserContext.AcquisitionDate.Value.ToString("O"));   
        }
コード例 #15
0
        public void CrossProcessBarrierTest()
        {
            IEnumerable<string> allNames = new List<string>
                                {
                                    "deployment(400).GenericWorkerRole.Cloud.WebRole.0_Web",
                                    "deployment(400).GenericWorkerRole.Cloud.WebRole.1_Web",
                                    "deployment(400).GenericWorkerRole.Cloud.WebRole.2_Web",
                                    "deployment(400).GenericWorkerRole.Cloud.WebRole.3_Web",
                                    "deployment(400).GenericWorkerRole.Cloud.WebRole.4_Web"
                                };

            Func<string, string> escapeMutexName = instanceId => instanceId.Replace("(", ".").Replace(")", ".").Replace(".", "");
            allNames = allNames.Select(escapeMutexName);
            
            var tasks = new List<Task>();
            foreach (var currentName in allNames)
            {
                var peerNames = new List<string>(allNames);
                peerNames.Remove(currentName);

                var c = CrossProcessBarrier.GetInstance(currentName, peerNames, TimeSpan.Zero);
                tasks.Add(Task.Factory.StartNew(c.Wait));
                Trace.TraceInformation("Launched task {0}", currentName);
            }

            Trace.TraceInformation("Waiting for all tasks to reach the barrier");
            Task.WaitAll(tasks.ToArray());
            Trace.TraceInformation("All tasks reached the barrier");
        }
コード例 #16
0
        public void Local_Async_Should_Be_Faster()
        {
            var iterations = Enumerable.Range(1, 100).ToList();

            var tasks = new List<Task>();
            var stopWatch = Stopwatch.StartNew();
            iterations.ForEach(i =>
                                   {
                                       var task = Task.Run(async () => await Task.Delay(1));
                                       tasks.Add(task);
                                   });
            Task.WaitAll(tasks.ToArray());
            stopWatch.Stop();
            var asyncElapsed = stopWatch.ElapsedMilliseconds;
            Console.WriteLine(asyncElapsed);

            stopWatch = Stopwatch.StartNew();
            iterations.ForEach(i => Thread.Sleep(1));
            stopWatch.Stop();
            var syncElapsed = stopWatch.ElapsedMilliseconds;
            Console.WriteLine(syncElapsed);

            stopWatch = Stopwatch.StartNew();
            Parallel.ForEach(iterations, i => Thread.Sleep(1));
            stopWatch.Stop();
            var parallelElapsed = stopWatch.ElapsedMilliseconds;
            Console.WriteLine(parallelElapsed);

            asyncElapsed.Should().BeLessThan(syncElapsed);
            asyncElapsed.Should().BeLessThan(parallelElapsed);
        }
コード例 #17
0
        public BinaryTree[] GenerateTrees(int n)
        {
            cachedResults[0] = new BinaryTree[1] { null };
            cachedResults[1] = new BinaryTree[1] { new BinaryTree(1) };

            for (int i = 2; i <= n; i++) // get answer i: i+1 nodes
            {
                if (cachedResults.ContainsKey(i))
                {
                    continue;
                }
                // left part can have 0 - i-1 nodes, if i nodes in all
                List<BinaryTree> trees = new List<BinaryTree>();
                for (int left = 0; left <= i - 1; left++)
                {
                    var root = new BinaryTree(left + 1);
                    foreach (var possibleLeft in cachedResults[left])
                    {
                        foreach (var possibleRight in cachedResults[i - 1 - left])
                        {
                            root.Left = possibleLeft;
                            root.Right = CloneTree(possibleRight, left + 1);
                            trees.Add(CloneTree(root, 0));
                        }
                    }
                }
                cachedResults[i] = trees.ToArray();
            }

            return cachedResults[n];
        }
コード例 #18
0
ファイル: GenerateReportSteps.cs プロジェクト: jhonner72/plat
        private static ExecuteReportRequest[] ExtractReportRequests(IEnumerable<RequestHelper> requestHelper)
        {
            var allReportRequests = new List<ExecuteReportRequest>();

            foreach (var requestInfo in requestHelper)
            {
                var parameters = ExtractParameters(requestInfo);

                FormatType formatType;
                if (!Enum.TryParse(requestInfo.OutputFormatType, out formatType))
                {
                    Assert.Fail("OutputFormatType not recognized");
                }

                var executeReportRequest = new ExecuteReportRequest
                {
                    reportName = requestInfo.ReportName,
                    outputFilename = requestInfo.OutputFilename,
                    outputFormatType = formatType,
                    parameters = parameters
                };

                allReportRequests.Add(executeReportRequest);
            }

            return allReportRequests.ToArray();
        }
コード例 #19
0
ファイル: XMLGenerator.cs プロジェクト: oneminot/everest
        internal static bool GenerateInstance(Type instanceType, Stream outputStream, out IResultDetail[] details)
        {

            string resourceName = String.Format(instanceType.FullName).Replace(".", "");

            var formatter = new MARC.Everest.Formatters.XML.ITS1.XmlIts1Formatter();
            formatter.Settings = MARC.Everest.Formatters.XML.ITS1.SettingsType.DefaultUniprocessor;
            formatter.ValidateConformance = false;
            // Testing pregen
            formatter.GraphAides.Add(new MARC.Everest.Formatters.XML.Datatypes.R1.DatatypeFormatter());
            formatter.BuildCache(Assembly.Load("MARC.Everest.RMIM.CA.R020402").GetTypes());

            IGraphable result = TypeCreator.GetCreator(instanceType).CreateInstance() as IGraphable;

            Trace.WriteLine("Starting Serialization");
            DateTime start = DateTime.Now;
            var gresult = formatter.Graph(outputStream, result);
            Trace.WriteLine(String.Format("            ->{0}", DateTime.Now.Subtract(start).TotalMilliseconds));
            Trace.WriteLine(String.Format("            ->{0} bytes", outputStream.Length));
            List<IResultDetail> dlist = new List<IResultDetail>();
            dlist.AddRange(gresult.Details);
            details = dlist.ToArray();

            return gresult.Code == MARC.Everest.Connectors.ResultCode.Accepted;
        }
コード例 #20
0
        public void QueryForIssueFromExternalId()
        {
            string PrimaryWorkitemType = "PrimaryWorkitem";
            string externalSystemName = Enviornment.instance.GetVersionOneSource;
            string externalFieldName = Enviornment.instance.GetVersionOneReference;
            string externalId = "VOID-41";

            queryBuilder.AddProperty (Entity.NameProperty,VersionOneProcessor.PrimaryWorkitemType, false);
            queryBuilder.AddProperty( Workitem.DescriptionProperty,VersionOneProcessor.PrimaryWorkitemType, false);
            queryBuilder.AddProperty( Entity.StatusProperty,VersionOneProcessor.PrimaryWorkitemType, false);
            queryBuilder.AddProperty( Workitem.ReferenceProperty,VersionOneProcessor.PrimaryWorkitemType, false);
            queryBuilder.AddProperty( Workitem.AssetTypeProperty,VersionOneProcessor.PrimaryWorkitemType, false);

             var filters = new List<IFilter> {
                    Filter.Closed(false),
                    Filter.OfTypes(VersionOneProcessor.StoryType, VersionOneProcessor.DefectType),
                    Filter.Equal(Entity.SourceNameProperty, externalSystemName),
                    Filter.Equal(externalFieldName, externalId),
                };

            var filter = GroupFilter.And(filters.ToArray());

            var result = queryBuilder.Query(PrimaryWorkitemType, filter);

            Console.WriteLine(string.Format("Returned count: {0}", result.Count));
            Assert.IsTrue(result.Count == 1);
        }
コード例 #21
0
ファイル: UnitTest1.cs プロジェクト: Xol4/CrossTheBridge
        public void GetSmallestNumberIndex_2()
        {
            CrossTheBridgeHelper helper = new CrossTheBridgeHelper();
            List<int> people = new List<int>() { 10, 5, 2, 0 };

            Assert.AreEqual(helper.GetSmallestNumberIndex(people.ToArray()), 2);
        }
コード例 #22
0
ファイル: Q015_3Sum.cs プロジェクト: dullcat/leetcode_csharp
 public int[][] ThreeSum(int[] num)
 {
     List<int[]> result = new List<int[]>();
     var sortedNums = num.OrderBy(n => n).ToArray(); // sort first
     for (int i = 0; i < sortedNums.Length - 2; i++)
     {
         int left = i + 1;
         int right = sortedNums.Length - 1;
         while (left < right)
         {
             int tmp = sortedNums[i] + sortedNums[left] + sortedNums[right];
             if (tmp > 0)
             {
                 right--;
             }
             else if (tmp < 0)
             {
                 left++;
             }
             else
             {
                 if (!result.Any(r => r[0] == sortedNums[i] && r[1] == sortedNums[left] && r[2] == sortedNums[right]))
                 {
                     result.Add(new[] { sortedNums[i], sortedNums[left], sortedNums[right] });
                 }
                 right--;
                 left++;
             }
         }
     }
     return result.ToArray();
 }
コード例 #23
0
        private void InitializeTest(Type typeInLibraryToTest)
        {
            BaseType = typeof(ViewModelBase);
              AllTypes = new TypeList();
              AllTypes.AddRange(typeInLibraryToTest.Assembly.GetTypes());

              AllTypesToCheck = new TypeList();
              DataTypesToCheck = new TypeList();
              TypeProperties = new Dictionary<Type, PropertyInfo[]>();
              foreach (Type currentType in AllTypes)
              {
            if (currentType.IsAbstract)
              continue;

            if (ReflectionUtil.IsClassOfType(currentType, BaseType))
            {
              AllTypesToCheck.Add(currentType);
              if (ReflectionUtil.IsClassOfType(currentType, BaseType))
            DataTypesToCheck.Add(currentType);

              PropertyInfo[] properties = currentType.GetProperties();
              List<PropertyInfo> finalProperties = new List<PropertyInfo>();
              foreach (PropertyInfo current in properties)
              {
            NotMappedAttribute notMappedAttribute = current.GetCustomAttribute<NotMappedAttribute>();
            if (notMappedAttribute != null)
              continue;

            finalProperties.Add(current);
              }

              TypeProperties.Add(currentType, finalProperties.ToArray());
            }
              }
        }
コード例 #24
0
        public string[] FullJustify(string[] words, int length)
        {
            List<string> results = new List<string>();

            int currentLength = 0, start = 0;
            for (int i = 0; i < words.Length; i++)
            {
                if (currentLength + words[i].Length + i - start > length)
                {
                    Print(words, start, i - 1, currentLength, length, results);
                    start = i;
                    currentLength = words[i].Length;
                }
                else
                {
                    currentLength += words[i].Length;
                }
            }

            if (currentLength > 0)
            {
                Print(words, start, words.Length - 1, currentLength, length, results);
            }

            if (results.Count == 0)
                results.Add(new string(' ', length));
            return results.ToArray();
        }
コード例 #25
0
ファイル: Tests4.cs プロジェクト: filar7/abstrakcyjne
        public void CheckIteratorTest()
        {
            Executeable<int> identity = (Func<int, int>)((int x) => x);
            Executeable<int> linearfunction = (Func<int, int>)((int x) => 3 * x - 2);
            Executeable<int> quadraticfunction = (Func<int, int>)((int x) => 2 * x * x - 5);
            Executeable<int> cubicfunction = (Func<int, int>)((int x) => x * x * x + x * x + x + 1);

            List<Executeable<int>> functions = new List<Executeable<int>>();
            functions.Add(identity);
            functions.Add(linearfunction);
            functions.Add(quadraticfunction);
            functions.Add(cubicfunction);
            Composition<int> comp = new Composition<int>(functions.ToArray());
            int[] tab0 = new int[] { 0, -2, -5, 1 };
            int[] tab1 = new int[] { 1, 1, -3, 4 };
            int[] tab2 = new int[] { 2, 4, 3, 15 };
            int i = 0;
            foreach (var f in comp)
            {
                Assert.AreEqual((int)f.Execute(0), tab0[i]);
                Assert.AreEqual((int)f.Execute(1), tab1[i]);
                Assert.AreEqual((int)f.Execute(2), tab2[i]);
                i++;
            }
        }
コード例 #26
0
ファイル: AverageTests.cs プロジェクト: admal/GradingBook
        public void TestWeightedMean()
        {
            List<SubjectDetailsViewModel> grades = new List<SubjectDetailsViewModel>();
            var rnd = new Random();
            var sum = 0.0;
            var num = 0.0;

            for (var i = 0; i < 5; i++)
            {
                var val = rnd.Next(2, 6);
                var weight = rnd.Next(1, 10);
                var grade = new SubjectDetailsViewModel()
                {
                    grade_value = val,
                    grade_weight = weight
                };
                grades.Add(grade);
                sum += grade.grade_weight * grade.grade_value;
                num += grade.grade_weight;
            }
            var mean =Math.Round(sum/num, 2);

            var calc = new AverageCalc();
            var result = calc.WeightedAverage(grades.ToArray());

            Assert.AreEqual(mean, result);

        }
コード例 #27
0
        public void Test_Parsing_Names_Contains_No_First_Names()
        {
            // Arrange
            List<string> names = new List<string>();
            names.Add("Bob, Alice");
            names.Add("Redfield, Chris");
            names.Add("Valentine, ");
            names.Add("Redfield, Claire");
            names.Add("Smith, Agent");

            // Act
            Person[] people = _nameParser.ParseNames(names.ToArray());

            // Assert
            Assert.IsNotNull(people);
            Assert.AreEqual(5, people.Length);
            Assert.AreEqual("Bob", people[0].LastName);
            Assert.AreEqual("Alice", people[0].FirstName);
            Assert.AreEqual("Redfield", people[1].LastName);
            Assert.AreEqual("Chris", people[1].FirstName);
            Assert.AreEqual("Valentine", people[2].LastName);
            Assert.AreEqual(string.Empty, people[2].FirstName);
            Assert.AreEqual("Redfield", people[3].LastName);
            Assert.AreEqual("Claire", people[3].FirstName);
            Assert.AreEqual("Smith", people[4].LastName);
            Assert.AreEqual("Agent", people[4].FirstName);
        }
コード例 #28
0
 public int[][] Insert(int[][] intervals, int[] newInterval)
 {
     List<int[]> result = new List<int[]>();
     var tuples = intervals.Select(i => Tuple.Create(i[0], i[1])).ToArray();
     int mergedLow = newInterval[0];
     int mergedHigh = newInterval[1];
     bool mergedWritten = false;
     for (int i = 0; i < tuples.Length; i++)
     {
         var currentTuple = tuples[i];
         if (currentTuple.Item1 > mergedHigh) // curent token is ahead merging one, merging complete
         {
             if (!mergedWritten)
             {
                 mergedWritten = true;
                 result.Add(new int[] { mergedLow, mergedHigh });
             }
             result.Add(new int[] { currentTuple.Item1, currentTuple.Item2 });
         }
         else if (currentTuple.Item2 < mergedLow)
         {
             result.Add(new int[] { currentTuple.Item1, currentTuple.Item2 });
         }
         else // current tuple has overlap with merging one
         {
             mergedLow = Math.Min(mergedLow, currentTuple.Item1);
             mergedHigh = Math.Max(mergedHigh, currentTuple.Item2);
         }
     }
     if (!mergedWritten) // from inmerging to non-imerging
     {
         result.Add(new int[] { mergedLow, mergedHigh });
     }
     return result.ToArray();
 }
コード例 #29
0
 public string[] GenerateParenthesis(int n)
 {
     List<string> answer = new List<string>();
     GenerateParenthesisRecursive(n, n, answer, "");
     answer.Sort();
     return answer.ToArray();
 }
コード例 #30
0
        public void CleanupTestDomains()
        {
            const int BatchSize = 10;

            IDnsService provider = CreateProvider();
            using (CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(TestTimeout(TimeSpan.FromSeconds(60))))
            {
                Func<DnsDomain, bool> domainFilter =
                    domain =>
                    {
                        if (domain.Name.StartsWith(TestDomainPrefix, StringComparison.OrdinalIgnoreCase))
                            return true;
                        else if (domain.Name.IndexOf('.' + TestDomainPrefix, StringComparison.OrdinalIgnoreCase) >= 0)
                            return true;

                        return false;
                    };

                DnsDomain[] allDomains = ListAllDomains(provider, null, null, cancellationTokenSource.Token).Where(domainFilter).ToArray();

                List<Task> deleteTasks = new List<Task>();
                for (int i = 0; i < allDomains.Length; i += BatchSize)
                {
                    for (int j = i; j < i + BatchSize && j < allDomains.Length; j++)
                        Console.WriteLine("Deleting domain: {0}", allDomains[j].Name);

                    deleteTasks.Add(provider.RemoveDomainsAsync(allDomains.Skip(i).Take(BatchSize).Select(domain => domain.Id), true, AsyncCompletionOption.RequestCompleted, cancellationTokenSource.Token, null));
                }

                Task.WaitAll(deleteTasks.ToArray());
            }
        }