public void Next_ShouldReturnNextIndex() { // Assign var list = new CircularList<int>(GetNumbers()); // Act int current = list.Current; int next0 = list.Next(); int next1 = list.Next(); int next2 = list.Next(); int next3 = list.Next(); int next4 = list.Next(); int next5 = list.Next(); int next6 = list.Next(); // Assert Assert.AreEqual(0, current); Assert.AreEqual(1, next0); Assert.AreEqual(2, next1); Assert.AreEqual(3, next2); Assert.AreEqual(4, next3); Assert.AreEqual(0, next4); Assert.AreEqual(1, next5); Assert.AreEqual(2, next6); }
public void CheckQuickSorting() { CircularList <int> list = new CircularList <int>(); list.Add(5); list.Add(2); list.Add(3); list.Add(5); list.Add(6); list.Add(2); list.Add(5); list.Add(7); list.QuickSort(); int[] expected = { 2, 2, 3, 5, 5, 5, 6, 7 }; int[] result = list.GetSlice(); Assert.AreEqual(expected.Length, result.Length, "Не совпадает количество элементов в массивах"); bool isDif = false; for (int i = 0; i < expected.Length; i++) { if (result[i] != expected[i]) { isDif = true; } } Assert.AreEqual(false, isDif, "Есть несовпадающие элементы"); int checkPoint = 8 * 6 + 6; // (n*k) + (l-1) int expectedVal = 6; Assert.AreEqual(expectedVal, list[checkPoint], "Список не работает, как кольцевой"); }
public void TestRemoveAt() { CircularList <Point> points = new CircularList <Point>(); Point p1 = new Point(1, 1); Point p2 = new Point(2, 2); Point p3 = new Point(3, 3); points.Insert(0, p1); points.Insert(1, p2); points.Insert(2, p3); //Проверка удаления с середины points.RemoveAt(1); Assert.AreEqual(points[1], p3); // Проверка удаления с головы points.RemoveAt(0); Assert.AreEqual(points[0], p3); //Проверка удаления последнего элемента points.RemoveAt(0); Assert.AreEqual(points.Count, 0); //Проверка удаления не существующего индекса points.RemoveAt(0); Assert.AreEqual(points.Count, 0); //Проверка удаления не существующего индекса points.Insert(0, p1); points.RemoveAt(1); Assert.AreEqual(points.Count, 1); }
static Node Move(CircularList state, Node current) { var removedThree = state.RemoveThreeAfter(current); var removedValues = new HashSet <int> { removedThree.Value, removedThree.Next.Value, removedThree.Next.Next.Value }; var destinationValue = current.Value - 1; while (destinationValue == 0 || removedValues.Contains(destinationValue)) { if (destinationValue == 0) { destinationValue = state.Max; } else { destinationValue--; } } state.InsertThreeAfter(state.Find(destinationValue), removedThree); return(current.Next); }
public static string KnotHash(string input) { var list = new CircularList(); var lengths = Encoding.ASCII.GetBytes(input).Concat(new byte[] { 17, 31, 73, 47, 23 }).ToList(); int iCur = 0, skip = 0; for (int round = 0; round < 64; round++) { foreach (int length in lengths) { var tmpList = list.GetRange(iCur, length).Reverse().ToList(); for (int l = 0; l < length; l++) { list[iCur + l] = tmpList[l]; } iCur += length + skip; skip++; } } var hash = ""; for (int i = 0; i < 16; i++) { hash += list.GetRange(i * 16, 16).Aggregate(0, (a, b) => a ^ b).ToString("x2"); } return(hash); }
public void Enumerator() { CircularList <string> list = PrepareList <string>(10, 7, 9); List <string> reference = new List <string>(list); Assert.IsTrue(list.SequenceEqual(reference)); }
public RandomUserAgent() { var formattedUserAgentsLength = FormattedUserAgents.Length; formattedUserAgentsCircularList = new CircularList <int>(() => new UniqueRandomizer().GenerateRandom(formattedUserAgentsLength, 0, formattedUserAgentsLength)); templateFields = new Dictionary <String, Func <object> >(); templateFields.Add("AndroidVersion", () => $"{RandomizerHq.RandomInt(2, 6)}.{RandomizerHq.RandomInt(0, 4)}.{RandomizerHq.RandomInt(0, 5)}"); templateFields.Add("BaiduSpiderName", () => BaiduSpiderNames[RandomizerHq.RandomInt(0, BaiduSpiderNames.Length)]); templateFields.Add("BotVersion", () => { var value = RandomizerHq.RandomInt(200, 500).ToString(); return($"{value[0]}.{value[1]}.{value[2]}"); }); templateFields.Add("BlackBerryVersion", () => 9000 + 100 * RandomizerHq.RandomInt(1, 9) + 10 * RandomizerHq.RandomInt(1, 5)); templateFields.Add("FacebookBotName", () => FacebookBotNames[RandomizerHq.RandomInt(0, FacebookBotNames.Length)]); templateFields.Add("FacebookBotVersion", () => RandomizerHq.RandomInt(10, 21).ToString("0.0")); templateFields.Add("GenericVersion", () => $"{RandomizerHq.RandomInt(4, 7)}.{RandomizerHq.RandomInt(0, 6)}.{RandomizerHq.RandomInt(2, 7)}.{RandomizerHq.RandomInt(100, 666)}"); templateFields.Add("GoogleBotName", () => GoogleBotNames[RandomizerHq.RandomInt(0, GoogleBotNames.Length)]); templateFields.Add("IeVersion", () => IeVersions[RandomizerHq.RandomInt(0, IeVersions.Length)]); templateFields.Add("IOsVersion", () => $"{RandomizerHq.RandomInt(3, 7)}_{RandomizerHq.RandomInt(0, 4)}_{RandomizerHq.RandomInt(0, 5)}"); templateFields.Add("MozillaVersion", () => (RandomizerHq.RandomInt(30, 50) / 10).ToString("0.0")); templateFields.Add("OperaVersion", () => RandomizerHq.RandomInt(5, 10)); templateFields.Add("RvVersion", () => $"{RandomizerHq.RandomInt(36, 47)}.0"); templateFields.Add("SafariVersion", () => $"{RandomizerHq.RandomInt(333, 999)}.{RandomizerHq.RandomInt(1, 69)}"); templateFields.Add("WindowsVersion", () => WindowsVersions[RandomizerHq.RandomInt(0, WindowsVersions.Length)]); }
public void IndexOfWorksOnObjects() { var testInst = new CircularList <object>(500); for (int i = 50; i < 100; i++) { testInst.AddLast(i); } for (int i = 49; i >= 0; i--) { testInst.AddFirst(i); } for (int i = 0; i < 100; i++) { testInst.Add(i); } for (int i = 0; i < 100; i++) { Assert.AreEqual(i, testInst.IndexOf(i)); } Assert.AreEqual(-1, testInst.IndexOf(null)); testInst.AddFirst(null); Assert.AreEqual(0, testInst.IndexOf(null)); }
public void SerializeCircularListsIgnore() { CircularList circularList = new CircularList(); circularList.Add(null); circularList.Add(new CircularList { null }); circularList.Add(new CircularList { new CircularList { circularList } }); string json = JsonConvert.SerializeObject(circularList, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); StringAssert.AreEqual(@"[ null, [ null ], [ [] ] ]", json); }
protected override void ProcessFigure(CircularList<Point> list, Point3DCollection vertices, Vector3DCollection normals, Int32Collection indices, PointCollection textures) { int offset = vertices.Count; for (int i = 0; i <= list.Count; i++) { Point pt = list[i]; // Set vertices. vertices.Add(new Point3D(pt.X, pt.Y, 0)); vertices.Add(new Point3D(pt.X, pt.Y, -Depth)); // Set texture coordinates. textures.Add(new Point((double)i / list.Count, 0)); textures.Add(new Point((double)i / list.Count, 1)); // Set triangle indices. if (i < list.Count) { indices.Add(offset + i * 2 + 0); indices.Add(offset + i * 2 + 2); indices.Add(offset + i * 2 + 1); indices.Add(offset + i * 2 + 1); indices.Add(offset + i * 2 + 2); indices.Add(offset + i * 2 + 3); } } }
public void TestRemovePositiveTest() { CircularList <Point> points = new CircularList <Point>(); Point p1 = new Point(1, 1); Point p2 = new Point(2, 2); Point p3 = new Point(3, 3); points.Insert(0, p1); points.Insert(1, p2); points.Insert(2, p3); //Проверка удаления с середины Assert.AreEqual(points.Remove(p2), true); Assert.AreEqual(points[1], p3); // Проверка удаления с головы Assert.AreEqual(points.Remove(p1), true); Assert.AreEqual(points[0], p3); //Проверка удаления последнего элемента Assert.AreEqual(points.Remove(p3), true); Assert.AreEqual(points.Count, 0); }
public RandomReferer() { var referersLength = referers.Length; referersCircularList = new CircularList <int>(() => new UniqueRandomizer().GenerateRandom(referersLength, 0, referersLength)); }
// Use this for initialization void Start() { validateData = new Regex("(-)*([0-9])+.([0-9])+"); framerateFilter = new CircularList <float>(60); lastUpdate = System.DateTime.Now; actualRotation = Quaternion.identity; baselineRotation = Quaternion.identity; invBaselineRotation = Quaternion.identity; lastRotation = Quaternion.identity; headActualRotation = Quaternion.identity; headBaselineRotation = Quaternion.identity; headInvBaselineRotation = Quaternion.identity; //Icredibly enough the Unity orientation methods work OK in Japan Input.gyro.enabled = true; orientationFilter = new CircularList <Quaternion>(FilterSize); headOrientationFilter = new CircularList <Quaternion>(FilterSize); StartCoroutine(FPS()); CommToAndroid.CallAndroidMethod("setGameObject", this.name); if (SystemInfo.deviceType == DeviceType.Handheld) { SensorMode currentSensor = (SensorMode)System.Enum.Parse(typeof(SensorMode), CommToAndroid.CallAndroidMethod <string>("getSensorMode")); if (currentSensor != SourceIMU) { SetSourceIMU(SourceIMU); } } }
public static void Walk(CircularList circlist) { Node aux = circlist.head; if (aux == null) { return; } while (true) { Console.Clear(); Console.WriteLine("-----{ Walk Contact }-----"); Console.WriteLine("Left arrow: previous"); Console.WriteLine("Right arrow: next"); Console.WriteLine("Esc to Exit"); Console.WriteLine("--------------------------"); Console.WriteLine(aux.data); string key = Console.ReadKey().Key.ToString(); if (key == "LeftArrow") { aux = aux.temp; } else if (key == "RightArrow") { aux = aux.next; } else if (key == "Escape") { break; } } Console.Clear(); }
public void TestRemoveNegativeTest() { CircularList <Point> points = new CircularList <Point>(); Point p1 = new Point(1, 1); Point p2 = new Point(2, 2); Point p3 = new Point(3, 3); Point p4 = new Point(4, 4); //Проверка удаления не существующего элемента в пустом списке Assert.AreEqual(points.Remove(p3), false); points.Insert(0, p1); //Проверка удаления не существующего элемента в списке длиной 1 Assert.AreEqual(points.Remove(p3), false); points.Insert(1, p2); //Проверка удаления не существующего элемента в списке длиной 2 Assert.AreEqual(points.Remove(p3), false); points.Insert(2, p3); //Проверка удаления не существующего элемента в списке длиной 3 Assert.AreEqual(points.Remove(p3), false); }
public void RemoveRangeSimple() { CircularList <int> list = PrepareList <int>(8, 4, 8); // remove 2 of wrapped, remains wrapped list.RemoveRange(6, 2); // last 2 // remove both wrapped an non-wrapped part list.RemoveRange(3, 3); // last 3 // remove from non-wrapped list.RemoveRange(1, 2); // last 2 Assert.AreEqual(1, list.Count); Assert.AreEqual(0, list[0]); list = PrepareList <int>(8, 4, 8); // remove 2 of non-wrapped list.RemoveRange(0, 2); // remove both wrapped an non-wrapped part list.RemoveRange(0, 3); // remove from non-wrapped list.RemoveRange(0, 2); Assert.AreEqual(1, list.Count); Assert.AreEqual(7, list[0]); // 1 element wrapped from down list = new CircularList <int>(4); list.InsertRange(0, new[] { 1 }); // startIndex = 3, count = 1 list.RemoveRange(0, 1); Assert.AreEqual(0, list.Count); }
public void LastIndexOfWorks() { var testInst = new CircularList <int>(500); Assert.AreEqual(-1, testInst.LastIndexOf(100)); for (int i = 50; i < 100; i++) { testInst.AddLast(i); } for (int i = 49; i >= 0; i--) { testInst.AddFirst(i); } for (int i = 0; i < 100; i++) { Assert.AreEqual(i, testInst.LastIndexOf(i)); } Assert.AreEqual(-1, testInst.LastIndexOf(-1)); for (int i = 0; i < 100; i++) { testInst.AddFirst(i); } for (int i = 0; i < 100; i++) { Assert.AreEqual(i + 100, testInst.LastIndexOf(i)); } }
public void FindIndexWorks() { var testInst = new CircularList <int>(500); for (int i = 0; i < 500; i++) { testInst.AddLast(i); } for (int i = 0; i < 200; i++) { testInst.RemoveFirst(); } for (int i = 0; i < 100; i++) { testInst.AddLast(i); } for (int i = 0; i < 100; i++) { int index = testInst.FindIndex(val => val == i); Assert.AreEqual(i + 300, index); } Assert.AreEqual(-1, testInst.FindIndex(val => false)); }
public static void Initialize <T>(this CircularList <T> value) { if (value.Any()) { value.CurrentItem = value[0]; } }
private CameraTriggerService() { SelectedDeviceIndex = -1; CaptureDevices = new List<string>(); RegionOfInterestPoints = new List<System.Drawing.Point>(); diffHistory = new CircularList<int>(MOVING_AVERAGE_FRAMES); FilterInfoCollection fc = new FilterInfoCollection(FilterCategory.VideoInputDevice); for (int i = 0; i < fc.Count; i++) { CaptureDevices.Add(fc[i].Name); } // NOTE: We always use the first found capture device // In cases where we have an internal device (integrated webcam) // and an external device (which is the prefered device) we maybe // have to implement some logic that the prefered device is taken by default! SetCameraDevice(0); // NOTE: The default value of 10s should be a good enough default value TriggerBlockTimeMs = 10 * 1000; // NOTE: We specify a default ROI which is a rectangle in the middle of the // captured frame RegionOfInterestPoints.Add(new System.Drawing.Point(CAPTURE_FRAME_WIDTH / 2 - 20, 0)); RegionOfInterestPoints.Add(new System.Drawing.Point(CAPTURE_FRAME_WIDTH / 2 + 20, 0)); RegionOfInterestPoints.Add(new System.Drawing.Point(CAPTURE_FRAME_WIDTH / 2 + 20, CAPTURE_FRAME_HEIGHT)); RegionOfInterestPoints.Add(new System.Drawing.Point(CAPTURE_FRAME_WIDTH / 2 - 20, CAPTURE_FRAME_HEIGHT)); }
public void ClearWorks() { var testInst = new CircularList <int>(500); for (int i = 0; i < 100; i++) { testInst.AddLast(i); } for (int i = 0; i < 100; i++) { testInst.AddFirst(i); } Assert.AreEqual(200, testInst.Count); Assert.AreEqual(500, testInst.Capacity); testInst.Clear(); Assert.AreEqual(0, testInst.Count); Assert.AreEqual(500, testInst.Capacity); testInst.TrimExcess(); Assert.AreEqual(0, testInst.Count); Assert.AreEqual(0, testInst.Capacity); }
public RandomGoogleReferer() { var googleDomainExtensionsLength = GoogleDomainExtensions.Length; googleDomainExtensionCircularList = new CircularList <int>(() => new UniqueRandomizer().GenerateRandom(googleDomainExtensionsLength, 0, googleDomainExtensionsLength)); }
/// <summary> /// Performs a binary search on the list using the comparer. /// </summary> private protected static int BinarySearchWithComparer(CircularList <T> list, int index, int length, T value, IComparer <T> comparer) { int lo = index; int hi = index + length - 1; while (lo <= hi) { int i = lo + ((hi - lo) >> 1); int order = comparer.Compare(list.ElementAt(i), value); if (order == 0) { return(i); } if (order < 0) { lo = i + 1; } else { hi = i - 1; } } return(~lo); }
public void RemoveFirstLastWorks() { var testInst = new CircularList <int>(); var cmpList = new List <int>(); for (int i = 0; i < 100; i++) { testInst.AddFirst(i); testInst.AddLast(-i); cmpList.Insert(0, i); cmpList.Add(-i); } AreEqual(cmpList, testInst, "RemoveFirstLastWorks.Initial"); for (int i = 99; i >= 0; i--) { Assert.AreEqual(i, testInst.RemoveFirst()); Assert.AreEqual(-i, testInst.RemoveLast()); cmpList.RemoveAt(0); cmpList.RemoveAt(cmpList.Count - 1); AreEqual(cmpList, testInst, "RemoveFirstLastWorks"); } }
public void RemoveAtWorksRandomTest() { var testInst = new CircularList <int>(); var cmpList = new List <int>(); int seed = Environment.TickCount; Random rnd = new Random(seed); for (int i = 1; i < 200; i++) { if (rnd.Next(2) == 0) { testInst.AddFirst(i); cmpList.Insert(0, i); } else { testInst.Add(i); cmpList.Add(i); } } AreEqual(cmpList, testInst, "RemoveAtWorksRandomTest.Prepare. Seed = " + seed.ToString()); for (int i = 1; i < 200; i++) { int index = rnd.Next(0, testInst.Count); testInst.RemoveAt(index); cmpList.RemoveAt(index); AreEqual(cmpList, testInst, "RemoveAtWorksRandomTest. Seed = " + seed.ToString()); } }
void GetCircular() { //MvvmTest.Helpers.CommonHelpers.ShowAlert("circular"); List <CircularModel> circularList = null; Task.Factory.StartNew(() => { ISyncServices syncService = new SyncServices(); circularList = syncService.GetCircular(); }).ContinueWith((obj) => { Device.BeginInvokeOnMainThread(() => { if (circularList != null) { //MvvmTest.Helpers.CommonHelpers.ShowAlert("circular success"); foreach (var item in circularList) { item.cirName = item.cirName.ToUpper(); CircularList.Add(item); } //CircularList = new ObservableCollection<CircularModel>(circularList); } }); }); }
public void AddLastWorks() { var testInst = new CircularList <int>(); var cmpList = new List <int>(); for (int i = 0; i < 100; i++) { testInst.AddLast(i); cmpList.Add(i); AreEqual(cmpList, testInst, "AddLast"); } for (int i = 0; i < 50; i++) { testInst.RemoveFirst(); cmpList.RemoveAt(0); AreEqual(cmpList, testInst, "AddLast.Remove"); } for (int i = 0; i < 200; i++) { testInst.AddLast(i); cmpList.Add(i); AreEqual(cmpList, testInst, "AddLast.Second"); } }
public void LastIndexOfOnSubrangeWorks() { var testInst = new CircularList <int>(500); for (int i = 50; i < 100; i++) { testInst.AddLast(i); } for (int i = 49; i >= 0; i--) { testInst.AddFirst(i); } var cmpList = new List <int>(Enumerable.Range(0, 100)); for (int i = 0; i < 100; i++) { Assert.AreEqual(cmpList.LastIndexOf(i, Math.Min(testInst.Count - 1, i + 10), Math.Min(20, i + 11)), testInst.LastIndexOf(i, Math.Min(testInst.Count - 1, i + 10), Math.Min(20, i + 11))); Assert.AreEqual(i, testInst.LastIndexOf(i, Math.Min(testInst.Count - 1, i + 10), Math.Min(20, i + 11))); } Assert.AreEqual(-1, testInst.LastIndexOf(50, 60, 10)); Assert.AreEqual(-1, testInst.LastIndexOf(-1, 99, 100)); Assert.AreEqual(-1, testInst.LastIndexOf(0, 99, 1)); }
public void RemoveAll() { CircularList <int?> clist = PrepareList <int?>(10, 4, 8); List <int?> list = new List <int?>(clist); // no removing list.RemoveAll(i => false); clist.RemoveAll(i => false); Assert.IsTrue(clist.SequenceEqual(list)); // remove from the end list.RemoveAll(i => i > 4); clist.RemoveAll(i => i > 4); Assert.IsTrue(clist.SequenceEqual(list)); // remove from the beginning clist = PrepareList <int?>(10, 8, 8); list = new List <int?>(clist); list.RemoveAll(i => i < 4); clist.RemoveAll(i => i < 4); Assert.IsTrue(clist.SequenceEqual(list)); // remove every second clist = PrepareList <int?>(10, 8, 8); list = new List <int?>(clist); list.RemoveAll(i => (i & 1) == 0); clist.RemoveAll(i => (i & 1) == 0); Assert.IsTrue(clist.SequenceEqual(list)); }
static IEnumerable <T> ToEnumerator(CircularList <T> list) { for (int i = 0; i < list.Count; i++) { yield return(list[i]); } }
public void RemoveLastAndFirst() { // normal, non-wrapped list CircularList <int> list = PrepareList <int>(4, 0, 4); list.Remove(3); // last list.Remove(0); // first list.Remove(2); // last list.Remove(1); // first Assert.AreEqual(0, list.Count); // wrapped list, removing lasts list = PrepareList <int>(4, 2, 4); list.Remove(3); list.Remove(2); list.Remove(1); Assert.AreEqual(1, list.Count); Assert.AreEqual(0, list[0]); // wrapped list, removing firsts list = PrepareList <int>(4, 2, 4); list.RemoveAt(0); list.RemoveAt(0); list.RemoveAt(0); Assert.AreEqual(1, list.Count); Assert.AreEqual(3, list[0]); }
public void CopyToWorks() { var testInst = new CircularList <int>(500); for (int i = 50; i < 100; i++) { testInst.AddLast(i); } for (int i = 49; i >= 0; i--) { testInst.AddFirst(i); } int[] array = new int[200]; testInst.CopyTo(array, 100); for (int i = 0; i < 100; i++) { Assert.AreEqual(0, array[i]); } for (int i = 0; i < 100; i++) { Assert.AreEqual(i, array[i + 100]); } }
public void ContainsWorksWithOffset() { var testInst = new CircularList <int>(500); for (int i = 50; i < 100; i++) { testInst.AddLast(i); } for (int i = 49; i >= 0; i--) { testInst.AddFirst(i); } for (int i = -100; i < 0; i++) { Assert.IsFalse(testInst.Contains(i)); } for (int i = 0; i < 100; i++) { Assert.IsTrue(testInst.Contains(i)); } for (int i = 100; i < 200; i++) { Assert.IsFalse(testInst.Contains(i)); } }
public void Constructor_CustomCapacity() { CircularList<SimpleElement> list = new CircularList<SimpleElement>(55); Assert.AreEqual(55, list.MaxLength, "Capacity should be 55"); Assert.IsEmpty(list, "List should be empty"); Assert.AreEqual(-1, list.CurrentIndex, "Current index should be -1"); }
public CircularListTests() { m_list = new CircularList<int>(10); m_list.MoveNext(); for (int i = 0; i < m_list.Size; ++i) m_list[i] = i; }
public GameContext(Player[] players, IEnumerable<IDoorsFactory> doorsFactories, IEnumerable<ITreasuresFactory> treasuresFactories) { _doorsFactories = doorsFactories; _treasuresFactories = treasuresFactories; Players = new CircularList<Player>(players); RequestSink = new RequestSink(); Dungeon = new Dungeon(this); }
public void TestCircularList() { var a = new List<int> {1, 2, 3, 4}; var c = new CircularList<int>(a); Assert.AreEqual(4, c.Count); Assert.AreEqual(2, c[5]); Assert.AreEqual(4, c[-1]); }
/// <summary> /// Initializes a new instance of the <see cref="GameController"/> class. /// </summary> /// <param name="isOnline">if set to <c>true</c> [the game is online].</param> /// <param name="names">The names of the players.</param> /// <param name="sizeOfBoard">The size of board.</param> public GameController(bool isOnline, List<string> names, uint sizeOfBoard) { IsOnline = isOnline; Players = new Players(names, Globals.NumberOfLetters); Board = new Board(0, sizeOfBoard); Changes = new CircularList<Change>(); IsFirstTime = true; }
public AutoupdateRegister(int registerSize = 100) { if (registerSize <= 0) throw new ArgumentOutOfRangeException("registerSize"); Contract.EndContractBlock(); m_register = new CircularList<List<IAutoupdateableGameActor>>(registerSize); m_register.MoveNext(); }
/// <summary> /// Constructor, initializing the sample size to the specified number. /// </summary> public SimpleMovingAverage(int numSamples) { if (numSamples <= 0) { throw new ArgumentOutOfRangeException("numSamples can't be negative or 0."); } samples = new CircularList<float>(numSamples); total = 0; }
// ProcessFigure override. protected override void ProcessFigure(CircularList<Point> list, Point3DCollection vertices, Vector3DCollection normals, Int32Collection indices, PointCollection textures) { int k = Slices * list.Count; int offset = vertices.Count; for (int i = 0; i < list.Count; i++) { Point ptBefore = list[i - 1]; Point pt = list[i]; Point ptAfter = list[i + 1]; Vector v1 = pt - ptBefore; v1.Normalize(); Vector v1Rotated = new Vector(-v1.Y, v1.X); Vector v2 = ptAfter - pt; v2.Normalize(); Vector v2Rotated = new Vector(-v2.Y, v2.X); Line2D line1 = new Line2D(pt, ptBefore); Line2D line2 = new Line2D(pt, ptAfter); for (int slice = 0; slice < Slices; slice++) { // Angle ranges from 0 to 360 degrees. double angle = slice * 2 * Math.PI / Slices; double scale = EllipseWidth / 2 * Math.Sin(angle); double depth = -Depth / 2 * (1 - Math.Cos(angle)); Line2D line1Shifted = line1 + scale * v1Rotated; Line2D line2Shifted = line2 + scale * v2Rotated; Point ptIntersect = line1Shifted * line2Shifted; // Set vertex. vertices.Add(new Point3D(ptIntersect.X, ptIntersect.Y, depth)); // Set texture coordinate. textures.Add(new Point((double)i / list.Count, Math.Sin(angle / 2))); // Set triangle indices. indices.Add(offset + (Slices * i + slice + 0) % k); indices.Add(offset + (Slices * i + slice + 1) % k); indices.Add(offset + (Slices * i + slice + 0 + Slices) % k); indices.Add(offset + (Slices * i + slice + 0 + Slices) % k); indices.Add(offset + (Slices * i + slice + 1) % k); indices.Add(offset + (Slices * i + slice + 1 + Slices) % k); } } }
/// <summary> /// Constructor, initializing the sample size to the specified number. /// </summary> public MA(int numSamples) { this.count = numSamples; if (numSamples <= 0) { throw new ArgumentOutOfRangeException("numSamples can't be negative or 0."); } samples = new CircularList<double>(numSamples); total = 0; }
public void Clear_BeforeLooping() { CircularList<SimpleElement> list = new CircularList<SimpleElement>(3); SimpleElement one = new SimpleElement() { String = "One" }; SimpleElement two = new SimpleElement() { String = "Two" }; list.Add(one); list.Add(two); list.Clear(); Assert.IsEmpty(list, "List should be empty as it has just been cleared"); Assert.AreEqual(-1, list.CurrentIndex, "The index should have been reset by the clear"); }
private static void CircularList() { CircularList<String> circularList = new CircularList<String>(); circularList.Add("Tomas"); circularList.Add("Nico"); circularList.Add("Andreas"); Console.WriteLine(circularList.Current()); circularList.Next(); Console.WriteLine(circularList.Current()); circularList.Next(); Console.WriteLine(circularList.Current()); circularList.Next(); Console.WriteLine(circularList.Current()); Console.WriteLine("Virker foreach?"); foreach (var str in circularList) { Console.WriteLine(str); } }
public void Enumerator_AboutToLoop_LongerList() { CircularList<SimpleElement> list = new CircularList<SimpleElement>(5); SimpleElement one = new SimpleElement() { String = "One" }; SimpleElement two = new SimpleElement() { String = "Two" }; SimpleElement three = new SimpleElement() { String = "Three" }; SimpleElement four = new SimpleElement() { String = "Four" }; SimpleElement five = new SimpleElement() { String = "FIve" }; list.Add(one); list.Add(two); list.Add(three); list.Add(four); list.Add(five); List<SimpleElement> actual = new List<SimpleElement>(); foreach (SimpleElement cur in list) { actual.Add(cur); } Assert.AreEqual(5, actual.Count, "The foreach should have yielded 5 items"); Assert.AreEqual(one, actual[0], "First yielded item is wrong"); Assert.AreEqual(two, actual[1], "Second yielded item is wrong"); Assert.AreEqual(three, actual[2], "Third yielded item is wrong"); Assert.AreEqual(four, actual[3], "Fourth yielded item is wrong"); Assert.AreEqual(five, actual[4], "Fifth yielded item is wrong"); }
public void Enumerator_AfterLooping_LongerList() { CircularList<SimpleElement> list = new CircularList<SimpleElement>(3); SimpleElement one = new SimpleElement() { String = "One" }; SimpleElement two = new SimpleElement() { String = "Two" }; SimpleElement three = new SimpleElement() { String = "Three" }; SimpleElement four = new SimpleElement() { String = "Four" }; SimpleElement five = new SimpleElement() { String = "Five" }; list.Add(one); // ==> 0 list.Add(two); // ==> 1 list.Add(three); // ==> 2 list.Add(four); // ==> 0 list.Add(five); // ==> 1 List<SimpleElement> actual = new List<SimpleElement>(); foreach (SimpleElement cur in list) { actual.Add(cur); } Assert.AreEqual(3, actual.Count, "The foreach should have yielded 3 items"); Assert.AreEqual(three, actual[0], "First yielded item is wrong"); Assert.AreEqual(four, actual[1], "Second yielded item is wrong"); Assert.AreEqual(five, actual[2], "Third yielded item is wrong"); }
public void Contains_AboutToLoop() { CircularList<SimpleElement> list = new CircularList<SimpleElement>(2); SimpleElement one = new SimpleElement() { String = "One" }; SimpleElement two = new SimpleElement() { String = "Two" }; SimpleElement three = new SimpleElement() { String = "Three" }; list.Add(one); list.Add(two); Assert.IsTrue(list.Contains(two), "The element should be in the list"); Assert.IsTrue(list.Contains(one), "The element should be in the list"); Assert.IsFalse(list.Contains(three), "The element should not be in the list"); }
/// <summary> /// This method can be used to send multiple messages to a queue or a topic. /// </summary> /// <param name="messageSender">A MessageSender object used to send messages.</param> /// <param name="messageTemplateEnumerable">A collection of message templates to use to clone messages from.</param> /// <param name="getMessageNumber">This function returns the message number.</param> /// <param name="messageCount">The total number of messages to send.</param> /// <param name="taskId">The sender task id.</param> /// <param name="updateMessageId">Indicates whether to use a unique id for each message.</param> /// <param name="addMessageNumber">Indicates whether to add a message number property.</param> /// <param name="oneSessionPerTask">Indicates whether to use a different session for each sender task.</param> /// <param name="logging">Indicates whether to enable logging of message content and properties.</param> /// <param name="verbose">Indicates whether to enable verbose logging.</param> /// <param name="statistics">Indicates whether to enable sender statistics.</param> /// <param name="messageInspector">A BrokeredMessage inspector object.</param> /// <param name="updateStatistics">When statistics = true, this delegate is invoked to update statistics.</param> /// <param name="sendBatch">Indicates whether to use SendBatch.</param> /// <param name="isBinary">Indicates if the body is binary or not.</param> /// <param name="senderThinkTime">Indicates whether to use think time.</param> /// <param name="thinkTime">Indicates the value of the sender think time.</param> /// <param name="batchSize">Indicates the batch size.</param> /// <param name="bodyType">Contains the body type.</param> /// <param name="cancellationTokenSource">The cancellation token.</param> /// <param name="traceMessage">A trace message.</param> /// <returns>True if the method completed without exceptions, false otherwise.</returns> public bool SendMessages(MessageSender messageSender, IEnumerable<BrokeredMessage> messageTemplateEnumerable, Func<long> getMessageNumber, long messageCount, int taskId, bool updateMessageId, bool addMessageNumber, bool oneSessionPerTask, bool logging, bool verbose, bool statistics, bool sendBatch, bool isBinary, int batchSize, bool senderThinkTime, int thinkTime, BodyType bodyType, IBrokeredMessageInspector messageInspector, UpdateStatisticsDelegate updateStatistics, CancellationTokenSource cancellationTokenSource, out string traceMessage) { if (messageSender == null) { throw new ArgumentNullException(MessageSenderCannotBeNull); } if (messageTemplateEnumerable == null) { throw new ArgumentNullException(BrokeredMessageCannotBeNull); } if (cancellationTokenSource == null) { throw new ArgumentNullException(CancellationTokenSourceCannotBeNull); } var messageTemplateCircularList = new CircularList<BrokeredMessage>(messageTemplateEnumerable); long messagesSent = 0; long totalElapsedTime = 0; long minimumSendTime = long.MaxValue; long maximumSendTime = 0; bool ok = true; string exceptionMessage = null; var wcfUri = IsCloudNamespace ? new Uri(namespaceUri, messageSender.Path) : new UriBuilder { Host = namespaceUri.Host, Path = string.Format("{0}/{1}", namespaceUri.AbsolutePath, messageSender.Path), Scheme = "sb" }.Uri; try { long messageNumber; if (sendBatch && batchSize > 1) { var more = true; while (!cancellationTokenSource.Token.IsCancellationRequested && more) { var messageList = new List<BrokeredMessage>(); var messageNumberList = new List<long>(); while (!cancellationTokenSource.Token.IsCancellationRequested && messageNumberList.Count < batchSize && more) { messageNumber = getMessageNumber(); if (messageNumber < messageCount) { messageNumberList.Add(messageNumber); } else { more = false; } } if (messageNumberList.Count > 0) { long elapsedMilliseconds = 0; RetryHelper.RetryAction(() => { var useWcf = bodyType == BodyType.Wcf; for (var i = 0; i < messageNumberList.Count; i++) { messageList.Add(useWcf? CreateMessageForWcfReceiver( messageTemplateCircularList.Next, taskId, updateMessageId, oneSessionPerTask, wcfUri) : CreateMessageForApiReceiver( messageTemplateCircularList.Next, taskId, updateMessageId, oneSessionPerTask, isBinary, bodyType, messageInspector)); if (addMessageNumber) { messageList[i].Properties[MessageNumber] = messageNumberList[i]; } } if (messageNumberList.Count > 0) { SendBatch(messageSender, messageList, taskId, isBinary, useWcf, logging, verbose, out elapsedMilliseconds); } }, writeToLog); messagesSent += messageList.Count; if (elapsedMilliseconds > maximumSendTime) { maximumSendTime = elapsedMilliseconds; } if (elapsedMilliseconds < minimumSendTime) { minimumSendTime = elapsedMilliseconds; } totalElapsedTime += elapsedMilliseconds; if (statistics) { updateStatistics(messageList.Count, elapsedMilliseconds, DirectionType.Send); } } if (senderThinkTime) { WriteToLog(string.Format(SleepingFor, thinkTime)); Thread.Sleep(thinkTime); } } } else { while ((messageNumber = getMessageNumber()) < messageCount && !cancellationTokenSource.Token.IsCancellationRequested) { long elapsedMilliseconds = 0; RetryHelper.RetryAction(() => { var useWcf = bodyType == BodyType.Wcf; var outboundMessage = useWcf ? CreateMessageForWcfReceiver( messageTemplateCircularList.Next, taskId, updateMessageId, oneSessionPerTask, wcfUri) : CreateMessageForApiReceiver( messageTemplateCircularList.Next, taskId, updateMessageId, oneSessionPerTask, isBinary, bodyType, messageInspector); if (addMessageNumber) { // ReSharper disable AccessToModifiedClosure outboundMessage.Properties[MessageNumber] = messageNumber; // ReSharper restore AccessToModifiedClosure } SendMessage(messageSender, outboundMessage, taskId, isBinary, useWcf, logging, verbose, out elapsedMilliseconds); }, writeToLog); messagesSent++; if (elapsedMilliseconds > maximumSendTime) { maximumSendTime = elapsedMilliseconds; } if (elapsedMilliseconds < minimumSendTime) { minimumSendTime = elapsedMilliseconds; } totalElapsedTime += elapsedMilliseconds; if (statistics) { updateStatistics(1, elapsedMilliseconds, DirectionType.Send); } if (senderThinkTime) { WriteToLog(string.Format(SleepingFor, thinkTime)); Thread.Sleep(thinkTime); } } } } catch (ServerBusyException ex) { messageSender.Abort(); exceptionMessage = string.Format(ExceptionOccurred, ex.Message); ok = false; } catch (MessageLockLostException ex) { messageSender.Abort(); exceptionMessage = string.Format(ExceptionOccurred, ex.Message); ok = false; } catch (CommunicationObjectAbortedException ex) { messageSender.Abort(); exceptionMessage = string.Format(ExceptionOccurred, ex.Message); ok = false; } catch (CommunicationObjectFaultedException ex) { messageSender.Abort(); exceptionMessage = string.Format(ExceptionOccurred, ex.Message); ok = false; } catch (CommunicationException ex) { messageSender.Abort(); exceptionMessage = string.Format(ExceptionOccurred, ex.Message); ok = false; } catch (TimeoutException ex) { messageSender.Abort(); exceptionMessage = string.Format(ExceptionOccurred, ex.Message); ok = false; } catch (Exception ex) { messageSender.Abort(); exceptionMessage = string.Format(ExceptionOccurred, ex.Message); ok = false; } var averageSendTime = messagesSent > 0 ? totalElapsedTime / messagesSent : maximumSendTime; // ReSharper disable RedundantCast var messagesPerSecond = totalElapsedTime > 0 ? (double)(messagesSent * 1000) / (double)totalElapsedTime : 0; // ReSharper restore RedundantCast var builder = new StringBuilder(); builder.AppendLine(string.Format(CultureInfo.CurrentCulture, SenderStatisticsHeader, taskId)); if (!string.IsNullOrWhiteSpace(exceptionMessage)) { builder.AppendLine(exceptionMessage); } builder.AppendLine(string.Format(CultureInfo.CurrentCulture, SenderStatitiscsLine1, messagesSent, messagesPerSecond, totalElapsedTime)); builder.AppendLine(string.Format(CultureInfo.CurrentCulture, SenderStatitiscsLine2, averageSendTime, minimumSendTime == long.MaxValue ? 0 : minimumSendTime, maximumSendTime)); traceMessage = builder.ToString(); return ok; }
public void CircularListTest1() { ICircularList<int> lst = new CircularList<int>(5); for (int i = 0; i < 5; ++i) lst.Add(i); // verify assert's integrity Assert.True(lst.Count == 5); Assert.True(lst.GetItem(0) == 0); Assert.True(lst.GetItem(4) == 4); lst.Add(5); // step out from the max size Assert.True(lst.Count == 5); Assert.True(lst.GetItem(0) == 1); Assert.True(lst.GetItem(4) == 5); // complete count items for (int i = 0; i < 4; ++i) lst.Add(6 + i); // verify assert's integrity Assert.True(lst.Count == 5); Assert.True(lst.GetItem(0) == 5); Assert.True(lst.GetItem(4) == 9); }
/// <summary> /// Plays a hand from the start. Note that this method will <b>not</b> resume a game from a saved hand _history. /// </summary> /// <param name="handHistory">An new hand _history with the list of players and the game parameters.</param> public void PlayHand(HandHistory handHistory) { #region Hand Setup _seats = handHistory.Players; handHistory.HoleCards = new ulong[_seats.Length]; handHistory.DealtCards = 0UL; handHistory.Flop = 0UL; handHistory.Turn = 0UL; handHistory.River = 0UL; //Setup the hand _history this._history = handHistory; //Create a new map from player names to player chips for the BetManager Dictionary<string, double> namesToChips = new Dictionary<string, double>(); //Create a new list of players for the PlayerManager _playerIndices = new CircularList<int>(); _playerIndices.Loop = true; for (int i = 0; i < _seats.Length; i++) { namesToChips[_seats[i].Name] = _seats[i].Chips; if (_seats[i].SeatNumber == _history.Button) { _buttonIdx = i; _utgIdx = (i + 1) % _seats.Length; } } for (int i = (_buttonIdx + 1) % _seats.Length; _playerIndices.Count < _seats.Length;) { _playerIndices.Add(i); i = (i + 1) % _seats.Length; } _betManager = new BetManager(namesToChips, _history.BettingStructure, _history.AllBlinds, _history.Ante); _potManager = new PotManager(_seats); #endregion if (_betManager.In > 1) { GetBlinds(); DealHoleCards(); } _history.CurrentRound = Round.Preflop; if (_betManager.CanStillBet > 1) { GetBets(_history.PreflopActions); } if (_betManager.In <= 1) { payWinners(); return; } DealFlop(); _history.CurrentRound = Round.Flop; if (_betManager.CanStillBet > 1) { GetBets(_history.FlopActions); } if (_betManager.In <= 1) { payWinners(); return; } DealTurn(); _history.CurrentRound = Round.Turn; if (_betManager.CanStillBet > 1) { GetBets(_history.TurnActions); } if (_betManager.In <= 1) { payWinners(); return; } DealRiver(); _history.CurrentRound = Round.River; if (_betManager.CanStillBet > 1) { GetBets(_history.RiverActions); } if (_betManager.In <= 1) { payWinners(); return; } payWinners(); _history.ShowDown = true; _history.CurrentRound = Round.Over; }
public void Enumerator_BeforeLooping() { CircularList<SimpleElement> list = new CircularList<SimpleElement>(3); SimpleElement one = new SimpleElement() { String = "One" }; SimpleElement two = new SimpleElement() { String = "Two" }; list.Add(one); list.Add(two); List<SimpleElement> actual = new List<SimpleElement>(); foreach (SimpleElement cur in list) { actual.Add(cur); } Assert.AreEqual(2, actual.Count, "The foreach should have yielded 2 items"); Assert.AreEqual(one, actual[0], "First yielded item is wrong"); Assert.AreEqual(two, actual[1], "Second yielded item is wrong"); }
public void ForLoop_BeforeLooping() { CircularList<SimpleElement> list = new CircularList<SimpleElement>(3); var elements = new List<SimpleElement>() { new SimpleElement() { String = "One" }, new SimpleElement() { String = "Two" } }; foreach (var cur in elements) { list.Add(cur); } for (int i=0; i!=list.Count; i++) { Assert.AreEqual(elements[i], list[i], "Item {0} is wrong"); } }
public void IndexOf_AfterLooping() { CircularList<SimpleElement> list = new CircularList<SimpleElement>(2); SimpleElement one = new SimpleElement() { String = "One" }; SimpleElement two = new SimpleElement() { String = "Two" }; SimpleElement three = new SimpleElement() { String = "Three" }; list.Add(one); list.Add(two); list.Add(three); Assert.AreEqual(1, list.IndexOf(two), "Index should be 1 as this is the second element"); Assert.AreEqual(-1, list.IndexOf(one), "Index should be -1 as this item has been replaced by new content"); Assert.AreEqual(0, list.IndexOf(three), "Index should be 0 as the item is the first to be added after looping"); }
public void IndexOf_BeforeLooping() { CircularList<SimpleElement> list = new CircularList<SimpleElement>(3); SimpleElement one = new SimpleElement() { String = "One" }; SimpleElement two = new SimpleElement() { String = "Two" }; SimpleElement three = new SimpleElement() { String = "Three" }; list.Add(one); list.Add(two); Assert.AreEqual(1, list.IndexOf(two), "Index should be 1 as this is the second element"); Assert.AreEqual(0, list.IndexOf(one), "Index should be 0 as this is the first element"); Assert.AreEqual(-1, list.IndexOf(three), "Index should be -1 as the item is not in the list"); }
public void CircularListTest2() { ICircularList<int> lst = new CircularList<int>(5); for (int i = 0; i < 15; ++i) lst.Add(i); // verify assert's integrity Assert.True(lst.Count == 5); Assert.True(lst.GetItem(0) == 10); Assert.True(lst.GetItem(4) == 14); var l = lst.Items.ToList(); Assert.True(l.Count == 5); Assert.True(l[0] == 10); Assert.True(l[4] == 14); }
public MA(CircularList<double> samples,int c ) { this.samples = samples; count = c; total = 0; }
/// <summary> /// This method can be used to send multiple messages to a queue or a topic. /// </summary> /// <param name="eventHubClient">An EventHubClient object used to send messages.</param> /// <param name="eventDataTemplateEnumerable">A collection of message templates to use to clone messages from.</param> /// <param name="getMessageNumber">This function returns the message number.</param> /// <param name="messageCount">The total number of messages to send.</param> /// <param name="taskId">The sender task id.</param> /// <param name="updatePartitionKey">Indicates whether to use a unique template key for each message.</param> /// <param name="addMessageNumber">Indicates whether to add a message number property.</param> /// <param name="logging">Indicates whether to enable logging of message content and properties.</param> /// <param name="verbose">Indicates whether to enable verbose logging.</param> /// <param name="statistics">Indicates whether to enable sender statistics.</param> /// <param name="eventDataInspector">Event Data inspector.</param> /// <param name="updateStatistics">When statistics = true, this delegate is invoked to update statistics.</param> /// <param name="sendBatch">Indicates whether to use SendBatch.</param> /// <param name="senderThinkTime">Indicates whether to use think time.</param> /// <param name="thinkTime">Indicates the value of the sender think time.</param> /// <param name="batchSize">Indicates the batch size.</param> /// <param name="cancellationTokenSource">The cancellation token.</param> /// <returns>Trace message.</returns> public async Task<string> SendEventData(EventHubClient eventHubClient, IEnumerable<EventData> eventDataTemplateEnumerable, Func<long> getMessageNumber, long messageCount, int taskId, bool updatePartitionKey, bool addMessageNumber, bool logging, bool verbose, bool statistics, bool sendBatch, int batchSize, bool senderThinkTime, int thinkTime, IEventDataInspector eventDataInspector, UpdateStatisticsDelegate updateStatistics, CancellationTokenSource cancellationTokenSource) { if (eventHubClient == null) { throw new ArgumentNullException(EventHubClientCannotBeNull); } if (eventDataTemplateEnumerable == null) { throw new ArgumentNullException(EventDataTemplateEnumerableCannotBeNull); } if (cancellationTokenSource == null) { throw new ArgumentNullException(CancellationTokenSourceCannotBeNull); } var eventDataCircularList = new CircularList<EventData>(eventDataTemplateEnumerable); long messagesSent = 0; long totalElapsedTime = 0; long minimumSendTime = long.MaxValue; long maximumSendTime = 0; string exceptionMessage = null; try { if (sendBatch && batchSize > 1) { //var more = true; //while (!cancellationTokenSource.Token.IsCancellationRequested && more) //{ // var eventDataList = new List<EventData>(); // var messageNumberList = new List<long>(); // while (!cancellationTokenSource.Token.IsCancellationRequested && // messageNumberList.Count < batchSize && more) // { // messageNumber = getMessageNumber(); // if (messageNumber < messageCount) // { // messageNumberList.Add(messageNumber); // } // else // { // more = false; // } // } // if (messageNumberList.Count > 0) // { // long elapsedMilliseconds = 0; // await RetryHelper.RetryActionAsync(async () => // { // for (var i = 0; i < messageNumberList.Count; i++) // { // eventDataList.Add(eventDataInspector != null? // eventDataInspector.BeforeSendMessage(eventDataCircularList.Next.Clone()) : // eventDataCircularList.Next.Clone()); // if (addMessageNumber) // { // eventDataList[i].Properties[MessageNumber] = messageNumberList[i]; // } // } // if (messageNumberList.Count > 0) // { // elapsedMilliseconds = await SendEventDataBatch(eventHubClient, // eventDataList, // messageNumberList, // taskId, // logging, // verbose); // } // }, // writeToLog); // messagesSent += eventDataList.Count; // if (elapsedMilliseconds > maximumSendTime) // { // maximumSendTime = elapsedMilliseconds; // } // if (elapsedMilliseconds < minimumSendTime) // { // minimumSendTime = elapsedMilliseconds; // } // totalElapsedTime += elapsedMilliseconds; // if (statistics) // { // updateStatistics(eventDataList.Count, elapsedMilliseconds, DirectionType.Send); // } // } // if (senderThinkTime) // { // WriteToLog(string.Format(SleepingFor, thinkTime)); // Thread.Sleep(thinkTime); // } //} } else { long messageNumber; while ((messageNumber = getMessageNumber()) < messageCount && !cancellationTokenSource.Token.IsCancellationRequested) { long elapsedMilliseconds = 0; long number = messageNumber; await RetryHelper.RetryActionAsync(async () => { var eventData = eventDataInspector != null ? eventDataInspector.BeforeSendMessage(eventDataCircularList.Next.Clone()) : eventDataCircularList.Next.Clone(); if (addMessageNumber) { // ReSharper disable AccessToModifiedClosure eventData.Properties[MessageNumber] = number; // ReSharper restore AccessToModifiedClosure } elapsedMilliseconds = await SendEventData(eventHubClient, eventData, number, taskId, logging, verbose); }, writeToLog); messagesSent++; if (elapsedMilliseconds > maximumSendTime) { maximumSendTime = elapsedMilliseconds; } if (elapsedMilliseconds < minimumSendTime) { minimumSendTime = elapsedMilliseconds; } totalElapsedTime += elapsedMilliseconds; if (statistics) { updateStatistics(1, elapsedMilliseconds, DirectionType.Send); } if (senderThinkTime) { WriteToLog(string.Format(SleepingFor, thinkTime)); Thread.Sleep(thinkTime); } } } } catch (ServerBusyException ex) { eventHubClient.Abort(); exceptionMessage = ex.Message; } catch (MessageLockLostException ex) { eventHubClient.Abort(); exceptionMessage = ex.Message; } catch (CommunicationObjectAbortedException ex) { eventHubClient.Abort(); exceptionMessage = ex.Message; } catch (CommunicationObjectFaultedException ex) { eventHubClient.Abort(); exceptionMessage = ex.Message; } catch (CommunicationException ex) { eventHubClient.Abort(); exceptionMessage = ex.Message; } catch (TimeoutException ex) { eventHubClient.Abort(); exceptionMessage = ex.Message; } catch (Exception ex) { eventHubClient.Abort(); exceptionMessage = ex.Message; } var averageSendTime = messagesSent > 0 ? totalElapsedTime / messagesSent : maximumSendTime; // ReSharper disable RedundantCast var messagesPerSecond = totalElapsedTime > 0 ? (double)(messagesSent * 1000) / (double)totalElapsedTime : 0; // ReSharper restore RedundantCast var builder = new StringBuilder(); builder.AppendLine(string.Format(CultureInfo.CurrentCulture, SenderStatisticsHeader, taskId)); if (!string.IsNullOrWhiteSpace(exceptionMessage)) { builder.AppendLine(exceptionMessage); throw new Exception(builder.ToString()); } builder.AppendLine(string.Format(CultureInfo.CurrentCulture, SenderStatitiscsLine1, messagesSent, messagesPerSecond, totalElapsedTime)); builder.AppendLine(string.Format(CultureInfo.CurrentCulture, SenderStatitiscsLine2, averageSendTime, minimumSendTime == long.MaxValue ? 0 : minimumSendTime, maximumSendTime)); return builder.ToString(); }
// Abstract method to convert figure to mesh geometry. protected abstract void ProcessFigure(CircularList<Point> list, Point3DCollection vertices, Vector3DCollection normals, Int32Collection indices, PointCollection textures);
public void Count_BeforeLooping() { CircularList<SimpleElement> list = new CircularList<SimpleElement>(3); SimpleElement one = new SimpleElement() { String = "One" }; SimpleElement two = new SimpleElement() { String = "Two" }; list.Add(one); list.Add(two); Assert.AreEqual(2, list.Count); }
public void Constructor_Default() { CircularList<SimpleElement> list = new CircularList<SimpleElement>(); Assert.AreEqual(10, list.MaxLength, "Default capacity should be 10"); Assert.IsEmpty(list, "List should be empty by default"); Assert.AreEqual(-1, list.CurrentIndex, "Current index should be -1"); }