public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1:Invoke the method CopyTo in the KeyCollection 1"); try { Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("str1", "Test1"); dic.Add("str2", "Test2"); Dictionary<string, string>.KeyCollection keys = new Dictionary<string, string>.KeyCollection(dic); string[] TKeys = new string[SIZE]; keys.CopyTo(TKeys, 0); string strKeys = null; for (int i = 0; i < TKeys.Length; i++) { if (TKeys[i] != null) { strKeys += TKeys[i].ToString(); } } if (TKeys[0].ToString() != "str1" || TKeys[1].ToString() != "str2" || strKeys != "str1str2") { TestLibrary.TestFramework.LogError("001", "the ExpecResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e); retVal = false; } return retVal; }
public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2:Invoke the method CopyTo in the ValueCollection 2"); try { Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("str1", "Test1"); dic.Add("str2", "Test2"); Dictionary<string, string>.ValueCollection values = new Dictionary<string, string>.ValueCollection(dic); string[] TVals = new string[SIZE]; values.CopyTo(TVals, 5); string strVals = null; for (int i = 0; i < TVals.Length; i++) { if (TVals[i] != null) { strVals += TVals[i].ToString(); } } if (TVals[5].ToString() != "Test1" || TVals[6].ToString() != "Test2" || strVals != "Test1Test2") { TestLibrary.TestFramework.LogError("003", "the ExpecResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e); retVal = false; } return retVal; }
public void Dictionary_CopyTo_requires_destination_of_sufficient_size() { IDictionary<int, string> dictionary = new Dictionary<int, string>(); dictionary[1] = "foo"; dictionary[2] = "foo"; dictionary[3] = "foo"; var destination = new KeyValuePair<int, string>[2]; dictionary.CopyTo(destination, 0); }
public void CopyTo_KeyCollectionWithOneElementDictionary_FirstElementEqualsOne() { var dictionary = new Dictionary<int, int>(); dictionary.Add(1, 1); var keyCollection = new Dictionary<int, int>.KeyCollection(dictionary); // int[] keys = new int[1]; keyCollection.CopyTo(keys, 0); Assert.Equal(1, keys[0]); }
public void CopyTo_KeyCollectionWithOneElementDictionary_FirstElementEqualsOne() { var dictionary = new Dictionary<int, int>(); dictionary.Add(1, 1); var valueCollection = new Dictionary<int, int>.ValueCollection(dictionary); // int[] values = new int[1]; valueCollection.CopyTo(values, 0); Assert.Equal(1, values[0]); }
public void copy_multiple_keys_that_all_exist_in_source() { var source = new Dictionary<string, object>(); source.Add("a", 1); source.Add("b", 2); source.Add("c", 3); var destination = new Dictionary<string, object>(); source.CopyTo(destination, "a", "b", "c"); destination["a"].ShouldBe(1); destination["b"].ShouldBe(2); destination["c"].ShouldBe(3); }
public void copy_multiple_keys_with_some_misses() { var source = new Dictionary<string, object>(); source.Add("a", 1); //source.Add("b", 1); source.Add("c", 3); var destination = new Dictionary<string, object>(); source.CopyTo(destination, "a", "b", "c"); destination["a"].ShouldBe(1); destination.ContainsKey("b").ShouldBeFalse(); destination["c"].ShouldBe(3); }
public bool PosTest1() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method ICollection.CopyTo(System.Array,System.Int32) ."); try { ICollection<KeyValuePair<String, String>> dictionary = new Dictionary<String, String>(); KeyValuePair<string, string> kvp1 = new KeyValuePair<String, String>("txt", "notepad.exe"); KeyValuePair<string, string> kvp2 = new KeyValuePair<String, String>("bmp", "paint.exe"); KeyValuePair<string, string> kvp3 = new KeyValuePair<String, String>("dib", "paint.exe"); KeyValuePair<string, string> kvp4 = new KeyValuePair<String, String>("rtf", "wordpad.exe"); dictionary.Add(kvp1); dictionary.Add(kvp2); dictionary.Add(kvp3); dictionary.Add(kvp4); KeyValuePair<string, string>[] kvpArray = new KeyValuePair<string, string>[dictionary.Count]; dictionary.CopyTo(kvpArray, 0); bool actual = (kvpArray[0].Equals(kvp1)) && (kvpArray[1].Equals(kvp2)) && (kvpArray[2].Equals(kvp3)) && (kvpArray[3].Equals(kvp4)); bool expected = true; if (actual != expected) { TestLibrary.TestFramework.LogError("001.1", "Method ICollectionCopyTo Err."); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; }
public void CopyToTest() { var Test = new Dictionary<string, int>(); var Test2 = new Dictionary<string, int>(); Test.Add("Q", 4); Test.Add("Z", 2); Test.Add("C", 3); Test.Add("A", 1); Test.CopyTo(Test2); string Value = ""; int Value2 = 0; foreach (string Key in Test2.Keys.OrderBy(x => x)) { Value += Key; Value2 += Test2[Key]; } Assert.Equal("ACQZ", Value); Assert.Equal(10, Value2); }
/// <summary> /// Copies all items present at the set to the specified array, starting at a specified index. /// </summary> /// <param name="array">one-dimensional array to copy to.</param> /// <param name="index">the zero-based index in array at which copying begins.</param> public void CopyTo(T[] array, int index) { list.CopyTo(array, index); }
/// <summary> /// OK button clicked, process input /// </summary> /// <returns></returns> DialogResult ProcessInput() { int rgCount; // number of Rgroups List <Rgroup> rgList; // list of existing Rgroups bool[] rgExists; // entry = true if rgroup exists in core Rgroup rg; bool oneD, twoD; // matrix dimensionality List <string> keys = null; Dictionary <string, List <QualifiedNumber> > mElem; // matrix element dictionary List <RgroupSubstituent>[] rSubs; // substituents seen for each Rgroup Query q, q0, q2; QueryTable qt, qt2; QueryColumn qc, qc2; MetaTable mt, mt2; MetaColumn mc, mc2; DataTableMx dt; DataRowMx dr; DialogResult dlgRslt; string tok; int ri, rii, si, qti, qci, bi, bi2; // Get core structure & list of R-groups MoleculeMx core = new MoleculeMx(MoleculeFormat.Molfile, SQuery.MolfileString); if (core.AtomCount == 0) { MessageBoxMx.ShowError("A Core structure with R-groups must be defined"); return(DialogResult.None); } if (!Structure.Checked && !Smiles.Checked && !Formula.Checked && !Weight.Checked && !Index.Checked) { MessageBoxMx.ShowError("At least one substituent display format must be selected."); return(DialogResult.None); } mt = MetaTableCollection.GetWithException("Rgroup_Decomposition"); qt = new QueryTable(mt); qc = qt.GetQueryColumnByNameWithException("Core"); qc.MolString = core.GetMolfileString(); // put core structure into table criteria qc.CriteriaDisplay = "Substructure search (SSS)"; qc.Criteria = "CORE SSS SQUERY"; qc = qt.GetQueryColumnByNameWithException("R1_Structure"); if (ShowCoreStructure.Checked) { qc.Label = "R-group, Core\tChime=" + core.GetChimeString(); // reference core in query col header label qc.MetaColumn.Width = 25; } RgroupDecomposition.SetSelected(qt, "R1_Structure", Structure.Checked); // select for retrieval if checked RgroupDecomposition.SetSelected(qt, "R1_Smiles", Smiles.Checked); RgroupDecomposition.SetSelected(qt, "R1_Formula", Formula.Checked); RgroupDecomposition.SetSelected(qt, "R1_Weight", Weight.Checked); RgroupDecomposition.SetSelected(qt, "R1_SubstNo", Index.Checked); string terminateOption = "First mapping"; // terminate on first complete match qc = qt.GetQueryColumnByNameWithException("Terminate_Option"); qc.Criteria = qt.MetaTable.Name + " = " + Lex.AddSingleQuotes(terminateOption); qc.CriteriaDisplay = "= " + Lex.AddSingleQuotes(terminateOption); QueryTable rgdQt = qt; // keep a ref to it if (QbUtil.Query == null || QbUtil.Query.Tables.Count == 0) { MessageBoxMx.ShowError("No current query."); return(DialogResult.None); } q0 = QbUtil.Query; // original query this analysis is based on q = q0.Clone(); // make copy of source query we can modify q.SingleStepExecution = false; qti = 0; while (qti < q.Tables.Count) // deselect query columns that we don't want { qt = q.Tables[qti]; if (Lex.Eq(qt.MetaTable.Name, "Rgroup_Decomposition")) { // remove any rgroup decomp table qti++; continue; } mt = qt.MetaTable; if (mt.MultiPivot || // check for tables not allowed in underlying query mt.MetaBrokerType == MetaBrokerType.CalcField || // (called ShouldPresearchAndTransform previously) mt.MetaBrokerType == MetaBrokerType.MultiTable || mt.MetaBrokerType == MetaBrokerType.RgroupDecomp) { MessageBoxMx.ShowError("Multipivot/Rgroup table \"" + qt.ActiveLabel + "\" can't be included in an underlying Rgroup Matrix query"); return(DialogResult.None); } for (qci = 0; qci < qt.QueryColumns.Count; qci++) { qc = qt.QueryColumns[qci]; if (qc.MetaColumn == null) { continue; } switch (qc.MetaColumn.DataType) { case MetaColumnType.CompoundId: // keep only these case MetaColumnType.Integer: case MetaColumnType.Number: case MetaColumnType.QualifiedNo: case MetaColumnType.String: break; default: qc.Selected = false; break; } } qti++; } q.AddQueryTable(rgdQt); // Add Rgroup decom table to end of cloned source query Progress.Show("Retrieving data..."); try { dlgRslt = ToolHelper.ExecuteQuery(ref q, out keys); if (dlgRslt != DialogResult.OK) { return(dlgRslt); } } catch (Exception ex) { MessageBoxMx.ShowError("Error executing query:\r\n" + ex.Message); return(DialogResult.None); } if (keys == null || keys.Count == 0) { Progress.Hide(); MessageBoxMx.ShowError("No results were returned by the query."); return(DialogResult.None); } // Scan modified query to get list of rgroup indexes that are present rgExists = new bool[32]; rgList = new List <Rgroup>(); QueryTable rgQt = q.GetQueryTableByName("Rgroup_Decomposition"); foreach (QueryColumn qc0 in rgQt.QueryColumns) { mc = qc0.MetaColumn; if (!(mc.Name.StartsWith("R") && mc.Name.EndsWith("_STRUCTURE") && qc0.Selected)) { continue; // skip if not a selected Rgroup structure } int len = mc.Name.Length - ("R" + "_STRUCTURE").Length; tok = mc.Name.Substring(1, len); if (!int.TryParse(tok, out ri)) { continue; } rgExists[ri - 1] = true; rg = new Rgroup(); rg.RIndex = ri; rg.VoPos = qc0.VoPosition; rgList.Add(rg); } for (bi = 1; bi < rgList.Count; bi++) { // sort by increasing R index rg = rgList[bi]; for (bi2 = bi - 1; bi2 >= 0; bi2--) { if (rg.RIndex >= rgList[bi2].RIndex) { break; } rgList[bi2 + 1] = rgList[bi2]; } rgList[bi2 + 1] = rg; } rgCount = rgList.Count; twoD = TwoD.Checked; if (rgCount == 1) { twoD = false; // if only 1 rgroup can't do as 2d } oneD = !twoD; // Read data into mElem and rgroup substituents into rSubs. // Matrix mElem is keyed on [R1Smiles, R2Smiles,... RnSmiles, FieldName] for 1d and // [R1Smiles, R2Smiles,... FieldName, RnSmiles] for 2d QueryManager qm = q.QueryManager as QueryManager; DataTableManager dtm = qm.DataTableManager; dt = qm.DataTable; mElem = new Dictionary <string, List <QualifiedNumber> >(); // matrix element dictionary rSubs = new List <RgroupSubstituent> [32]; // list of substituents seen for each Rgroup for (rii = 0; rii < rgCount; rii++) // alloc substituent list for rgroup { rSubs[rii] = new List <RgroupSubstituent>(); } int rowCount = 0; while (true) { // scan data accumulating rgroup substituents and data values dr = dtm.FetchNextDataRow(); if (dr == null) { break; } rowCount++; string cid = dr[dtm.KeyValueVoPos] as string; string lastMapCid = "", rgroupKey = "", rgroupKeyLast = ""; int mapCount = 0; for (rii = 0; rii < rgCount; rii++) // for { MoleculeMx rSub = dr[rgList[rii].VoPos] as MoleculeMx; if (rSub == null || rSub.AtomCount == 0) { continue; } ri = rgList[rii].RIndex; // actual R index in query int subIdx = RgroupSubstituent.Get(rSub, rSubs[rii]); // if (ri == 1 && subIdx != 0) subIdx = subIdx; // debug if (subIdx < 0) { continue; } string rKey = "R" + ri.ToString() + "_" + (subIdx + 1).ToString(); if (oneD || rii < rgCount - 1) { if (rgroupKey != "") { rgroupKey += "\t"; } rgroupKey += rKey; } else { rgroupKeyLast = rKey; } lastMapCid = cid; mapCount++; } if (lastMapCid == cid) // add the data if compound has a mapping { AccumulateMatrixElements(mElem, q, dr, rgroupKey, rgroupKeyLast, cid); } if (Progress.IsTimeToUpdate) { Progress.Show("Retrieving data: " + StringMx.FormatIntegerWithCommas(rowCount) + " rows..."); } } if (rowCount == 0) { Progress.Hide(); MessageBoxMx.ShowError("No data rows retrieved"); return(DialogResult.None); } if (twoD && (rSubs[rgCount - 1] == null || rSubs[rgCount - 1].Count == 0)) { // if 2D be sure we have at least one substituent for the last Rgroup Progress.Hide(); MessageBoxMx.ShowError("No substituents found for R" + rgCount.ToString()); return(DialogResult.None); } // Create a MetaTable & DataTable for matrix results Progress.Show("Analyzing data..."); mt = new MetaTable(); // create output table MatrixCount++; mt.Name = "RGROUPMATRIX_" + MatrixCount; mt.Label = "R-group Matrix " + MatrixCount; mt.MetaBrokerType = MetaBrokerType.RgroupDecomp; mc = // use sequence for key mt.AddMetaColumn("RgroupMatrixId", "No.", MetaColumnType.Integer, ColumnSelectionEnum.Selected, 3); mc.ClickFunction = "None"; // avoid hyperlink on this key mc.IsKey = true; int maxLeftR = rgCount; if (twoD) { maxLeftR = rgCount - 1; } for (ri = 0; ri < maxLeftR; ri++) { string rStr = "R" + (ri + 1).ToString(); if (Structure.Checked) { mc = mt.AddMetaColumn(rStr + "Str", rStr, MetaColumnType.Structure, ColumnSelectionEnum.Selected, 12); if (ri == 0 && ShowCoreStructure.Checked) // include core structure above R1 if requested { string chimeString = MoleculeMx.MolfileStringToSmilesString(SQuery.MolfileString); mc.Label = "R1, Core\tChime=" + chimeString; mc.Width = 25; } } if (Smiles.Checked) { mc = mt.AddMetaColumn(rStr + "Smi", rStr + " Smiles", MetaColumnType.String, ColumnSelectionEnum.Selected, 12); } if (Formula.Checked) { mc = mt.AddMetaColumn(rStr + "Mf", rStr + " Formula", MetaColumnType.String, ColumnSelectionEnum.Selected, 8); } if (Weight.Checked) { mc = mt.AddMetaColumn(rStr + "MW", rStr + " Mol. Wt.", MetaColumnType.Number, ColumnSelectionEnum.Selected, 6, ColumnFormatEnum.Decimal, 2); } if (Index.Checked) { mc = mt.AddMetaColumn(rStr + "Index", rStr + " Subst. Idx.", MetaColumnType.Number, ColumnSelectionEnum.Selected, 4); mc.Format = ColumnFormatEnum.Decimal; } } mc = // add column to contain result type mt.AddMetaColumn("ResultType", "Result Type", MetaColumnType.String, ColumnSelectionEnum.Selected, 12); if (oneD) // add just 1 column to contain results { mc = mt.AddMetaColumn("Results", "Results", MetaColumnType.QualifiedNo, ColumnSelectionEnum.Selected, 12); mc.MetaBrokerType = MetaBrokerType.RgroupDecomp; // broker to do special col handling for cond formtting if (QbUtil.Query.UserObject.Id > 0) { mc.DetailsAvailable = true; } } else // add col for each substituent for last rgroup { string rStr = "R" + rgCount.ToString(); for (si = 0; si < rSubs[rgCount - 1].Count; si++) { string cName = rStr + "_" + (si + 1).ToString(); string cLabel = cName.Replace("_", "."); RgroupSubstituent rgs = rSubs[ri][si]; // get substituent info if (Structure.Checked) // include structure { cLabel += "\tChime=" + rgs.Struct.GetChimeString(); } else if (Smiles.Checked) { cLabel += " = " + rgs.Struct.GetSmilesString(); } else if (Formula.Checked) { cLabel += " = " + rgs.Struct.MolFormula; } else if (Weight.Checked) { cLabel += " = " + rgs.Struct.MolWeight; } else if (Index.Checked) { cLabel += " = " + (si + 1).ToString(); } mc = mt.AddMetaColumn(cName, cLabel, MetaColumnType.QualifiedNo, ColumnSelectionEnum.Selected, 12); mc.MetaBrokerType = MetaBrokerType.RgroupDecomp; if (QbUtil.Query.UserObject.Id > 0) { mc.DetailsAvailable = true; } } } MetaTableCollection.UpdateGlobally(mt); // add as a known metatable if (mElem.Count == 0) // be sure we have a matrix { Progress.Hide(); MessageBoxMx.ShowError("No matrix can be created because insufficient data was found."); return(DialogResult.None); } // Build the DataTable Progress.Show("Building data table..."); q2 = new Query(); // build single-table query to hold matrix qt2 = new QueryTable(q2, mt); dt = DataTableManager.BuildDataTable(q2); Dictionary <string, List <QualifiedNumber> > .KeyCollection kc = mElem.Keys; string[] rgKeys = new string[mElem.Count]; kc.CopyTo(rgKeys, 0); Array.Sort(rgKeys); string[] rgKey = null, lastRgKey = null; int rki = 0; for (rki = 0; rki < rgKeys.Length; rki++) { rgKey = rgKeys[rki].Split('\t'); int riTop = rgCount + 1; // all r substituents & field name on left if (twoD) { riTop = rgCount; } for (ri = 0; ri < riTop; ri++) // see if any changes in left side substituents or field name { if (lastRgKey == null || rgKey[ri] != lastRgKey[ri]) { break; } } if (ri < riTop || oneD) // if 2d then new row only if some change before last R { dr = dt.NewRow(); dt.Rows.Add(dr); dr[dtm.KeyValueVoPos + 1] = new NumberMx(dt.Rows.Count); // integer row key } if (!HideRepeatingSubstituents.Checked) { ri = 0; // start at first if not hiding } lastRgKey = rgKey; for (ri = ri; ri < riTop; ri++) // build row with these { string rgSub = rgKey[ri]; // get substituent id or table.column name if (rgSub == "") { continue; } if (ri < riTop - 1) { // output substituent and/or smiles string rStr = "R" + (ri + 1).ToString(); si = rgSub.IndexOf("_"); si = Int32.Parse(rgSub.Substring(si + 1)) - 1; // get substituent index RgroupSubstituent rgs = rSubs[ri][si]; // get substituent info if (Structure.Checked) { qc2 = qt2.GetQueryColumnByName(rStr + "Str"); dr[QcToDcName(qc2)] = rgs.Struct; } if (Smiles.Checked) { qc2 = qt2.GetQueryColumnByName(rStr + "Smi"); dr[QcToDcName(qc2)] = new StringMx(rgs.Struct.GetSmilesString()); } if (Formula.Checked) { qc2 = qt2.GetQueryColumnByName(rStr + "Mf"); dr[QcToDcName(qc2)] = new StringMx(rgs.Struct.MolFormula); } if (Weight.Checked) { qc2 = qt2.GetQueryColumnByName(rStr + "Mw"); dr[QcToDcName(qc2)] = new NumberMx(rgs.Struct.MolWeight); } if (Index.Checked) { qc2 = qt2.GetQueryColumnByName(rStr + "Index"); dr[QcToDcName(qc2)] = new NumberMx(si + 1); } } else // output field name { string[] sa = rgSub.Split('.'); // get field name qt = q.GetQueryTableByName(sa[0]); qc = qt.GetQueryColumnByName(sa[1]); string fieldName = qc.ActiveLabel; if (q0.Tables.Count >= 3) // qualify by table if 3 or more tables in original query { fieldName = qt.ActiveLabel + " - " + fieldName; } qc2 = qt2.GetQueryColumnByName("ResultType"); dr[QcToDcName(qc2)] = new StringMx(fieldName); } } // Output value string cName; if (oneD) { cName = "Results"; } else { cName = rgKey[rgCount]; // get key for this substituent (e.g. R2_1) } if (Lex.IsUndefined(cName)) { continue; // may be no substituent match } qc2 = qt2.GetQueryColumnByName(cName); QualifiedNumber qn = SummarizeData(mElem[rgKeys[rki]]); // get summarized value dr[QcToDcName(qc2)] = qn; } ToolHelper.DisplayData(q2, dt, true); UsageDao.LogEvent("RgroupMatrix"); Progress.Hide(); return(DialogResult.OK); }
/// <summary> /// 游戏 /// </summary> /// <param name="rm"></param> public void Game() { //等待玩家初始化完成 while (true) { int t = 0; for (int i = 0; i < maxPlayer; i++) { if (isReady[i]) { t++; } } if (t == maxPlayer) { //开始游戏 for (int i = 0; i < maxPlayer; i++) { Players[i].client.Send("BG"); } break; } } while (!isFinish) { //更新玩家数据 for (int i = 0; i < Players.Length; i++) { Players[i].Update(deltaTime); } //更新单位状态 if (UpdateBehavious != null) { UpdateBehavious(Time, deltaTime); } //发送玩家事件 int c = 0; string data_1 = "BM"; for (int i = 0; i < Players.Length; i++) { if (Players[i].msgQueue.Count > 0) { data_1 += Players[i].getMsg(); c++; } } if (c > 0) { BroadcastMsg(data_1); } //处理待发事件队列 if (sendEventQueue.Count > 0) { string t_msg = "GE"; while (sendEventQueue.Count > 0) { Event_waitSend t = sendEventQueue.Dequeue(); t_msg += t.ToString(); AddEvent(t); } BroadcastMsg(t_msg); } //处理待回答事件列表 long currentTimeStamp = ServerFunction.getTimeStamp_milSeconds(); if (answerEventList.Count > 0) { Dictionary <int, Event_waitAnswer> .KeyCollection keysCollect = null; keysCollect = answerEventList.Keys; int[] keys = new int[keysCollect.Count]; keysCollect.CopyTo(keys, 0); for (int i = 0; i < keys.Length; i++) { Event_waitAnswer t = answerEventList[keys[i]]; //超时 if (currentTimeStamp > t.endTime) { //如果超过一半玩家应答则予以回应 if (t.getAnswerNum() > maxPlayer * 0.5f) { int t_answer = t.Answer(); string t_data = string.Format("EA {0}:{1}", t.data.selfIndex, t_answer); t.data.client.Send(t_data); } Console.WriteLine("Timeout"); answerEventList.Remove(keys[i]); } } } //获取玩家信息包 string data = "PD "; for (int i = 0; i < Players.Length; i++) { data += (getPlayerData(i)); if (i != Players.Length - 1) { data += "#"; } } //发送玩家信息包 int j = 0; for (int i = 0; i < Players.Length; i++) { if (Players[i].client.isLink) { Players[i].client.Send(data); } else { j++; } } //检测是否所有玩家都已掉线 if (j == maxPlayer) { Console.WriteLine(name + "_房间结束游戏"); isFinish = true; break; } //更新时间参数 deltaTime = (currentTimeStamp - lastTime) / 1000.0f; lastTime = currentTimeStamp; Time += deltaTime; //检测是否结束游戏 int t3 = 0; for (int i = 0; i < Players.Length; i++) { if (Players[i].isEnd) { t3++; } } if (t3 == Players.Length) { //结束游戏 Console.WriteLine(name + "_房间结束游戏"); string data_EG = getEndGameData(); BroadcastMsg(data_EG); break; } Thread.Sleep(50); } while (true) { //检测是否所有玩家都已退出 int j = 0; for (int i = 0; i < Players.Length; i++) { if (!Players[i].client.isLink && !Players[i].isLeftGameRoom) { Players[i].isLeftGameRoom = true; } if (Players[i].isLeftGameRoom) { j++; } } if (j == maxPlayer) { isFinish = true; break; } Thread.Sleep(1000); } }
public bool NegTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest4:The number of elements in the source Dictionary.ValueCollection is greater than the available space from index to the end of the destination array"); try { Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("str1", "Test1"); dic.Add("str1", "Test1"); Dictionary<string, string>.ValueCollection values = new Dictionary<string, string>.ValueCollection(dic); string[] TVals = new string[SIZE]; int index = SIZE - 1; values.CopyTo(TVals, index); TestLibrary.TestFramework.LogError("N007", "The ExpectResult should throw exception but the ActualResult not throw exception"); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N008", "Unexpect exception:" + e); retVal = false; } return retVal; }
public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2:The argument index is less than zero"); try { Dictionary<string, string> dic = new Dictionary<string, string>(); Dictionary<string, string>.ValueCollection values = new Dictionary<string, string>.ValueCollection(dic); string[] TVals = new string[SIZE]; int index = -1; values.CopyTo(TVals, index); TestLibrary.TestFramework.LogError("N003", "The argument index is less than zero but not throw exception"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N004", "Unexpect exception:" + e); retVal = false; } return retVal; }
public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3:Invoke the method CopyTo in the ValueCollection 3"); try { Dictionary<string, string> dic = new Dictionary<string, string>(); Dictionary<string, string>.ValueCollection values = new Dictionary<string, string>.ValueCollection(dic); string[] TVals = new string[SIZE]; values.CopyTo(TVals, 0); for (int i = 0; i < TVals.Length; i++) { if (TVals[i] != null) { TestLibrary.TestFramework.LogError("005", "the ExpecResult is not the ActualResult"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e); retVal = false; } return retVal; }
void ICollection <KeyValuePair <string, ParamValue> > .CopyTo(KeyValuePair <string, ParamValue>[] array, int arrayIndex) { Dictionary.CopyTo(array, arrayIndex); }
// Emit the CrstTypes.h output file. void WriteHeaderFile(string fileName) { FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None); StreamWriter writer = new StreamWriter(stream); // Create a collection based on all the Crst types we've stored in the hash. We do this so we can sort // the Crst types we emit (lexically, based on type name). Dictionary <string, CrstType> .ValueCollection crstCollection = m_crsts.Values; CrstType[] crsts = new CrstType[crstCollection.Count]; crstCollection.CopyTo(crsts, 0); Array.Sort(crsts); // Emit the header. Contains copyright information, the usual goop to avoid multiple inclusion and a // header comment to discourage direct editing and point the user at the CrstTypes.def file instead // (where all will be explained in greater detail). writer.WriteLine("//"); writer.WriteLine("// Licensed to the .NET Foundation under one or more agreements."); writer.WriteLine("// The .NET Foundation licenses this file to you under the MIT license."); writer.WriteLine("// See the LICENSE file in the project root for more information."); writer.WriteLine("//"); writer.WriteLine(); writer.WriteLine("#ifndef __CRST_TYPES_INCLUDED"); writer.WriteLine("#define __CRST_TYPES_INCLUDED"); writer.WriteLine(); writer.WriteLine("// **** THIS IS AN AUTOMATICALLY GENERATED HEADER FILE -- DO NOT EDIT!!! ****"); writer.WriteLine(); writer.WriteLine("// This file describes the range of Crst types available and their mapping to a numeric level (used by the"); writer.WriteLine("// runtime in debug mode to validate we're deadlock free). To modify these settings edit the"); writer.WriteLine("// file:CrstTypes.def file and run the clr\\bin\\CrstTypeTool utility to generate a new version of this file."); writer.WriteLine(); // Emit the CrstType enum to define a value for each crst type (along with the kNumberOfCrstTypes // constant). writer.WriteLine("// Each Crst type is declared as a value in the following CrstType enum."); writer.WriteLine("enum CrstType"); writer.WriteLine("{"); for (int i = 0; i < crsts.Length; i++) { writer.WriteLine(" Crst" + crsts[i].Name + " = " + i.ToString() + ","); } writer.WriteLine(" kNumberOfCrstTypes = " + crsts.Length.ToString()); writer.WriteLine("};"); writer.WriteLine(); // This is the end of the regular part of the header included by most files. writer.WriteLine("#endif // __CRST_TYPES_INCLUDED"); writer.WriteLine(); // There is a second section of the header intended for inclusion only by vm\Crst.cpp. This contains // some data tables used to map crst type to rank or name. We could instead define two separate // headers, but on the whole it seems simpler to do it this way. writer.WriteLine("// Define some debug data in one module only -- vm\\crst.cpp."); writer.WriteLine("#if defined(__IN_CRST_CPP) && defined(_DEBUG)"); writer.WriteLine(); // Emit the crst type to rank mapping table. writer.WriteLine("// An array mapping CrstType to level."); writer.WriteLine("int g_rgCrstLevelMap[] ="); writer.WriteLine("{"); foreach (CrstType crst in crsts) { writer.WriteLine(" " + crst.Level + ",\t\t\t// Crst" + crst.Name); } writer.WriteLine("};"); writer.WriteLine(); // Emit the crst type to name mapping table. writer.WriteLine("// An array mapping CrstType to a stringized name."); writer.WriteLine("LPCSTR g_rgCrstNameMap[] ="); writer.WriteLine("{"); foreach (CrstType crst in crsts) { writer.WriteLine(" \"Crst" + crst.Name + "\","); } writer.WriteLine("};"); writer.WriteLine(); // Emit the constant Crst.cpp uses to record an unordered rank. writer.WriteLine("// Define a special level constant for unordered locks."); writer.WriteLine("#define CRSTUNORDERED (-1)"); writer.WriteLine(); // Emit a couple of inline helpers to map type to rank or name (and validate the type while they're at // it). writer.WriteLine("// Define inline helpers to map Crst types to names and levels."); writer.WriteLine("inline static int GetCrstLevel(CrstType crstType)"); writer.WriteLine("{"); writer.WriteLine(" LIMITED_METHOD_CONTRACT;"); writer.WriteLine(" _ASSERTE(crstType >= 0 && crstType < kNumberOfCrstTypes);"); writer.WriteLine(" return g_rgCrstLevelMap[crstType];"); writer.WriteLine("}"); writer.WriteLine("inline static LPCSTR GetCrstName(CrstType crstType)"); writer.WriteLine("{"); writer.WriteLine(" LIMITED_METHOD_CONTRACT;"); writer.WriteLine(" _ASSERTE(crstType >= 0 && crstType < kNumberOfCrstTypes);"); writer.WriteLine(" return g_rgCrstNameMap[crstType];"); writer.WriteLine("}"); writer.WriteLine(); // And that's the end of the second section of the header file. writer.WriteLine("#endif // defined(__IN_CRST_CPP) && defined(_DEBUG)"); writer.Close(); stream.Close(); }
public void CopyTo(KeyValuePair <string, object>[] array, int arrayIndex) { IDictionary <string, object> intermediate = new Dictionary <string, object>(_underlying.ExtensionData.ToDictionary(i => i.Key, i => (object)i.Value)); intermediate.CopyTo(array, arrayIndex); }
/// <inheritdoc /> protected async override Task <ExchangeOrderResult> OnPlaceOrderAsync(ExchangeOrderRequest order) { //{ // "market": "XRP-PERP", // "side": "sell", // "price": 0.306525, // "type": "limit", // "size": 31431.0, // "reduceOnly": false, // "ioc": false, // "postOnly": false, // "clientId": null //} IEnumerable <ExchangeMarket> markets = await OnGetMarketSymbolsMetadataAsync(); ExchangeMarket market = markets.Where(m => m.MarketSymbol == order.MarketSymbol).First(); var payload = await GetNoncePayloadAsync(); var parameters = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase) { { "market", market.MarketSymbol }, { "side", order.IsBuy ? "buy" : "sell" }, { "type", order.OrderType.ToStringLowerInvariant() }, { "size", order.RoundAmount() } }; if (!string.IsNullOrEmpty(order.ClientOrderId)) { parameters.Add("clientId", order.ClientOrderId); } if (order.IsPostOnly != null) { parameters.Add("postOnly", order.IsPostOnly); } if (order.OrderType != OrderType.Market) { int precision = BitConverter.GetBytes(decimal.GetBits((decimal)market.PriceStepSize)[3])[2]; if (order.Price == null) { throw new ArgumentNullException(nameof(order.Price)); } parameters.Add("price", Math.Round(order.Price.Value, precision)); } else { parameters.Add("price", null); } parameters.CopyTo(payload); order.ExtraParameters.CopyTo(payload); var response = await MakeJsonRequestAsync <JToken>("/orders", null, payload, "POST"); ExchangeOrderResult result = new ExchangeOrderResult { OrderId = response["id"].ToStringInvariant(), ClientOrderId = response["clientId"].ToStringInvariant(), OrderDate = CryptoUtility.ToDateTimeInvariant(response["createdAt"]), Price = CryptoUtility.ConvertInvariant <decimal>(response["price"]), AmountFilled = CryptoUtility.ConvertInvariant <decimal>(response["filledSize"]), AveragePrice = CryptoUtility.ConvertInvariant <decimal>(response["avgFillPrice"]), Amount = CryptoUtility.ConvertInvariant <decimal>(response["size"]), MarketSymbol = response["market"].ToStringInvariant(), IsBuy = response["side"].ToStringInvariant() == "buy" }; return(result); }
public static string[] ToArray <T>(this Dictionary <string, T> .KeyCollection collection) { string[] keys = new string[collection.Count]; collection.CopyTo(keys, 0); return(keys); }
void Start() { Dictionary <int, string> myDic = new Dictionary <int, string>(); //添加鍵值 myDic.Add(0, "Night"); myDic.Add(1, "NF"); myDic.Add(3, "Feather"); myDic.Add(5, "LF"); myDic.Add(7, "NightFeather"); myDic.Add(13, "Light"); myDic.Add(30, "LightFeather"); //移除鍵值 myDic.Remove(5); //清空字典 //myDic.Clear(); //取得字典中的個數 int count = myDic.Count; Debug.Log(count); //檢查字典中 是否包含指定Key bool b = myDic.ContainsKey(2); Debug.Log(b); //檢查字典中 是否包含指定Value bool c = myDic.ContainsValue("TA"); Debug.Log(c); //嘗試取指定的Key 所對應的Values string str; myDic.TryGetValue(5, out str); Debug.Log(str); //特別的方式 示範轉為一維數組 Dictionary <int, string> .KeyCollection keyCollection = myDic.Keys; Dictionary <int, string> .ValueCollection valueCollection = myDic.Values; //數組大小先決定好 CopyTo 目標 與 原本的第幾個開始復製 keyCollection.CopyTo(arrayInt, 0); Debug.Log(arrayInt.Length); foreach (var item in keyCollection) { Debug.Log(item); } valueCollection.CopyTo(arrayStr, 0); Debug.Log(arrayStr.Length); foreach (var item in valueCollection) { Debug.Log(item); } for (int i = 0; i < arrayStr.Length; i++) { Debug.Log(arrayStr[i]); } }
public static void exec(Dictionary <long, object> .ValueCollection items, System.Type InKeyType, System.Type InValueType) { object[] array = new object[items.Count]; items.CopyTo(array, 0); exec(array, InKeyType, InValueType); }
void ICollection <KeyValuePair <TKey, TItem> > .CopyTo(KeyValuePair <TKey, TItem>[] array, int arrayIndex) => Dictionary.CopyTo(array, arrayIndex);
public void DictionaryAsIDictionaryWorks() { IDictionary <int, string> d = new Dictionary <int, string> { { 1, "a" }, { 2, "b" } }; // IDictionary<TKey, TValue> Assert.AreEqual("a", d[1], "Getter[1]"); Assert.Throws <KeyNotFoundException>(() => { var r = d[3]; }, "Getter[3] should fail"); d[1] = "aa"; Assert.AreEqual("aa", d[1], "Getter[1] after setter"); d[3] = "cc"; Assert.AreEqual("cc", d[3], "Getter[3] after setter"); Assert.True(d.Remove(3), "Remove(3)"); Assert.AreEqual(2, d.Count, "Count after Remove(3)"); Assert.AreEqual("aa", d[1], "Getter[1] after Remove(3)"); Assert.AreEqual("b", d[2], "Getter[2] after Remove(3)"); Assert.False(d.Remove(4), "Remove(4)"); Assert.AreEqual(2, d.Count, "Count after Remove(4)"); Assert.AreEqual("aa", d[1], "Getter[1] after Remove(4)"); Assert.AreEqual("b", d[2], "Getter[2] after Remove(4)"); Assert.True(d.Remove(1), "Remove(1)"); Assert.AreEqual(1, d.Count, "Count after Remove(1)"); Assert.AreEqual("b", d[2], "Getter[2] after Remove(1)"); Assert.True(d.Remove(2), "Remove(2)"); Assert.AreEqual(0, d.Count, "Count after Remove(2)"); d.Add(2, "b"); Assert.AreEqual(1, d.Count, "Count after Add(2)"); Assert.AreEqual("b", d[2], "Getter[1] after Add(2)"); d.Add(1, "a"); Assert.AreEqual(2, d.Count, "Count after Add(1)"); Assert.AreEqual("a", d[1], "Getter[1] after Add(1)"); Assert.Throws <ArgumentException>(() => { d.Add(2, "c"); }, "Add(2) should fail"); var keys = d.Keys; Assert.True((object)keys is ICollection <int>, "Keys is ICollection<int>"); Assert.True((object)keys is IEnumerable <int>, "Keys is IEnumerable<int>"); Assert.True((object)keys is IEnumerable, "Keys is IEnumerable"); int count = 0; foreach (var key in d.Keys) { Assert.True(key == 1 || key == 2, "Expected key " + key); count++; } Assert.AreEqual(2, count, "Keys count"); var values = d.Values; Assert.True((object)values is ICollection <string>, "Values is ICollection<string>"); Assert.True((object)values is IEnumerable <string>, "Values is IEnumerable<string>"); Assert.True((object)values is IEnumerable, "Values is IEnumerable"); count = 0; foreach (var value in d.Values) { Assert.True(value == "a" || value == "b", "Expected value " + value); count++; } Assert.AreEqual(2, count, "Values count"); Assert.True(d.ContainsKey(1), "ContainsKey(1)"); Assert.False(d.ContainsKey(3), "ContainsKey(3)"); string v; Assert.True(d.TryGetValue(2, out v), "TryGetValue(2)"); Assert.AreEqual("b", v, "TryGetValue(2) value"); Assert.False(d.TryGetValue(0, out v), "TryGetValue(0)"); Assert.AreEqual(null, v, "TryGetValue(0) value"); // IEnumerable<KeyValuePair<TKey, TValue>> var en = d.GetEnumerator(); // #2541 var el = en.Current; Assert.AreEqual(0, el.Key, "Enumerable initial key"); Assert.AreEqual(null, el.Value, "Enumerable initial value"); Assert.True(en.MoveNext(), "Enumerable MoveNext true"); #if false el = en.Current; Assert.AreEqual(2, el.Key, "Enumerable first key"); Assert.AreEqual("b", el.Value, "Enumerable first value"); Assert.True(en.MoveNext(), "Enumerable MoveNext true"); el = en.Current; Assert.AreEqual(1, el.Key, "Enumerable second key"); Assert.AreEqual("a", el.Value, "Enumerable second value"); Assert.False(en.MoveNext(), "Enumerable MoveNext false"); #endif // ICollection<T> Assert.AreEqual(2, d.Count, "Count"); Assert.False(d.IsReadOnly, "IsReadOnly"); d.Add(new KeyValuePair <int, string>(3, "c")); Assert.AreEqual(3, d.Count, "ICollection<KeyValuePair> Count after Add(3)"); Assert.AreEqual("c", d[3], "ICollection<KeyValuePair> Getter[3] after Add(3)"); Assert.Throws <ArgumentException>(() => { d.Add(new KeyValuePair <int, string>(1, "d")); }, "ICollection<KeyValuePair> Add(1) should fail"); Assert.True(d.Remove(new KeyValuePair <int, string>(3, "c")), "ICollection<KeyValuePair> Remove(3)"); Assert.AreEqual(2, d.Count, "ICollection<KeyValuePair> Count after Remove(3)"); Assert.AreEqual("a", d[1], "ICollection<KeyValuePair> Getter[1] after Remove(3)"); Assert.AreEqual("b", d[2], "ICollection<KeyValuePair> Getter[2] after Remove(3)"); var cta = new KeyValuePair <int, string> [3]; d.CopyTo(cta, 0); #if false Assert.AreEqual(2, cta[0].Key, "ICollection<KeyValuePair> CopyTo Getter[0] Key"); Assert.AreEqual("b", cta[0].Value, "ICollection<KeyValuePair> CopyTo Getter[0] Value"); Assert.AreEqual(1, cta[1].Key, "ICollection<KeyValuePair> CopyTo Getter[1] Key"); Assert.AreEqual("a", cta[1].Value, "ICollection<KeyValuePair> CopyTo Getter[1] Value"); Assert.AreEqual(0, cta[2].Key, "ICollection<KeyValuePair> CopyTo Getter[2] Key"); Assert.AreEqual(null, cta[2].Value, "ICollection<KeyValuePair> CopyTo Getter[2] Value"); #endif Assert.True(d.Contains(new KeyValuePair <int, string>(1, "a")), "ICollection<KeyValuePair> Contains(1, \"a\")"); Assert.True(d.Contains(new KeyValuePair <int, string>(2, "b")), "ICollection<KeyValuePair> Contains(2, \"b\")"); Assert.False(d.Contains(new KeyValuePair <int, string>(1, "b")), "ICollection<KeyValuePair> Contains(1, \"b\")"); Assert.False(d.Contains(new KeyValuePair <int, string>(3, "a")), "ICollection<KeyValuePair> Contains(3, \"a\")"); Assert.False(d.Contains(new KeyValuePair <int, string>(0, "a")), "ICollection<KeyValuePair> Contains(0, \"a\")"); d.Clear(); Assert.AreEqual(0, d.Count, "ICollection<KeyValuePair> Count after Clear"); Assert.Throws <KeyNotFoundException>(() => { var a = d[1]; }, "ICollection<KeyValuePair> Getter[1] should fail after clear"); }
public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentNullException is not thrown when array is null ref."); try { ICollection<KeyValuePair<String, String>> dictionary = new Dictionary<String, String>(); KeyValuePair<string, string> kvp1 = new KeyValuePair<String, String>("txt", "notepad.exe"); KeyValuePair<string, string> kvp2 = new KeyValuePair<String, String>("bmp", "paint.exe"); KeyValuePair<string, string> kvp3 = new KeyValuePair<String, String>("dib", "paint.exe"); KeyValuePair<string, string> kvp4 = new KeyValuePair<String, String>("rtf", "wordpad.exe"); dictionary.Add(kvp1); dictionary.Add(kvp2); dictionary.Add(kvp3); dictionary.Add(kvp4); KeyValuePair<string, string>[] kvpArray = null; dictionary.CopyTo(kvpArray, 0); TestLibrary.TestFramework.LogError("101.1", "ArgumentNullException is not thrown."); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; }
void ICollection.CopyTo(Array array, int index) { Dictionary.CopyTo((KeyValuePair <TKey, TValue>[])array, index); }
public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1:The argument array is null"); try { Dictionary<string, string> dic = new Dictionary<string, string>(); Dictionary<string, string>.ValueCollection values = new Dictionary<string, string>.ValueCollection(dic); string[] TVals = null; values.CopyTo(TVals, 0); TestLibrary.TestFramework.LogError("N001", "The argument array is null but not throw exception"); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N002", "Unexpect exception:" + e); retVal = false; } return retVal; }
public DictionaryEnumerator(Dictionary <ulong, T> .ValueCollection values) { data = new T[values.Count]; values.CopyTo(data, 0); }
public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3:The argument index is larger than array length"); try { Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("str1", "Test1"); Dictionary<string, string>.ValueCollection values = new Dictionary<string, string>.ValueCollection(dic); string[] TVals = new string[SIZE]; int index = SIZE + 1; values.CopyTo(TVals, index); TestLibrary.TestFramework.LogError("N005", "The argument index is larger than array length but not throw exception"); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N006", "Unexpect exception:" + e); retVal = false; } return retVal; }
public void CopyTo(KeyValuePair <TKey, TValue>[] array, int arrayIndex) { Dictionary.CopyTo(array, arrayIndex); }
public void CopyTo(T[] array, int arrayIndex) { keys.CopyTo(array, arrayIndex); }
public void CopyToException() { var array = new System.Collections.Generic.KeyValuePair <int, string> [5]; dictionary.CopyTo(array, 4); }