private static void DeriveKeyAndIV(string passphrase, byte[] salt, out byte[] key, out byte[] iv) { // generate key and iv List<byte> concatenatedHashes = new List<byte>(48); byte[] password = Encoding.UTF8.GetBytes(passphrase); byte[] currentHash = new byte[0]; MD5 md5 = MD5.Create(); bool enoughBytesForKey = false; // See http://www.openssl.org/docs/crypto/EVP_BytesToKey.html#KEY_DERIVATION_ALGORITHM while (!enoughBytesForKey) { int preHashLength = currentHash.Length + password.Length + salt.Length; byte[] preHash = new byte[preHashLength]; Buffer.BlockCopy(currentHash, 0, preHash, 0, currentHash.Length); Buffer.BlockCopy(password, 0, preHash, currentHash.Length, password.Length); Buffer.BlockCopy(salt, 0, preHash, currentHash.Length + password.Length, salt.Length); currentHash = md5.ComputeHash(preHash); concatenatedHashes.AddRange(currentHash); if (concatenatedHashes.Count >= 48) enoughBytesForKey = true; } key = new byte[32]; iv = new byte[16]; concatenatedHashes.CopyTo(0, key, 0, 32); concatenatedHashes.CopyTo(32, iv, 0, 16); md5.Clear(); md5 = null; }
public static List<List<bool>> CalculateCombinations(List<bool> currentForm, int numberOfFeautres) { List<List<bool>> theList = new List<List<bool>>(); bool[] form1 = new bool[currentForm.Count + 1]; currentForm.CopyTo(form1); form1[currentForm.Count] = true; bool[] form2 = new bool[currentForm.Count + 1]; currentForm.CopyTo(form2); form2[currentForm.Count] = false; if (form1.Length == numberOfFeautres) { theList.Add(form1.ToList()); if (form2.ToArray().Count(x => x == false) != numberOfFeautres) { theList.Add(form2.ToList()); } return theList; } List<List<bool>> otemp = CalculateCombinations(form1.ToList(), numberOfFeautres); theList.AddRange(otemp.GetRange(0, otemp.Count)); List<List<bool>> ztemp = CalculateCombinations(form2.ToList(), numberOfFeautres); theList.AddRange(ztemp.GetRange(0, ztemp.Count)); return theList; }
static void Main(string[] args) { List<string> words = new List<string>(); // New string-typed list words.Add("melon"); words.Add("avocado"); words.AddRange(new[] { "banana", "plum" }); words.Insert(0, "lemon"); // Insert at start words.InsertRange(0, new[] { "peach", "nashi" }); // Insert at start words.Remove("melon"); words.RemoveAt(3); // Remove the 4th element words.RemoveRange(0, 2); // Remove first 2 elements words.RemoveAll(s => s.StartsWith("n"));// Remove all strings starting in 'n' Console.WriteLine(words[0]); // first word Console.WriteLine(words[words.Count - 1]); // last word foreach (string s in words) Console.WriteLine(s); // all words List<string> subset = words.GetRange(1, 2); // 2nd->3rd words string[] wordsArray = words.ToArray(); // Creates a new typed array string[] existing = new string[1000];// Copy first two elements to the end of an existing array words.CopyTo(0, existing, 998, 2); List<string> upperCastWords = words.ConvertAll(s => s.ToUpper()); List<int> lengths = words.ConvertAll(s => s.Length); ArrayList al = new ArrayList(); al.Add("hello"); string first = (string)al[0]; string[] strArr = (string[])al.ToArray(typeof(string)); List<string> list = al.Cast<string>().ToList(); }
public void Start(){ //Double check you're the server if (!isServer) return; //Set up and shuffle deck lists persons_deck_list = new List<int> (); features_deck_list = new List<int> (); for (int i = 0; i<25; i++) { int randomIndex = Random.Range (0, persons_deck_list.Count); persons_deck_list.Insert(randomIndex, i); randomIndex = Random.Range (0, features_deck_list.Count); persons_deck_list.Insert(randomIndex, i); } //make hands for(int i = 0; i < 4; i++) { persons_hands_array[i] = new int[6]; persons_deck_list.CopyTo(i*6, persons_hands_array[i], i*6, 6); features_hands_array[i] = new int[6]; features_deck_list.CopyTo(i * 6, persons_hands_array[i], i * 6, 6); } //give hands //for(CardGamePlayerObject player : cgm.p) }
private void dfs(List<int> tmp, int tmpSum, int target, int startIdx) { if (tmpSum == target) { int[] res = new int[tmp.Count]; tmp.CopyTo(res); result.Add(res); return; //剪枝,因为升序排列,后面的数字一定的大于当前值 } else if (tmpSum > target) { return; //剪枝,因为升序排列,后面的数字一定的大于当前值 } else { for (int i = startIdx; i < arr.Length; i++) { if (i > startIdx && arr[i] == arr[i - 1]) continue; //去除重复数字,重复数字可导致重复结果 tmp.Add(arr[i]); this.dfs(tmp, tmpSum + arr[i], target, i + 1); //不可重复,i+1 tmp.RemoveAt(tmp.Count - 1); } } }
static void Main() { string sentence = "C# is not C++, not PHP and not Delphi!"; List<int> commas = new List<int>(); int countEmptySpace = 0; //With this loop we count at which consecutive empty space there is comma //If comma is found in the list we add the index of the empty space, otherwise we add 0 for (int i = 0; i < sentence.Length; i++) { if (sentence[i] == ' ') { countEmptySpace++; if (sentence[i - 1] == ',') { commas.Add(countEmptySpace); } else { commas.Add(0); } } } commas.Add(0); int[] comma = new int[commas.Count]; commas.CopyTo(comma); char sentenceEnd = sentence[sentence.Length -1]; //takes the symbol on which the sentence ends ReverseSentence(sentence, sentenceEnd, comma);
public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: The list is type of string and copy the date to the array whose beginning index is zero"); try { string[] strArray = { "Tom", "Jack", "Mike" }; List<string> listObject = new List<string>(strArray); string[] result = new string[3]; listObject.CopyTo(2, result, 0, 1); if (result[0] != "Mike") { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; }
public MailboxTO(gov.va.medora.mdo.domain.sm.Mailbox mailbox) { if (mailbox == null) { return; } IList<FolderTO> allFolders = new List<FolderTO>(); if (mailbox.UserFolders != null && mailbox.UserFolders.Count > 0) { for (int i = 0; i < mailbox.UserFolders.Count; i++) { allFolders.Add(new FolderTO(mailbox.UserFolders[i])); } } if (mailbox.SystemFolders != null && mailbox.SystemFolders.Count > 0) { for (int i = 0; i < mailbox.SystemFolders.Count; i++) { allFolders.Add(new FolderTO(mailbox.SystemFolders[i])); } } if (allFolders.Count > 0) { folders = new FolderTO[allFolders.Count]; allFolders.CopyTo(folders, 0); } }
public DocumentParser(string path) { using (var br = new BinaryReader(File.OpenRead(path))) { if (br.PeekChar() == '@') { List<byte> processed = new List<byte>(); while (br.BaseStream.Position != br.BaseStream.Length) { var s = IWantToFiddle(ReadLine(br, 256)); if (s != null) { processed.AddRange(s); processed.Add(13); processed.Add(10); } } data = new byte[processed.Count]; processed.CopyTo(data); bFiddled = true; } else { data = br.ReadBytes((int)br.BaseStream.Length); } } }
public static List<Vector2> GetSmoothPoint(List<Vector2> targetArray, float precision, bool headtotial = true) { //1.获取采样点 if (precision == 1) { return targetArray; } List<Vectorr2> samplePoint = new List<Vectorr2>(); int samcount = (int)((float)targetArray.Count * precision); int interval = targetArray.Count / samcount; for (int sam = 0; sam < samcount; sam++) { Vector2 get = targetArray[sam * interval]; samplePoint.Add(new Vectorr2(get.x, get.y)); } samplePoint.Add(new Vectorr2(targetArray[targetArray.Count - 1].x, targetArray[targetArray.Count - 1].y)); //2.从采样点开始对用户画的点数据进行重采样 List<Vector2> tempToGl = new List<Vector2>();//准备交给Gl的数据 int glCount = targetArray.Count; float inter = 1.0f / (float)glCount; for (float a = 0; a < 1; ) { Vectorr2[] test1 = new Vectorr2[samcount + 1]; samplePoint.CopyTo(test1); Vectorr2 myV = GetBezierPoint(test1, a); tempToGl.Add(new Vector2(myV.x, myV.y)); a += inter; } //3.将重建的点数据处理并交给Gl if (headtotial) tempToGl[tempToGl.Count - 1] = tempToGl[0]; return tempToGl; //结束平滑代码 }
public static void SetBackConnectionRegKey(List<string> urls) { const string KEY_NAME = "SYSTEM\\CurrentControlSet\\Control\\Lsa\\MSV1_0"; const string KEY_VAL_NAME = "BackConnectionHostNames"; RegistryKey reg = Registry.LocalMachine.OpenSubKey(KEY_NAME, true); if (reg != null) { string[] existing = (string[])reg.GetValue(KEY_VAL_NAME); if (existing != null) { foreach (string val in existing) { if (!urls.Contains(val.ToLower())) urls.Add(val.ToLower()); } } string[] multiVal = new string[urls.Count]; urls.CopyTo(multiVal); foreach (string url in urls) { Logger.Write("Setting {0}", url); } reg.SetValue(KEY_VAL_NAME, multiVal, RegistryValueKind.MultiString); } else { throw new SPException("Unable to open registry key."); } }
private static void Part1() { var dWires = new Dictionary<string, ushort>(); var reloop = new List<string>(); for (int i = 0; i < Day07.Input.Count; i++) { var s = Day07.Input[i]; if (!Day07.ProcessOpLine(s, dWires)) reloop.Add(s); } while (reloop.Count > 0) { var tmpArr = new string[reloop.Count]; reloop.CopyTo(tmpArr); var tmpReloop = new List<string>(tmpArr); reloop = new List<string>(); for (int i = 0; i < tmpReloop.Count; i++) { var s = tmpReloop[i]; if (!Day07.ProcessOpLine(s, dWires)) reloop.Add(s); } } var wire = "a"; Console.WriteLine(" Wire \"" + wire + "\" is recieving signal " + dWires[wire] + "..."); }
/// <summary> /// Splits a word with MixedCase into words, like Mixed Case. /// </summary> /// <param name="value"></param> /// <returns></returns> public static string SplitWords(string multiWordString) { List<string> words = new List<string>(); int wordCount = 0; int start = 0; for (int i = 1; i < multiWordString.Length; i++) { if (char.IsUpper(multiWordString[i])) { words.Add(multiWordString.Substring(start, i - start)); wordCount++; start = i; } } //Grab the last word, if necessary if (start > 0) { words.Add(multiWordString.Substring(start, multiWordString.Length - start)); wordCount++; } if (wordCount == 0) return multiWordString; else { string[] wordArr = new string[words.Count]; words.CopyTo(wordArr); return string.Join(" ", wordArr).Trim(); } }
public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: The list is type of int"); try { int[] iArray = { 1, 9, 3, 6, 5, 8, 7, 2, 4, 0 }; List<int> listObject = new List<int>(iArray); int[] result = new int[10]; listObject.CopyTo(result); for (int i = 0; i < 10; i++) { if (listObject[i] != result[i]) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,i is: " + i); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; }
/// <summary> /// Construct the palette quantizer /// </summary> /// <param name="palette">The color palette to quantize to</param> /// <remarks> /// Palette quantization only requires a single quantization step /// </remarks> public PaletteQuantizer(List<Color> palette) : base(true) { this._colorMap = new Dictionary<uint, byte>(); this._colors = new Color[palette.Count]; palette.CopyTo(this._colors); }
/// <summary> /// Analyzes the text using each of the analyzers and returns /// their results as a series of runs. /// </summary> public void GenerateResults(TextAnalyzer textAnalyzer, out Run[] runs, out LineBreakpoint[] breakpoints) { // Initially start out with one result that covers the entire range. // This result will be subdivided by the analysis processes. LinkedRun initialRun = new LinkedRun() { nextRunIndex = 0, textStart = 0, textLength = text_.Length, bidiLevel = (readingDirection_ == ReadingDirection.RightToLeft) ? 1 : 0 }; runs_ = new List<LinkedRun>(); runs_.Add(initialRun); breakpoints_ = new List<LineBreakpoint>(); textAnalyzer.AnalyzeLineBreakpoints(this, 0, text_.Length, this); textAnalyzer.AnalyzeBidi(this, 0, text_.Length, this); textAnalyzer.AnalyzeScript(this, 0, text_.Length, this); textAnalyzer.AnalyzeNumberSubstitution(this, 0, text_.Length, this); //Call each of the analyzers in sequence, recording their results. breakpoints = new LineBreakpoint[breakpoints_.Count]; breakpoints_.CopyTo(breakpoints); // Resequence the resulting runs in order before returning to caller. runs = new Run[runs_.Count]; int nextRunIndex = 0; for (int i = 0; i < runs_.Count; i++) { runs[i] = runs_[nextRunIndex].AsRun; nextRunIndex = runs_[nextRunIndex].nextRunIndex; } }
public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: The list is type of string"); try { string[] strArray = { "Tom", "Jack", "Mike" }; List<string> listObject = new List<string>(strArray); string[] result = new string[3]; listObject.CopyTo(result); if ((result[0] != "Tom") || (result[1] != "Jack") || (result[2] != "Mike")) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; }
public void copyPiles(List<CPile> src, List<CPile> dest) { dest.Clear(); CPile[] arrPiles = new CPile[src.Count]; src.CopyTo(arrPiles); dest.AddRange(arrPiles); }
public static List<Tuple<int, int, int, int, long>> GetTuple(List<int> primes) { var list = new List<Tuple<int, int, int, int, long>>(); Tuple<int, int, int, int, long> tuple; var array = new int[primes.Count]; primes.CopyTo(array); var copy = array.ToList(); for (int i = 0; i < primes.Count - 3; i++) { for (int j = i + 1; j < primes.Count - 2; j++) { for (int k = j + 1; k < primes.Count - 1; k++) { for (int m = k + 1; m < primes.Count; m++) { long result = 1; result = result*primes[i]*primes[j]*primes[k]*primes[m]; if (IsDigitOk(result)) { tuple = new Tuple<int, int, int, int, long>(primes[i], primes[j], primes[k], primes[m], result); list.Add(tuple); } } } } } return list; }
/// <summary> /// Returns an array of any MethodInfo's on a Type that are marked as ValidationMethod /// </summary> /// <param name="objectType">CLR Type to search for validation methods</param> /// <returns></returns> public static MethodInfo[] GetValidationMethods(Type objectType) { var methodList = new List<MethodInfo>(); var methods = objectType.GetMethods(); foreach (var method in methods) { var att = method.GetAttribute<ValidationMethodAttribute>(); if (att != null) { if (method.GetParameters().Length > 0) { var msg = string.Format( "Method *{0}* in Class *{1}* cannot be a validation method because it has parameters", method.Name, objectType.AssemblyQualifiedName); throw new ArgumentException(msg); } methodList.Add(method); } } var returnValue = new MethodInfo[methodList.Count]; methodList.CopyTo(returnValue, 0); return returnValue; }
public static IList<int> GetRow(int rowIndex) { if (rowIndex == 0) { return null; } int[] prev = new int[rowIndex + 1]; prev[0] = 1; List<int> result = new List<int>(rowIndex); result.Add(1); for(int i = 1; i <= rowIndex; i++) { result[0] = 1; int j = 1; for(; j < i; j++) { result[j] = prev[j - 1] + prev[j]; } result.Add(1); result.CopyTo(prev); } return result; }
public static void FindSequence(List<int> nums) { int longestSeq = 0; var currentList = new List<int>(); var resultList = new int[currentList.Count]; for (int i = 0; i < nums.Count; i++) { int counter = 0; currentList.Clear(); for (int k = 1; k < nums.Count; k++) { if (nums[i] == nums[k]) { counter++; currentList.Add(nums[k]); } } if (counter >= longestSeq) { longestSeq = counter; resultList = new int[currentList.Count]; currentList.CopyTo(resultList); } } foreach (var item in resultList) { Console.WriteLine (item); } }
public static Encoding IdentifyEncoding ( byte[] data , Encoding defaultEncoding ) { EncodingInfo[] encodingInfos = Encoding.GetEncodings(); List<Encoding> list = new List<Encoding>(); foreach (EncodingInfo info in encodingInfos) { Encoding e = info.GetEncoding(); if (e.GetPreamble().Length > 0) { list.Add(e); //System.Console.WriteLine(e.EncodingName); } } Encoding[] encodings = new Encoding[list.Count]; list.CopyTo(encodings); return IdentifyEncoding ( data , defaultEncoding , encodings ); }
/// <summary> /// Read an order from the database /// </summary> /// <param name="orderId">Order Id</param> /// <returns>All information about the order</returns> public OrderInfo GetOrder(int orderId) { OrderInfo order = new OrderInfo(); //Create a parameter SqlParameter parm = new SqlParameter(PARM_ORDER_ID, SqlDbType.Int); parm.Value = orderId; //Execute a query to read the order using (SqlDataReader rdr = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringOrderDistributedTransaction, CommandType.Text, SQL_SELECT_ORDER, parm)) { if (rdr.Read()) { //Generate an order header from the first row AddressInfo billingAddress = new AddressInfo(rdr.GetString(5), rdr.GetString(6), rdr.GetString(7), rdr.GetString(8), rdr.GetString(9), rdr.GetString(10), rdr.GetString(11), rdr.GetString(12), null, "email"); AddressInfo shippingAddress = new AddressInfo(rdr.GetString(13), rdr.GetString(14), rdr.GetString(15), rdr.GetString(16), rdr.GetString(17), rdr.GetString(18), rdr.GetString(19), rdr.GetString(20), null, "email"); order = new OrderInfo(orderId, rdr.GetDateTime(0), rdr.GetString(1), null, billingAddress, shippingAddress, rdr.GetDecimal(21), null, null); IList<LineItemInfo> lineItems = new List<LineItemInfo>(); LineItemInfo item = null; //Create the lineitems from the first row and subsequent rows do { item = new LineItemInfo(rdr.GetString(22), string.Empty, rdr.GetInt32(23), rdr.GetInt32(24), rdr.GetDecimal(25)); lineItems.Add(item); } while (rdr.Read()); order.LineItems = new LineItemInfo[lineItems.Count]; lineItems.CopyTo(order.LineItems, 0); } } return order; }
public void BuildMap() { List<Hexagon> borders = new List<Hexagon>(); _hexagons = new Hexagon[GridManager.instance.gridHeightInHexes * GridManager.instance.gridWidthInHexes]; for (int x = 0; x < GridManager.instance.gridWidthInHexes; x++) for (int y = 0; y < GridManager.instance.gridHeightInHexes; y++) { _hexagons[x + y * GridManager.instance.gridWidthInHexes] = GridManager.instance.CreateHexagonAt(x, y); _hexagons[x + y * GridManager.instance.gridWidthInHexes].ClickEvent += new HexagonEventHandler(GridManager.instance.UserInteraction.OnHexagonClickedEvent); //Making the border array: if (x == 0 || y == 0 || x == GridManager.instance.gridWidthInHexes - 1 || y == GridManager.instance.gridHeightInHexes - 1) borders.Add(_hexagons[x + y * GridManager.instance.gridWidthInHexes]); } HexBorders = new Hexagon[borders.Count]; borders.CopyTo(HexBorders, 0); foreach (var hexagon in _hexagons) { hexagon.SurroundingHexagons = GetSurroundingTiles(hexagon); } treeGenerator = new TreeGenerator(); }
static void Main(string[] args) { List<string> list = new List<string>(); list.Add("1"); list.Add("2"); list.Add("3"); string[] arr = list.ToArray(); string[] arr2 = new string[3]; list.CopyTo(arr2); list.Add("4"); Console.WriteLine("List Element:"); foreach (string s in list) { Console.WriteLine(s); } Console.WriteLine("Array Element:"); arr[1] = "a"; foreach (string s in arr) { Console.WriteLine(s); } Console.WriteLine("Array2 Element:"); foreach (string s in arr2) { Console.WriteLine(s); } Console.ReadLine(); }
public void Apply(ref SRegion[] regions) { List<SRegion> a = new List<SRegion>(); List<SRegion> b = new List<SRegion>(); List<SRegion> c = new List<SRegion>(); TotalRegionsSize = base.Count(regions); foreach (SRegion region in regions) { float sizePercent = (float)region.Size / (float)TotalRegionsSize * 100F; if (sizePercent > 80) { a.Add(region); } else if (sizePercent > 60) { b.Add(region); } else { c.Add(region); } } A = new SRegion[a.Count]; B = new SRegion[b.Count]; C = new SRegion[c.Count]; a.CopyTo(A); b.CopyTo(B); c.CopyTo(C); }
public void Apply(ref SRegion[] regions) { float count = (float)base.Count(regions); List<SRegion> temp = new List<SRegion>(); unsafe { int* max = (int*)regions.Length; int* min = (int*)0; int incr = 1; for (int* i = min; i < max; i = (int*)((int)i + incr)) { int id = (int)i; SRegion region = regions[id]; float size = (float)region.Size / count; if (size > this.minMargin & size < this.maxMargin) temp.Add(region); } } SRegion[] result = new SRegion[temp.Count]; temp.CopyTo(result); regions = result; }
/// <summary>Return the list of all the pages used by this buffer</summary> /// <returns>Array of pages used by the buffer</returns> public Slice[] GetPages() { var pages = new Slice[this.PageCount]; m_chunks?.CopyTo(pages); pages[pages.Length - 1] = m_current.AsSlice(0, m_pos); return(pages); }
private void EcoLevelWindow_Load(object sender, EventArgs e) { List<string> dimensionsX = new List<string>(); string[] dimensionsY = new string[6]; string[] dimensionsZ = new string[6]; dimensionsX.Add("16"); dimensionsX.Add("32"); dimensionsX.Add("64"); dimensionsX.Add("128"); dimensionsX.Add("256"); dimensionsX.Add("512"); dimensionsX.CopyTo(dimensionsY); dimensionsX.CopyTo(dimensionsZ); comboBoxX.DataSource = dimensionsX; comboBoxY.DataSource = dimensionsY; comboBoxZ.DataSource = dimensionsZ; List<string> types = new List<string>(); types.Add("Flat"); types.Add("Pixel"); types.Add("Island"); types.Add("Mountains"); types.Add("Ocean"); types.Add("Forest"); types.Add("Desert"); types.Add("Space"); types.Add("Rainbow"); types.Add("Hell"); comboBoxType.DataSource = types; if (edit) { textBoxName.Text = lvledit.name; numericUpDownPrice.Value = lvledit.price; comboBoxX.SelectedItem = lvledit.x; comboBoxY.SelectedItem = lvledit.y; comboBoxZ.SelectedItem = lvledit.z; comboBoxType.SelectedItem = lvledit.type; } else { numericUpDownPrice.Value = 1000; comboBoxX.SelectedItem = "64"; comboBoxY.SelectedItem = "64"; comboBoxZ.SelectedItem = "64"; comboBoxType.SelectedItem = "Flat"; } buttonOk.Enabled = edit; }
/// <summary> /// Converts a list of strings into its corresponding array /// </summary> /// <param name="data"></param> /// <returns></returns> public static string[] toArray(List<string> data) { string[] retVal = new string[data.Count]; data.CopyTo(retVal); return retVal; }
public void CloneTo(UserConfigurationSet configurations) { configurations.ValidateMappingPlans = ValidateMappingPlans; _mappedObjectCachingSettings?.CopyTo(configurations.MappedObjectCachingSettings); _mapToNullConditions?.CopyTo(configurations.MapToNullConditions); _nullCollectionsSettings?.CopyTo(configurations.NullCollectionsSettings); _objectFactories?.CloneItems().CopyTo(configurations.ObjectFactories); _identifiers?.CloneTo(configurations.Identifiers); _ignoredMembers?.CloneItems().CopyTo(configurations.IgnoredMembers); _enumPairings?.CopyTo(configurations._enumPairings); _dictionaries?.CloneTo(configurations.Dictionaries); _dataSourceFactories?.CloneItems().CopyTo(configurations.DataSourceFactories); _mappingCallbackFactories?.CopyTo(configurations.MappingCallbackFactories); _creationCallbackFactories?.CopyTo(configurations.CreationCallbackFactories); _exceptionCallbackFactories?.CopyTo(configurations.ExceptionCallbackFactories); _derivedTypes?.CloneTo(configurations.DerivedTypes); }
/// <summary> /// Copies the objects of <see cref="IThreadSynchronizedObject"/> to synchronize in the <see /// cref="UnityThreadSynchronizer"/> to an <see cref="System.Array"/>, starting at a particular <see /// cref="System.Array"/> index. /// </summary> /// <param name="array"> /// The one-dimensional <see cref="System.Array"/> that is the destination of the elements /// copied from <see cref="UnityThreadSynchronizer"/>. The <see cref="System.Array"/> must have /// zero-based indexing. /// </param> /// <param name="arrayIndex"> /// The zero-based index in <paramref name="array"/> at which copying begins. /// </param> public void CopyTo(IThreadSynchronizedObject[] array, int arrayIndex) { synchronizedObjects?.CopyTo(array, arrayIndex); }
/// <summary> /// Smart method of splitting a string. Skips quoted elements, removes the quotes. /// </summary> /// <remarks> /// This split function works somewhat like the String.Split() function in that it breaks apart a string into /// pieces and returns the pieces as an array. The primary differences are: /// <list type="bullet"> /// <item><description>Only one character can be provided as a separator character</description></item> /// <item><description>Quoted text inside the string is skipped over when searching for the separator, and the quotes are removed.</description></item> /// </list> /// Thus, if splitting the following string looking for a comma:<br/> /// One,Two, "Three, Four", Five<br/> /// <br/> /// The resulting array would contain<br/> /// [0] One<br/> /// [1] Two<br/> /// [2] Three, Four<br/> /// [3] Five<br/> /// <br/> /// Note that the leading and trailing spaces were removed from each item during the split. /// </remarks> /// <param name="source">Source string to split apart</param> /// <param name="separator">Separator character</param> /// <returns>A string array of the split up elements</returns> public static string[] Split(string source, char separator) { char[] toks = new char[2] { '\"', separator }; char[] quot = new char[1] { '\"' }; int n = 0; List <string> ls = new List <string>(); string s; while (source.Length > 0) { n = source.IndexOfAny(toks, n); if (n == -1) { break; } if (source[n] == toks[0]) { //source = source.Remove(n, 1); n = source.IndexOfAny(quot, n + 1); if (n == -1) { //source = "\"" + source; break; } n++; //source = source.Remove(n, 1); } else { s = source.Substring(0, n).Trim(); if (s.Length > 1 && s[0] == quot[0] && s[s.Length - 1] == s[0]) { s = s.Substring(1, s.Length - 2); } source = source.Substring(n + 1).Trim(); if (s.Length > 0) { ls.Add(s); } n = 0; } } if (source.Length > 0) { s = source.Trim(); if (s.Length > 1 && s[0] == quot[0] && s[s.Length - 1] == s[0]) { s = s.Substring(1, s.Length - 2); } ls.Add(s); } string[] ar = new string[ls.Count]; ls.CopyTo(ar, 0); return(ar); }
public void CopyTo(TPoint[] array, int arrayIndex) { points.CopyTo(array, arrayIndex); }
public void CopyTo(T[] array, int arrayIndex) { _list?.CopyTo(array, arrayIndex); }
/// <summary> /// Copies the list prioritized items to an array starting at the specified index. /// </summary> /// <param name="array">The array to copy to.</param> /// <param name="arrayIndex">The index to start at.</param> public void CopyTo(PrioritizedItem <T>[] array, int arrayIndex) { _items.CopyTo(array, arrayIndex); }
public void CopyTo(Array array, int index) { items.CopyTo((object[])array, index); }
/// <summary> /// Copies views to specified array starting at particular index. /// </summary> /// <param name="array">Target array.</param> /// <param name="arrayIndex">Starting array index.</param> public override void CopyTo(ViewBase[] array, int arrayIndex) { // Let type safe collection perform operation _views?.CopyTo(array, arrayIndex); }
public void CopyTo(T[] array, int arrayIndex) { EnsureIsLoaded(); _list.CopyTo(array, arrayIndex); }
public void CopyTo(YamlDocument[] array, int arrayIndex) { _documents.CopyTo(array, arrayIndex); }
public RawModel LoadObjModel(string fileName, Loader loader) { string line; List <Vector3> vertices = new List <Vector3>(); List <Vector2> textures = new List <Vector2>(); List <Vector3> normals = new List <Vector3>(); List <Vector3> faces = new List <Vector3>(); List <int> indices = new List <int>(); float[] verticesArray; float[] texturesArray; float[] normalsArray; int[] indicesArray; StreamReader stream; try { stream = new StreamReader($"{PATH}{fileName}.obj"); } catch (IOException ex) { stream = new StreamReader($"{PATH}default_model.obj"); Console.WriteLine($"Model file [ {fileName}.obj ] not found. Loaded default model."); Console.WriteLine(ex.StackTrace); } using (stream) { while (!stream.EndOfStream) { line = stream.ReadLine(); string[] currentLine = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (currentLine.Length != 0) { if (currentLine[0] == "v") { float.TryParse(currentLine[1], out float x); float.TryParse(currentLine[2], out float y); float.TryParse(currentLine[3], out float z); var vertex = new Vector3(x, y, z); vertices.Add(vertex); } else if (currentLine[0] == "vt") { float.TryParse(currentLine[1], out float u); float.TryParse(currentLine[2], out float v); var texture = new Vector2(u, v); textures.Add(texture); } else if (currentLine[0] == "vn") { float.TryParse(currentLine[1], out float x); float.TryParse(currentLine[2], out float y); float.TryParse(currentLine[3], out float z); var normal = new Vector3(x, y, z); normals.Add(normal); } else if (currentLine[0] == "f") { for (int i = 1; i < 4; i++) { var face = currentLine[i].Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); int.TryParse(face[0], out int v); int.TryParse(face[1], out int vt); int.TryParse(face[2], out int vn); faces.Add(new Vector3(v, vt, vn)); } } } } } verticesArray = new float[vertices.Count * 3]; texturesArray = new float[vertices.Count * 2]; normalsArray = new float[vertices.Count * 3]; foreach (var face in faces) { ProcessVertex(face, indices, textures, normals, texturesArray, normalsArray); } int pointer = 0; foreach (var vertex in vertices) { verticesArray[pointer++] = vertex.X; verticesArray[pointer++] = vertex.Y; verticesArray[pointer++] = vertex.Z; } indicesArray = new int[indices.Count]; indices.CopyTo(indicesArray); return(loader.LoadToVao(verticesArray, texturesArray, normalsArray, indicesArray)); }
public void CopyTo(CodeStatement[] array, int arrayIndex) { _statements.CopyTo(array, arrayIndex); }
public void CopyTo(string[] array, int arrayIndex) { values.CopyTo(array, arrayIndex); }
public static void testForUnionPlines() { Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; Database db = doc.Database; // get argument to choose boolean operation mode PromptKeywordOptions pko = new PromptKeywordOptions("\nChoose boolean operation mode " + "[Union/Subtract]: ", "Union Subtract"); // The default depends on our current settings pko.Keywords.Default = "Union"; PromptResult pkr = ed.GetKeywords(pko); if (pkr.Status != PromptStatus.OK) { return; } string choice = pkr.StringResult; bool doUnion = choice == "Union" ? true : false; List <Region> regLst = new List <Region>(); List <Polyline> delPline = new List <Polyline>(); using (DocumentLock doclock = doc.LockDocument()) { //start a transaction using (Transaction tr = db.TransactionManager.StartTransaction()) { TypedValue[] tvs = new TypedValue[3] { new TypedValue(0, "lwpolyline"), new TypedValue(-4, "&"), new TypedValue(70, 1) }; SelectionFilter filter = new SelectionFilter(tvs); PromptSelectionOptions pso = new PromptSelectionOptions(); pso.MessageForRemoval = "\nSelect closed polylines only: "; pso.MessageForAdding = "\nSelect closed polylines: "; PromptSelectionResult result = ed.GetSelection(filter); if (result.Status != PromptStatus.OK) { return; } try { SelectionSet sset = result.Value; ObjectId[] ids = sset.GetObjectIds(); BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite, false); Region objreg1 = new Region(); for (int n = 0; n < ids.Count(); n++) { DBObject obj = tr.GetObject(ids[n], OpenMode.ForRead) as DBObject; Polyline pline1 = obj as Polyline; if (pline1 == null) { return; } // Add the polyline to the List to rerase them all at the end of execution delPline.Add(pline1); // Add the polyline to the array DBObjectCollection objArray1 = new DBObjectCollection(); objArray1.Add(pline1); // create the 1 st region DBObjectCollection objRegions1 = new DBObjectCollection(); objRegions1 = Region.CreateFromCurves(objArray1); objreg1 = objRegions1[0] as Region; btr.AppendEntity(objreg1); tr.AddNewlyCreatedDBObject(objreg1, true); objreg1.ColorIndex = 1;//optional // add the region to the List<Region> for the future work regLst.Add(objreg1); } //ed.WriteMessage("\nCount regions:\t{0}\n", regLst.Count);//just for the debug // sort regions by areas Region[] items = regLst.ToArray(); Array.Sort(items, (Region x, Region y) => y.Area.CompareTo(x.Area)); // get the biggest region first Region mainReg = items[0]; // ed.WriteMessage("\nMain region area:\t{0:f3}\n", items[0].Area);//just for the debug if (!mainReg.IsWriteEnabled) { mainReg.UpgradeOpen(); } if (items.Length == 2) { if (!doUnion) { mainReg.BooleanOperation(BooleanOperationType.BoolSubtract, (Region)items[1]); } else { mainReg.BooleanOperation(BooleanOperationType.BoolUnite, (Region)items[1]); } } else { // starting iteration from the second region int i = 1; do { Region reg1 = items[i]; Region reg2 = items[i + 1]; if ((reg1 == null) || (reg2 == null)) { break; } else { // subtract region 1 from region 2 if (reg1.Area > reg2.Area) { // subtract the smaller region from the larger one // reg1.BooleanOperation(BooleanOperationType.BoolUnite, reg2); if (!doUnion) { mainReg.BooleanOperation(BooleanOperationType.BoolSubtract, reg1); } else { mainReg.BooleanOperation(BooleanOperationType.BoolUnite, reg1); } } else { // subtract the smaller region from the larger one reg2.BooleanOperation(BooleanOperationType.BoolUnite, reg1); if (!doUnion) { mainReg.BooleanOperation(BooleanOperationType.BoolSubtract, reg2); } else { mainReg.BooleanOperation(BooleanOperationType.BoolUnite, reg2); } } } // increase counter i++; } while (i < items.Length - 1); } mainReg.ColorIndex = 1;// put dummy color for region // erase polylines foreach (Polyline poly in delPline) { if (poly != null) { if (!poly.IsWriteEnabled) { poly.UpgradeOpen(); } poly.Erase(); if (!poly.IsDisposed) { poly.Dispose(); } } } // --- explode region and create polyline from exploded entities --- // DBObjectCollection regexpl = new DBObjectCollection(); mainReg.Explode(regexpl); List <ObjectId> exids = new List <ObjectId>(); // gather selected object into the List<ObjectId> if (regexpl.Count > 0) { foreach (DBObject obj in regexpl) { Entity ent = obj as Entity; if (ent != null) { ObjectId eid = btr.AppendEntity(ent); tr.AddNewlyCreatedDBObject(ent, true); exids.Add(eid); } } } // define AcadDocument as object object ActiveDocument = doc.GetAcadDocument(); ObjectId[] entids = new ObjectId[] { }; Array.Resize(ref entids, exids.Count); // convert List<ObjectId> to array of ObjectID exids.CopyTo(entids, 0); ed.Regen(); // create a new selection set and exploded items SelectionSet newset = SelectionSet.FromObjectIds(entids); ed.SetImpliedSelection(newset.GetObjectIds()); PromptSelectionResult pfres = ed.SelectImplied(); // execute Sendcommand synchronously ActiveDocument.GetType().InvokeMember( "SendCommand", System.Reflection.BindingFlags.InvokeMethod, null, ActiveDocument, new object[] { "select\n" }); // execute Sendcommand synchronously string cmd = "_pedit _M _P" + " " + "" + " " + "_J" + " " + "" + " " + "" + "\n"; ActiveDocument.GetType().InvokeMember( "SendCommand", System.Reflection.BindingFlags.InvokeMethod, null, ActiveDocument, new object[] { cmd }); // rerase region if this is do not erased (relative to current DELOBJ variable value) if (mainReg != null) { if (!mainReg.IsWriteEnabled) { mainReg.UpgradeOpen(); } } mainReg.Erase(); tr.Commit(); } catch (Autodesk.AutoCAD.Runtime.Exception ex) { ed.WriteMessage("\nAutoCAD exception:\n" + ex.Message + "\n" + ex.StackTrace); } finally { ed.WriteMessage("\n{0}", new Autodesk.AutoCAD.Runtime.ErrorStatus().ToString());//optional, might be removed } } } }
/// <summary> /// Copies all the <see cref="Galaxia.ParticlesPrefab"/> to another array /// </summary> /// <param name="array">The array used to copy tp</param> /// <param name="arrayIndex">The index to start at</param> public void CopyTo(ParticlesPrefab[] array, int arrayIndex) { m_particlePrefabs.CopyTo(array, arrayIndex); }
/// <summary> /// Execute lua function by name /// </summary> /// <param name="fname">Function name as defined in WoWData.xml</param> /// <param name="param_list">List of parameters</param> /// <param name="res_list">List of parameters needs to be returned</param> /// <returns> /// Array with result. Final array enumerated from 0 to (size of returning list - 1). /// For ex if you need parameters 2 and 5 (total 2) to be returned from lua calls than /// in returning array the parameter 2 can be found by index 0 and parameter 5 by index 1 /// </returns> private string[] ExecLua(LuaFunction lf, object[] param_list, int[] res_list, bool get_all) { string[] res = null; // Check number of parameters int pcount = (param_list == null) ? 0 : param_list.Length; if (lf.ParamSize != pcount) { ProcessManager.TerminateOnInternalBug( ProcessManager.Bugs.WRONG_LUA_PARAMETER_LIST, "Number of parameters '" + pcount + "' different from " + lf.ParamSize + " that configured for lua function '" + lf.Name + "'. Terminating application."); } // format lua code with parameter list string code = lf.Code; if (param_list != null) { try { code = string.Format(code, param_list); } catch (Exception e) { ProcessManager.TerminateOnInternalBug( ProcessManager.Bugs.WRONG_LUA_RESULT_LIST, "Unable format parameters '" + param_list.ToString() + "' with lua function '" + lf.Name + "'. " + e.Message); } } // Check if result expected if (!get_all && (res_list == null)) { Lua_DoString(code); } else { Lua_DoStringEx(code); values = RemoteObject.GetValues(); // Check returning result if (values == null) { ProcessManager.TerminateOnInternalBug( ProcessManager.Bugs.NULL_LUA_RETURN, "Null returning result from lua function '" + lf.Name + "'"); } if (get_all) { res = new string[values.Count]; values.CopyTo(res); } else { if (values.Count != res_list.Length) { ProcessManager.TerminateOnInternalBug( ProcessManager.Bugs.WRONG_LUA_RETURN_LIST, "Number of returning parameters " + values.Count + " from lua function '" + lf.Name + "' is different from expected " + res_list.Length); } res = new string[res_list.Length]; // Initialize returning result for (int i = 0; i < res_list.Length; i++) { if (i == values.Count) { break; } res[i] = values[i]; } } } return(res); }
/// <summary> /// Copies all of the contained parameters to the specified array. /// </summary> /// <remarks> /// Copies all of the parameters within the <see cref="ParameterList"/> into the array, /// starting at the specified array index. /// </remarks> /// <param name="array">The array to copy the parameters to.</param> /// <param name="arrayIndex">The index into the array.</param> public void CopyTo(Parameter[] array, int arrayIndex) { parameters.CopyTo(array, arrayIndex); }
private int GenerateTournament(int numRounds) { //Limpiamos las tablas _tablePlayers.Clear(); _tablesWithAll.Clear(); _tablesByPlayer.Clear(); _rivalsByPlayer.Clear(); int currentRound, currentTable, currentTablePlayer; for (currentRound = 1; currentRound <= numRounds; currentRound++) {//Iteramos por rondas //Copiamos la lista de jugadores para ir borrando los que vayamos usando cada ronda List <int> playersNotUsedThisRound = _players.Select(x => x.Clone()).ToList().Select(x => x.Id).ToList(); for (currentTable = 1; currentTable <= _players.Count / 4; currentTable++) { //Iteramos por mesas en cada ronda for (currentTablePlayer = 1; currentTablePlayer <= 4; currentTablePlayer++) { //Iteramos por jugador en cada mesa //Copiamos la lista de jugadores para ir borrando los que vayamos descartando int[] arrayPlayersIdsNotDiscarded = new int[playersNotUsedThisRound.Count]; playersNotUsedThisRound.CopyTo(arrayPlayersIdsNotDiscarded); List <int> playersIdsNotDiscarded = new List <int>(arrayPlayersIdsNotDiscarded); bool playerFounded = false; //Si no hay jugador elegido y no hemos recorrido todos los jugadores lo reintentamos. while (!playerFounded && playersIdsNotDiscarded.Count > 0) { //Obtenemos la lista de jugadores de la actual mesa List <TablePlayer> currentTableTablePlayers = _tablePlayers.FindAll (x => x.round == currentRound && x.table == currentTable).ToList(); List <Player> currentTablePlayers = new List <Player>(); foreach (TablePlayer tp in currentTableTablePlayers) { currentTablePlayers.Add(GetPlayerById(tp.playerId)); } //Elegimos un jugador al azar y lo quitamos de la lista de no descartados int r = random.Next(0, arrayPlayersIdsNotDiscarded.Count()); Player choosenOne = GetPlayerById(arrayPlayersIdsNotDiscarded[r]); playersIdsNotDiscarded.Remove(choosenOne.Id); //Obtenemos la lista de jugadores que han jugado en anteriores rondas contra el elegido List <int> playersWHPATCO = GetPlayersWhoHavePlayedAgainstTheChoosenOne(choosenOne, currentRound); bool anyoneHavePlayed = false; foreach (int ctp in currentTablePlayers.Select(x => x.Id)) { if (playersWHPATCO.Contains(ctp)) { anyoneHavePlayed = true; } } /*Si el elegido ya ha jugado contra alguno de los de la mesa actual * o es del mismo equipo que alguno de los de la mesa actual(si el cálculo de equipos está seleccionado), * hay que buscar un nuevo candidato para esta mesa*/ if (anyoneHavePlayed || (_isTeamsChecked && currentTablePlayers.Select(x => x.Team).Contains(choosenOne.Team))) { playerFounded = false; } else {/*Si no ha jugado contra ninguno ni son de su mismo equipo, lo añadimos a la mesa * y lo quitamos de la lista de jugadores sin usar esta ronda*/ playerFounded = true; _tablePlayers.Add(new TablePlayer(currentRound, currentTable, currentTablePlayer, choosenOne.Id)); playersNotUsedThisRound.Remove(choosenOne.Id); } } //Si no se ha encontrado un posible jugador delvolvemos error para volver a empezar todo. if (!playerFounded && playersIdsNotDiscarded.Count == 0) { return(-1); } } } } //Si llegamos aqui es que todo ha ido bien y se ha terminado el cálculo return(1); }
/// <summary> /// Copies the <see cref="ToolboxLibrary.DesignerContainerItemCollection"/> values to a one-dimensional <see cref="System.Array"/> instance at the /// specified index. /// </summary> /// <param name="array">The one-dimensional <see cref="System.Array"/> that is the destination of the values copied from <see cref="ToolboxLibrary.DesignerContainerItemCollection"/> .</param> /// <param name="index">The index in <paramref name="array"/> where copying begins.</param> /// <remarks><exception cref="System.ArgumentException"><paramref name="array"/> is multidimensional. <para>-or-</para> <para>The number of elements in the <see cref="ToolboxLibrary.DesignerContainerItemCollection"/> is greater than the available space between <paramref name="arrayIndex"/> and the end of <paramref name="array"/>.</para></exception> /// <exception cref="System.ArgumentNullException"><paramref name="array"/> is <see langword="null"/>. </exception> /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than <paramref name="array"/>"s lowbound. </exception> /// <seealso cref="System.Array"/> /// </remarks> /// <history> /// [dineshc] 3/26/2003 Created /// </history> public void CopyTo(DesignerContainerItem[] array, int index) { List.CopyTo(array, index); }
public void CloneTo(NamingSettings settings) { settings._matchingNameFactories.AddRange(_matchingNameFactories.Skip(3)); settings._joinedNameFactories.AddRange(_joinedNameFactories.Skip(2)); _customNameMatchers?.CopyTo(settings.CustomNameMatchers); }
/// <summary> /// Copies the elements of the attributes /// to an <see cref="T:System.Array" />, starting at a particular <see cref="T:System.Array" /> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array" /> that is the destination /// of the elements copied from attributes. /// The <see cref="T:System.Array" /> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array" /> at which copying begins.</param> public void CopyTo(Attribute[] array, int arrayIndex) => _attributes?.CopyTo(array, arrayIndex);
/// <summary> /// Copies the elements of the container to an <see cref="T:System.Array" />, /// starting at a particular <see cref="T:System.Array" /> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array" /> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1" />. The <see cref="T:System.Array" /> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array" /> at which copying begins.</param> public void CopyTo(IElement[] array, int arrayIndex) => Elements?.CopyTo(array, arrayIndex);
public void CopyTo(A[] array, int arrayIndex) => backing.CopyTo(array, arrayIndex);
/// <summary> /// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="array"/> is null. /// </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="arrayIndex"/> is less than 0. /// </exception> /// <exception cref="T:System.ArgumentException"> /// <paramref name="array"/> is multidimensional. /// -or- /// <paramref name="arrayIndex"/> is equal to or greater than the length of <paramref name="array"/>. /// -or- /// The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>. /// -or- /// Type <see cref="GameControl"/> cannot be cast automatically to the type of the destination <paramref name="array"/>. /// </exception> void ICollection <GameControl> .CopyTo(GameControl[] array, int arrayIndex) { _gameControls.CopyTo(array, arrayIndex); }
/// <summary> /// Provides the next small buffer that the audio device requests. /// the buffer to fill is a non-null reference to the buffer that needs to be filled /// The return value represents how many bytes were written to buffer. /// </summary> public int ProvideNext(byte[] bufferToFill) { var renderTime = Media.RealtimeClock.PositionSeconds; var audioBufferTargetLength = bufferToFill.Length; var renderFrame = Media.AudioFramesCache.GetFrame(renderTime, true); var startFrameIndex = Media.AudioFramesCache.IndexOf(renderFrame); if (renderFrame == null) { AudioBuffer.Clear(); ContainedFrameTimes.Clear(); return(0); } while (AudioBuffer.Count < audioBufferTargetLength) { renderFrame = Media.AudioFramesCache.GetFrameAt(startFrameIndex); startFrameIndex++; if (renderFrame == null) { var emptyBuffer = new byte[bufferToFill.Length]; AudioBuffer.AddRange(emptyBuffer); continue; } if (ContainedFrameTimes.ContainsKey(renderFrame.StartTime)) { continue; } AudioBuffer.AddRange(renderFrame.AudioBuffer); ContainedFrameTimes.Add(renderFrame.StartTime, true); } const decimal keepThreshold = 0.5M; var keyFrames = ContainedFrameTimes.Keys.ToArray(); foreach (var frameTime in keyFrames) { if (frameTime < renderTime - keepThreshold || frameTime > renderTime + keepThreshold) { ContainedFrameTimes.Remove(frameTime); } } if (Media.IsPlaying && Media.SpeedRatio >= Constants.DefaultSpeedRatio) { AudioBuffer.CopyTo(0, bufferToFill, 0, bufferToFill.Length); AudioBuffer.RemoveRange(0, bufferToFill.Length); return(bufferToFill.Length); } else { // Write out all zeroes if we don't need to play any sound var silenceBuffer = new byte[bufferToFill.Length]; silenceBuffer.CopyTo(bufferToFill, 0); return(bufferToFill.Length); //return 0; } }
/// <summary> /// Copies the elements of the collection to an <see cref="T:System.Array"></see>, starting at a particular <see cref="T:System.Array"></see> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array"></see> that is the destination of the elements copied from the collection. The <see cref="T:System.Array"></see> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in array at which copying begins.</param> /// <exception cref="T:System.ArgumentOutOfRangeException">arrayIndex is less than 0.</exception> /// <exception cref="T:System.ArgumentNullException">array is null.</exception> /// <exception cref="T:System.ArgumentException">array is multidimensional.-or-arrayIndex is equal to or greater than the length of array.-or-The number of elements in the source collection is greater than the available space from arrayIndex to the end of the destination array.-or-Type T cannot be cast automatically to the type of the destination array.</exception> public void CopyTo(SortDescription[] array, int arrayIndex) { descriptions.CopyTo(array, 0); }
public void CopyTo(Exception[] array, int arrayIndex) { exceptions.CopyTo(array, arrayIndex); }
public void CopyTo(Property[] array, int arrayIndex) { _properties.CopyTo(array, arrayIndex); }
//////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1" /> to an /// <see cref="T:System.Array" />, starting at a particular <see cref="T:System.Array" /> index. /// </summary> /// /// <param name="array"> . </exception> </param> //////////////////////////////////////////////////////////////////////////////////////////////////// public void CopyTo([NotNull] T[] array) { m_innerList?.CopyTo(array); }