public void TestClearBasic() { StringBuilder sblMsg = new StringBuilder(99); SortedList sl2 = null; StringBuilder sbl3 = new StringBuilder(99); StringBuilder sbl4 = new StringBuilder(99); StringBuilder sblWork1 = new StringBuilder(99); String s1 = null; String s2 = null; int i = 0; // // Constructor: Create SortedList using this as IComparer and default settings. // sl2 = new SortedList(this); // Verify that the SortedList is not null. Assert.NotNull(sl2); // Verify that the SortedList is empty. Assert.Equal(0, sl2.Count); // now Clear the list and verify the Count sl2.Clear(); //removes 0 element Assert.Equal(0, sl2.Count); // Testcase: add few key-val pairs for (i = 0; i < 100; i++) { sblMsg.Length = 0; sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); sblMsg.Length = 0; sblMsg.Append("val_"); sblMsg.Append(i); s2 = sblMsg.ToString(); sl2.Add(s1, s2); } // now get the list Count and verify Assert.Equal(100, sl2.Count); // now Clear the list and verify the Count sl2.Clear(); //removes all the 100 elements Assert.Equal(0, sl2.Count); }
public void Clear() { _agents?.Clear(); _agents = null; _drawingArea = null; g = null; BMP = null; _envSize = Size.Empty; _kof = 0; }
public void Clear() { _height = 0; _width = 0; _offsetXY = new Point(); _response.Clear(); _response = null; _space?.Clear(); _space = null; for (int i = 0; i < _environmenThreads.Count; i++) { _environmenThreads[i].Abort(); _environmenThreads[i] = null; } _environmenThreads.Clear(); _environmenThreads = null; }
/// <summary> /// 获得显示项的已排序的列表 /// </summary> /// <param name="strRTypeID"></param> /// <param name="intSummaryOrDetail"></param> /// <param name="intUporDown"></param> /// <returns></returns> public static SortedList<int, string> GetShowItems(string strRTypeID, int intSummaryOrDetail, int intUporDown) { SortedList<int, string> showItems = new SortedList<int, string>(); string strSql = "select * from T_ReceiptModCfg where RTypeID='{0}' and SummaryOrDetail={1} and UporDown={2}"; strSql = string.Format(strSql, strRTypeID, intSummaryOrDetail, intUporDown); DataTable dt = (new SqlDBConnect()).Get_Dt(strSql); if (dt == null || dt.Rows.Count <= 0) return null; showItems.Clear(); foreach (DataRow dr in dt.Rows) { showItems.Add(Convert.ToInt32(dr["OrderNum"].ToString().Trim()), dr["ShowItem"].ToString().Trim()); } return showItems; }
public void ResetArena() { // Reset current arena buffer _ptrCurrent = _ptrStart; #if !MEM_GUARD _fragements?.Clear(); #endif // Free old buffers not being used anymore if (_olderBuffers == null) { _used = 0; return; } foreach (var unusedBuffer in _olderBuffers) { _used += unusedBuffer.Item2; NativeMemory.Free((byte *)unusedBuffer.Item1, unusedBuffer.Item2, unusedBuffer.Item3); } _olderBuffers = null; if (_used <= _allocated) { _used = 0; return; } // we'll likely need more memory in the next round, let us increase the size we hold on to NativeMemory.Free(_ptrStart, _allocated, _allocatingThread); // we'll allocate some multiple of the currently allocated amount, that will prevent big spikes in memory // consumption and has the worst case usage of doubling memory utilization var newSize = (_used / _allocated + (_used % _allocated == 0 ? 0 : 1)) * _allocated; _allocated = newSize; _used = 0; if (_allocated > MaxArenaSize) { _allocated = MaxArenaSize; } _ptrCurrent = _ptrStart = null; }
public void createPedestrians() { positions = positions.OrderBy(x => x.getID()).ThenBy(y => y.getTime()).ToList<PedestrianPosition>(); SortedList currentList = new SortedList (); population = new int[(int)pc.total_time + 1]; for (int i = 0; i < positions.Count; i ++) { if (positions.Count() > (i + 1) && positions[i].getX() == positions[i + 1].getX() && positions[i].getY() == positions[i + 1].getY()) { // Only take into account time steps with changed coordinates. We want smooth animation. continue; } currentList.Add(positions[i].getTime(), positions[i]); population[(int) positions[i].getTime ()]++; if ((i == (positions.Count - 1) || positions[i].getID()!=positions[i + 1].getID()) && currentList.Count > 0) { //GameObject p = (GameObject) Instantiate(ped); GameObject p = null; //diff pedestrian prefabs int gender = rnd.Next(0, 2); //Debug.Log(gender); if(gender == 0) p = (GameObject) Instantiate(ped1); else p = (GameObject) Instantiate(ped2); p.tag = "pedestrian"; if(p == null) throw new UnityException("not initialized pedestrian"); p.GetComponent<Pedestrian>().setGender(gender); //p.transform.parent = null; p.GetComponent<Pedestrian>().setPositions(currentList); p.GetComponent<Pedestrian>().setID(positions[i].getID()); pedestrians.Add(p); currentList.Clear(); p.transform.SetParent(Pedestrians.transform); } } }
public void TestIndexOfValueBasic() { StringBuilder sblMsg = new StringBuilder(99); // SortedList sl2 = null; StringBuilder sbl3 = new StringBuilder(99); StringBuilder sbl4 = new StringBuilder(99); StringBuilder sblWork1 = new StringBuilder(99); string s1 = null; string s2 = null; string s3 = null; string s4 = null; int i = 0; int j = 0; // // Constructor: Create SortedList using this as IComparer and default settings. // sl2 = new SortedList(this); // Verify that the SortedList is not null. Assert.NotNull(sl2); // Verify that the SortedList is empty. Assert.Equal(0, sl2.Count); // with null - should return -1 // null val j = sl2.IndexOfValue((string)null); Assert.Equal(-1, j); // invalid val - should return -1 j = sl2.IndexOfValue("No_Such_Val"); Assert.Equal(-1, j); // null is a valid value sl2.Add("Key_0", null); j = sl2.IndexOfValue(null); Assert.NotEqual(-1, j); // first occurrence check sl2.Add("Key_1", "Val_Same"); sl2.Add("Key_2", "Val_Same"); j = sl2.IndexOfValue("Val_Same"); Assert.Equal(1, j); sl2.Clear(); // Testcase: add few key-val pairs for (i = 0; i < 100; i++) { sblMsg.Length = 0; sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); sblMsg.Length = 0; sblMsg.Append("val_"); sblMsg.Append(i); s2 = sblMsg.ToString(); sl2.Add(s1, s2); } // // Testcase: test IndexOfVal // for (i = 0; i < sl2.Count; i++) { sblMsg.Length = 0; sblMsg.Append("key_"); //key sblMsg.Append(i); s1 = sblMsg.ToString(); sblMsg.Length = 0; sblMsg.Append("val_"); //value sblMsg.Append(i); s2 = sblMsg.ToString(); // now use IndexOfKey and IndexOfVal to obtain the same object and check s3 = (string)sl2.GetByIndex(sl2.IndexOfKey(s1)); //Get the index of this key and then get object s4 = (string)sl2.GetByIndex(sl2.IndexOfValue(s2)); //Get the index of this val and then get object Assert.True(s3.Equals(s4)); // now Get using the index obtained thru IndexOfKey () and compare it with s2 s3 = (string)sl2.GetByIndex(sl2.IndexOfKey(s1)); Assert.True(s3.Equals(s2)); } // // Remove a key and then check // sblMsg.Length = 0; sblMsg.Append("key_50"); s1 = sblMsg.ToString(); sl2.Remove(s1); //removes "Key_50" j = sl2.IndexOfValue(s1); Assert.Equal(-1, j); }
public void calcPrognoz() { if (PArr.Count % 24 != 0) { int addCnt=24 - PArr.Count % 24; for (int i=0; i < addCnt; i++) { DateTime last=PArr.Last().Key; PArr.Add(last.AddMinutes(30), PArr[last]); } } SortedList<int,double>prevDataRashodArray=new SortedList<int, double>(); SortedList<int,double>prevDataNBArray=new SortedList<int, double>(); SortedList<int,double>prevDataVBArray=new SortedList<int, double>(); prognoz=new SortedList<DateTime, double>(); int index=0; double k=0; foreach (DateTime date in FirstData.Keys) { prevDataRashodArray.Add(index, FirstData[date].Q); prevDataNBArray.Add(index, FirstData[date].NB); prevDataVBArray.Add(index, FirstData[date].VB); k = FirstData[date].Q / RashodTable.getStationRashod(FirstData[date].P, FirstData[date].VB - FirstData[date].NB, RashodCalcMode.avg); index++; } napors=new SortedList<DateTime, double>(); rashods = new SortedList<DateTime, double>(); double napor=prevDataVBArray.Last().Value - prevDataNBArray.Last().Value; foreach (KeyValuePair<DateTime,double>de in pArr) { napors.Add(de.Key, napor); } foreach (KeyValuePair<DateTime,double> de in PArr) { double rashod=IsQFakt ? de.Value : RashodTable.getStationRashod(de.Value, napors[de.Key], RashodCalcMode.avg) * k; rashods.Add(de.Key, rashod); prognoz.Add(de.Key, 0); } //prognoz.Add(rashods.First().Key.AddMinutes(-30), prevDataNBArray[4]); double currentNapor=napors.First().Value; SortedList<DateTime,double> dataForPrognoz=new SortedList<DateTime, double>(); SortedList<DateTime,double> naporsForPrognoz=new SortedList<DateTime, double>(); for (int indexPoint=0; indexPoint < pArr.Keys.Count; indexPoint++) { DateTime Key=pArr.Keys[indexPoint]; dataForPrognoz.Add(Key, pArr[Key]); naporsForPrognoz.Add(Key, napors[Key]); if (dataForPrognoz.Count == 24) { SortedList<int,double> outputVector=new SortedList<int, double>(); for (int step=0; step <= 3; step++) { SortedList<int, double> inputVector=new SortedList<int, double>(); inputVector[0] = DatePrognozStart.Year; inputVector[1] = DatePrognozStart.DayOfYear; inputVector[2] = T; inputVector[3] = prevDataVBArray[1]; inputVector[4] = prevDataVBArray[2]; inputVector[5] = prevDataVBArray[3]; inputVector[6] = prevDataVBArray[4]; inputVector[7] = prevDataRashodArray[1]; inputVector[8] = prevDataRashodArray[2]; inputVector[9] = prevDataRashodArray[3]; inputVector[10] = prevDataRashodArray[4]; for (int i=0; i < 24; i++) { double rashod=0; if (!IsQFakt) { rashod = RashodTable.getStationRashod(pArr[dataForPrognoz.Keys[i]], naporsForPrognoz[dataForPrognoz.Keys[i]], RashodCalcMode.avg)*k; } else { rashod = rashods[dataForPrognoz.Keys[i]]; } rashods[dataForPrognoz.Keys[i]] = rashod; inputVector[i + 11] = rashod; } inputVector[35] = prevDataNBArray[1]; inputVector[36] = prevDataNBArray[2]; inputVector[37] = prevDataNBArray[3]; inputVector[38] = prevDataNBArray[4]; outputVector = nnet.calc(inputVector); for (int i=0; i < outputVector.Count; i++) { prognoz[dataForPrognoz.Keys[i]] = outputVector[i]; } for (int i=0; i < 24; i++) { naporsForPrognoz[dataForPrognoz.Keys[i]] = prevDataVBArray[4] - prognoz[dataForPrognoz.Keys[i]]; napors[dataForPrognoz.Keys[i]] = naporsForPrognoz[dataForPrognoz.Keys[i]]; } } for (int i=0; i <= 4; i++) { prevDataNBArray[i] = prognoz[dataForPrognoz.Keys[19 + i]]; prevDataRashodArray[i] = rashods[dataForPrognoz.Keys[19 + i]]; } dataForPrognoz.Clear(); } } while (prognoz.Last().Key > DatePrognozEnd) { prognoz.Remove(prognoz.Last().Key); } while (rashods.Last().Key > DatePrognozEnd) { rashods.Remove(rashods.Last().Key); } while (napors.Last().Key > DatePrognozEnd) { napors.Remove(napors.Last().Key); } }
public virtual void recalcData() { serieTUP = new SortedList <DateTime, double>(); serieTDn = new SortedList <DateTime, double>(); serieLvl1 = new SortedList <DateTime, double>(); serieLvl2 = new SortedList <DateTime, double>(); serieLvlCor = new SortedList <DateTime, double>(); serieTAvg = new SortedList <DateTime, double>(); serieF = new SortedList <DateTime, double>(); serieV = new SortedList <DateTime, double>(); serieVRun = new SortedList <double, double>(); serieVStop = new SortedList <double, double>(); serieVFull = new SortedList <double, double>(); SortedList <DateTime, double> prevF = new SortedList <DateTime, double>(); SortedList <DateTime, double> prevL1 = new SortedList <DateTime, double>(); SortedList <DateTime, double> prevL2 = new SortedList <DateTime, double>(); foreach (DateTime date in report.ResultData.Keys) { double Lvl1 = report.ResultData[date][recLvl1.Id]; double Lvl2 = report.ResultData[date][recLvl2.Id]; double TUp = report.ResultData[date][recTUp.Id]; double TDn = report.ResultData[date][recTDn.Id]; double F = report.ResultData[date][recF.Id]; double vOv = 0; double Tavg = (TUp + TDn) / 2; if (serieF.Count > 0 && Math.Abs(F - serieF.Values.Last()) > 40) { prevL1.Clear(); prevL2.Clear(); } prevF.Add(date, F); prevL1.Add(date, Lvl1); prevL2.Add(date, Lvl2); if (lMinutes > 0 && prevL1.Count > 0 && prevL2.Count > 0) { double l1Min = prevL1.Values.Min(); double l2Min = prevL2.Values.Min(); double l1Max = prevL1.Values.Max(); double l2Max = prevL2.Values.Max(); Lvl1 = prevL1.Values.Average(); Lvl2 = prevL2.Values.Average(); /*Lvl1 = (l1Min + l1Max) / 2; * Lvl2 = (l2Min + l2Max) / 2;*/ } double Lvl = datch == 0 ? (Lvl1 + Lvl2) / 2.0 : (datch == 1 ? Lvl1 : Lvl2); double lvlCor = F > 49 ? Lvl + LDiff : Lvl; double v1 = (V0 + lvlCor * V1mm) * (1 + (Tbaz - Tavg) * Tkoef) * 1000; if (TUp != 0 && TDn != 0 && Lvl1 != 0 && Lvl2 != 0) { serieTUP.Add(date, TUp); serieTDn.Add(date, TDn); serieF.Add(date, F); serieTAvg.Add(date, Tavg); serieLvl1.Add(date, Lvl1); serieLvl2.Add(date, Lvl2); if ((prevF.Values.Max() < 1 || prevF.Values.Min() > 49 || fMinutes == 0) /*&& (l1Min / l1Max > 0.95) && (l2Min / l2Max > 0.95)*/) { serieLvlCor.Add(date, lvlCor); serieV.Add(date, v1); if (F > 49) { serieVRun.Add(serieVRun.Count(), v1); } else { serieVStop.Add(serieVStop.Count(), v1); } serieVFull.Add(serieVFull.Count(), v1); } else { serieLvlCor.Add(date, double.NegativeInfinity); serieV.Add(date, double.NegativeInfinity); } } while (prevF.Keys.First().AddMinutes(fMinutes) < prevF.Keys.Last()) { prevF.RemoveAt(0); } if (prevL1.Count > 0) { while (prevL1.Keys.First().AddMinutes(lMinutes) < prevL1.Keys.Last()) { prevL1.RemoveAt(0); prevL2.RemoveAt(0); } } } if (vMinutes > 1) { serieVFull = new SortedList <double, double>(); serieVRun = new SortedList <double, double>(); serieVStop = new SortedList <double, double>(); SortedList <DateTime, double> otr = new SortedList <DateTime, double>(); List <DateTime> keys = serieV.Keys.ToList(); foreach (DateTime date in keys) { double val = serieV[date]; if (val != double.NegativeInfinity) { otr.Add(date, val); } if (otr.Count == vMinutes && val != double.NegativeInfinity) { otr.RemoveAt(0); } if (val == double.NegativeInfinity) { otr.Clear(); } else { serieV[date] = otr.Values.Average(); } if (val != double.NegativeInfinity) { serieVFull.Add(serieVFull.Count, serieV[date]); if (serieF[date] > 49) { serieVRun.Add(serieVRun.Count(), serieV[date]); } else { serieVStop.Add(serieVStop.Count(), serieV[date]); } } } } }
public void TestGetKeyListBasic() { StringBuilder sblMsg = new StringBuilder(99); // SortedList sl2 = null; IEnumerator en = null; StringBuilder sbl3 = new StringBuilder(99); StringBuilder sbl4 = new StringBuilder(99); StringBuilder sblWork1 = new StringBuilder(99); int i3 = 0; int i = 0; int j = 0; // // Constructor: Create SortedList using this as IComparer and default settings. // sl2 = new SortedList(); //using default IComparable implementation from Integer4 // which is used here as key-val elements. // Verify that the SortedList is not null. Assert.NotNull(sl2); // Verify that the SortedList is empty. Assert.Equal(0, sl2.Count); // Testcase: Set - null key, ArgExc expected Assert.Throws<ArgumentNullException>(() => { sl2[null] = 0; }); Assert.Equal(0, sl2.Count); // Testcase: Set - null val sl2[(Object)100] = (Object)null; Assert.Equal(1, sl2.Count); // Testcase: vanila Set sl2[(Object)100] = 1; Assert.Equal(1, sl2.Count); sl2.Clear(); Assert.Equal(0, sl2.Count); // Testcase: add key-val pairs for (i = 0; i < 100; i++) { sl2.Add(i + 100, i); } Assert.Equal(100, sl2.Count); for (i = 0; i < 100; i++) { j = i + 100; Assert.True(sl2.ContainsKey((int)j)); Assert.True(sl2.ContainsValue(i)); } // testcase: GetKeyList // first test the boundaries on the Remove method thru GetEnumerator implementation en = (IEnumerator)sl2.GetKeyList().GetEnumerator(); // Boundary for Current Assert.Throws<InvalidOperationException>(() => { Object objThrowAway = en.Current; } ); j = 100; // go over the enumarator en = (IEnumerator)sl2.GetKeyList().GetEnumerator(); while (en.MoveNext()) { // Current to see the order i3 = (int)en.Current; Assert.Equal(i3, j); // Current again to see the same order i3 = (int)en.Current; Assert.Equal(i3, j); j++; } // Boundary for Current Assert.Throws<InvalidOperationException>(() => { Object objThrowAway = en.Current; } ); // Boundary for MoveNext: call MoveNext to make sure it returns false Assert.False((en.MoveNext()) || (j != 200)); // call again MoveNext to make sure it still returns false Assert.False(en.MoveNext()); }
public virtual bool runTest() { Console.Error.WriteLine( "Co4347SetObject_object runTest() started." ); String strLoc="Loc_000oo"; StringBuilder sblMsg = new StringBuilder( 99 ); int iCountErrors = 0; int iCountTestcases = 0; SortedList sl2 = null; StringBuilder sbl3 = new StringBuilder( 99 ); StringBuilder sbl4 = new StringBuilder( 99 ); StringBuilder sblWork1 = new StringBuilder( 99 ); String s1 = null; String s2 = null; String s3 = null; int[] in4a = new int[9]; bool bol = false; int i = 0; try { do { strLoc="100cc"; iCountTestcases++; sl2 = new SortedList( this ); iCountTestcases++; if ( sl2 == null ) { Console.WriteLine( strTest+ "E_101" ); Console.WriteLine( strTest+ "SortedList creation failure" ); ++iCountErrors; break; } iCountTestcases++; if ( sl2.Count != 0 ) { Console.WriteLine( strTest+ "E_102" ); Console.WriteLine( strTest+ "New SortedList is not empty" ); ++iCountErrors; } strLoc="Loc_100aa"; ++iCountTestcases; try { sl2[null] = "first value" ; ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_2764! - must 've thrown ArgExc" ); Console.Error.WriteLine( sblMsg.ToString() ); } catch (ArgumentException) {} ++iCountTestcases; if (sl2.Count != 0) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_48ff! - Count == " ); sblMsg.Append( sl2.Count ); Console.Error.WriteLine( sblMsg.ToString() ); } strLoc="Loc_110aa"; ++iCountTestcases; try { sl2["first key"] = (String) null ; } catch (ArgumentException ) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_34fj! - must 've thrown ArgExc" ); Console.Error.WriteLine( sblMsg.ToString() ); } ++iCountTestcases; if (sl2.Count != 1) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_60ff! - Count == " ); sblMsg.Append( sl2.Count ); Console.Error.WriteLine( sblMsg.ToString() ); } strLoc="Loc_120aa"; ++iCountTestcases; sl2[(int) 0] = "first value" ; if (sl2.Count != 2) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_2i20bc! - Count == " ); sblMsg.Append( sl2.Count ); Console.Error.WriteLine( sblMsg.ToString() ); } strLoc="Loc_130aa"; ++iCountTestcases; bol = sl2.ContainsKey ("first key"); if (!bol) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_213h! - bol == " ); sblMsg.Append( bol ); Console.Error.WriteLine( sblMsg.ToString() ); } strLoc="Loc_140aa"; ++iCountTestcases; sl2["first key"] = "first value"; s2 = (String) sl2["first key"] ; if (!s2.Equals("first value")) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_1uid! - s2.Equals(first value) == " ); sblMsg.Append( s2.Equals("first value") ); Console.Error.WriteLine( sblMsg.ToString() ); } strLoc="Loc_150aa"; ++iCountTestcases; sl2["first key"] = "second value"; if (sl2.Count != 2) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_58fj! - Count == " ); sblMsg.Append( sl2.Count ); Console.Error.WriteLine( sblMsg.ToString() ); } strLoc="Loc_160aa"; ++iCountTestcases; s2 = (String) sl2["first key"] ; if (!s2.Equals("second value")) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_49d! - s2.Equals(second value) == " ); sblMsg.Append( s2.Equals("second value") ); Console.Error.WriteLine( sblMsg.ToString() ); } sl2.Clear(); strLoc="Loc_141aa"; for (i=0; i<50; i++) { ++iCountTestcases; sblMsg.Length = 0 ; sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); sblMsg.Length = 0 ; sblMsg.Append("val_"); sblMsg.Append(i); s2 = sblMsg.ToString(); sl2.Add (s1, s2); } strLoc="Loc_145aa"; for (i=0; i<50; i++) { ++iCountTestcases; ++iCountTestcases; sblMsg.Length = 0 ; sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); sblMsg.Length = 0 ; sblMsg.Append("new_val_"); sblMsg.Append(i); s2 = sblMsg.ToString(); sl2[s1] = s2; } strLoc="Loc_125aa"; ++iCountTestcases; if (sl2.Count != 50) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_294y! - Count == " ); sblMsg.Append( sl2.Count ); Console.Error.WriteLine( sblMsg.ToString() ); } strLoc="Loc_145aa"; for (i=0; i<50; i++) { ++iCountTestcases; sblMsg.Length = 0 ; sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); sblMsg.Length = 0 ; sblMsg.Append("new_val_"); sblMsg.Append(i); s2 = sblMsg.ToString(); s3 = (String) sl2[s1] ; if (!s3.Equals(s2)) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_49d! - s3.Equals(s2) == " ); sblMsg.Append( s2.Equals(s2) ); sblMsg.Append( " for key == " ); sblMsg.Append( s1 + "; returned Val == " + s3 ); Console.Error.WriteLine( sblMsg.ToString() ); } } } while ( false ); } catch( Exception exc_general ) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_343un! (Co4347SetObject_object) exc_general==" + exc_general ); Console.Error.WriteLine( "EXTENDEDINFO: (Err_343un) strLoc==" + strLoc ); } if ( iCountErrors == 0 ) { Console.Error.WriteLine( "paSs. SortedList\\Co4347SetObject_object.cs iCountTestcases==" + iCountTestcases ); return true; } else { Console.Error.WriteLine( "FAiL! SortedList\\Co4347SetObject_object.cs iCountErrors==" + iCountErrors ); return false; } }
public static SortedList<uint, String> DisassembleRegion(byte[] bFile, uint instance, uint desiredStart, int rows) { SortedList<uint, String> region = new SortedList<uint, String>(); if (instance <= desiredStart && bFile.Length + instance > desiredStart ) { uint address = desiredStart - (desiredStart % 0x10); // The beginning of HEX line. while(instance < address) { uint lastfourth = System.BitConverter.ToUInt32(bFile, (int)(address - instance - 4)); if (lastfourth == 0x90909090 || lastfourth == 0xCCCCCCCC) break; else address -= 0x10; } int length; while (address < desiredStart) { DisassembleLine(bFile, address-instance, address, DisassembleMode.Disasm_Size, out length); if (length <= 0) return region; address += (uint)length; } if (address > desiredStart) { region.Add(desiredStart, ToByteSequence(bFile, desiredStart - instance, (int)(address - desiredStart))); } while (region.Count < rows) { String instruction = DisassembleLine(bFile, address - instance, address, DisassembleMode.Disasm_Code, out length); if (length <= 0) { region.Clear(); return region; } region.Add(address, instruction); address += (uint)length; } } return region; }
//清空工作队列(切换场景时) public void ClearAllTask() { m_mapLoadTask.Clear(); }
public void Clear() { members.Clear(); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Session["scale"] = "stand"; // set grid size for stand Session["simCols"] = 5; Session["simRows"] = 5; // if management dictionary has records from landscape mode, delete records SortedList <string, ArrayList> managementDict = new SortedList <string, ArrayList>(); managementDict = (SortedList <string, ArrayList>)Session["managementDict"]; if (managementDict.Count > 0) { if (managementDict.Keys[0].Substring(7, 4) != "0000") { managementDict.Clear(); } } // if natDisturb dictionary has records from landscape mode, delete records SortedList <string, ArrayList> natDisturbDict = new SortedList <string, ArrayList>(); natDisturbDict = (SortedList <string, ArrayList>)Session["natDisturbDict"]; if (natDisturbDict.Count > 0) { natDisturbDict.Clear(); } // ***** Delete all user directories more than 2 days old try { // Only get subdirectories that begin with "user" string appPath = Request.PhysicalApplicationPath; // requires System.Diagnostics string landCarbDir = "LandCarbData31"; string[] dirs = Directory.GetDirectories(appPath + landCarbDir, "user*"); foreach (string dir in dirs) { // Get the creation time of a well-known directory. DateTime dt = Directory.GetCreationTime(dir); //TextBox1.Text += "\n" + dir + " is " + DateTime.Now.Subtract(dt).TotalDays.ToString() + " days old"; if (DateTime.Now.Subtract(dt).TotalDays >= 2) { System.IO.Directory.Delete(dir, true); // TextBox1.Text += "\nDirectory " + dir + " deleted"; } } } catch // (Exception ex) { // Label_upload.Text = ex.Message.ToString(); // TextBox1.Text += "Delete failed: " + ex.ToString(); // Response.Write(@"<script language='javascript'> // alert('Error deleting user directories > 2 days old on server.'); // </script>"); // MessageBox.Show("Error deleting user directories > 2 days old on server", "Deletion Error", // MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } }
public KCT_KSC FromConfigNode(ConfigNode node) { VABUpgrades.Clear(); SPHUpgrades.Clear(); RDUpgrades.Clear(); VABList.Clear(); VABWarehouse.Clear(); SPHList.Clear(); SPHWarehouse.Clear(); VABPlans.Clear(); SPHPlans.Clear(); KSCTech.Clear(); //TechList.Clear(); Recon_Rollout.Clear(); AirlaunchPrep.Clear(); VABRates.Clear(); SPHRates.Clear(); this.KSCName = node.GetValue("KSCName"); if (!int.TryParse(node.GetValue("ActiveLPID"), out this.ActiveLaunchPadID)) { this.ActiveLaunchPadID = 0; } ConfigNode vabup = node.GetNode("VABUpgrades"); foreach (string upgrade in vabup.GetValues("Upgrade")) { this.VABUpgrades.Add(int.Parse(upgrade)); } ConfigNode sphup = node.GetNode("SPHUpgrades"); foreach (string upgrade in sphup.GetValues("Upgrade")) { this.SPHUpgrades.Add(int.Parse(upgrade)); } ConfigNode rdup = node.GetNode("RDUpgrades"); foreach (string upgrade in rdup.GetValues("Upgrade")) { this.RDUpgrades.Add(int.Parse(upgrade)); } ConfigNode tmp = node.GetNode("VABList"); foreach (ConfigNode vessel in tmp.GetNodes("KCTVessel")) { KCT_BuildListStorage.BuildListItem listItem = new KCT_BuildListStorage.BuildListItem(); ConfigNode.LoadObjectFromConfig(listItem, vessel); KCT_BuildListVessel blv = listItem.ToBuildListVessel(); blv.shipNode = vessel.GetNode("ShipNode"); blv.KSC = this; this.VABList.Add(blv); } tmp = node.GetNode("SPHList"); foreach (ConfigNode vessel in tmp.GetNodes("KCTVessel")) { KCT_BuildListStorage.BuildListItem listItem = new KCT_BuildListStorage.BuildListItem(); ConfigNode.LoadObjectFromConfig(listItem, vessel); KCT_BuildListVessel blv = listItem.ToBuildListVessel(); blv.shipNode = vessel.GetNode("ShipNode"); blv.KSC = this; this.SPHList.Add(blv); } tmp = node.GetNode("VABWarehouse"); foreach (ConfigNode vessel in tmp.GetNodes("KCTVessel")) { KCT_BuildListStorage.BuildListItem listItem = new KCT_BuildListStorage.BuildListItem(); ConfigNode.LoadObjectFromConfig(listItem, vessel); KCT_BuildListVessel blv = listItem.ToBuildListVessel(); blv.shipNode = vessel.GetNode("ShipNode"); blv.KSC = this; this.VABWarehouse.Add(blv); } tmp = node.GetNode("SPHWarehouse"); foreach (ConfigNode vessel in tmp.GetNodes("KCTVessel")) { KCT_BuildListStorage.BuildListItem listItem = new KCT_BuildListStorage.BuildListItem(); ConfigNode.LoadObjectFromConfig(listItem, vessel); KCT_BuildListVessel blv = listItem.ToBuildListVessel(); blv.shipNode = vessel.GetNode("ShipNode"); blv.KSC = this; this.SPHWarehouse.Add(blv); } if (node.TryGetNode("VABPlans", ref tmp)) { if (tmp.HasNode("KCTVessel")) { foreach (ConfigNode vessel in tmp.GetNodes("KCTVessel")) { KCT_BuildListStorage.BuildListItem listItem = new KCT_BuildListStorage.BuildListItem(); ConfigNode.LoadObjectFromConfig(listItem, vessel); KCT_BuildListVessel blv = listItem.ToBuildListVessel(); blv.shipNode = vessel.GetNode("ShipNode"); blv.KSC = this; if (this.VABPlans.ContainsKey(blv.shipName)) { this.VABPlans.Remove(blv.shipName); } this.VABPlans.Add(blv.shipName, blv); } } } if (node.TryGetNode("SPHPlans", ref tmp)) { if (tmp.HasNode("KCTVessel")) { foreach (ConfigNode vessel in tmp.GetNodes("KCTVessel")) { KCT_BuildListStorage.BuildListItem listItem = new KCT_BuildListStorage.BuildListItem(); ConfigNode.LoadObjectFromConfig(listItem, vessel); KCT_BuildListVessel blv = listItem.ToBuildListVessel(); blv.shipNode = vessel.GetNode("ShipNode"); blv.KSC = this; if (this.SPHPlans.ContainsKey(blv.shipName)) { this.SPHPlans.Remove(blv.shipName); } this.SPHPlans.Add(blv.shipName, blv); } } } tmp = node.GetNode("Recon_Rollout"); foreach (ConfigNode RRCN in tmp.GetNodes("Recon_Rollout_Item")) { KCT_Recon_Rollout tempRR = new KCT_Recon_Rollout(); ConfigNode.LoadObjectFromConfig(tempRR, RRCN); Recon_Rollout.Add(tempRR); } if (node.TryGetNode("Airlaunch_Prep", ref tmp)) { foreach (ConfigNode APCN in tmp.GetNodes("Airlaunch_Prep_Item")) { KCT_AirlaunchPrep temp = new KCT_AirlaunchPrep(); ConfigNode.LoadObjectFromConfig(temp, APCN); AirlaunchPrep.Add(temp); } } if (node.HasNode("KSCTech")) { tmp = node.GetNode("KSCTech"); foreach (ConfigNode upBuild in tmp.GetNodes("UpgradingBuilding")) { KCT_UpgradingBuilding tempUP = new KCT_UpgradingBuilding(); tempUP.Load(upBuild); KSCTech.Add(tempUP); } } if (node.HasNode("LaunchPads")) { LaunchPads.Clear(); tmp = node.GetNode("LaunchPads"); foreach (ConfigNode LP in tmp.GetNodes("KCT_LaunchPad")) { KCT_LaunchPad tempLP = new KCT_LaunchPad("LP0"); ConfigNode.LoadObjectFromConfig(tempLP, LP); tempLP.DestructionNode = LP.GetNode("DestructionState"); LaunchPads.Add(tempLP); } } if (node.HasNode("VABRateCache")) { foreach (string rate in node.GetNode("VABRateCache").GetValues("rate")) { double r; if (double.TryParse(rate, out r)) { VABRates.Add(r); } } } if (node.HasNode("SPHRateCache")) { foreach (string rate in node.GetNode("SPHRateCache").GetValues("rate")) { double r; if (double.TryParse(rate, out r)) { SPHRates.Add(r); } } } return(this); }
public void Clear() { lock (list) { list.Clear(); } }
IEnumerator StartBattling() { aliveTeammateList.TrimExcess(); aliveEnemyList.TrimExcess(); for (int i = 0; i < 4; i++) { meButtons [i].SetActive(false); } battleLog.SetActive(true); playerTurn = false; yield return(SelectAIMove()); //MakeMoves (); method is under this print(pressedEnter); //says its true because we hit enter for the final selection of target pressedEnter = false; for (int i = 0; i < moveList.Count; i++) { print("i is " + i); MoveMessenger m = (MoveMessenger)(moveList.GetKey(i)); if (m.getAttackingPlayer().getHealth() > 0) { if (m.getAttackedPlayer().isAlive() != true) { updateBattleLog(m.getAttackingPlayer().getName() + "'s target was dead before move. Attacking next person in the enemy line"); yield return(StartCoroutine(chatEnter())); int newTarget = m.getIndexOfAttackedPlayer(); if (m.getAttackingPlayer().getTeam() == "team") { if (newTarget > aliveEnemyList.Capacity - 1) { newTarget = 0; } m.setAttackedPlayer(aliveEnemyList [newTarget]); } else { if (newTarget > aliveTeammateList.Capacity - 1) { newTarget = 0; } m.setAttackedPlayer(aliveTeammateList [newTarget]); } m.setIndexOfAttackedPlayer(newTarget); m.recalculateDamage(m.getAttackingPlayer().moveList [m.getIndexOfMove()].getDamage()); } updateBattleLog(m.getAttackingPlayer().getName() + " is attacking " + m.getAttackedPlayer().getName() + " with damage: " + m.getRecalculatedDamage()); updateBattleLog(m.getAttackedPlayer().getName() + "'s health before the move is: " + m.getAttackedPlayer().getHealth()); int health = m.getAttackedPlayer().receiveDamage((MoveMessenger)moveList.GetKey(i)); updateBattleLog(m.getAttackedPlayer().getName() + "'s health after the move is: " + health); yield return(StartCoroutine(chatEnter())); m.getAttackedPlayer().setHealth(health); if (health <= 0) { updateBattleLog(m.getAttackedPlayer().getName() + " has died"); if (m.getAttackedPlayer().team == "team") { relocateToDeadTeammateList(m); } else //no need to check if he's enemy, because he will be { relocateToDeadEnemyList(m); } yield return(StartCoroutine(chatEnter())); //moveList.RemoveAt (moveList.IndexOfValue (m.getAttackedPlayer ().getName ())); //the line that causes skipped turns if (isBattleOver()) { yield return(StartCoroutine(chatEnter())); updateBattleLog("Switching back to movement scene..."); yield return(new WaitForSeconds(1f)); BattleOver(); } } } else { updateBattleLog(m.getAttackingPlayer().getName() + "'s hp was " + m.getAttackingPlayer().getHealth() + " so his turn is skipped."); yield return(StartCoroutine(chatEnter())); } } moveList.Clear(); print("MoveList cleared"); currentChar = 0; print("CurrentChar has been reset"); currentPageOfMovesOrTargets = 0; battleLog.SetActive(false); playerTurn = true; updateMovesForChar(); EventSystem.current.SetSelectedGameObject(meButtons[0]); needToPrint = true; }
void calculatePrice() //void 表示此方法沒有回傳值,()內可設定欲傳入的參數 { totalPrice = 0.0; afterDiscountTotalPrice = 0.0; foreach (int index in shoppingCart) //購物車訂單總價-未折扣 { iiiDrink[index].drinkTotalPrice = iiiDrink[index].drinkPrice * iiiDrink[index].drinkCupQuantity; totalPrice += iiiDrink[index].drinkTotalPrice; } if (cbEvent.Checked == true) //促銷活動打勾時 { if (rbtnEvent01.Checked == true) //同品項第二件6折 { int intQuotient = 0; //商數 => 需要折扣的數量 foreach (int index in shoppingCart) { intQuotient = iiiDrink[index].drinkCupQuantity / 2; iiiDrink[index].drinkDiscountPrice = iiiDrink[index].drinkPrice * intQuotient * arrayDiscount[1]; //個別品項的折扣金額(負值) } } else if (rbtnEvent02.Checked == true) //不同品項買三送一(共四杯,送最低價者) { priceSort.Clear(); //將買三送一價格排序專用的SortedList內容清除,以避免再次計算買三送一時產生索引值被重複使用的例外錯誤 int intAllDrinkCupQuantity = 0; //總杯數 foreach (int index in shoppingCart) { intAllDrinkCupQuantity += iiiDrink[index].drinkCupQuantity; } int intQuotient = intAllDrinkCupQuantity / 4; //商數 => 需要折扣的數量 //將購物車裡,所存放的索引值,其對應品項的價格與索引值加入資料型別為SortedList的priceSort。Key為價格(因為要以價格高低來排序),Value為索引值。成員加入後,會自動由小到大排序 foreach (int index in shoppingCart) { priceSort.Add(iiiDrink[index].drinkPrice, index); } foreach (KeyValuePair <double, int> pS in priceSort) { if (intQuotient - iiiDrink[pS.Value].drinkCupQuantity >= 0) { iiiDrink[pS.Value].drinkDiscountPrice = iiiDrink[pS.Value].drinkPrice * iiiDrink[pS.Value].drinkCupQuantity * arrayDiscount[2]; //個別品項的折扣金額(負值) intQuotient -= iiiDrink[pS.Value].drinkCupQuantity; } else if (intQuotient - iiiDrink[pS.Value].drinkCupQuantity < 0) { iiiDrink[pS.Value].drinkDiscountPrice = iiiDrink[pS.Value].drinkPrice * intQuotient * arrayDiscount[2]; //最後一個折扣品項的折扣金額(負值) intQuotient = 0; break; } } } else { MessageBox.Show("請選擇促銷活動", "未選擇促銷活動", MessageBoxButtons.OK, MessageBoxIcon.Information); } foreach (int index in shoppingCart) { afterDiscountTotalPrice += iiiDrink[index].drinkTotalPrice + iiiDrink[index].drinkDiscountPrice; //促銷折扣後總價 } afterDiscountTotalPrice = afterDiscountTotalPrice * arrayDiscount[0] / 10.0; //促銷折扣後總價再打折 } else //促銷活動未打勾時 { gbEvent.Enabled = false; afterDiscountTotalPrice = totalPrice * arrayDiscount[0] / 10.0; } lblTotalPrice.Text = $"{totalPrice:C}"; lblAfterDiscountTotalPrice.Text = $"{afterDiscountTotalPrice:C}"; }
public virtual bool runTest() { Console.Error.WriteLine( "Co4332IndexOfValue runTest() started." ); String strLoc="Loc_000oo"; StringBuilder sblMsg = new StringBuilder( 99 ); int iCountErrors = 0; int iCountTestcases = 0; SortedList sl2 = null; StringBuilder sbl3 = new StringBuilder( 99 ); StringBuilder sbl4 = new StringBuilder( 99 ); StringBuilder sblWork1 = new StringBuilder( 99 ); String str5 = null; String str6 = null; String str7 = null; String s1 = null; String s2 = null; String s3 = null; String s4 = null; int[] in4a = new int[9]; int nCapacity = 100; bool bol = false; int i = 0; int j = 0; try { LABEL_860_GENERAL: do { strLoc="100cc"; iCountTestcases++; sl2 = new SortedList( this ); iCountTestcases++; if ( sl2 == null ) { Console.WriteLine( strTest+ "E_101" ); Console.WriteLine( strTest+ "SortedList creation failure" ); ++iCountErrors; break; } iCountTestcases++; if ( sl2.Count != 0 ) { Console.WriteLine( strTest+ "E_102" ); Console.WriteLine( strTest+ "New SortedList is not empty" ); ++iCountErrors; } iCountTestcases++; try { j = sl2.IndexOfValue((String)null); if (j != -1) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_39re! - should return -1..." ); Console.Error.WriteLine( "returned: " + j ); } } catch (Exception exc) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_59f! - " + exc.ToString() ); } iCountTestcases++; j = sl2.IndexOfValue("No_Such_Val"); if (j != -1) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_658d! - should return -1..." ); Console.Error.WriteLine( "returned: " + j ); } strLoc="100.5cc"; sl2.Add ("Key_0", null); j = sl2.IndexOfValue(null); if (j == -1) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_47d! - should not return -1..." ); } strLoc="100.6cc"; sl2.Add ("Key_1", "Val_Same"); sl2.Add ("Key_2", "Val_Same"); try { j = sl2.IndexOfValue("Val_Same"); if (j != 1) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_985g! - IndexOf failed to return first occurrence..." ); Console.Error.WriteLine( "returned: " + j ); } } catch (Exception exc) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_095! - " + exc.ToString() ); } strLoc="100.7cc"; sl2.Clear(); strLoc="Loc_141aa"; for (i=0; i<100; i++) { ++iCountTestcases; sblMsg.Length = 0 ; sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); sblMsg.Length = 0 ; sblMsg.Append("val_"); sblMsg.Append(i); s2 = sblMsg.ToString(); sl2.Add (s1, s2); } strLoc="Loc_151aa"; for (i=0; i < sl2.Count ; i++) { sblMsg.Length = 0 ; sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); sblMsg.Length = 0 ; sblMsg.Append("val_"); sblMsg.Append(i); s2 = sblMsg.ToString(); ++iCountTestcases; s3 = (String) sl2.GetByIndex(sl2.IndexOfKey(s1)) ; s4 = (String) sl2.GetByIndex(sl2.IndexOfValue(s2)) ; strLoc="Loc_161aa"; if (!s3.Equals (s4)) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_1032bc! - s4 == " ); sblMsg.Append( s4 ); sblMsg.Append( "; s3 == " ); sblMsg.Append( s3 ); Console.Error.WriteLine( sblMsg.ToString() ); } strLoc="Loc_171aa"; ++iCountTestcases; s3 = (String) sl2.GetByIndex(sl2.IndexOfKey(s1)) ; if (!s3.Equals (s2)) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_1032.2bc! - s2 == " ); sblMsg.Append( s2 ); sblMsg.Append( "; s3 == " ); sblMsg.Append( s3 ); Console.Error.WriteLine( sblMsg.ToString() ); } } ++iCountTestcases; sblMsg.Length = 0 ; sblMsg.Append("key_50"); s1 = sblMsg.ToString(); sl2.Remove (s1); strLoc="Loc_181aa"; ++iCountTestcases; j = sl2.IndexOfValue(s1); if (j != -1) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_39fd! - should return -1..." ); Console.Error.WriteLine( "returned: " + j ); } } while ( false ); } catch( Exception exc_general ) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_343un! (Co4332IndexOfValue) exc_general==" + exc_general ); Console.Error.WriteLine( "EXTENDEDINFO: (Err_343un) strLoc==" + strLoc ); } if ( iCountErrors == 0 ) { Console.Error.WriteLine( "paSs. SortedList\\Co4332IndexOfValue.cs iCountTestcases==" + iCountTestcases ); return true; } else { Console.Error.WriteLine( "FAiL! SortedList\\Co4332IndexOfValue.cs iCountErrors==" + iCountErrors ); return false; } }
public void DumpSchema (XmlSchema schema) { schema.Compile (null); SortedList sl = new SortedList (); IndentLine ("**XmlSchema**"); IndentLine ("TargetNamespace: " + schema.TargetNamespace); IndentLine ("AttributeGroups:"); foreach (DictionaryEntry entry in schema.AttributeGroups) sl.Add (entry.Key.ToString (), entry.Value); foreach (DictionaryEntry entry in sl) DumpAttributeGroup ((XmlSchemaAttributeGroup) entry.Value); sl.Clear (); IndentLine ("Attributes:"); foreach (DictionaryEntry entry in schema.Attributes) sl.Add (entry.Key.ToString (), entry.Value); foreach (DictionaryEntry entry in sl) DumpAttribute ((XmlSchemaAttribute) entry.Value); sl.Clear (); IndentLine ("Elements:"); foreach (DictionaryEntry entry in schema.Elements) sl.Add (entry.Key.ToString (), entry.Value); foreach (DictionaryEntry entry in sl) DumpElement ((XmlSchemaElement) entry.Value); sl.Clear (); IndentLine ("Groups"); foreach (DictionaryEntry entry in schema.Groups) sl.Add (entry.Key.ToString (), entry.Value); foreach (DictionaryEntry entry in sl) DumpGroup ((XmlSchemaGroup) entry.Value); sl.Clear (); IndentLine ("IsCompiled: " + schema.IsCompiled); IndentLine ("Notations"); foreach (DictionaryEntry entry in schema.Notations) sl.Add (entry.Key.ToString (), entry.Value); foreach (DictionaryEntry entry in sl) DumpNotation ((XmlSchemaNotation) entry.Value); sl.Clear (); IndentLine ("SchemaTypes:"); foreach (DictionaryEntry entry in schema.Notations) sl.Add (entry.Key.ToString (), entry.Value); foreach (DictionaryEntry entry in sl) if (entry.Value is XmlSchemaSimpleType) DumpSimpleType ((XmlSchemaSimpleType) entry.Value); else DumpComplexType ((XmlSchemaComplexType) entry.Value); sl.Clear (); }
static void Main(string[] args) { string path = Environment.CurrentDirectory; string toolPath = path + "/tool/bsdiff.exe"; string configPath = path + "/ChannelConfig.csv"; string outputPath = path + "/patchs/"; string outputJson = outputPath + "patchs.txt"; DirectoryInfo folder = new DirectoryInfo(path); DirectoryInfo[] childFolders = folder.GetDirectories(); versionList.Clear(); foreach (DirectoryInfo di in childFolders) { float val = GetVersionValue(di.Name); if (val >= 0) { versionList.Add(val, di); } } if (versionList.Count == 0) { Console.WriteLine("no version!"); Console.ReadKey(); return; } PatchConfig patchConfig = new PatchConfig(); patchConfig.channels = new List <PatchConfig.Channel>(); patchConfig.newVersion = versionList.Keys[versionList.Count - 1].ToString(); Console.WriteLine("new version : " + patchConfig.newVersion); ChannelConfig channels = new ChannelConfig(configPath); foreach (KeyValuePair <string, string> pair in channels.channelConfigs) { string channelName = pair.Key; string downloadName = pair.Value; string apk_all = downloadName + ".apk"; string apk_mini = "_" + downloadName + ".apk"; string new_all = path + "/" + patchConfig.newVersion + "/" + apk_all; string new_mini = path + "/" + patchConfig.newVersion + "/" + apk_mini; if (!File.Exists(new_all) && !File.Exists(new_mini)) { continue; } bool hasOldVersion = false; for (int i = 0; i < versionList.Count - 1; ++i) { if ((int)versionList.Keys[i] == (int)GetVersionValue(patchConfig.newVersion)) { continue; } string oldVersion = versionList[versionList.Keys[i]].Name; if (File.Exists(path + "/" + oldVersion + "/" + apk_all) || File.Exists(path + "/" + oldVersion + "/" + apk_mini)) { hasOldVersion = true; break; } } if (hasOldVersion) { Console.WriteLine("begin patch channel : " + channelName); PatchConfig.Channel patchChannel = new PatchConfig.Channel(); patchChannel.patchs = new List <PatchConfig.Channel.Patch>(); patchChannel.name = channelName; patchChannel.md5_all = GetFileMd5(new_all); patchChannel.md5_mini = GetFileMd5(new_mini); patchChannel.size_all = GetFileSize(new_all); patchChannel.size_mini = GetFileSize(new_mini); for (int i = 0; i < versionList.Count - 1; ++i) { float oldVersion = versionList.Keys[i]; if ((int)oldVersion == (int)GetVersionValue(patchConfig.newVersion)) { continue; } string old_all = path + "/" + oldVersion + "/" + apk_all; string old_mini = path + "/" + oldVersion + "/" + apk_mini; if (!File.Exists(old_all) && !File.Exists(old_mini)) { continue; } Console.WriteLine("begin patch version:" + oldVersion + "->" + patchConfig.newVersion); PatchConfig.Channel.Patch patch = new PatchConfig.Channel.Patch(); patch.oldVersion = oldVersion.ToString(); string patchFolderName = oldVersion + "-" + patchConfig.newVersion; string patchFolderPath = outputPath + "/" + patchFolderName; if (!Directory.Exists(patchFolderPath)) { Directory.CreateDirectory(patchFolderPath); } if (File.Exists(old_all)) { if (File.Exists(new_all)) { string patchName = patchFolderName + "/" + downloadName + ".patch"; Console.WriteLine("begin patch : " + patchName); string patchPath = outputPath + patchName; patch.patch_all = patchName; patch.oldmd5_all = GetFileMd5(old_all); Process p = new Process(); string param = old_all + " " + new_all + " " + patchPath; param = param.Replace("/", "\\"); //Console.WriteLine("param : " + param); ProcessStartInfo pi = new ProcessStartInfo(toolPath, param); pi.UseShellExecute = false; pi.CreateNoWindow = true; p.StartInfo = pi; p.Start(); p.WaitForExit(); patch.size_all = GetFileSize(patchPath); } else { Console.WriteLine("lost new version : " + new_all); } } if (File.Exists(old_mini)) { if (File.Exists(new_mini)) { string patchName = patchFolderName + "/_" + downloadName + ".patch"; Console.WriteLine("begin patch : " + patchName); string patchPath = outputPath + patchName; patch.patch_mini = patchName; patch.oldmd5_mini = GetFileMd5(old_mini); Process p = new Process(); string param = old_mini + " " + new_mini + " " + patchPath; param = param.Replace("/", "\\"); //Console.WriteLine("param : " + param); ProcessStartInfo pi = new ProcessStartInfo(toolPath, param); pi.UseShellExecute = false; pi.CreateNoWindow = true; p.StartInfo = pi; p.Start(); p.WaitForExit(); patch.size_mini = GetFileSize(patchPath); } else { Console.WriteLine("lost new version : " + new_mini); } } patchChannel.patchs.Add(patch); } patchConfig.channels.Add(patchChannel); } } string json = LitJson.JsonMapper.ToJson(patchConfig); File.WriteAllText(outputJson, json); Console.WriteLine(json); try { PatchConfig a = LitJson.JsonMapper.ToObject <PatchConfig>(json); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine("finish!"); Console.ReadKey(); }
private void checkForNewPackages() { var newUpdates = new SortedList<releaseInfo, updatePackage>(); //Alle Pakete vorher schon sortieren, um den "SP-Bug" zu beheben. var allUpdates = new SortedList<releaseInfo, updatePackage>(); foreach (updatePackage uPackage in currentConfiguration.updatePackages) allUpdates.Add(uPackage.releaseInfo, uPackage); foreach (var package in allUpdates) { //Überspringe Update wenn noch nicht veröffentlicht if (!package.Value.Published) continue; //Überprüfe ob die Zielarchitektur stimmt if (package.Value.TargetArchitecture != updatePackage.SupportedArchitectures.Both && package.Value.TargetArchitecture != Helper.GetArchitecture()) continue; if (package.Value.releaseInfo > _controllerInstance.releaseInfo) { //Überspringe das Update wenn der Releasetyp nicht zum eingestellten Filter passt. if (!_controllerInstance.releaseFilter.Contains(package.Value.releaseInfo.Type)) continue; //Anfrage an das Programm schicken, ob das Update bestätigt werden soll. if (!_controllerInstance.onConfirmUpdatePackage(new confirmUpdatePackageEventArgs(package.Value))) continue; //Wenn dieses Updatepaket nur für bestimmte Versionen verfügbar sein soll if (package.Value.UseOwnVersionList) { bool versionFound = false; foreach (VersionEx version in package.Value.OwnVersionList) if (version.ToVersion().Equals(new Version(_controllerInstance.releaseInfo.Version))) { versionFound = true; break; } if (!versionFound) continue; } //Wenn das aktuelle Update ein ServicePack ist, dann alle vorherigen entfernen if (package.Value.isServicePack) newUpdates.Clear(); newUpdates.Add(package.Value.releaseInfo, package.Value); } } foundUpdates.Clear(); foreach (var item in newUpdates) { foundUpdates.Add(item.Value); } }
public void Clear() { _pc.Clear(); }
public static void RenameMembers() { int tCount = 0, mCount = 0, eCount = 0, nCount = 0, rCount = 0, moCount = 0, dCounter = 0, frmCount = 0; var namespaces = new SortedList<string, List<TypeDefinition>>(); string oldName; Logger.VSLog("Renaming symbols..."); Logger.VLog(""); foreach (var typeDef in AsmDef.Modules.SelectMany(modDef => modDef.Types)) if (namespaces.Keys.Contains(typeDef.Namespace)) namespaces[typeDef.Namespace].Add(typeDef); else namespaces.Add(typeDef.Namespace, new List<TypeDefinition> {typeDef}); foreach (var ns in namespaces) { if (_scheme.Namespaces) { oldName = ns.Key; foreach (var typeDef in ns.Value) typeDef.Namespace = "Namespace_" + nCount; Logger.VLog("[Rename(Namespace)] " + oldName + " -> " + "Namespace_" + nCount); nCount++; } } namespaces.Clear(); foreach (var modDef in AsmDef.Modules) { modDef.Name = "Module_" + moCount++; foreach ( var typeDef in modDef.GetAllTypes().Where( tDef => !tDef.IsRuntimeSpecialName && !tDef.IsSpecialName && !(tDef.Name.StartsWith("<") && tDef.Name.EndsWith(">")))) { oldName = typeDef.Name; if (typeDef.BaseType == null || typeDef.BaseType.Name != "Form") typeDef.Name = "Type_" + tCount++; else typeDef.Name = "Form_" + frmCount++; Logger.VLog("[Rename(Type)] " + oldName + " -> " + typeDef.Name); } foreach (var typeDef in modDef.GetAllTypes()) { #region Methods if (_scheme.Methods) foreach (var mDef in typeDef.Methods.Where(mDef => !mDef.IsRuntimeSpecialName)) { oldName = mDef.Name; mDef.Name = "Method_" + mCount++; Logger.VLog("[Rename(Method)] " + oldName + " -> " + mDef.Name); var pCount = 0; foreach (var paramDef in mDef.Parameters) { oldName = paramDef.Name; paramDef.Name = paramDef.ParameterType.Name.ToLower() + "_" + pCount++; Logger.VLog("[Rename(Parameter)] " + oldName + " -> " + paramDef.Name); } } #endregion #region Fields if (_scheme.Fields) { var fCount = 0; foreach (var fieldDef in typeDef.Fields) { if (fieldDef.IsRuntimeSpecialName) continue; oldName = fieldDef.Name; fieldDef.Name = fieldDef.FieldType.Name.ToLower() + "_" + fCount++; Logger.VLog("[Rename(Field)] " + oldName + " -> " + fieldDef.Name); } } #endregion #region Events if (_scheme.Events) foreach (var eventDef in typeDef.Events) { if (eventDef.IsRuntimeSpecialName || eventDef.IsSpecialName) continue; oldName = eventDef.Name; eventDef.Name = "Event_" + eCount++; Logger.VLog("[Rename(Event)] " + oldName + " -> " + eventDef.Name); } #endregion #region Properties if (_scheme.Properties) { int prCount = 0; foreach (var propDef in typeDef.Properties) { if (propDef.IsRuntimeSpecialName || propDef.IsSpecialName) continue; oldName = propDef.Name; propDef.Name = "prop" + propDef.PropertyType.Name + "_" + prCount++; Logger.VLog("[Rename(Property)] " + oldName + " -> " + propDef.Name); } } #endregion #region Delegates if (typeDef.BaseType == null) continue; if (_scheme.Delegates) if (typeDef.BaseType.ToString().ToLower().Contains("multicastdelegate")) { if (typeDef.IsRuntimeSpecialName || typeDef.IsSpecialName) continue; oldName = typeDef.Name; typeDef.Name = "delegate_" + dCounter++; Logger.VLog("[Rename(Delegate)] " + oldName + " -> " + typeDef.Name); } #endregion } if (_scheme.Resources) foreach (var res in modDef.Resources) { oldName = res.Name; res.Name = "Resource_" + rCount++; // we need to update all resourcemanager initialization strings if we rename resources AsmDef.ReplaceString(oldName.Replace(".resources", null), res.Name); Logger.VLog("[Rename(Resource)] " + oldName + " -> " + res.Name); } } }
public virtual bool runTest() { Console.Error.WriteLine("Co4348GetKey runTest() started."); String strLoc = "Loc_000oo"; StringBuilder sblMsg = new StringBuilder(99); int iCountErrors = 0; int iCountTestcases = 0; SortedList sl2 = null; StringBuilder sbl3 = new StringBuilder(99); StringBuilder sbl4 = new StringBuilder(99); StringBuilder sblWork1 = new StringBuilder(99); String s1 = null; String s2 = null; int[] in4a = new int[9]; int i = 0; try { do { strLoc = "100cc"; iCountTestcases++; sl2 = new SortedList(this); iCountTestcases++; if (sl2 == null) { Console.WriteLine(strTest + "E_101"); Console.WriteLine(strTest + "SortedList creation failure"); ++iCountErrors; break; } iCountTestcases++; if (sl2.Count != 0) { Console.WriteLine(strTest + "E_102"); Console.WriteLine(strTest + "New SortedList is not empty"); ++iCountErrors; } strLoc = "Loc_100aa"; ++iCountTestcases; try { sl2.GetKey(0); ++iCountErrors; sblMsg.Length = 0; sblMsg.Append("POINTTOBREAK: Error Err_2764! - must 've thrown ArgExc"); Console.Error.WriteLine(sblMsg.ToString()); } catch (ArgumentException) {} strLoc = "Loc_110aa"; ++iCountTestcases; try { sl2["first key"] = (String)null; } catch (ArgumentException) { ++iCountErrors; sblMsg.Length = 0; sblMsg.Append("POINTTOBREAK: Error Err_34fj! - must 've thrown ArgExc"); Console.Error.WriteLine(sblMsg.ToString()); } ++iCountTestcases; if (sl2.Count != 1) { ++iCountErrors; sblMsg.Length = 0; sblMsg.Append("POINTTOBREAK: Error Err_60ff! - Count == "); sblMsg.Append(sl2.Count); Console.Error.WriteLine(sblMsg.ToString()); } strLoc = "Loc_120aa"; ++iCountTestcases; sl2.Clear(); strLoc = "Loc_141aa"; for (i = 0; i < 50; i++) { ++iCountTestcases; sblMsg.Length = 0; sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); sblMsg.Length = 0; sblMsg.Append("val_"); sblMsg.Append(i); s2 = sblMsg.ToString(); sl2.Add(s1, s2); } strLoc = "Loc_145aa"; for (i = 0; i < 50; i++) { ++iCountTestcases; ++iCountTestcases; sblMsg.Length = 0; sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); if (!((String)sl2.GetKey(sl2.IndexOfKey(s1))).Equals(s1)) { ++iCountErrors; sblMsg.Length = 0; sblMsg.Append("POINTTOBREAK: Error Err_49d! - s3.Equals(s1); "); sblMsg.Append(" for key == "); sblMsg.Append(s1 + "; returned Val == " + ((String)sl2.GetKey(sl2.IndexOfKey(s1)))); Console.Error.WriteLine(sblMsg.ToString()); } } strLoc = "Loc_125aa"; ++iCountTestcases; if (sl2.Count != 50) { ++iCountErrors; sblMsg.Length = 0; sblMsg.Append("POINTTOBREAK: Error Err_294y! - Count == "); sblMsg.Append(sl2.Count); Console.Error.WriteLine(sblMsg.ToString()); } } while (false); } catch (Exception exc_general) { ++iCountErrors; Console.Error.WriteLine("POINTTOBREAK: Error Err_343un! (Co4348GetKey) exc_general==" + exc_general); Console.Error.WriteLine("EXTENDEDINFO: (Err_343un) strLoc==" + strLoc); } if (iCountErrors == 0) { Console.Error.WriteLine("paSs. SortedList\\Co4348GetKey.cs iCountTestcases==" + iCountTestcases); return(true); } else { Console.Error.WriteLine("FAiL! SortedList\\Co4348GetKey.cs iCountErrors==" + iCountErrors); return(false); } }
private void GetProfiles() { string requiredAtributes = ""; string optionalAtributes = ""; SpSharedRecoContext recoContext; ISpeechObjectTokens tokens; SpObjectToken token; this.profiles = new SortedList<string, SpObjectToken>(); string profileName; selectedProfile = 0; // Attempt to get profile list try { recoContext = new SpeechLib.SpSharedRecoContext(); tokens = recoContext.Recognizer.GetProfiles(requiredAtributes, optionalAtributes); for (int i = 0; i < tokens.Count; ++i) { token = tokens.Item(i); profileName = token.GetDescription(0); this.profiles.Add(profileName, token); } selectedProfile = this.profiles.IndexOfKey(recoContext.Recognizer.Profile.GetDescription(0)); } catch { // If no profiles could be retreived or an error occurred, clear the list and add a default profile with no token profiles.Clear(); profiles.Add("Default", null); } }
/// <summary> /// Validates whether new match is an exact sub match with any of the previous matches if not then returns the match in /// out param. /// </summary> /// <param name="queryIndex">Query index</param> /// <param name="referenceIndex">Reference index</param> /// <param name="matchLength">Match length</param> /// <param name="previousMatches">Previous matches</param> /// <param name="match">New match</param> /// <returns>Returns true if the new match is not an exact sub match with any of the previous matches, else returns false</returns> private static bool ValidateMatch( long queryIndex, long referenceIndex, long matchLength, SortedList<long, Dictionary<long, SortedList<long, SortedSet<long>>>> previousMatches, out Match match) { bool isoverlapedMatchFound = false; long lastQueryEndIndex; int overlappingMatchesCount = previousMatches.Keys.Count(); if (overlappingMatchesCount > 0) { lastQueryEndIndex = previousMatches.Keys.Last(); if (lastQueryEndIndex < queryIndex) { previousMatches.Clear(); } } overlappingMatchesCount = previousMatches.Keys.Count(); for (int listIndex = overlappingMatchesCount - 1; listIndex >= 0; listIndex--) { lastQueryEndIndex = previousMatches.Keys[listIndex]; if (lastQueryEndIndex >= queryIndex + matchLength) { Dictionary<long, SortedList<long, SortedSet<long>>> diffMap = previousMatches[lastQueryEndIndex]; SortedList<long, SortedSet<long>> refEndIndexMap; if (diffMap.TryGetValue(queryIndex - referenceIndex, out refEndIndexMap)) { int refEndIndexCount = refEndIndexMap.Count; for (int refEndMapIndex = refEndIndexCount - 1; refEndMapIndex >= 0; refEndMapIndex--) { long refEndindex = refEndIndexMap.Keys[refEndMapIndex]; if (refEndindex >= referenceIndex + matchLength) { SortedSet<long> refStartIndexes = refEndIndexMap[refEndindex]; isoverlapedMatchFound = refStartIndexes.Any(refStartIndex => refStartIndex <= referenceIndex); if (isoverlapedMatchFound) { break; } } } if (isoverlapedMatchFound) { break; } } } else { if (lastQueryEndIndex < queryIndex) { previousMatches.Remove(lastQueryEndIndex); } break; } } match = new Match(); if (!isoverlapedMatchFound) { match.ReferenceSequenceOffset = referenceIndex; match.QuerySequenceOffset = queryIndex; match.Length = matchLength; long queryEndIndex = queryIndex + matchLength; long diffValue = queryIndex - referenceIndex; long refEndIndex = referenceIndex + matchLength; Dictionary<long, SortedList<long, SortedSet<long>>> diffsMap; SortedList<long, SortedSet<long>> refEndIndexMap; SortedSet<long> refStartIndexes; if (previousMatches.TryGetValue(queryEndIndex, out diffsMap)) { if (diffsMap.TryGetValue(diffValue, out refEndIndexMap)) { if (refEndIndexMap.TryGetValue(refEndIndex, out refStartIndexes)) { refStartIndexes.Add(referenceIndex); } else { refStartIndexes = new SortedSet<long>(); refStartIndexes.Add(referenceIndex); refEndIndexMap.Add(refEndIndex, refStartIndexes); } } else { refEndIndexMap = new SortedList<long, SortedSet<long>>(); refStartIndexes = new SortedSet<long>(); refStartIndexes.Add(referenceIndex); refEndIndexMap.Add(refEndIndex, refStartIndexes); diffsMap.Add(diffValue, refEndIndexMap); } } else { diffsMap = new Dictionary<long, SortedList<long, SortedSet<long>>>(); refEndIndexMap = new SortedList<long, SortedSet<long>>(); refStartIndexes = new SortedSet<long>(); refStartIndexes.Add(referenceIndex); refEndIndexMap.Add(refEndIndex, refStartIndexes); diffsMap.Add(diffValue, refEndIndexMap); previousMatches.Add(queryEndIndex, diffsMap); } } return !isoverlapedMatchFound; }
public void TestIndexcAccessBasic() { StringBuilder sblMsg = new StringBuilder(99); // SortedList sl2 = null; StringBuilder sbl3 = new StringBuilder(99); StringBuilder sbl4 = new StringBuilder(99); StringBuilder sblWork1 = new StringBuilder(99); string s1 = null; string s2 = null; string s3 = null; int i = 0; // // Constructor: Create SortedList using this as IComparer and default settings. // sl2 = new SortedList(this); // Verify that the SortedList is not null. Assert.NotNull(sl2); // Verify that the SortedList is empty. Assert.Equal(0, sl2.Count); // Testcase: Set - null key, ArgExc expected Assert.Throws<ArgumentNullException>(() => { sl2[null] = "first value"; }); Assert.Equal(0, sl2.Count); // Testcase: Set - null val, should pass sl2["first key"] = (string)null; Assert.Equal(1, sl2.Count); // Testcase: vanila Set sl2[(int)0] = "first value"; Assert.Equal(2, sl2.Count); // Testcase: check to see whether the key is there Assert.True(sl2.ContainsKey("first key")); // Testcase: Get and check the value sl2["first key"] = "first value"; s2 = (string)sl2["first key"]; Assert.Equal("first value", s2); // Testcase: Set again with a diff value sl2["first key"] = "second value"; Assert.Equal(2, sl2.Count); // Testcase: now, Get again and check the value set s2 = (string)sl2["first key"]; Assert.Equal("second value", s2); sl2.Clear(); // Testcase: add 50 key-val pairs for (i = 0; i < 50; i++) { sblMsg.Length = 0; sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); sblMsg.Length = 0; sblMsg.Append("val_"); sblMsg.Append(i); s2 = sblMsg.ToString(); sl2.Add(s1, s2); } // // Testcase: now set their val again using Set (index, newVal) // for (i = 0; i < 50; i++) { sblMsg.Length = 0; sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); sblMsg.Length = 0; sblMsg.Append("new_val_"); sblMsg.Append(i); s2 = sblMsg.ToString(); sl2[s1] = s2; } Assert.Equal(50, sl2.Count); // Testcase: check the values for (i = 0; i < 50; i++) { sblMsg.Length = 0; sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); sblMsg.Length = 0; sblMsg.Append("new_val_"); sblMsg.Append(i); s2 = sblMsg.ToString(); s3 = (string)sl2[s1]; Assert.True(s3.Equals(s2)); } }
private const float MAX_ANGLE_SIN = 0.1305261922f; // sine of maximum angle permitted between segments internal static List <Vector2> CreateBezier(List <Vector2> input) { List <Vector2> output = new List <Vector2>(); // linear formula if (input.Count == 2) { LinearPart(output, input[0], input[1], MAX_LENGTH); output.Add(input[1]); return(output); } SortedList <float, Vector2> points = new SortedList <float, Vector2>(); points.Add(0.0f, input[0]); points.Add(1.0f, input[input.Count - 1]); SortedList <float, Vector2> addedPoints = new SortedList <float, Vector2>(); do { addedPoints.Clear(); float angle0 = 0.0f, angle1; if (points.Count < 3) { addedPoints.Add(0.5f, BezierPoint(ref input, 0.5f)); } else { for (int x = 0; x < points.Count - 2; x++) { Vector2 p0 = points.Values[x]; Vector2 p1 = points.Values[x + 1]; Vector2 p2 = points.Values[x + 2]; Vector2 v0 = p1 - p0; Vector2 v1 = p2 - p1; // find angle between using cross product since sin(x) has more accuracy near 0 than cos(x). float r = v0.LengthSquared; angle1 = Math.Abs(v0.X * v1.Y - v0.Y * v1.X) * MathHelper.InverseSqrtFast(r * v1.LengthSquared); // todo: the dependency on angle should be a weighted function of length instead of all/nothing if (r > MIN_LENGTH_SQUARED && (angle0 > MAX_ANGLE_SIN || angle1 > MAX_ANGLE_SIN || r > MAX_LENGTH_SQUARED)) { float t = (points.Keys[x] + points.Keys[x + 1]) * 0.5f; if (!addedPoints.ContainsKey(t)) { addedPoints.Add(t, BezierPoint(ref input, t)); } } angle0 = angle1; } Vector2 _p0 = points.Values[points.Count - 2]; Vector2 _p1 = points.Values[points.Count - 1]; float _r = (_p1 - _p0).LengthSquared; if (_r > MIN_LENGTH_SQUARED && (angle0 > MAX_ANGLE_SIN || _r > MAX_LENGTH_SQUARED)) { float t = (points.Keys[points.Count - 2] + 1.0f) * 0.5f; if (!addedPoints.ContainsKey(t)) { addedPoints.Add(t, BezierPoint(ref input, t)); } } } foreach (KeyValuePair <float, Vector2> k in addedPoints) { points.Add(k.Key, k.Value); } } while (addedPoints.Count > 0); output.AddRange(points.Values); return(output); }
public virtual bool runTest() { Console.Error.WriteLine( "Co4338GetEnumerator runTest() started." ); String strLoc="Loc_000oo"; StringBuilder sblMsg = new StringBuilder( 99 ); int iCountErrors = 0; int iCountTestcases = 0; SortedList sl2 = null; IDictionaryEnumerator dicen = null; StringBuilder sbl3 = new StringBuilder( 99 ); StringBuilder sbl4 = new StringBuilder( 99 ); StringBuilder sblWork1 = new StringBuilder( 99 ); int i3 = 0; int i2 = 0; int[] in4a = new int[9]; int i = 0; int j = 0; try { do { strLoc="100cc"; iCountTestcases++; sl2 = new SortedList( this ); iCountTestcases++; if ( sl2 == null ) { Console.WriteLine( strTest+ "E_101" ); Console.WriteLine( strTest+ "SortedList creation failure" ); ++iCountErrors; break; } iCountTestcases++; if ( sl2.Count != 0 ) { Console.WriteLine( strTest+ "E_102" ); Console.WriteLine( strTest+ "New SortedList is not empty" ); ++iCountErrors; } strLoc="Loc_100aa"; ++iCountTestcases; try { sl2[null] = 0 ; ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_2764! - must 've thrown ArgExc" ); Console.Error.WriteLine( sblMsg.ToString() ); } catch (ArgumentException) {} ++iCountTestcases; if (sl2.Count != 0) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_48ff! - Count == " ); sblMsg.Append( sl2.Count ); Console.Error.WriteLine( sblMsg.ToString() ); } strLoc="Loc_110aa"; ++iCountTestcases; try { sl2[(Object)100] = (Object)null ; } catch (InvalidOperationException aexc) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_34fj! - must not 've thrown ArgExc " + aexc.ToString() ); Console.Error.WriteLine( sblMsg.ToString() ); } ++iCountTestcases; if (sl2.Count != 1) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_60ff! - Count == " ); sblMsg.Append( sl2.Count ); Console.Error.WriteLine( sblMsg.ToString() ); } strLoc="Loc_120aa"; ++iCountTestcases; try { sl2[(Object)100] = 1 ; } catch (Exception exc) { ++iCountErrors; Console.Error.WriteLine ( "POINTTOBREAK: Error Err_49ff! - " + exc.ToString()); } if (sl2.Count != 1) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_2i20bc! - Count == " ); sblMsg.Append( sl2.Count ); Console.Error.WriteLine( sblMsg.ToString() ); } sl2.Clear(); if (sl2.Count != 0) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_03rf! - Count == " ); sblMsg.Append( sl2.Count ); Console.Error.WriteLine( sblMsg.ToString() ); } strLoc="Loc_141aa"; for (i=0; i<100; i++) { ++iCountTestcases; sl2.Add (i+100, i); } if (sl2.Count != 100) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_dhc3! - Count == " ); sblMsg.Append( sl2.Count ); Console.Error.WriteLine( sblMsg.ToString() ); } strLoc = "Loc_02tgr"; for (i=0; i<100; i++) { ++iCountTestcases; j = i+100; if (!sl2.ContainsKey ((int)j)) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_0dj! - ContainsKey failed at i == " ); sblMsg.Append( i ); Console.Error.WriteLine( sblMsg.ToString() ); break; } ++iCountTestcases; if (!sl2.ContainsValue (i)) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_hd3! -ContainsValue failed at i == " ); sblMsg.Append( i ); Console.Error.WriteLine( sblMsg.ToString() ); break; } ++iCountTestcases; try { Object o2 = sl2[(Object)(j)]; if (o2 != null) i2 = (int) o2; else { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_9dsh! -Get (Object) failed at i == " ); sblMsg.Append( i ); Console.Error.WriteLine( sblMsg.ToString() ); break; } } catch (Exception exc) { Console.Error.WriteLine (exc); } strLoc = "Loc_t02hf"; i3 = (int)sl2.GetByIndex(i); ++iCountTestcases; if ((i3 != i) || (i2 != i)) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_03dh! - i3 != i; at i == " ); sblMsg.Append( i ); Console.Error.WriteLine( sblMsg.ToString() ); break; } } strLoc="Loc_ugj2"; ++iCountTestcases; dicen = (IDictionaryEnumerator) sl2.GetEnumerator(); ++iCountTestcases; try { Object throwaway = dicen.Current; ++iCountErrors; Console.WriteLine( "Err_001, InvalidOperationException should have been thrown but it was not" ); } catch (InvalidOperationException) {} catch (Exception exc) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_1127dh! - " + exc.ToString() ); } strLoc="Loc_f2aa"; j = 0; while (dicen.MoveNext()) { ++iCountTestcases; i3 = (int) dicen.Value; if (! j.Equals( i3 ) ) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_1128dh! - i3 != j; at j == " ); sblMsg.Append( j ); sblMsg.Append( "i3 == " + i3 ); Console.Error.WriteLine( sblMsg.ToString() ); break; } ++iCountTestcases; i3 = (int) dicen.Value; if (i3 != j) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_1109dh! - i3 != j; at j == " ); sblMsg.Append( j ); sblMsg.Append( "i3 == " + i3 ); Console.Error.WriteLine( sblMsg.ToString() ); break; } j++; } strLoc="Loc_oi21u"; ++iCountTestcases; try { Object throwaway = dicen.Current; ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_001dt! - should have thrown InvalidOperationException" ); } catch ( InvalidOperationException ) {} catch (Exception exc) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_11gd29! - " + exc.ToString() ); } strLoc="Loc_783"; ++iCountTestcases; if ((dicen.MoveNext()) || (j != 100)) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_11oh32! - dicen.MoveNext returned " ); sblMsg.Append( dicen.MoveNext() ); Console.Error.WriteLine( sblMsg.ToString() ); } strLoc="Loc_1jo"; ++iCountTestcases; if (dicen.MoveNext()) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_1130dh! - dicen.MoveNext returned " ); sblMsg.Append( dicen.MoveNext() ); Console.Error.WriteLine( sblMsg.ToString() ); } } while ( false ); } catch( Exception exc_general ) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_343un! (Co4338GetEnumerator) exc_general==" + exc_general ); Console.Error.WriteLine( "EXTENDEDINFO: (Err_343un) strLoc==" + strLoc ); } if ( iCountErrors == 0 ) { Console.Error.WriteLine( "paSs. SortedList\\Co4338GetEnumerator.cs iCountTestcases==" + iCountTestcases ); return true; } else { Console.Error.WriteLine( "FAiL! SortedList\\Co4338GetEnumerator.cs iCountErrors==" + iCountErrors ); return false; } }
public void Dispose() { _Services.Clear(); System.GC.Collect(); }
static public void ClearCache() { _slTypeInfoCache.Clear(); }
public void TestGetValueListBasic() { StringBuilder sblMsg = new StringBuilder(99); SortedList sl2 = null; IEnumerator en = null; StringBuilder sbl3 = new StringBuilder(99); StringBuilder sbl4 = new StringBuilder(99); StringBuilder sblWork1 = new StringBuilder(99); int i3 = 0; int i = 0; int j = 0; // // Constructor: Create SortedList using this as IComparer and default settings. // sl2 = new SortedList(); // Verify that the SortedList is not null. Assert.NotNull(sl2); // Verify that the SortedList is empty. Assert.Equal(0, sl2.Count); // Testcase: Set - null key, ArgExc expected Assert.Throws<ArgumentNullException>(() => { sl2[null] = 0; }); Assert.Equal(0, sl2.Count); // Testcase: Set - null val sl2[(object)100] = (object)null; Assert.Equal(1, sl2.Count); // Testcase: vanila Set sl2[(object)100] = 1; Assert.Equal(1, sl2.Count); sl2.Clear(); Assert.Equal(0, sl2.Count); // Testcase: add key-val pairs for (i = 0; i < 100; i++) { sl2.Add(i + 100, i); } Assert.Equal(100, sl2.Count); for (i = 0; i < 100; i++) { j = i + 100; Assert.True(sl2.ContainsKey((int)j)); Assert.True(sl2.ContainsValue(i)); object o2 = sl2[(int)j]; Assert.NotNull(o2); Assert.True(o2.Equals(i), "Error, entry for key " + j.ToString() + " is " + o2.ToString() + " but should have been " + i.ToString()); } // FOR // testcase: GetValueList // ICollection.GetEnumerator() first test the boundaries on the Remove method thru GetEnumerator implementation en = (IEnumerator)sl2.GetValueList().GetEnumerator(); // Boundary for Current Assert.Throws<InvalidOperationException>(() => { object throwaway = en.Current; } ); j = 0; // go over the enumarator en = (IEnumerator)sl2.GetValueList().GetEnumerator(); while (en.MoveNext()) { // Current to see the order i3 = (int)en.Current; Assert.Equal(i3, j); // GetObject again to see the same order i3 = (int)en.Current; Assert.Equal(i3, j); j++; } // Boundary for GetObject Assert.Throws<InvalidOperationException>(() => { object throwawayobj = en.Current; } ); // Boundary for MoveNext: call MoveNext to make sure it returns false Assert.False((en.MoveNext()) || (j != 100)); // call again MoveNext to make sure it still returns false Assert.False(en.MoveNext()); Assert.Equal(100, sl2.Count); // now modify the sortedlist while enumerator is still active en = (IEnumerator)sl2.GetKeyList().GetEnumerator(); //can remove an item thru en en.MoveNext(); sl2[1] = 0; // Set (int index, object val) // this works fine // Boundary for MoveNext Assert.Throws<InvalidOperationException>(() => { en.MoveNext(); }); }
public void TestGetEnumeratorBasic() { StringBuilder sblMsg = new StringBuilder(99); // SortedList sl2 = null; IDictionaryEnumerator dicen = null; StringBuilder sbl3 = new StringBuilder(99); StringBuilder sbl4 = new StringBuilder(99); StringBuilder sblWork1 = new StringBuilder(99); int i3 = 0; int i2 = 0; int i = 0; int j = 0; // // Constructor: Create SortedList using this as IComparer and default settings. // sl2 = new SortedList(this); // Verify that the SortedList is not null. Assert.NotNull(sl2); // Verify that the SortedList is empty. Assert.Equal(0, sl2.Count); // Testcase: Set - null key, ArgExc expected Assert.Throws<ArgumentNullException>(() => { sl2[null] = 0; }); Assert.Equal(0, sl2.Count); // Testcase: Set - null val sl2[(object)100] = (object)null; Assert.Equal(1, sl2.Count); // Testcase: vanila Set sl2[(object)100] = 1; Assert.Equal(1, sl2.Count); sl2.Clear(); Assert.Equal(0, sl2.Count); // Testcase: add key-val pairs for (i = 0; i < 100; i++) { sl2.Add(i + 100, i); } Assert.Equal(100, sl2.Count); for (i = 0; i < 100; i++) { j = i + 100; Assert.True(sl2.ContainsKey((int)j)); Assert.True(sl2.ContainsValue(i)); object o2 = sl2[(object)(j)]; //need to cast: Get (object key) Assert.NotNull(o2); i2 = (int)o2; i3 = (int)sl2.GetByIndex(i); //Get (index i) Assert.False((i3 != i) || (i2 != i)); // testcase: GetEnumerator dicen = (IDictionaryEnumerator)sl2.GetEnumerator(); // Boundary for Current Assert.Throws<InvalidOperationException>(() => { object throwaway = dicen.Current; } ); j = 0; // go over the enumarator while (dicen.MoveNext()) { // Current to see the order i3 = (int)dicen.Value; Assert.True(j.Equals(i3)); // Current again to see the same order i3 = (int)dicen.Value; Assert.Equal(i3, j); j++; } // Boundary for Current Assert.Throws<InvalidOperationException>(() => { object throwaway = dicen.Current; } ); // Boundary for MoveNext: call MoveNext to make sure it returns false Assert.False((dicen.MoveNext()) || (j != 100)); // call again MoveNext to make sure it still returns false Assert.False(dicen.MoveNext()); } }
public static double MinImpCatProgressive(NodeTargetCategorical n, Predictor p) { //For some partitions gets the min Impiance int valueCount = p.DistinctValuesCount; double impBest= double.NaN; int i; int instanceCount = n.Table.RowCount; double imp = Double.NaN; double impIfValueGoesLeft = Double.NaN, impIfValueGoesRight = Double.NaN; List<NTT> nttLst; double impBeforePhase2; int improvementCode = 0; p.SplitStatus = Predictor.SplitStatusEnum.CanBeUsed; if (valueCount < 2) { p.SplitStatus = Predictor.SplitStatusEnum.OnlyOneValueAvailable; p.Gain = 0; return 0; } List<string> lComb = new List<string>(valueCount); List<string> rComb = new List<string>(valueCount); SortedList<string, int> lPredVal = new SortedList<string, int>(); SortedList<string, int> rPredVal = new SortedList<string, int>(); string sql = @"SELECT ALL " + " count(*), " + Def.DbBsTb + "." + p.Variable.Name + ", " + Def.DbBsTb + "." + Def.Schema.Target.Name + " " + "FROM " + Def.DbBsTb + "," + Def.DbTrTb + n.Id + " " + "WHERE " + Def.DbBsTb + "." + Def.DbTableIdName + " = " + Def.DbTrTb + n.Id + "." + Def.DbTableIdName + " AND " + Def.DbBsTb + "." + p.Variable.Name + " IS NOT NULL " + "GROUP BY " + Def.DbBsTb + "." + Def.Schema.Target.Name + ", " + Def.DbBsTb + "." + p.Variable.Name + " "; nttLst = Def.Db.GetNTTLst(sql); lComb.Clear(); rComb.Clear(); lPredVal.Clear(); rPredVal.Clear(); lComb.Add(p.ValueSd.Keys[0]); // Adds the 1st value to the combination of the left node rComb.Add(p.ValueSd.Keys[1]); // Adds the 2nd value to the combination of the right node //Done only if the number of values is 2 if (valueCount == 2) { imp = fillPredVals(lPredVal, rPredVal, lComb, rComb, nttLst, n); p.ChildrenGroups.ValueGroupLst[0].Clear(); p.ChildrenGroups.ValueGroupLst[1].Clear(); if (Double.IsNaN(imp)) { p.SplitStatus = Predictor.SplitStatusEnum.NotEnoughCases; p.ImpUniMin = Double.NaN; p.Gain = Double.NaN; p.ChildrenGroups.ValueGroupLst[0].Clear(); p.ChildrenGroups.ValueGroupLst[1].Clear(); return 0; } foreach(string s in lComb){ p.ChildrenGroups.ValueGroupLst[0].Add(s); } foreach(string s in rComb){ p.ChildrenGroups.ValueGroupLst[1].Add(s); } n.ImpBestUniSplit = imp; p.Gain = (n.Imp - imp) * 100 / n.Imp; p.Gain *= (double)(n.Table.RowCount - p.NullCount) / n.Table.RowCount; return p.Gain; } //IF valueCount > 2 for (i = 2; i < valueCount; ++i) { //try to adding to the left lComb.Add(p.ValueSd.Keys[i]); impIfValueGoesLeft = fillPredVals(lPredVal, rPredVal, lComb, rComb, nttLst, n); //Changes the side rComb.Add(p.ValueSd.Keys[i]); lComb.RemoveAt(lComb.Count - 1); impIfValueGoesRight = fillPredVals(lPredVal, rPredVal, lComb, rComb, nttLst, n); if (!Double.IsNaN(impIfValueGoesLeft) && !Double.IsNaN(impIfValueGoesRight)) { if (impIfValueGoesLeft < impIfValueGoesRight) { imp = impIfValueGoesLeft; lComb.Add(p.ValueSd.Keys[i]); rComb.RemoveAt(rComb.Count - 1); } else { imp = impIfValueGoesRight; } } else { if (Double.IsNaN(impIfValueGoesLeft)) { imp = impIfValueGoesRight; } if (Double.IsNaN(impIfValueGoesRight)) { imp = impIfValueGoesLeft; lComb.Add(p.ValueSd.Keys[i]); rComb.RemoveAt(rComb.Count - 1); } } } impBest = imp; if (Def.ClfOptimisationLevelForCatSearch >= 1) { #region enhanced progressive phase 1 // 0 = no improvement // 1 = 1 // 2 = 2 // 3 = 3 //if (valueCount > 2) { // Final combinations for the two 1st values // 1- Removes 1st val from left and put in the right // 2- Removes 2nd val from right and send to left // 3- Puts back the 1st val to left // 0) Initial status // left 0xxxxxx // right 1xxxxxx // 1) // left xxxxxx // right 1xxxxxx0 // 2) // left xxxxxx1 // right xxxxxx0 // 3) // left xxxxxx10 // right xxxxxx // 1 lComb.RemoveAt(0); rComb.Add(p.ValueSd.Keys[0]); imp = fillPredVals(lPredVal, rPredVal, lComb, rComb, nttLst, n); if (imp < impBest) { improvementCode = 1; impBest = imp; } // 2 rComb.RemoveAt(0); lComb.Add(p.ValueSd.Keys[1]); imp = fillPredVals(lPredVal, rPredVal, lComb, rComb, nttLst, n); if (imp < impBest) { improvementCode = 2; impBest = imp; } // 3 rComb.RemoveAt(rComb.Count - 1); lComb.Add(p.ValueSd.Keys[0]); imp = fillPredVals(lPredVal, rPredVal, lComb, rComb, nttLst, n); if (imp < impBest) { improvementCode = 3; impBest = imp; } if (improvementCode == 0) { rComb.Add(lComb[lComb.Count - 2]); lComb.RemoveAt(lComb.Count - 2); } if (improvementCode == 1) { lComb.RemoveAt(lComb.Count - 1); lComb.RemoveAt(lComb.Count - 1); rComb.Add(p.ValueSd.Keys[0]); rComb.Add(p.ValueSd.Keys[1]); } if (improvementCode == 2) { lComb.RemoveAt(lComb.Count - 1); rComb.RemoveAt(rComb.Count - 1); lComb.Add(p.ValueSd.Keys[1]); rComb.Add(p.ValueSd.Keys[0]); } #endregion enhanced progressive phase 1 #region enhanced progressive phase 2 if (Def.ClfOptimisationLevelForCatSearch >= 2) { impBeforePhase2 = imp; int lCombCount = lComb.Count; for (int lidx = 0; lidx < lCombCount; ++lidx) { rComb.Add(lComb[0]); lComb.RemoveAt(0); imp = fillPredVals(lPredVal, rPredVal, lComb, rComb, nttLst, n); if (imp < impBest) { impBest = imp; } else { lComb.Add(rComb[rComb.Count - 1]); rComb.RemoveAt(rComb.Count - 1); } } int rCombCount = rComb.Count; for (int ridx = 0; ridx < rCombCount; ++ridx) { lComb.Add(rComb[0]); rComb.RemoveAt(0); imp = fillPredVals(lPredVal, rPredVal, lComb, rComb, nttLst, n); if (imp < impBest) { impBest = imp; } else { rComb.Add(lComb[lComb.Count - 1]); lComb.RemoveAt(lComb.Count - 1); } } }//If optimisation >=2 #endregion phase 2 }//If optimisation >=1 if (Double.IsNaN(impBest)) { p.SplitStatus = Predictor.SplitStatusEnum.NotEnoughCases; p.ImpUniMin = Double.NaN; p.Gain = Double.NaN; p.ChildrenGroups.ValueGroupLst[0].Clear(); p.ChildrenGroups.ValueGroupLst[1].Clear(); return 0; } p.ChildrenGroups.ValueGroupLst[0].Clear(); p.ChildrenGroups.ValueGroupLst[1].Clear(); foreach(string s in lComb){ p.ChildrenGroups.ValueGroupLst[0].Add(s); } foreach(string s in rComb){ p.ChildrenGroups.ValueGroupLst[1].Add(s); } imp = impBest; p.ImpUniMin = imp; p.Gain = (n.Imp - imp) * 100 / n.Imp; p.Gain *= (double)(n.Table.RowCount - p.NullCount) / n.Table.RowCount; return p.Gain; }
public override async Task StreamingPull(StreamingPullRequest request, IServerStreamWriter <StreamingPullResponse> responseStream, ServerCallContext context) { var subscription = subscriptions[request.Id]; subscription.SubscriberThread = new Thread(() => { SortedList <long, ConsumeResult <string, byte[]> > toBeSend = new SortedList <long, ConsumeResult <string, byte[]> >((int)subscription.BufferSize); long lastTimestamp = 0; while (!context.CancellationToken.IsCancellationRequested) // The code here won't work if the send data is wrong. { var consumeResult = subscription.Consumer.Consume(context.CancellationToken); if (consumeResult == null) { continue; } if (consumeResult.Headers.TryGetLast("previous", out var previous)) { if (long.TryParse(Encoding.ASCII.GetString(previous), out var previousTimestamp)) { if (previousTimestamp == lastTimestamp) { toBeSend.Add(consumeResult.Timestamp.UnixTimestampMs, consumeResult); } else if (previousTimestamp < lastTimestamp) { toBeSend.Add(consumeResult.Timestamp.UnixTimestampMs, consumeResult); continue; } else { _logger.LogError("This should not be possible"); } } } foreach (var(key, result) in toBeSend) { subscription.Buffer.Post(new DataMessage() { Data = ByteString.CopyFrom(result.Value, 0, result.Value.Length), Index = result.Offset.Value.ToString(), Key = (uint)result.Timestamp.UnixTimestampMs, Partition = (uint)result.Partition.Value, PartitionKey = result.Key, Redelivary = false }); lastTimestamp = result.Timestamp.UnixTimestampMs; } toBeSend.Clear(); } subscription.Buffer.Complete(); }); subscription.SubscriberThread.Start(); while (subscription.Buffer.Completion.IsCompleted) { var message = await subscription.Buffer.ReceiveAsync(); await responseStream.WriteAsync(new StreamingPullResponse() { Message = message }); } }
/// Sets the best p.SplitHyperplane and p.Gain /// <summary> /// Look for the local minimum by fixing all the coeficients except one and then vary it /// </summary> // public static double MinImpMvStartingFromBestNumericalNoOtherOrder(NodeTargetCategorical n, Predictor p) { // bool infoNotYetCalculated = true; // List<double> bestCoefLst = new List<double>(); // List<double> testCoefLst = new List<double>(); // VariableToBeTestedCoodinates // SortedList<string, int> leftNode = new SortedList<string, int>(); // SortedList<string, int> rightNode = new SortedList<string, int>(); // List<int> optimisedVariableLst = new List<int>(); //Stores the index of predictors that have been used // List<int> NonOptimisedVariableLst = new List<int>(); //Stores the index of predictors that have been used // // starts with the best split index // double leftImp = 0, rightImp = 0; // List<double> azLst = new List<double>(); // double leftCount = 0, rightCount = 0;// Left and right item count // double c=0; // (= best split coordinate) Constant of the equation A1X1 + A2X2 + C = V [0] normalised [1] original value // double az; // New linear coefficient // double aSplit = 0; // Linear coefficient candidate for the split // double xjm = 0; // Normalised coordinate // double xts = 0; // Normalised coordinate of the variable being tested // double lowestSplitImp = n.ImpBestUniSplit, splitImp = 0; // double OptVarSum; // double aSplitB = 0, xtsB = 0, xjmB = 0; // double v=0; // see On growing better decision trees from data page 49 // double bestMvGain; // int j; // NonOptimisedVariableLst index // List<double> orderedNumericGain = new List<double>(); // value, index or PredictorLst // int bestNumericSplitIdx = -1; // Def.LogMessage += "Starting MinImpContMvStartingFromBestNumericalNoOtherOrder" + Environment.NewLine; // for (int i = 0; i < n.PredictorLst.Count; ++i) { // if (n.PredictorLst[i].Variable.VariableTypeUserSet == SchemaVariable.VariableTypeEnum.Continuous) { // orderedNumericGain.Add(n.PredictorLst[i].Gain); // } // } // orderedNumericGain.Sort(); // if (orderedNumericGain.Count == 0) { // Def.LogMessage += "No suitable numeric split to be used as startpoint" + Environment.NewLine; // return -1; // } // bestNumericSplitIdx = orderedNumericGain.Count - 1; // foreach (PredictorMv pmv in n.PredMvLst) { // pmv.Coef = 0; // if (pmv.Variable.VariableTypeUserSet == SchemaVariable.VariableTypeEnum.Categorical) { // pmv.Optimised = true; // optimisedVariableLst.Add(pmv.PredMvLstIdx); // pmv.Coef = 0; // //caseLst = n.PredictorLst[pmv.PredictorLstIdx].ChildrenGroups.ValueGroupLst[0]; // //for (int i = 0; i < caseLst.Count; ++i) { // // n.PredMvLst[pmv.PredMvLstIdx + caseLst[i]].BestCoef = 1; // //} // } // } // n.MvTb.DataFill(); // c = n.PredictorLst[bestNumericSplitIdx].SplitValue; // n.PredMvLst[n.PredictorLst[bestNumericSplitIdx].PredMvBase].Coef = 1; // variable used to split has coef 1 // n.PredMvLst[n.PredictorLst[bestNumericSplitIdx].PredMvBase].Optimised = true; // optimisedVariableLst.Add(n.PredictorLst[bestNumericSplitIdx].PredMvBase); // //if (n.BestSplit.Variable.VariableTypeUserSet == SchemaVariable.VariableTypeEnum.Continuous) { // // c=n.SplitValue; // // n.PredMvLst[n.BestSplit.PredMvBase].BestCoef = 1; // variable used to split has coef 1 // // n.PredMvLst[n.BestSplit.PredMvBase].Optimised = true; // // optimisedVariableLst.Add(n.BestSplit.PredMvBase); // //} // //else { // // c = 0; // // caseLst = n.BestSplit.ChildrenGroups.ValueGroupLst[0]; // // for (int i = 0; i < caseLst.Count; ++i) { // // n.PredMvLst[n.BestSplit.PredMvBase + caseLst[i]].BestCoef=0; // // } // //} // //for (int pidx = 0; pidx < n.PredictorLst.Count; ++pidx) { // // caseLst = n.PredictorLst[pidx].ChildrenGroups.ValueGroupLst[0]; // // for (int i = 0; i < caseLst.Count; ++i) { // // n.PredMvLst[n.PredictorLst[pidx].PredMvBase + caseLst[i]].BestCoef = 0; // // } // //} // for (int i = 0; i < n.PredMvLst.Count; ++i) { // if (n.PredMvLst[i].Optimised == false) // NonOptimisedVariableLst.Add(i); // } // for (j = 0; j < NonOptimisedVariableLst.Count; ++j) { // azLst.Clear(); // for (int y = 0; y < n.Table.RowCount; ++y) { // OptVarSum = 0; // for (int i = 0; i < optimisedVariableLst.Count; ++i) { // OptVarSum += n.PredMvLst[optimisedVariableLst[i]].Coef * n.PredMvLst[optimisedVariableLst[i]].X(y); // } // v = OptVarSum + c; // az = ((n.PredMvLst[NonOptimisedVariableLst[j]].Coef * n.PredMvLst[NonOptimisedVariableLst[j]].X(y)) -v ) / n.PredMvLst[NonOptimisedVariableLst[j]].X(y); // azLst.Add(az); // } // azLst.Sort(); // for (int azIdx = 0; azIdx < azLst.Count - 1; ++azIdx) { // //Finally we got a new linear coefficient for a variable that // //had linear coefficient = 0 // //The new hyperplane is: // // A1X1 + (1)X2 + c = 0 (c= - bestSplitNorm) // // (new midpoint coef) * testVar + (coordinate of the bestSplit variable) - bestSplitNorm; // // aSplit * Fcn.NormP1(testLst[y], PredictorLst[i].LowerNumber, PredictorLst[i].HigherNumber); // // + // aSplit = (azLst[azIdx] + azLst[azIdx + 1]) / 2; // for (int y = 0; y < n.Table.RowCount; ++y) { // xts = n.PredMvLst[NonOptimisedVariableLst[j]].X(y); //// // xjm = Fcn.NormP1(nnt.N0, n.BestSplit.LowerNumber, n.BestSplit.HigherNumber); // //am = Fcn.NormP1(n.BestSplit.SplitValue, n.PredictorLst[i].LowerNumber, n.PredictorLst[i].HigherNumber); // OptVarSum = 0; // for (int i = 0; i < optimisedVariableLst.Count; ++i) { // OptVarSum += n.PredMvLst[optimisedVariableLst[i]].Coef * n.PredMvLst[optimisedVariableLst[i]].X(y); // } // if ((aSplit * xts + OptVarSum + c) > 0) { // ++leftCount; // if (!leftNode.ContainsKey(n.MvTb.Data.TC[y])) // leftNode.Add(n.MvTb.Data.TC[y], 1); // else // ++leftNode[n.MvTb.Data.TC[y]]; // } else { // ++rightCount; // if (!rightNode.ContainsKey(n.MvTb.Data.TC[y])) // rightNode.Add(n.MvTb.Data.TC[y], 1); // else // ++rightNode[n.MvTb.Data.TC[y]]; // } // } // leftImp = Gini.ImpCat(leftNode, (int)leftCount); // rightImp = Gini.ImpCat(rightNode, (int)rightCount); // if (infoNotYetCalculated) { // lowestSplitImp = (leftCount * leftImp + rightCount * rightImp) / n.Table.RowCount; // aSplitB = aSplit; xtsB = xts; xjmB = xjm; // infoNotYetCalculated = false; // n.PredMvLst[NonOptimisedVariableLst[j]].Coef = aSplit; // } else { // splitImp = (leftCount * leftImp + rightCount * rightImp) / n.Table.RowCount; // if (splitImp < lowestSplitImp) { // lowestSplitImp = splitImp; // n.PredMvLst[NonOptimisedVariableLst[j]].Coef = aSplit; // aSplitB = aSplit; xtsB = xts; xjmB = xjm; // } // } // leftNode.Clear(); // rightNode.Clear(); // leftCount = 0; // rightCount = 0; // } // } // double bestUniGain = p.Gain; // bestMvGain = (n.Imp - lowestSplitImp) * 100 / n.Imp; // bestMvGain *= (double)(n.Table.RowCount - p.NullCount) / n.Table.RowCount; // string coefStr=""; // for (int i = 0; i < n.PredMvLst.Count; ++i){ // if(n.PredMvLst[i].Variable.VariableTypeUserSet == SchemaVariable.VariableTypeEnum.Continuous) // coefStr += n.PredMvLst[i].Coef + "(" + n.PredMvLst[i].Variable.Name + ") "; // else // coefStr += n.PredMvLst[i].Coef + "(" + n.PredMvLst[i].Variable.Name + n.PredMvLst[i].Offset + ") "; // } // coefStr +="c= " + c; // //MessageBox.Show("Gain= " + p.Gain + " bestUniGain= " + bestUniGain + Environment.NewLine + coefStr); // Def.LogMessage += "Gain= " + bestMvGain + " bestUniGain= " + bestUniGain + Environment.NewLine + coefStr + Environment.NewLine + Environment.NewLine; // n.MvTb.DataEmpty(); // return p.Gain; // } /// Sets the best p.SplitHyperplane and p.Gain /// <summary> /// Starts from the best numerical split and then try each possible combination of splits for /// nominal and numerical variables. /// /// Each nominal is tested for 0 and 1 and numeric variables are set to include each coordinate /// </summary> //public static double MinImpMvStartingFromBestNumericalOrderedByBestUnivariateNumericalSplits(NodeTargetCategorical n, Predictor p) { // bool infoNotYetCalculated = true; // List<double> bestCoefLst = new List<double>(); // List<double> testCoefLst = new List<double>(); // VariableToBeTestedCoodinates // SortedList<string, int> leftNode = new SortedList<string, int>(); // SortedList<string, int> rightNode = new SortedList<string, int>(); // List<int> optimisedVariableLst = new List<int>(); //Stores the index of predictors that have been used // List<int> NonOptimisedVariableLst = new List<int>(); //Stores the index of predictors that have been used // // starts with the best split index // double leftImp = 0, rightImp = 0; // List<double> azLst = new List<double>(); // double leftCount = 0, rightCount = 0;// Left and right item count // double c = 0; // (= best split coordinate) Constant of the equation A1X1 + A2X2 + C = V [0] normalised [1] original value // double az; // New linear coefficient // double aSplit = 0; // Linear coefficient candidate for the split // double xjm = 0; // Normalised coordinate // double xts = 0; // Normalised coordinate of the variable being tested // double lowestSplitImp = n.Imp, splitImp = 0; // double OptVarSum; // double aSplitB = 0, xtsB = 0, xjmB = 0; // double v = 0; // see On growing better decision trees from data page 49 // double bestMvGain; // int j; // NonOptimisedVariableLst index // List<int> orderedNumericGainIdx = new List<int>(); // index or PredNumLst // int bestNumericSplitIdx = -1; // Def.LogMessage += "Starting MinImpContMvStartingFromBestNumericalOrderedByBestUnivariateNumericalSplits" + Environment.NewLine; // int orderedNumericGainIdxCount; // if (n.PredNumLst.Count > 0) { // orderedNumericGainIdx.Add(0); // for (int pn = 1; pn < n.PredNumLst.Count; ++pn) { // orderedNumericGainIdxCount = orderedNumericGainIdx.Count; // for (int i = 0; i < orderedNumericGainIdxCount; ++i) { // if (n.PredNumLst[pn].Gain < n.PredNumLst[orderedNumericGainIdx[i]].Gain) { // orderedNumericGainIdx.Insert(i, pn); // continue; // } // orderedNumericGainIdx.Add(pn); // } // } // } // if (orderedNumericGainIdx.Count == 0) { // Def.LogMessage += "No suitable numeric split to be used as startpoint" + Environment.NewLine; // return -1; // } // bestNumericSplitIdx = n.PredNumLst[orderedNumericGainIdx[0]].PredictorLstIdx; // foreach (PredictorMv pmv in n.PredMvLst) { // pmv.Coef = 0; // if (pmv.Variable.VariableTypeUserSet == SchemaVariable.VariableTypeEnum.Categorical) { // pmv.Optimised = true; // optimisedVariableLst.Add(pmv.PredMvLstIdx); // //caseLst = n.PredictorLst[pmv.PredictorLstIdx].ChildrenGroups.ValueGroupLst[0]; // //for (int i = 0; i < caseLst.Count; ++i) { // // n.PredMvLst[pmv.PredMvLstIdx + caseLst[i]].BestCoef = 1; // //} // } // } // n.MvTb.DataFill(); // c = n.PredictorLst[bestNumericSplitIdx].SplitValue; // n.PredMvLst[n.PredictorLst[bestNumericSplitIdx].PredMvBase].Coef = 1; // variable used to split has coef 1 // n.PredMvLst[n.PredictorLst[bestNumericSplitIdx].PredMvBase].Optimised = true; // optimisedVariableLst.Add(n.PredictorLst[bestNumericSplitIdx].PredMvBase); // //if (n.BestSplit.Variable.VariableTypeUserSet == SchemaVariable.VariableTypeEnum.Continuous) { // // c=n.SplitValue; // // n.PredMvLst[n.BestSplit.PredMvBase].BestCoef = 1; // variable used to split has coef 1 // // n.PredMvLst[n.BestSplit.PredMvBase].Optimised = true; // // optimisedVariableLst.Add(n.BestSplit.PredMvBase); // //} // //else { // // c = 0; // // caseLst = n.BestSplit.ChildrenGroups.ValueGroupLst[0]; // // for (int i = 0; i < caseLst.Count; ++i) { // // n.PredMvLst[n.BestSplit.PredMvBase + caseLst[i]].BestCoef=0; // // } // //} // //for (int pidx = 0; pidx < n.PredictorLst.Count; ++pidx) { // // caseLst = n.PredictorLst[pidx].ChildrenGroups.ValueGroupLst[0]; // // for (int i = 0; i < caseLst.Count; ++i) { // // n.PredMvLst[n.PredictorLst[pidx].PredMvBase + caseLst[i]].BestCoef = 0; // // } // //} // //Set the order for nonOptimisedVariables to start by the univariate gain // //orderedNumericGain.Count -1 is the best and was used already // for (int i = 0; i < orderedNumericGainIdx.Count; ++i) { // NonOptimisedVariableLst.Add(n.PredNumLst[orderedNumericGainIdx[i]].PredMvBase); // } // for (int i = 0; i < n.PredMvLst.Count; ++i) { // if (n.PredMvLst[i].Optimised == false) { // if(!NonOptimisedVariableLst.Contains(i)) // NonOptimisedVariableLst.Add(i); // } // } // for (j = 0; j < NonOptimisedVariableLst.Count; ++j) { // azLst.Clear(); // for (int y = 0; y < n.Table.RowCount; ++y) { // OptVarSum = 0; // for (int i = 0; i < optimisedVariableLst.Count; ++i) { // OptVarSum += n.PredMvLst[optimisedVariableLst[i]].Coef * n.PredMvLst[optimisedVariableLst[i]].X(y); // } // v = OptVarSum + c; // az = ((n.PredMvLst[NonOptimisedVariableLst[j]].Coef * n.PredMvLst[NonOptimisedVariableLst[j]].X(y)) - v) / n.PredMvLst[NonOptimisedVariableLst[j]].X(y); // azLst.Add(az); // } // azLst.Sort(); // for (int azIdx = 0; azIdx < azLst.Count - 1; ++azIdx) { // //Finally we got a new linear coefficient for a variable that // //had linear coefficient = 0 // //The new hyperplane is: // // A1X1 + (1)X2 + c = 0 (c= - bestSplitNorm) // // (new midpoint coef) * testVar + (coordinate of the bestSplit variable) - bestSplitNorm; // // aSplit * Fcn.NormP1(testLst[y], PredictorLst[i].LowerNumber, PredictorLst[i].HigherNumber); // // + // aSplit = (azLst[azIdx] + azLst[azIdx + 1]) / 2; // for (int y = 0; y < n.Table.RowCount; ++y) { // xts = n.PredMvLst[NonOptimisedVariableLst[j]].X(y); // // // xjm = Fcn.NormP1(nnt.N0, n.BestSplit.LowerNumber, n.BestSplit.HigherNumber); // //am = Fcn.NormP1(n.BestSplit.SplitValue, n.PredictorLst[i].LowerNumber, n.PredictorLst[i].HigherNumber); // OptVarSum = 0; // for (int i = 0; i < optimisedVariableLst.Count; ++i) { // OptVarSum += n.PredMvLst[optimisedVariableLst[i]].Coef * n.PredMvLst[optimisedVariableLst[i]].X(y); // } // if ((aSplit * xts + OptVarSum + c) > 0) { // ++leftCount; // if (!leftNode.ContainsKey(n.MvTb.Data.TC[y])) // leftNode.Add(n.MvTb.Data.TC[y], 1); // else // ++leftNode[n.MvTb.Data.TC[y]]; // } else { // ++rightCount; // if (!rightNode.ContainsKey(n.MvTb.Data.TC[y])) // rightNode.Add(n.MvTb.Data.TC[y], 1); // else // ++rightNode[n.MvTb.Data.TC[y]]; // } // } // leftImp = Gini.ImpCat(leftNode, (int)leftCount); // rightImp = Gini.ImpCat(rightNode, (int)rightCount); // if (infoNotYetCalculated) { // lowestSplitImp = (leftCount * leftImp + rightCount * rightImp) / n.Table.RowCount; // aSplitB = aSplit; xtsB = xts; xjmB = xjm; // infoNotYetCalculated = false; // n.PredMvLst[NonOptimisedVariableLst[j]].Coef = aSplit; // } else { // splitImp = (leftCount * leftImp + rightCount * rightImp) / n.Table.RowCount; // if (splitImp < lowestSplitImp) { // lowestSplitImp = splitImp; // n.PredMvLst[NonOptimisedVariableLst[j]].Coef = aSplit; // aSplitB = aSplit; xtsB = xts; xjmB = xjm; // } // } // leftNode.Clear(); // rightNode.Clear(); // leftCount = 0; // rightCount = 0; // } // } // double bestUniGain = p.Gain; // bestMvGain = (n.Imp - lowestSplitImp) * 100 / n.Imp; // bestMvGain *= (double)(n.Table.RowCount - p.NullCount) / n.Table.RowCount; // string coefStr = ""; // for (int i = 0; i < n.PredMvLst.Count; ++i) { // if (n.PredMvLst[i].Variable.VariableTypeUserSet == SchemaVariable.VariableTypeEnum.Continuous) // coefStr += n.PredMvLst[i].Coef + "(" + n.PredMvLst[i].Variable.Name + ") "; // else // coefStr += n.PredMvLst[i].Coef + "(" + n.PredMvLst[i].Variable.Name + n.PredMvLst[i].Offset + ") "; // } // coefStr += "c= " + c; // //MessageBox.Show("Gain= " + p.Gain + " bestUniGain= " + bestUniGain + Environment.NewLine + coefStr); // Def.LogMessage += "Gain= " + bestMvGain + " bestUniGain= " + bestUniGain + Environment.NewLine + coefStr + Environment.NewLine + Environment.NewLine; // n.MvTb.DataEmpty(); // return p.Gain; //} /// Sets the best p.SplitHyperplane and p.Gain /// <summary> /// Look for the local minimum by fixing all the coeficients except one and then vary it /// </summary> //public static double MinImpMvStartingFromBestNominalNoOtherOrder(NodeTargetCategorical n, Predictor p) { // bool infoNotYetCalculated = true; // List<double> bestCoefLst = new List<double>(); // List<double> testCoefLst = new List<double>(); // VariableToBeTestedCoodinates // SortedList<string, int> leftNode = new SortedList<string, int>(); // SortedList<string, int> rightNode = new SortedList<string, int>(); // List<int> optimisedVariableLst = new List<int>(); //Stores the index of predictors that have been used // List<int> NonOptimisedVariableLst = new List<int>(); //Stores the index of predictors that have been used // // starts with the best split index // double leftImp = 0, rightImp = 0; // List<double> azLst = new List<double>(); // double leftCount = 0, rightCount = 0;// Left and right item count // double c = 0; // (= best split coordinate) Constant of the equation A1X1 + A2X2 + C = V [0] normalised [1] original value // double az; // New linear coefficient // double aSplit = 0; // Linear coefficient candidate for the split // double xjm = 0; // Normalised coordinate // double xts = 0; // Normalised coordinate of the variable being tested // double lowestSplitImp = n.Imp, splitImp = 0; // double OptVarSum; // double aSplitB = 0, xtsB = 0, xjmB = 0; // double v = 0; // see On growing better decision trees from data page 49 // double bestMvGain; // int j; // NonOptimisedVariableLst index // SortedList<double, int> orderedNominalGain = new SortedList<double, int>(); // value, index or PredictorLst // int bestNominalSplitIdx = -1; // SortedList<double, int> orderedNumericGain = new SortedList<double, int>(); // value, index or PredictorLst // Def.LogMessage += "Starting MinImpContMvStartingFromBestNominalNoOtherOrder" + Environment.NewLine; // for (int i = 0; i < n.PredictorLst.Count; ++i) { // if (n.PredictorLst[i].Variable.VariableTypeUserSet == SchemaVariable.VariableTypeEnum.Categorical) { // orderedNominalGain.Add(n.PredictorLst[i].Gain, i); // } // } // if (orderedNominalGain.Count == 0) { // Def.LogMessage += "No suitable nominal split to be used as startpoint" + Environment.NewLine; // return -1; // } // bestNominalSplitIdx = orderedNominalGain.Values[orderedNominalGain.Count - 1]; // List<int> caseLst; // foreach (PredictorMv pmv in n.PredMvLst) { // pmv.Coef = 0; // if (pmv.Variable.VariableTypeUserSet == SchemaVariable.VariableTypeEnum.Categorical) { // pmv.Optimised = true; // optimisedVariableLst.Add(pmv.PredMvLstIdx); // pmv.Coef = 0; // } // } // n.MvTb.DataFill(); // c = 0; // caseLst = n.PredictorLst[bestNominalSplitIdx].ChildrenGroups.ValueGroupLst[0]; // for (int i = 0; i < caseLst.Count; ++i) { // n.PredMvLst[n.PredictorLst[bestNominalSplitIdx].PredMvBase + caseLst[i]].Coef = 1; // } // //if (n.BestSplit.Variable.VariableTypeUserSet == SchemaVariable.VariableTypeEnum.Continuous) { // // c=n.SplitValue; // // n.PredMvLst[n.BestSplit.PredMvBase].BestCoef = 1; // variable used to split has coef 1 // // n.PredMvLst[n.BestSplit.PredMvBase].Optimised = true; // // optimisedVariableLst.Add(n.BestSplit.PredMvBase); // //} // //else { // // c = 0; // // caseLst = n.BestSplit.ChildrenGroups.ValueGroupLst[0]; // // for (int i = 0; i < caseLst.Count; ++i) { // // n.PredMvLst[n.BestSplit.PredMvBase + caseLst[i]].BestCoef=0; // // } // //} // //for (int pidx = 0; pidx < n.PredictorLst.Count; ++pidx) { // // caseLst = n.PredictorLst[pidx].ChildrenGroups.ValueGroupLst[0]; // // for (int i = 0; i < caseLst.Count; ++i) { // // n.PredMvLst[n.PredictorLst[pidx].PredMvBase + caseLst[i]].BestCoef = 0; // // } // //} // for (int i = 0; i < n.PredMvLst.Count; ++i) { // if (n.PredMvLst[i].Optimised == false) // NonOptimisedVariableLst.Add(i); // } // for (j = 0; j < NonOptimisedVariableLst.Count; ++j) { // azLst.Clear(); // for (int y = 0; y < n.Table.RowCount; ++y) { // OptVarSum = 0; // for (int i = 0; i < optimisedVariableLst.Count; ++i) { // OptVarSum += n.PredMvLst[optimisedVariableLst[i]].Coef * n.PredMvLst[optimisedVariableLst[i]].X(y); // } // v = OptVarSum + c; // az = ((n.PredMvLst[NonOptimisedVariableLst[j]].Coef * n.PredMvLst[NonOptimisedVariableLst[j]].X(y)) - v) / n.PredMvLst[NonOptimisedVariableLst[j]].X(y); // azLst.Add(az); // } // azLst.Sort(); // for (int azIdx = 0; azIdx < azLst.Count - 1; ++azIdx) { // //Finally we got a new linear coefficient for a variable that // //had linear coefficient = 0 // //The new hyperplane is: // // A1X1 + (1)X2 + c = 0 (c= - bestSplitNorm) // // (new midpoint coef) * testVar + (coordinate of the bestSplit variable) - bestSplitNorm; // // aSplit * Fcn.NormP1(testLst[y], PredictorLst[i].LowerNumber, PredictorLst[i].HigherNumber); // // + // aSplit = (azLst[azIdx] + azLst[azIdx + 1]) / 2; // for (int y = 0; y < n.Table.RowCount; ++y) { // xts = n.PredMvLst[NonOptimisedVariableLst[j]].X(y); // // // xjm = Fcn.NormP1(nnt.N0, n.BestSplit.LowerNumber, n.BestSplit.HigherNumber); // //am = Fcn.NormP1(n.BestSplit.SplitValue, n.PredictorLst[i].LowerNumber, n.PredictorLst[i].HigherNumber); // OptVarSum = 0; // for (int i = 0; i < optimisedVariableLst.Count; ++i) { // OptVarSum += n.PredMvLst[optimisedVariableLst[i]].Coef * n.PredMvLst[optimisedVariableLst[i]].X(y); // } // if ((aSplit * xts + OptVarSum + c) > 0) { // ++leftCount; // if (!leftNode.ContainsKey(n.MvTb.Data.TC[y])) // leftNode.Add(n.MvTb.Data.TC[y], 1); // else // ++leftNode[n.MvTb.Data.TC[y]]; // } else { // ++rightCount; // if (!rightNode.ContainsKey(n.MvTb.Data.TC[y])) // rightNode.Add(n.MvTb.Data.TC[y], 1); // else // ++rightNode[n.MvTb.Data.TC[y]]; // } // } // leftImp = Gini.ImpCat(leftNode, (int)leftCount); // rightImp = Gini.ImpCat(rightNode, (int)rightCount); // if (infoNotYetCalculated) { // lowestSplitImp = (leftCount * leftImp + rightCount * rightImp) / n.Table.RowCount; // aSplitB = aSplit; xtsB = xts; xjmB = xjm; // infoNotYetCalculated = false; // n.PredMvLst[NonOptimisedVariableLst[j]].Coef = aSplit; // } else { // splitImp = (leftCount * leftImp + rightCount * rightImp) / n.Table.RowCount; // if (splitImp < lowestSplitImp) { // lowestSplitImp = splitImp; // n.PredMvLst[NonOptimisedVariableLst[j]].Coef = aSplit; // aSplitB = aSplit; xtsB = xts; xjmB = xjm; // } // } // leftNode.Clear(); // rightNode.Clear(); // leftCount = 0; // rightCount = 0; // } // } // double bestUniGain = p.Gain; // bestMvGain = (n.Imp - lowestSplitImp) * 100 / n.Imp; // bestMvGain *= (double)(n.Table.RowCount - p.NullCount) / n.Table.RowCount; // string coefStr = ""; // for (int i = 0; i < n.PredMvLst.Count; ++i) { // if (n.PredMvLst[i].Variable.VariableTypeUserSet == SchemaVariable.VariableTypeEnum.Continuous) // coefStr += n.PredMvLst[i].Coef + "(" + n.PredMvLst[i].Variable.Name + ") "; // else // coefStr += n.PredMvLst[i].Coef + "(" + n.PredMvLst[i].Variable.Name + n.PredMvLst[i].Offset + ") "; // } // coefStr += "c= " + c; // //MessageBox.Show("Gain= " + p.Gain + " bestUniGain= " + bestUniGain + Environment.NewLine + coefStr); // Def.LogMessage += "Gain= " + bestMvGain + " bestUniGain= " + bestUniGain + Environment.NewLine + coefStr + Environment.NewLine + Environment.NewLine; // n.MvTb.DataEmpty(); // return p.Gain; //} /// Sets the best p.SplitHyperplane and p.Gain /// <summary> /// Look for the local minimum by fixing all the coeficients except one and then vary it /// </summary> //public static double MinImpMvStartingFromBestNominalOrderedByBestUnivariateNumericalSplit(NodeTargetCategorical n, Predictor p) { // bool infoNotYetCalculated = true; // List<double> bestCoefLst = new List<double>(); // List<double> testCoefLst = new List<double>(); // VariableToBeTestedCoodinates // SortedList<string, int> leftNode = new SortedList<string, int>(); // SortedList<string, int> rightNode = new SortedList<string, int>(); // List<int> optimisedVariableLst = new List<int>(); //Stores the index of predictors that have been used // List<int> NonOptimisedVariableLst = new List<int>(); //Stores the index of predictors that have been used // // starts with the best split index // double leftImp = 0, rightImp = 0; // List<double> azLst = new List<double>(); // double leftCount = 0, rightCount = 0;// Left and right item count // double c = 0; // (= best split coordinate) Constant of the equation A1X1 + A2X2 + C = V [0] normalised [1] original value // double az; // New linear coefficient // double aSplit = 0; // Linear coefficient candidate for the split // double xjm = 0; // Normalised coordinate // double xts = 0; // Normalised coordinate of the variable being tested // double lowestSplitImp = n.Imp, splitImp = 0; // double OptVarSum; // double aSplitB = 0, xtsB = 0, xjmB = 0; // double v = 0; // see On growing better decision trees from data page 49 // double bestMvGain; // int j; // NonOptimisedVariableLst index // SortedList<double, int> orderedNominalGain = new SortedList<double, int>(); // value, index or PredictorLst // SortedList<double, int> orderedNumericGain = new SortedList<double, int>(); // value, index or PredictorLst // int bestNominalSplitIdx = -1; // Def.LogMessage += "Starting MinImpContMvStartingFromBestNominalOrderedByBestUnivariateNumericalSplit" + Environment.NewLine; // for (int i = 0; i < n.PredictorLst.Count; ++i) { // if (n.PredictorLst[i].Variable.VariableTypeUserSet == SchemaVariable.VariableTypeEnum.Categorical) { // orderedNominalGain.Add(n.PredictorLst[i].Gain, i); // } // } // if (orderedNominalGain.Count == 0) { // Def.LogMessage += "No suitable nominal split to be used as startpoint" + Environment.NewLine; // return -1; // } // bestNominalSplitIdx = orderedNominalGain.Values[orderedNominalGain.Count - 1]; // for (int i = 0; i < n.PredictorLst.Count; ++i) { // if (n.PredictorLst[i].Variable.VariableTypeUserSet == SchemaVariable.VariableTypeEnum.Continuous) { // orderedNumericGain.Add(n.PredictorLst[i].Gain, i); // } // } // List<int> caseLst; // foreach (PredictorMv pmv in n.PredMvLst) { // pmv.Coef = 0; // if (pmv.Variable.VariableTypeUserSet == SchemaVariable.VariableTypeEnum.Categorical) { // pmv.Optimised = true; // optimisedVariableLst.Add(pmv.PredMvLstIdx); // pmv.Coef = 0; // //caseLst = n.PredictorLst[pmv.PredictorLstIdx].ChildrenGroups.ValueGroupLst[0]; // //for (int i = 0; i < caseLst.Count; ++i) { // // n.PredMvLst[pmv.PredMvLstIdx + caseLst[i]].BestCoef = 1; // //} // } // } // n.MvTb.DataFill(); // c = 0; // caseLst = n.PredictorLst[bestNominalSplitIdx].ChildrenGroups.ValueGroupLst[0]; // for (int i = 0; i < caseLst.Count; ++i) { // n.PredMvLst[n.PredictorLst[bestNominalSplitIdx].PredMvBase + caseLst[i]].Coef = 1; // } // //if (n.BestSplit.Variable.VariableTypeUserSet == SchemaVariable.VariableTypeEnum.Continuous) { // // c=n.SplitValue; // // n.PredMvLst[n.BestSplit.PredMvBase].BestCoef = 1; // variable used to split has coef 1 // // n.PredMvLst[n.BestSplit.PredMvBase].Optimised = true; // // optimisedVariableLst.Add(n.BestSplit.PredMvBase); // //} // //else { // // c = 0; // // caseLst = n.BestSplit.ChildrenGroups.ValueGroupLst[0]; // // for (int i = 0; i < caseLst.Count; ++i) { // // n.PredMvLst[n.BestSplit.PredMvBase + caseLst[i]].BestCoef=0; // // } // //} // //for (int pidx = 0; pidx < n.PredictorLst.Count; ++pidx) { // // caseLst = n.PredictorLst[pidx].ChildrenGroups.ValueGroupLst[0]; // // for (int i = 0; i < caseLst.Count; ++i) { // // n.PredMvLst[n.PredictorLst[pidx].PredMvBase + caseLst[i]].BestCoef = 0; // // } // //} // //Set the order for nonOptimisedVariables to start by the univariate gain // //orderedNumericGain.Count -1 is the best and was used already // for (int i = orderedNumericGain.Count - 2; i >= 0; --i) { // NonOptimisedVariableLst.Add(n.PredictorLst[orderedNumericGain.Values[i]].PredMvBase); // } // for (int i = 0; i < n.PredMvLst.Count; ++i) { // if (n.PredMvLst[i].Optimised == false) { // if (!NonOptimisedVariableLst.Contains(i)) // NonOptimisedVariableLst.Add(i); // } // } // for (j = 0; j < NonOptimisedVariableLst.Count; ++j) { // azLst.Clear(); // for (int y = 0; y < n.Table.RowCount; ++y) { // OptVarSum = 0; // for (int i = 0; i < optimisedVariableLst.Count; ++i) { // OptVarSum += n.PredMvLst[optimisedVariableLst[i]].Coef * n.PredMvLst[optimisedVariableLst[i]].X(y); // } // v = OptVarSum + c; // az = ((n.PredMvLst[NonOptimisedVariableLst[j]].Coef * n.PredMvLst[NonOptimisedVariableLst[j]].X(y)) - v) / n.PredMvLst[NonOptimisedVariableLst[j]].X(y); // azLst.Add(az); // } // azLst.Sort(); // for (int azIdx = 0; azIdx < azLst.Count - 1; ++azIdx) { // //Finally we got a new linear coefficient for a variable that // //had linear coefficient = 0 // //The new hyperplane is: // // A1X1 + (1)X2 + c = 0 (c= - bestSplitNorm) // // (new midpoint coef) * testVar + (coordinate of the bestSplit variable) - bestSplitNorm; // // aSplit * Fcn.NormP1(testLst[y], PredictorLst[i].LowerNumber, PredictorLst[i].HigherNumber); // // + // aSplit = (azLst[azIdx] + azLst[azIdx + 1]) / 2; // for (int y = 0; y < n.Table.RowCount; ++y) { // xts = n.PredMvLst[NonOptimisedVariableLst[j]].X(y); // // // xjm = Fcn.NormP1(nnt.N0, n.BestSplit.LowerNumber, n.BestSplit.HigherNumber); // //am = Fcn.NormP1(n.BestSplit.SplitValue, n.PredictorLst[i].LowerNumber, n.PredictorLst[i].HigherNumber); // OptVarSum = 0; // for (int i = 0; i < optimisedVariableLst.Count; ++i) { // OptVarSum += n.PredMvLst[optimisedVariableLst[i]].Coef * n.PredMvLst[optimisedVariableLst[i]].X(y); // } // if ((aSplit * xts + OptVarSum + c) > 0) { // ++leftCount; // if (!leftNode.ContainsKey(n.MvTb.Data.TC[y])) // leftNode.Add(n.MvTb.Data.TC[y], 1); // else // ++leftNode[n.MvTb.Data.TC[y]]; // } else { // ++rightCount; // if (!rightNode.ContainsKey(n.MvTb.Data.TC[y])) // rightNode.Add(n.MvTb.Data.TC[y], 1); // else // ++rightNode[n.MvTb.Data.TC[y]]; // } // } // leftImp = Gini.ImpCat(leftNode, (int)leftCount); // rightImp = Gini.ImpCat(rightNode, (int)rightCount); // if (infoNotYetCalculated) { // lowestSplitImp = (leftCount * leftImp + rightCount * rightImp) / n.Table.RowCount; // aSplitB = aSplit; xtsB = xts; xjmB = xjm; // infoNotYetCalculated = false; // n.PredMvLst[NonOptimisedVariableLst[j]].Coef = aSplit; // } else { // splitImp = (leftCount * leftImp + rightCount * rightImp) / n.Table.RowCount; // if (splitImp < lowestSplitImp) { // lowestSplitImp = splitImp; // n.PredMvLst[NonOptimisedVariableLst[j]].Coef = aSplit; // aSplitB = aSplit; xtsB = xts; xjmB = xjm; // } // } // leftNode.Clear(); // rightNode.Clear(); // leftCount = 0; // rightCount = 0; // } // } // double bestUniGain = p.Gain; // bestMvGain = (n.Imp - lowestSplitImp) * 100 / n.Imp; // bestMvGain *= (double)(n.Table.RowCount - p.NullCount) / n.Table.RowCount; // string coefStr = ""; // for (int i = 0; i < n.PredMvLst.Count; ++i) { // if (n.PredMvLst[i].Variable.VariableTypeUserSet == SchemaVariable.VariableTypeEnum.Continuous) // coefStr += n.PredMvLst[i].Coef + "(" + n.PredMvLst[i].Variable.Name + ") "; // else // coefStr += n.PredMvLst[i].Coef + "(" + n.PredMvLst[i].Variable.Name + n.PredMvLst[i].Offset + ") "; // } // coefStr += "c= " + c; // //MessageBox.Show("Gain= " + p.Gain + " bestUniGain= " + bestUniGain + Environment.NewLine + coefStr); // Def.LogMessage += "Gain= " + bestMvGain + " bestUniGain= " + bestUniGain + Environment.NewLine + coefStr + Environment.NewLine + Environment.NewLine; // n.MvTb.DataEmpty(); // return p.Gain; //} /// <summary> /// Receives one PredMvIdx to be tested, and the constant and return the: /// /// Return[0] the best value for the coefficient 0 or 1 /// Return[1] the lowestSplitImp for this coefficient /// </summary> /// <param name="n"></param> /// <param name="bestCoefLst"></param> /// <param name="c"></param> /// <param name="testPredMvIdx"></param> /// <returns></returns> public static double[] BestGainMvCategorical(NodeTargetCategorical n, double c, int testPredMvIdx, List<int> optimisedVariableLst) { double OptVarSum, bestAts=0; bool infoNotYetCalculated=true; double leftImp = 0, rightImp = 0; double leftCount = 0, rightCount = 0;// Left and right item count SortedList<string, int> leftNode = new SortedList<string, int>(); SortedList<string, int> rightNode = new SortedList<string, int>(); double lowestSplitImp =0, splitImp = 0; double minCoefCat = Def.AbsentCoefficientValue, maxCoefCat = Def.PresentCoefficientValue; //Instead of having a large list of coefficients, //there are only two possible linear coefficients, it will test the values for minCoefCat and maxCoefCat // ats = coeficient being tested for (double ats = minCoefCat; ats <= maxCoefCat; ats += maxCoefCat - minCoefCat) { leftNode.Clear(); rightNode.Clear(); leftCount = 0; rightCount = 0; for (int y = 0; y < n.Table.RowCount; ++y) { //Very important detail OptVarSum = ats * n.PredMvLst[testPredMvIdx].X(y); // for (int i = 0; i < optimisedVariableLst.Count; ++i) { // OptVarSum += n.PredMvLst[optimisedVariableLst[i]].Coef * n.PredMvLst[optimisedVariableLst[i]].X(y); for (int i = 0; i < n.PredMvLst.Count; ++i) { OptVarSum += n.PredMvLst[i].Coef * n.PredMvLst[i].X(y); } if ( ( OptVarSum + c ) <= 0) { ++leftCount; if (!leftNode.ContainsKey(n.MvTb.Data.TC[y])) leftNode.Add(n.MvTb.Data.TC[y], 1); else ++leftNode[n.MvTb.Data.TC[y]]; } else { ++rightCount; if (!rightNode.ContainsKey(n.MvTb.Data.TC[y])) rightNode.Add(n.MvTb.Data.TC[y], 1); else ++rightNode[n.MvTb.Data.TC[y]]; } } leftImp = Gini.ImpCat(leftNode, (int) leftCount); rightImp = Gini.ImpCat(rightNode, (int) rightCount); if (rightCount < Def.TreeMinNumberOfCasesPerNode || leftCount < Def.TreeMinNumberOfCasesPerNode) continue; if (infoNotYetCalculated) { lowestSplitImp = (leftCount * leftImp + rightCount * rightImp) / n.Table.RowCount; infoNotYetCalculated = false; bestAts = minCoefCat; } else { splitImp = (leftCount * leftImp + rightCount * rightImp) / n.Table.RowCount; if (splitImp < lowestSplitImp) { lowestSplitImp = splitImp; bestAts = maxCoefCat; } } } double[] r = new double[2]; r[0] = bestAts; r[1] = lowestSplitImp; if (infoNotYetCalculated) { r[0] = Double.NaN; r[1] = Double.NaN; } return r; }
/// <summary> /// Clears out the cached quest requirement statuses. /// </summary> public void Clear() { _statuses.Clear(); }
public void Clear() { _SortedKeys.Clear(); _SortedValues.Clear(); _InternalDict.Clear(); }
//It the number of variables is too large it can't compute //public static double KILLED_MinImpCatRandom(NodeTargetCategorical n, Predictor p) { // //For some partitions gets the min Impiance // int valueCount = p.DistinctValuesCount; // int pos, instanceI; // double partitionCount; // int c, i; // double bestPartition = 0, minImp = Double.NaN, imp = Double.NaN, lImp = Double.NaN, rImp = Double.NaN; // int nodeLfItemCount, nodeRtItemCount; // List<NTT> nttLst; // string binStr = ""; // p.SplitStatus = Predictor.SplitStatusEnum.CanBeUsed; // n.DescendentImpPreCalculated = new List<double>(2); // n.DescendentImpPreCalculated.Add(0); // n.DescendentImpPreCalculated.Add(0); // List<string> lComb = new List<string>(valueCount); // List<string> rComb = new List<string>(valueCount); // SortedList<string, int> lPredVal = new SortedList<string, int>(); // SortedList<string, int> rPredVal = new SortedList<string, int>(); // string sql = // @"SELECT ALL " + // " count(*), " + // Def.DbBsTb + "." + p.Variable.Name + ", " + // Def.DbBsTb + "." + Def.Schema.Target.Name + " " + // "FROM " // + Def.DbBsTb + "," + Def.DbTrTb + n.Id + " " + // "WHERE " // + Def.DbBsTb + "." + Def.DbTableIdName + " = " + // Def.DbTrTb + n.Id + "." + Def.DbTableIdName + " AND " + // Def.DbBsTb + "." + p.Variable.Name + " IS NOT NULL " + // "GROUP BY " + // Def.DbBsTb + "." + Def.Schema.Target.Name + ", " + // Def.DbBsTb + "." + p.Variable.Name + " "; // nttLst = Def.Db.GetNTTLst(sql); // int instanceCount = n.Table.RowCount; // partitionCount = Math.Pow(2, valueCount - 1) - 1; // double partitionCountMax = 0; // if (partitionCount > 4095) { // 4095 // partitionCountMax = 4095; // } else // partitionCountMax = partitionCount; // List<double> partLst = new List<double>((int)partitionCountMax); // i = 1; // //CHECK // for (int t = 0; t < partitionCountMax; ++t) { // partLst.Add((int)RNG.GetUniform(i, partitionCount)); // ++i; // } // for (i = 0; i < partitionCountMax; ++i) { // pos = 0; // binStr = Fcn.Decimal2BinaryStr(partLst[(int)i]); // lComb.Clear(); rComb.Clear(); // lPredVal.Clear(); rPredVal.Clear(); // nodeLfItemCount = nodeRtItemCount = 0; // for (c = 0; c < p.ValueSd.Count; ++c) { // if (binStr[binStr.Length - 1 - c] == '1') // lComb.Add(p.ValueSd.Keys[pos]); //if the 'case' is in, put it on the left // else // rComb.Add(p.ValueSd.Keys[pos]);//else, in the right side // ++pos; // } // for (instanceI = 0; instanceI < nttLst.Count; ++instanceI) { // foreach (string ls in lComb) { // if (nttLst[instanceI].T0 == ls) { // if (!lPredVal.ContainsKey(nttLst[instanceI].T1)) // lPredVal.Add(nttLst[instanceI].T1, (int)nttLst[instanceI].N); // else // lPredVal[nttLst[instanceI].T1] += (int)nttLst[instanceI].N; // nodeLfItemCount += (int)nttLst[instanceI].N; // break; // } // } // foreach (string rs in rComb) { // if (nttLst[instanceI].T0 == rs) { // if (!rPredVal.ContainsKey(nttLst[instanceI].T1)) // rPredVal.Add(nttLst[instanceI].T1, (int)nttLst[instanceI].N); // else // rPredVal[nttLst[instanceI].T1] += (int)nttLst[instanceI].N; // nodeRtItemCount += (int)nttLst[instanceI].N; // break; // } // } // } // if (nodeLfItemCount >= Def.TreeMinNumberOfCasesPerNode && nodeRtItemCount >= Def.TreeMinNumberOfCasesPerNode) { // lImp = ImpCat(lPredVal, nodeLfItemCount); // rImp = ImpCat(rPredVal, nodeRtItemCount); // if (Double.IsNaN(minImp)) { // bestPartition = partLst[(int)i]; // minImp = (double)(nodeLfItemCount) / instanceCount * lImp + (double)nodeRtItemCount / instanceCount * rImp; // n.DescendentImpPreCalculated[0] = lImp; // n.DescendentImpPreCalculated[1] = rImp; // } else { // imp = (double)(nodeLfItemCount) / instanceCount * lImp + (double)nodeRtItemCount / instanceCount * rImp; // if (imp < minImp) { // minImp = imp; // bestPartition = partLst[(int)i]; // n.DescendentImpPreCalculated[0] = lImp; // n.DescendentImpPreCalculated[1] = rImp; // } // } // } // } // if (bestPartition == 0) { // p.SplitStatus = Predictor.SplitStatusEnum.NotEnoughCases; // p.Gain = 0; // return 0; // } // //Set the possible children // ValueGroup valueGroup = new ValueGroup(2); // p.ChildrenGroups = valueGroup; // pos = 0; // binStr = Fcn.Decimal2BinaryStr((double)bestPartition); // for (c = 0; c < p.ValueSd.Count; ++c) { // // if ((bestPartition & c) == c) // if (binStr[binStr.Length - 1 - c] == '1') // valueGroup.ValueGroupLst[0].Add(pos); //if the 'case' is in put it on the left // else // valueGroup.ValueGroupLst[1].Add(pos);//else, in the right side // ++pos; // } // n.ImpBestUniSplit = minImp; // p.Gain = (n.Imp - minImp) * 100 / n.Imp; // p.Gain *= (double)(n.Table.RowCount - p.NullCount) / n.Table.RowCount; // return p.Gain; //} //Sets the best p.Gain, valueGroup.ValueGroupLst[0] (left child) and valueGroup.ValueGroupLst[1] (right child) public static double MinImpCatFullSearch(NodeTargetCategorical n, Predictor p) { //For each possible partition gets the min Imp int valueCount = p.DistinctValuesCount; if (valueCount > Def.ClfMaxNumberOfValuesForFullSearch) { p.SplitStatus = Predictor.SplitStatusEnum.TooManyValuesToSearch; p.Gain = 0; return 0; } int partitionCount, pos, instanceI; uint c, i, bestPartition = 0; double minImp = Double.NaN, imp = Double.NaN, lImp = Double.NaN, rImp = Double.NaN; int nodeLfItemCount, nodeRtItemCount; List<NTT> nttLst; p.SplitStatus = Predictor.SplitStatusEnum.CanBeUsed; n.DescendentImpPreCalculated = new List<double>(2); n.DescendentImpPreCalculated.Add(0); n.DescendentImpPreCalculated.Add(0); List<string> lComb = new List<string>(valueCount); List<string> rComb = new List<string>(valueCount); SortedList<string, int> lPredVal = new SortedList<string, int>(); SortedList<string, int> rPredVal = new SortedList<string, int>(); string sql = @"SELECT ALL " + " count(*), " + Def.DbBsTb + "." + p.Variable.Name + ", " + Def.DbBsTb + "." + Def.Schema.Target.Name + " " + "FROM " + Def.DbBsTb + "," + Def.DbTrTb + n.Id + " " + "WHERE " + Def.DbBsTb + "." + Def.DbTableIdName + " = " + Def.DbTrTb + n.Id + "." + Def.DbTableIdName + " AND " + Def.DbBsTb + "." + p.Variable.Name + " IS NOT NULL " + "GROUP BY " + Def.DbBsTb + "." + Def.Schema.Target.Name + ", " + Def.DbBsTb + "." + p.Variable.Name + " "; nttLst = Def.Db.GetNTTLst(sql); int instanceCount = n.Table.RowCount; partitionCount = (int)(Math.Pow(2, valueCount - 1) - 1); for (i = 1; i <= partitionCount; ++i) { //Enumerates all the possible partition but the empty pos = 0; lComb.Clear(); rComb.Clear(); lPredVal.Clear(); rPredVal.Clear(); nodeLfItemCount = nodeRtItemCount = 0; for (c = 1; c <= partitionCount + 1; c *= 2) { if ((i & c) == c) // i & c == c lComb.Add(p.ValueSd.Keys[pos]); //if the 'case' is in, put it on the left else rComb.Add(p.ValueSd.Keys[pos]);//else, in the right side ++pos; } for (instanceI = 0; instanceI < nttLst.Count; ++instanceI) { foreach (string ls in lComb) { if (nttLst[instanceI].T0 == ls) { if (!lPredVal.ContainsKey(nttLst[instanceI].T1)) lPredVal.Add(nttLst[instanceI].T1, (int)nttLst[instanceI].N); else lPredVal[nttLst[instanceI].T1] += (int)nttLst[instanceI].N; nodeLfItemCount += (int)nttLst[instanceI].N; break; } } foreach (string rs in rComb) { if (nttLst[instanceI].T0 == rs) { if (!rPredVal.ContainsKey(nttLst[instanceI].T1)) rPredVal.Add(nttLst[instanceI].T1, (int)nttLst[instanceI].N); else rPredVal[nttLst[instanceI].T1] += (int)nttLst[instanceI].N; nodeRtItemCount += (int)nttLst[instanceI].N; break; } } } if (nodeLfItemCount >= Def.TreeMinNumberOfCasesPerNode && nodeRtItemCount >= Def.TreeMinNumberOfCasesPerNode) { lImp = ImpCat(lPredVal, nodeLfItemCount); rImp = ImpCat(rPredVal, nodeRtItemCount); if (Double.IsNaN(minImp)) { bestPartition = i; minImp = (double)(nodeLfItemCount) / instanceCount * lImp + (double)nodeRtItemCount / instanceCount * rImp; n.DescendentImpPreCalculated[0] = lImp; n.DescendentImpPreCalculated[1] = rImp; } else { imp = (double)(nodeLfItemCount) / instanceCount * lImp + (double)nodeRtItemCount / instanceCount * rImp; if (imp < minImp) { minImp = imp; bestPartition = i; n.DescendentImpPreCalculated[0] = lImp; n.DescendentImpPreCalculated[1] = rImp; } } } } if (bestPartition == 0) { p.SplitStatus = Predictor.SplitStatusEnum.NotEnoughCases; p.Gain = 0; return 0; } //Set the possible children ValueGroup valueGroup = new ValueGroup(p, 2); p.ChildrenGroups = valueGroup; pos = 0; for (c = 1; c <= partitionCount + 1; c *= 2) { if ((bestPartition & c) == c) valueGroup.AddValueFromIndex(pos, 0); //if the 'case' is in put it on the left else valueGroup.AddValueFromIndex(pos, 1);//else, in the right side ++pos; } p.ImpUniMin = minImp; p.Gain = (n.Imp - minImp) * 100 / n.Imp; p.Gain *= (double)(n.Table.RowCount - p.NullCount) / n.Table.RowCount; return p.Gain; }
protected override void ClearItems() { lock (_sorted) _sorted.Clear(); _uiExecutive.MarshallWait(base.ClearItems); }
private static double fillPredVals(SortedList<string, int> lPredVal, SortedList<string, int> rPredVal, List<string> lComb, List<string> rComb, List<NTT> nttLst, NodeTargetCategorical n) { int nodeLfItemCount, nodeRtItemCount; int instanceI; double imp = Double.NaN, lImp = Double.NaN, rImp = Double.NaN; nodeLfItemCount = nodeRtItemCount = 0; lPredVal.Clear(); rPredVal.Clear(); for (instanceI = 0; instanceI < nttLst.Count; ++instanceI) { foreach (string ls in lComb) { if (nttLst[instanceI].T0 == ls) { if (!lPredVal.ContainsKey(nttLst[instanceI].T1)) lPredVal.Add(nttLst[instanceI].T1, (int)nttLst[instanceI].N); else lPredVal[nttLst[instanceI].T1] += (int)nttLst[instanceI].N; nodeLfItemCount += (int)nttLst[instanceI].N; break; } } foreach (string rs in rComb) { if (nttLst[instanceI].T0 == rs) { if (!rPredVal.ContainsKey(nttLst[instanceI].T1)) rPredVal.Add(nttLst[instanceI].T1, (int)nttLst[instanceI].N); else rPredVal[nttLst[instanceI].T1] += (int)nttLst[instanceI].N; nodeRtItemCount += (int)nttLst[instanceI].N; break; } } } if (nodeLfItemCount >= Def.TreeMinNumberOfCasesPerNode && nodeRtItemCount >= Def.TreeMinNumberOfCasesPerNode) { lImp = ImpCat(lPredVal, nodeLfItemCount); rImp = ImpCat(rPredVal, nodeRtItemCount); imp = (double)(nodeLfItemCount) / n.Table.RowCount * lImp + (double)nodeRtItemCount / n.Table.RowCount * rImp; } return imp; }
public void Clear() { using (IICLockRegion region = _lockSegs.LockForWrite()) { _searchEntrys.Clear(); } }
/// <summary> /// Receives one PredMvIdx to be tested, and the constant and returns: /// /// Return[0] the best value for the coefficient /// Return[1] the lowestSplitImp for this coefficient /// </summary> /// <param name="n"></param> /// <param name="bestCoefLst"></param> /// <param name="c"></param> /// <param name="testPredMvIdx"></param> /// <returns></returns> public static double[] BestGainMvNumeric(NodeTargetCategorical n, double c, int testPredMvIdx, List<int> optimisedVariableLst, FrmGraph fg) { double OptVarSum; bool infoNotYetCalculated = true; double leftImp = 0, rightImp = 0; double v, az, aSplit, xts,aSplitB=-9999999999; SortedList<double, int> azLst = new SortedList<double, int>(); double leftCount = 0, rightCount = 0;// Left and right item count SortedList<string, int> leftNode = new SortedList<string, int>(); SortedList<string, int> rightNode = new SortedList<string, int>(); double lowestSplitImp = 9999999, splitImp = 9999999; if (!Def.ExperimentRunning) { fg.ALst.Clear(); fg.AbsLst.Clear(); } azLst.Clear(); for (int y = 0; y < n.Table.RowCount; ++y) { OptVarSum = 0; //for (int i = 0; i < optimisedVariableLst.Count; ++i) { // OptVarSum += n.PredMvLst[optimisedVariableLst[i]].Coef * n.PredMvLst[optimisedVariableLst[i]].X(y); for (int i = 0; i < n.PredMvLst.Count; ++i) { OptVarSum += n.PredMvLst[i].Coef * n.PredMvLst[i].X(y); } v = OptVarSum + c; if (n.PredMvLst[testPredMvIdx].X(y) != 0) { az = ((n.PredMvLst[testPredMvIdx].Coef * n.PredMvLst[testPredMvIdx].X(y)) - v) / n.PredMvLst[testPredMvIdx].X(y); if (!azLst.ContainsKey(az) ) { azLst.Add(az, 1); if (!Def.ExperimentRunning) fg.ALst.Add((float)az); } } } for (int azIdx = 0; azIdx < azLst.Count - 1; ++azIdx) { //Finally we got a new linear coefficient for a variable that //had linear coefficient = 0 //The new hyperplane is: // A1X1 + (1)X2 + c = 0 (c= - bestSplitNorm) // (new midpoint coef) * testVar + (coordinate of the bestSplit variable) - bestSplitNorm; // aSplit * Fcn.NormP1(testLst[y], PredictorLst[i].LowerNumber, PredictorLst[i].HigherNumber); aSplit = (azLst.Keys[azIdx] + azLst.Keys[azIdx + 1]) / 2; leftNode.Clear(); rightNode.Clear(); leftCount = 0; rightCount = 0; if (!Def.ExperimentRunning) fg.AbsLst.Add((float)aSplit); for (int y = 0; y < n.Table.RowCount; ++y) { xts = n.PredMvLst[testPredMvIdx].X(y); OptVarSum = 0; for (int i = 0; i < optimisedVariableLst.Count; ++i) { OptVarSum += n.PredMvLst[optimisedVariableLst[i]].Coef * n.PredMvLst[optimisedVariableLst[i]].X(y); } if ((aSplit * xts + OptVarSum + c) <= 0) { ++leftCount; if (!leftNode.ContainsKey(n.MvTb.Data.TC[y])) leftNode.Add(n.MvTb.Data.TC[y], 1); else ++leftNode[n.MvTb.Data.TC[y]]; } else { ++rightCount; if (!rightNode.ContainsKey(n.MvTb.Data.TC[y])) rightNode.Add(n.MvTb.Data.TC[y], 1); else ++rightNode[n.MvTb.Data.TC[y]]; } } if (rightCount < Def.TreeMinNumberOfCasesPerNode || leftCount < Def.TreeMinNumberOfCasesPerNode) continue; leftImp = Gini.ImpCat(leftNode, (int)leftCount); rightImp = Gini.ImpCat(rightNode, (int)rightCount); if (infoNotYetCalculated) { infoNotYetCalculated = false; lowestSplitImp = (leftCount * leftImp + rightCount * rightImp) / n.Table.RowCount; if (n.PredMvLst[testPredMvIdx].Variable.VariableTypeDetected == SchemaVariable.VariableTypeEnum.Categorical) { MessageBox.Show("Error n.PredMvLst[testPredMvIdx].Variable is categorical "); } aSplitB = aSplit; } else { splitImp = (leftCount * leftImp + rightCount * rightImp) / n.Table.RowCount; if (splitImp < lowestSplitImp) { lowestSplitImp = splitImp; if (n.PredMvLst[testPredMvIdx].Variable.VariableTypeDetected == SchemaVariable.VariableTypeEnum.Categorical) { MessageBox.Show("Error n.PredMvLst[testPredMvIdx].Variable is categorical "); } aSplitB = aSplit; } } } //Creates bissections for the last and the 'x0 axis' if (azLst.Count > 1) { // if only 1 is the zero aSplit = azLst.Keys[azLst.Count-1] * 2; if (!Def.ExperimentRunning) fg.AbsLst.Add((float)aSplit); leftNode.Clear(); rightNode.Clear(); leftCount = 0; rightCount = 0; for (int y = 0; y < n.Table.RowCount; ++y) { xts = n.PredMvLst[testPredMvIdx].X(y); OptVarSum = 0; for (int i = 0; i < optimisedVariableLst.Count; ++i) { OptVarSum += n.PredMvLst[optimisedVariableLst[i]].Coef * n.PredMvLst[optimisedVariableLst[i]].X(y); } if ((aSplit * xts + OptVarSum + c) <= 0) { ++leftCount; if (!leftNode.ContainsKey(n.MvTb.Data.TC[y])) leftNode.Add(n.MvTb.Data.TC[y], 1); else ++leftNode[n.MvTb.Data.TC[y]]; } else { ++rightCount; if (!rightNode.ContainsKey(n.MvTb.Data.TC[y])) rightNode.Add(n.MvTb.Data.TC[y], 1); else ++rightNode[n.MvTb.Data.TC[y]]; } } if (rightCount >= Def.TreeMinNumberOfCasesPerNode && leftCount >= Def.TreeMinNumberOfCasesPerNode) { leftImp = Gini.ImpCat(leftNode, (int)leftCount); rightImp = Gini.ImpCat(rightNode, (int)rightCount); if (infoNotYetCalculated) { infoNotYetCalculated = false; lowestSplitImp = (leftCount * leftImp + rightCount * rightImp) / n.Table.RowCount; if (n.PredMvLst[testPredMvIdx].Variable.VariableTypeDetected == SchemaVariable.VariableTypeEnum.Categorical) { MessageBox.Show("Error n.PredMvLst[testPredMvIdx].Variable is categorical "); } aSplitB = aSplit; } else { splitImp = (leftCount * leftImp + rightCount * rightImp) / n.Table.RowCount; if (splitImp < lowestSplitImp) { lowestSplitImp = splitImp; if (n.PredMvLst[testPredMvIdx].Variable.VariableTypeDetected == SchemaVariable.VariableTypeEnum.Categorical) { MessageBox.Show("Error n.PredMvLst[testPredMvIdx].Variable is categorical "); } aSplitB = aSplit; } } }//end if (rightCount >= Def.TreeMinNumberOfCasesPerNode && leftCount >= Def.TreeMinNumberOfCasesPerNode) { } double[] r = new double[2]; r[0] = aSplitB; r[1] = lowestSplitImp; return r; }
public void Clear() { _table.Clear(); }
public virtual bool runTest() { Console.Error.WriteLine( "Co4345TrimToSize runTest() started." ); String strLoc="Loc_000oo"; StringBuilder sblMsg = new StringBuilder( 99 ); int iCountErrors = 0; int iCountTestcases = 0; SortedList sl2 = null; StringBuilder sbl3 = new StringBuilder( 99 ); StringBuilder sbl4 = new StringBuilder( 99 ); StringBuilder sblWork1 = new StringBuilder( 99 ); String str5 = null; String str6 = null; String str7 = null; String s1 = null; String s2 = null; String s3 = null; int[] in4a = new int[9]; int nCapacity = 100; bool bol = false; int i = 0; try { LABEL_860_GENERAL: do { strLoc="100cc"; iCountTestcases++; sl2 = new SortedList( this ); iCountTestcases++; if ( sl2 == null ) { Console.WriteLine( strTest+ "E_101" ); Console.WriteLine( strTest+ "SortedList creation failure" ); ++iCountErrors; break; } iCountTestcases++; if ( sl2.Count != 0 ) { Console.WriteLine( strTest+ "E_102" ); Console.WriteLine( strTest+ "New SortedList is not empty" ); ++iCountErrors; } if (s3 != null) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_101bc! " ); Console.Error.WriteLine( sblMsg.ToString() ); } strLoc="Loc_141aa"; for (i=0; i<32; i++) { ++iCountTestcases; sblMsg.Length = 0 ; sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); sblMsg.Length = 0 ; sblMsg.Append("val_"); sblMsg.Append(i); s2 = sblMsg.ToString(); sl2.Add (s1, s2); } ++iCountTestcases; sl2.Add ("key_32", "val_32"); ++iCountTestcases; if (sl2.Count != 33) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_gh40! - Count == " ); sblMsg.Append( sl2.Count ); Console.Error.WriteLine( sblMsg.ToString() ); } for (i=0; i < 10; i++) { ++iCountTestcases; sl2.Remove ("key_" + i.ToString()); } strLoc="Loc_141aa"; ++iCountTestcases; if (sl2.Count != 23) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_gh45! - Count == " ); sblMsg.Append( sl2.Count ); Console.Error.WriteLine( sblMsg.ToString() ); } ++iCountTestcases; sl2.TrimToSize (); ++iCountTestcases; sl2.Clear(); ++iCountTestcases; sl2.TrimToSize (); } while ( false ); } catch( Exception exc_general ) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_343un! (Co4345TrimToSize) exc_general==" + exc_general ); Console.Error.WriteLine( "EXTENDEDINFO: (Err_343un) strLoc==" + strLoc ); } if ( iCountErrors == 0 ) { Console.Error.WriteLine( "paSs. SortedList\\Co4345TrimToSize.cs iCountTestcases==" + iCountTestcases ); return true; } else { Console.Error.WriteLine( "FAiL! SortedList\\Co4345TrimToSize.cs iCountErrors==" + iCountErrors ); return false; } }
public void Clear() { sortedList.Clear(); }
public virtual bool runTest() { Console.Error.WriteLine( "Co4339GetKeyList runTest() started." ); String strLoc="Loc_000oo"; StringBuilder sblMsg = new StringBuilder( 99 ); int iCountErrors = 0; int iCountTestcases = 0; SortedList sl2 = null; IEnumerator en = null; StringBuilder sbl3 = new StringBuilder( 99 ); StringBuilder sbl4 = new StringBuilder( 99 ); StringBuilder sblWork1 = new StringBuilder( 99 ); int i3 = 0; int[] in4a = new int[9]; int i = 0; int j = 0; try { do { strLoc="100cc"; iCountTestcases++; sl2 = new SortedList(); iCountTestcases++; if ( sl2 == null ) { Console.WriteLine( strTest+ "E_101" ); Console.WriteLine( strTest+ "SortedList creation failure" ); ++iCountErrors; break; } iCountTestcases++; if ( sl2.Count != 0 ) { Console.WriteLine( strTest+ "E_102" ); Console.WriteLine( strTest+ "New SortedList is not empty" ); ++iCountErrors; } strLoc="Loc_100aa"; ++iCountTestcases; try { sl2[null] = 0; ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_2764! - must 've thrown ArgExc" ); Console.Error.WriteLine( sblMsg.ToString() ); } catch (ArgumentNullException ) {} catch (Exception ex ) { ++iCountErrors; Console.WriteLine( "Err_001dt, ArgumentNullException expected but got " + ex.ToString() ); } ++iCountTestcases; if (sl2.Count != 0) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_48ff! - Count == " ); sblMsg.Append( sl2.Count ); Console.Error.WriteLine( sblMsg.ToString() ); } strLoc="Loc_110aa"; ++iCountTestcases; try { sl2[(Object)100] = (Object)null ; } catch (ArgumentException) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_34fj! - must not 've thrown ArgExc" ); Console.Error.WriteLine( sblMsg.ToString() ); } ++iCountTestcases; if (sl2.Count != 1) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_60ff! - Count == " ); sblMsg.Append( sl2.Count ); Console.Error.WriteLine( sblMsg.ToString() ); } strLoc="Loc_120aa"; ++iCountTestcases; try { sl2[(Object)100] = 1; } catch (Exception exc) { ++iCountErrors; Console.Error.WriteLine ( "POINTTOBREAK: Error Err_49ff! - " + exc.ToString()); } if (sl2.Count != 1) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_2i20bc! - Count == " ); sblMsg.Append( sl2.Count ); Console.Error.WriteLine( sblMsg.ToString() ); } sl2.Clear(); if (sl2.Count != 0) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_03rf! - Count == " ); sblMsg.Append( sl2.Count ); Console.Error.WriteLine( sblMsg.ToString() ); } strLoc="Loc_141aa"; for (i=0; i<100; i++) { ++iCountTestcases; sl2.Add (i+100, i); } if (sl2.Count != 100) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_dhc3! - Count == " ); sblMsg.Append( sl2.Count ); Console.Error.WriteLine( sblMsg.ToString() ); } for (i=0; i<100; i++) { ++iCountTestcases; j = i+100; if (!sl2.ContainsKey ((int)j)) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_0dj! - ContainsKey failed at i == " ); sblMsg.Append( i ); Console.Error.WriteLine( sblMsg.ToString() ); break; } ++iCountTestcases; if (!sl2.ContainsValue (i)) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_hd3! -ContainsValue failed at i == " ); sblMsg.Append( i ); Console.Error.WriteLine( sblMsg.ToString() ); break; } } strLoc="Loc_346aws"; ++iCountTestcases; en = (IEnumerator) sl2.GetKeyList().GetEnumerator(); ++iCountTestcases; try { Object objThrowAway = en.Current; ++iCountErrors; Console.WriteLine( "Err_002dt, Expected InvalidOperationException to be thrown but nothing was thrown" ); } catch (InvalidOperationException) {} catch (Exception exc ) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_27dh! - " + exc.ToString() ); } j = 100; en = (IEnumerator) sl2.GetKeyList().GetEnumerator(); while (en.MoveNext()) { ++iCountTestcases; i3 = (int) en.Current; if (i3 != j) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_28dh! - i3 != j; at j == " ); sblMsg.Append( j ); sblMsg.Append( "i3 == " + i3 ); Console.Error.WriteLine( sblMsg.ToString() ); break; } ++iCountTestcases; i3 = (int) en.Current; if (i3 != j) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_09dh! - i3 != j; at j == " ); sblMsg.Append( j ); sblMsg.Append( "i3 == " + i3 ); Console.Error.WriteLine( sblMsg.ToString() ); break; } j++; } ++iCountTestcases; try { Object objThrowAway = en.Current; ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_001dt! - InvalidOperationException expected"); } catch ( InvalidOperationException ) {} catch (Exception exc) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_gd29! - " + exc.ToString() ); } strLoc="Loc_23aer"; ++iCountTestcases; if ((en.MoveNext()) || (j != 200)) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_oh32! - en.MoveNext returned " ); sblMsg.Append( en.MoveNext() ); Console.Error.WriteLine( sblMsg.ToString() ); } ++iCountTestcases; if (en.MoveNext()) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_30dh! - en.MoveNext returned " ); sblMsg.Append( en.MoveNext() ); Console.Error.WriteLine( sblMsg.ToString() ); } } while ( false ); } catch( Exception exc_general ) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_343un! (Co4339GetKeyList) exc_general==" + exc_general ); Console.Error.WriteLine( "EXTENDEDINFO: (Err_343un) strLoc==" + strLoc ); } if ( iCountErrors == 0 ) { Console.Error.WriteLine( "paSs. SortedList\\Co4339GetKeyList.cs iCountTestcases==" + iCountTestcases ); return true; } else { Console.Error.WriteLine( "FAiL! SortedList\\Co4339GetKeyList.cs iCountErrors==" + iCountErrors ); return false; } }
public void Clear() { _hash.Clear(); }
public bool GetNextReserve(ref ReserveData info) { bool ret = false; SortedList<String, ReserveData> sortList = new SortedList<String, ReserveData>(); foreach (ReserveData resInfo in reserveList.Values) { if (resInfo.RecSetting.RecMode != 5) { String key = resInfo.StartTime.ToString("yyyyMMddHHmmss"); key += resInfo.ReserveID.ToString("X8"); sortList.Add(key, resInfo); } } foreach (ReserveData resInfo in sortList.Values) { if (resInfo.StartTime > DateTime.Now) { info = resInfo; ret = true; break; } } sortList.Clear(); sortList = null; return ret; }
IEnumerator StartBattling() { for (int i = 0; i < 4; i++) { meButtons [i].SetActive(false); } battleLog.SetActive(true); playerTurn = false; currentChar++; print(new Time()); yield return(SelectAIMove()); print(new Time()); //MakeMoves (); method is under this print(pressedEnter); pressedEnter = false; for (int i = 0; i < moveList.Count && moveList[i] != null; i++) { print(i); MoveMessenger m = (MoveMessenger)(moveList.GetKey(i)); if (m.getAttackedPlayer().isAlive() != true) { updateBattleLog(m.getAttackingPlayer().getName() + "'s target was dead before move. Attacking next person in the enemy line"); yield return(chatEnter()); int newTarget = m.getIndexOfAttackedPlayer(); if (m.getAttackingPlayer().getTeam() == "team") { if (newTarget > aliveEnemyList.Capacity - 1) { newTarget = 0; } m.setAttackedPlayer(aliveEnemyList [newTarget]); } else { if (newTarget > aliveTeammateList.Capacity - 1) { newTarget = 0; } m.setAttackedPlayer(aliveTeammateList [newTarget]); } m.setIndexOfAttackedPlayer(newTarget); m.recalculateDamage(m.getAttackingPlayer().moveList [m.getIndexOfMove()].getDamage()); } updateBattleLog(m.getAttackingPlayer().getName() + " is attacking " + m.getAttackedPlayer().getName() + " with damage: " + m.getRecalculatedDamage()); updateBattleLog(m.getAttackedPlayer().getName() + "'s health before the move is: " + m.getAttackedPlayer().getHealth()); int health = m.getAttackedPlayer().receiveDamage((MoveMessenger)moveList.GetKey(i)); updateBattleLog(m.getAttackedPlayer().getName() + "'s health after the move is: " + health); yield return(chatEnter()); m.getAttackedPlayer().setHealth(health); if (health <= 0) { updateBattleLog(m.getAttackedPlayer().getName() + " has died"); if (m.getAttackedPlayer().team == "team") { aliveTeammateList.Remove(m.getAttackedPlayer()); } else //no need to check if he's enemy, because he will be { aliveEnemyList.Remove(m.getAttackedPlayer()); } yield return(chatEnter()); moveList [moveList.IndexOfValue(m.getAttackedPlayer().getName())] = null; //moveList.RemoveAt (moveList.IndexOfValue (m.getAttackedPlayer ().getName ())); //the line that causes skipped turns if (isBattleOver()) { updateBattleLog("Battle's over."); BattleOver(); } } } moveList.Clear(); print("MoveList cleared"); currentChar = 0; print("CurrentChar has been reset"); currentPageOfMovesOrTargets = 0; battleLog.SetActive(false); playerTurn = true; updateMovesForChar(); EventSystem.current.SetSelectedGameObject(meButtons[0]); needToPrint = true; }
public void TestTrimToSizeBasic() { StringBuilder sblMsg = new StringBuilder(99); // SortedList sl2 = null; StringBuilder sbl3 = new StringBuilder(99); StringBuilder sbl4 = new StringBuilder(99); StringBuilder sblWork1 = new StringBuilder(99); String s1 = null; String s2 = null; String s3 = null; int i = 0; // // Constructor: Create SortedList using this as IComparer and default settings. // sl2 = new SortedList(this); // Verify that the SortedList is not null. Assert.NotNull(sl2); // Verify that the SortedList is empty. Assert.Equal(0, sl2.Count); Assert.Null(s3); // Testcase: add few key-val pairs // start adding elements for (i = 0; i < 32; i++) { sblMsg.Length = 0; sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); sblMsg.Length = 0; sblMsg.Append("val_"); sblMsg.Append(i); s2 = sblMsg.ToString(); sl2.Add(s1, s2); } // // add one more elemnt now the capacity should be doubled // sl2.Add("key_32", "val_32"); Assert.Equal(33, sl2.Count); // // Testcase: now Remove few elements and TrimToSize // for (i = 0; i < 10; i++) { sl2.Remove("key_" + i.ToString()); // remove the current object } // Testcase: validate the Count and capacity Assert.Equal(23, sl2.Count); // now TrimToSize sl2.TrimToSize(); // clear the list sl2.Clear(); // now TrimToSize sl2.TrimToSize(); }
public void ClearEvaluatedPipelines() { _sortedSampledElements.Clear(); BatchCandidates = new PipelinePattern[0]; }
private List<Obstacle> ProcessUntrackedClusters(SceneEstimatorUntrackedClusterCollection clusters, List<Obstacle> trackedObstacles, Rect vehicleBox) { List<Obstacle> obstacles = new List<Obstacle>(); SortedList<Obstacle, List<Coordinates>> point_splits = new SortedList<Obstacle, List<Coordinates>>(); List<Coordinates> unclaimed_points = new List<Coordinates>(1500); foreach (SceneEstimatorUntrackedCluster cluster in clusters.clusters) { // clear out stored variables point_splits.Clear(); unclaimed_points.Clear(); // now determine if the point belongs to an old obstacle ObstacleClass targetClass; if (cluster.clusterClass == SceneEstimatorClusterClass.SCENE_EST_HighObstacle) targetClass = ObstacleClass.StaticLarge; else targetClass = ObstacleClass.StaticSmall; // only add points that are not within a tracked obstacle's extruded polygon for (int i = 0; i < cluster.points.Length; i++) { Coordinates pt = cluster.points[i]; // iterate over all tracked cluster bool did_hit = false; if (useOccupancyGrid && Services.OccupancyGrid.GetOccupancy(pt) == OccupancyStatus.Free) { occupancyDeletedCount++; did_hit = true; } else if (vehicleBox.IsInside(pt)) { did_hit = true; } else if (trackedObstacles != null) { foreach (Obstacle trackedObs in trackedObstacles) { if (trackedObs.extrudedPolygon != null && trackedObs.extrudedPolygon.BoundingCircle.IsInside(pt) && trackedObs.extrudedPolygon.IsInside(pt)) { did_hit = true; break; } } } // if there was a hit, skip this point if (!did_hit) { unclaimed_points.Add(pt); } //if (did_hit) // continue; //Obstacle oldObstacle = FindIntersectingCluster(pt, targetClass, previousObstacles); //if (oldObstacle != null) { // List<Coordinates> obstacle_points; // if (!point_splits.TryGetValue(oldObstacle, out obstacle_points)) { // obstacle_points = new List<Coordinates>(100); // point_splits.Add(oldObstacle, obstacle_points); // } // obstacle_points.Add(pt); //} //else { // unclaimed_points.Add(pt); //} } // we've split up all the points appropriately // now construct the obstacles // we'll start with the obstacle belonging to an existing polygon //foreach (KeyValuePair<Obstacle, List<Coordinates>> split in point_splits) { // if (split.Value != null && split.Value.Count >= 3) { // // the obstacle will inherit most of the properties of the old obstacle // Obstacle obs = new Obstacle(); // obs.age = split.Key.age+1; // obs.obstacleClass = split.Key.obstacleClass; // // don't bother doing a split operation on these clusters -- they have already been split // obs.obstaclePolygon = Polygon.GrahamScan(split.Value); // obstacles.Add(obs); // } //} // handle the unclaimed points IList<Polygon> polygons = WrapAndSplit(unclaimed_points, split_area_threshold, split_length_threshold); foreach (Polygon poly in polygons) { // create a new obstacle Obstacle obs = new Obstacle(); obs.age = 1; obs.obstacleClass = targetClass; obs.obstaclePolygon = poly; obstacles.Add(obs); } } // test all old obstacles and see if they intersect any new obstacles // project the previous static obstacles to the current time frame if (processedObstacles != null) { try { // get the relative transform List<Obstacle> carryOvers = new List<Obstacle>(); Circle mergeCircle = new Circle(merge_expansion_size, Coordinates.Zero); Polygon mergePolygon = mergeCircle.ToPolygon(24); RelativeTransform transform = Services.RelativePose.GetTransform(processedObstacles.timestamp, clusters.timestamp); foreach (Obstacle prevObs in processedObstacles.obstacles) { if (prevObs.obstacleClass == ObstacleClass.StaticLarge || prevObs.obstacleClass == ObstacleClass.StaticSmall) { prevObs.obstaclePolygon = prevObs.obstaclePolygon.Transform(transform); prevObs.age++; if (prevObs.age < 20) { Coordinates centroid = prevObs.obstaclePolygon.GetCentroid(); double dist = GetObstacleDistance(prevObs.obstaclePolygon); double angle = centroid.ArcTan; if (dist < 30 && dist > 6 && Math.Abs(centroid.Y) < 15 && Math.Abs(angle) < Math.PI/2.0) { try { prevObs.mergePolygon = Polygon.ConvexMinkowskiConvolution(mergePolygon, prevObs.obstaclePolygon); if (!TestIntersection(prevObs.mergePolygon, obstacles)) { bool dropObstacle = false; for (int i = 0; i < prevObs.obstaclePolygon.Count; i++) { Coordinates pt = prevObs.obstaclePolygon[i]; // iterate over all tracked cluster if (vehicleBox.IsInside(pt)) { dropObstacle = true; } else if (useOccupancyGrid && externalUseOccupancyGrid && Services.OccupancyGrid.GetOccupancy(pt) == OccupancyStatus.Free) { dropObstacle = true; } else if (trackedObstacles != null) { foreach (Obstacle trackedObs in trackedObstacles) { if (trackedObs.obstacleClass == ObstacleClass.DynamicCarlike) { Polygon testPoly = trackedObs.extrudedPolygon ?? trackedObs.mergePolygon; if (testPoly != null && testPoly.BoundingCircle.IsInside(pt) && testPoly.IsInside(pt)) { dropObstacle = true; break; } } } } if (dropObstacle) { break; } } if (!dropObstacle) { carryOvers.Add(prevObs); } } } catch (Exception) { } } } } } obstacles.AddRange(carryOvers); } catch (Exception) { } } // create the merge polygon for all these duder /*Circle mergeCircle = new Circle(merge_expansion_size, Coordinates.Zero); Polygon mergePolygon = mergeCircle.ToPolygon(24); foreach (Obstacle obs in obstacles) { obs.mergePolygon = Polygon.ConvexMinkowskiConvolution(mergePolygon, obs.obstaclePolygon); }*/ return obstacles; }
/// <summary> /// Clears the tables. /// </summary> public void Clear() { mVarByLabel.Clear(); mVarByValue.Clear(); }
/// <summary> /// Clear all transformations and resets <see cref="TransformDelay"/>. /// </summary> /// <param name="propagateChildren">Whether we also clear down the child tree.</param> public virtual void ClearTransforms(bool propagateChildren = false) { DelayReset(); transforms?.Clear(); }
private void BuildTypeTreeNode(ITypeDeclaration typeDeclaration, TreeNode parentNode) { SortedList <String, TreeNode> list = new SortedList <string, TreeNode>(); // Types foreach (ITypeDeclaration nestedTypeDeclaration in typeDeclaration.Types) { StringBuilder builder = new StringBuilder(); MakeTypeDeclarationName(nestedTypeDeclaration, builder); TreeNode typeNode = new TreeNode(builder.ToString()); typeNode.Tag = nestedTypeDeclaration; if (nestedTypeDeclaration.IsEnum) { typeNode.ImageIndex = EnumImageIndex; typeNode.SelectedImageIndex = EnumImageIndex; } else if (nestedTypeDeclaration.IsInterface) { typeNode.ImageIndex = InterfaceImageIndex; typeNode.SelectedImageIndex = InterfaceImageIndex; } else { typeNode.ImageIndex = ClassImageIndex; typeNode.SelectedImageIndex = ClassImageIndex; } BuildTypeTreeNode(nestedTypeDeclaration, typeNode); list.Add(builder.ToString(), typeNode); } parentNode.Nodes.AddRange(list.Values.ToArray()); list.Clear(); // Methods foreach (IMethodDeclaration methodDeclaration in typeDeclaration.Constructors) { TreeNode methodNode = GenerateMethodNode(methodDeclaration); if (!list.ContainsKey(methodNode.Text)) { list.Add(methodNode.Text, methodNode); } else { list.Add(methodNode.Text + Guid.NewGuid(), methodNode); } } parentNode.Nodes.AddRange(list.Values.ToArray()); list.Clear(); // Methods foreach (IMethodDeclaration methodDeclaration in typeDeclaration.Methods) { TreeNode methodNode = GenerateMethodNode(methodDeclaration); if (!list.ContainsKey(methodNode.Text)) { list.Add(methodNode.Text, methodNode); } else { list.Add(methodNode.Text + Guid.NewGuid(), methodNode); } } parentNode.Nodes.AddRange(list.Values.ToArray()); list.Clear(); // Properties foreach (IPropertyDeclaration propertyDeclaration in typeDeclaration.Properties) { TreeNode propertyNode = new TreeNode(propertyDeclaration.Name); propertyNode.Tag = propertyDeclaration; MethodVisibility propertyVisibility = DetermineVisibility(propertyDeclaration); if (propertyVisibility == MethodVisibility.Assembly) { propertyNode.ImageIndex = ProtectedPropertyImageIndex; propertyNode.SelectedImageIndex = ProtectedPropertyImageIndex; } else if ((propertyVisibility == MethodVisibility.Family) || (propertyVisibility == MethodVisibility.FamilyOrAssembly)) { propertyNode.ImageIndex = InternalPropertyImageIndex; propertyNode.SelectedImageIndex = InternalPropertyImageIndex; } else if (propertyVisibility == MethodVisibility.Private) { propertyNode.ImageIndex = PrivatePropertyImageIndex; propertyNode.SelectedImageIndex = PrivatePropertyImageIndex; } else { propertyNode.ImageIndex = PublicPropertyImageIndex; propertyNode.SelectedImageIndex = PublicPropertyImageIndex; } list.Add(propertyDeclaration.Name, propertyNode); if (propertyDeclaration.GetMethod != null) { propertyNode.Nodes.Add(GenerateMethodNode(propertyDeclaration.GetMethod.Resolve())); } if (propertyDeclaration.SetMethod != null) { propertyNode.Nodes.Add(GenerateMethodNode(propertyDeclaration.SetMethod.Resolve())); } } parentNode.Nodes.AddRange(list.Values.ToArray()); list.Clear(); // Non-Constant fields foreach (IFieldDeclaration fieldDeclaration in typeDeclaration.Fields) { if (!fieldDeclaration.IsConst) { TreeNode fieldNode = new TreeNode(fieldDeclaration.Name); fieldNode.Tag = fieldDeclaration; if (fieldDeclaration.Visibility == FieldVisibility.Public) { fieldNode.ImageIndex = PublicFieldIndex; fieldNode.SelectedImageIndex = PublicFieldIndex; } else if (fieldDeclaration.Visibility == FieldVisibility.Private) { fieldNode.ImageIndex = PrivateFieldIndex; fieldNode.SelectedImageIndex = PrivateFieldIndex; } else if (fieldDeclaration.Visibility == FieldVisibility.Assembly) { fieldNode.ImageIndex = InternalFieldIndex; fieldNode.SelectedImageIndex = InternalFieldIndex; } else { fieldNode.ImageIndex = ProtectedFieldIndex; fieldNode.SelectedImageIndex = ProtectedFieldIndex; } list.Add(fieldDeclaration.Name, fieldNode); } } parentNode.Nodes.AddRange(list.Values.ToArray()); list.Clear(); // Events foreach (IEventDeclaration eventDeclaration in typeDeclaration.Events) { TreeNode eventNode = new TreeNode(eventDeclaration.Name); eventNode.Tag = eventDeclaration; eventNode.Nodes.Add(GenerateMethodNode(eventDeclaration.AddMethod.Resolve())); eventNode.Nodes.Add(GenerateMethodNode(eventDeclaration.RemoveMethod.Resolve())); list.Add(eventDeclaration.Name, eventNode); } parentNode.Nodes.AddRange(list.Values.ToArray()); list.Clear(); // Constant fields foreach (IFieldDeclaration fieldDeclaration in typeDeclaration.Fields) { if (fieldDeclaration.IsConst) { TreeNode fieldNode = new TreeNode(fieldDeclaration.Name); fieldNode.Tag = fieldDeclaration; if (fieldDeclaration.Visibility == FieldVisibility.Public) { fieldNode.ImageIndex = PublicConstIndex; fieldNode.SelectedImageIndex = PublicConstIndex; } else if (fieldDeclaration.Visibility == FieldVisibility.Private) { fieldNode.ImageIndex = PrivateConstIndex; fieldNode.SelectedImageIndex = PrivateConstIndex; } else if (fieldDeclaration.Visibility == FieldVisibility.Assembly) { fieldNode.ImageIndex = InternalConstIndex; fieldNode.SelectedImageIndex = InternalConstIndex; } else { fieldNode.ImageIndex = ProtectedConstIndex; fieldNode.SelectedImageIndex = ProtectedConstIndex; } list.Add(fieldDeclaration.Name, fieldNode); } } parentNode.Nodes.AddRange(list.Values.ToArray()); }
public virtual bool runTest() { Console.Error.WriteLine( "Co4348GetKey runTest() started." ); String strLoc="Loc_000oo"; StringBuilder sblMsg = new StringBuilder( 99 ); int iCountErrors = 0; int iCountTestcases = 0; SortedList sl2 = null; StringBuilder sbl3 = new StringBuilder( 99 ); StringBuilder sbl4 = new StringBuilder( 99 ); StringBuilder sblWork1 = new StringBuilder( 99 ); String s1 = null; String s2 = null; int[] in4a = new int[9]; int i = 0; try { do { strLoc="100cc"; iCountTestcases++; sl2 = new SortedList( this ); iCountTestcases++; if ( sl2 == null ) { Console.WriteLine( strTest+ "E_101" ); Console.WriteLine( strTest+ "SortedList creation failure" ); ++iCountErrors; break; } iCountTestcases++; if ( sl2.Count != 0 ) { Console.WriteLine( strTest+ "E_102" ); Console.WriteLine( strTest+ "New SortedList is not empty" ); ++iCountErrors; } strLoc="Loc_100aa"; ++iCountTestcases; try { sl2.GetKey(0); ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_2764! - must 've thrown ArgExc" ); Console.Error.WriteLine( sblMsg.ToString() ); } catch (ArgumentException ) {} strLoc="Loc_110aa"; ++iCountTestcases; try { sl2["first key"] = (String) null ; } catch (ArgumentException ) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_34fj! - must 've thrown ArgExc" ); Console.Error.WriteLine( sblMsg.ToString() ); } ++iCountTestcases; if (sl2.Count != 1) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_60ff! - Count == " ); sblMsg.Append( sl2.Count ); Console.Error.WriteLine( sblMsg.ToString() ); } strLoc="Loc_120aa"; ++iCountTestcases; sl2.Clear(); strLoc="Loc_141aa"; for (i=0; i<50; i++) { ++iCountTestcases; sblMsg.Length = 0 ; sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); sblMsg.Length = 0 ; sblMsg.Append("val_"); sblMsg.Append(i); s2 = sblMsg.ToString(); sl2.Add (s1, s2); } strLoc="Loc_145aa"; for (i=0; i<50; i++) { ++iCountTestcases; ++iCountTestcases; sblMsg.Length = 0 ; sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); if ( !((String)sl2.GetKey(sl2.IndexOfKey (s1))).Equals(s1)) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_49d! - s3.Equals(s1); " ); sblMsg.Append( " for key == " ); sblMsg.Append( s1 + "; returned Val == " + ((String)sl2.GetKey(sl2.IndexOfKey (s1)))); Console.Error.WriteLine( sblMsg.ToString() ); } } strLoc="Loc_125aa"; ++iCountTestcases; if (sl2.Count != 50) { ++iCountErrors; sblMsg.Length = 0 ; sblMsg.Append( "POINTTOBREAK: Error Err_294y! - Count == " ); sblMsg.Append( sl2.Count ); Console.Error.WriteLine( sblMsg.ToString() ); } } while ( false ); } catch( Exception exc_general ) { ++iCountErrors; Console.Error.WriteLine( "POINTTOBREAK: Error Err_343un! (Co4348GetKey) exc_general==" + exc_general ); Console.Error.WriteLine( "EXTENDEDINFO: (Err_343un) strLoc==" + strLoc ); } if ( iCountErrors == 0 ) { Console.Error.WriteLine( "paSs. SortedList\\Co4348GetKey.cs iCountTestcases==" + iCountTestcases ); return true; } else { Console.Error.WriteLine( "FAiL! SortedList\\Co4348GetKey.cs iCountErrors==" + iCountErrors ); return false; } }
/// <summary> /// Called when the contents of the text buffer change. /// </summary> /// <param name="sender">The object that raised the event.</param> /// <param name="e">A <see cref="TextContentChangedEventArgs"/> that contains the event data.</param> public override void OnBufferChanged(Object sender, TextContentChangedEventArgs e) { // Remove symbols from lines which were touched. foreach (var change in e.Changes) { var oldLineStart = e.Before.GetLineFromPosition(change.OldPosition).LineNumber; var oldLineEnd = e.Before.GetLineFromPosition(change.OldEnd).LineNumber; for (int i = oldLineStart; i <= oldLineEnd; i++) { var line = e.Before.GetLineFromLineNumber(i); var lineText = DiscardSingleLineComments(line.GetText()); RemoveSymbolsOnLine(e.Before, line.Extent.Span, lineText); } } // Translate all of our symbols forward in time. foreach (var symbol in symbols) { symbol.Value.TranslateTo(e.After); symbolsTemp.Add(symbol.Value.Position, symbol.Value); } var temp = symbols; symbols = symbolsTemp; symbolsTemp = temp; symbolsTemp.Clear(); // Add symbols from lines which were touched. foreach (var change in e.Changes) { var newLineStart = e.After.GetLineFromPosition(change.NewPosition).LineNumber; var newLineEnd = e.After.GetLineFromPosition(change.NewEnd).LineNumber; for (int i = newLineStart; i <= newLineEnd; i++) { var line = e.After.GetLineFromLineNumber(i); var lineText = DiscardSingleLineComments(line.GetText()); AddSymbolsOnLine(e.After, line.Extent.Span, lineText); } } UpdateNesting(); }