internal byte[] ToArray() { var list = new List<byte>(); list.Add(ExtensionIntroducer); list.Add(GraphicControlLabel); list.Add(BlockSize); //Packed fields var bitArray = new BitArray(8); //Reserved for future use. Hahahaha. Yeah... bitArray.Set(0, false); bitArray.Set(1, false); bitArray.Set(2, false); var pixelBits = GifMethods.ToBitValues((int)DisposalMethod); bitArray.Set(3, pixelBits[0]); bitArray.Set(4, pixelBits[1]); bitArray.Set(5, pixelBits[2]); //User Input Flag. bitArray.Set(6, false); //Transparent Color Flag, uses tranparency? bitArray.Set(7, HasTransparency); list.Add(GifMethods.ConvertToByte(bitArray)); list.AddRange(BitConverter.GetBytes(Delay)); list.Add(TransparentIndex); list.Add(Terminator); return list.ToArray(); }
internal byte[] ToArray() { var list = new List<byte>(); list.AddRange(BitConverter.GetBytes(Width)); list.AddRange(BitConverter.GetBytes(Height)); //Packed fields, 1 byte var bitArray = new BitArray(8); bitArray.Set(0, HasGlobalColorTable); //Color resolution: 111 = (8 bits - 1) //Color depth - 1 //Global colors count = 2^color depth var pixelBits = GifMethods.ToBitValues(GlobalColorTableSize); bitArray.Set(1, pixelBits[0]); bitArray.Set(2, pixelBits[1]); bitArray.Set(3, pixelBits[2]); //Sort flag (for the global color table): 0 bitArray.Set(4, IsSorted); //Size of the Global Color Table (Zero, if not used.): var sizeInBits = GifMethods.ToBitValues(GlobalColorTableSize); bitArray.Set(5, sizeInBits[0]); bitArray.Set(6, sizeInBits[1]); bitArray.Set(7, sizeInBits[2]); list.Add(GifMethods.ConvertToByte(bitArray)); list.Add(BackgroundIndex); //Background color index, 1 byte list.Add(0); //Pixel aspect ratio - Assume 1:1, 1 byte return list.ToArray(); }
public static bool Increment(BitArray bits, int size) { int i = size - 1; while (i >= 0 && bits.Get(i)) { bits.Set(i--, false); } if (i < 0) { return false; } bits.Set(i, true); return true; }
public static void BitArray_SetTest() { // [] Set true to true, true to false // [] Set false to false and false to true is covered in BitArray_GetTest() above BitArray ba2 = new BitArray(6, true); ba2.Set(0, true); ba2.Set(1, false); ba2.Set(2, true); ba2.Set(5, true); Assert.True(ba2.Get(0)); //"Err_7! Expected ba4.Get(0) to be true" Assert.False(ba2.Get(1)); //"Err_8! Expected ba4.Get(1) to be false" Assert.True(ba2.Get(2)); //"Err_9! Expected ba4.Get(2) to be true" }
/// <summary> /// Get the bits from a Base32 encoded string. /// </summary> /// <param name="base32text">A Base32 encoded string to decode into a byte array.</param> /// <returns>An array of bits from the resulting byte array.</returns> public static BitArray GetBits(string base32text) { char[] input = base32text.ToLower().ToCharArray(); /* * Base32 = 5 bits in a character * Length = number of characters * 5 bits per character */ int bitsIn32 = 5; int resultsLength = input.Length * bitsIn32; // Use the length to create the resulting bits array BitArray results = new BitArray(resultsLength, false); int index = 0; for (int i = 0; i < input.Length; i++) { char c = input[i]; int value = Array.IndexOf(encodingTable, c); if (value == -1) throw new ApplicationException("The Base32 encoded string contains invalid characters."); BitArray bits = new BitArray(new byte[] { Convert.ToByte(value) }); for (int x = 0; x < bitsIn32; x++) { results.Set(index, bits.Get(x)); index++; } } return results; }
private void AjustLength(BitArray array) { int length = array.Length; int newLength = array.Length + 1; if ((newLength & 512) > 448) { newLength += 64; } newLength = ((newLength >> 9) << 9) | 448; array.Length = newLength; array.Set(length, true); for (int i = length + 1; i < newLength; i++) { array.Set(length, false); } }
public Chromosome(int length) { Data = new BitArray(length); Random rand = new Random(); for(int i = 0; i<length; i++) Data.Set(i,rand.Next(2) == 1); }
/// <summary> /// Mutates a gene by bitwise mutation. /// </summary> /// <param name="gene"></param> /// <returns></returns> public static Gene Mutate(Gene gene) { if ( gene is BinaryGene ) { BinaryGene g = (BinaryGene) gene.Clone(); g.Value = !(BinaryGene)gene; return g; } else if ( gene is DoubleGene ) { DoubleGene g = (DoubleGene) gene.Clone(); byte[] bytes = BitConverter.GetBytes(g.Value); BitArray ba = new BitArray(bytes); int p = Utils.Rand.Next( ba.Length ); ba.Set(p, !ba[p]); ba.CopyTo(bytes, 0); g.Value = BitConverter.ToDouble(bytes,0); return g; } else if ( gene is IntegerGene ) { IntegerGene g = (IntegerGene) gene.Clone(); byte[] bytes = BitConverter.GetBytes(g.Value); BitArray ba = new BitArray(bytes); int p = Utils.Rand.Next( ba.Length ); ba.Set(p, !ba[p]); ba.CopyTo(bytes, 0); g.Value = BitConverter.ToInt32(bytes,0); return g; } return (Gene) gene.Clone(); // default }
public long[] SieveOfEratosthenes() { var sieveBound = (_limit - 1) / 2; var upperSqrt = ((int)Math.Sqrt(_limit) - 1) / 2; var primeBits = new BitArray(sieveBound + 1, true); for (var i = 1; i <= upperSqrt; i++) { if (primeBits.Get(i)) { for (var j = i * 2 * (i + 1); j <= sieveBound; j += 2 * i + 1) { primeBits.Set(j, false); } } } var capacity = (int)(_limit / (Math.Log(_limit) - 1.08366)); var numbers = new List<long>(capacity) { 2 }; for (var i = 1; i <= sieveBound; i++) { if (primeBits.Get(i)) numbers.Add(2 * i + 1); } return numbers.ToArray(); }
public BitArray ToBitArray() { BitArray result = new BitArray(array.Length); for(int i = 0 ; i < array.Length ; i++) result.Set(i, array.Get(i)); return result; }
//Runs the algoritm for number of iterations public override void Run(Configuration config) { log = new RandomLogSpecification(data.DataFileName, config.RandomSeed, config.NumberOfRuns, config.PenaltyCoefficient); solution = new SolutionSpecification(); BitArray routerswitches = new BitArray((int)data.RouterCount); double highestfitness = 0.0; BitArray best = new BitArray((int)data.RouterCount); for(int i = 0; i < config.NumberOfRuns; i++) { routerswitches = new BitArray((int)data.RouterCount); int numbertoswitch = randomgenerator.Next((int)data.RouterCount); for(int j = 0; j < numbertoswitch; j++) { int switching; while(routerswitches.Get(switching = randomgenerator.Next((int)data.RouterCount)) == true); routerswitches.Set(switching, true); } double fitness = FitnessEvaluation(data.NetworkPaths, routerswitches, numbertoswitch, config.PenaltyCoefficient); if(fitness > highestfitness) { ((RandomLogSpecification)log).AddEvaluation(i, fitness); highestfitness = fitness; best = (BitArray)routerswitches.Clone(); } } solution.RoutersTurnedOff = ExtensionMethods.ConvertBitArrayToOffRouterNumbers(best, data.HostCount); }
protected void next_ServerClick(object sender, EventArgs e) { user u = new user(); u.user_id = (int)Session["id"]; u = os.getUserById(u); int seat_num = (int)Session["seat_num"]; o.SSR = this.SSR.Value ; o.type = type; FlightService fs = new FlightService(); String plane_type_name = searchF.plane.plane_type.name; BitArray seat = new BitArray(20); seat.SetAll(false); seat.Set(seat_num,true); o.seat = OrderService.BitArrayToByteArray(seat); if ( (o = os.generate(u, searchF, o, seat_num)) != null) { Session["new_order"] = o; Server.Transfer("payment.aspx"); } else { ShowPopUpMsg("Seat is book by others!"); } }
public static void BitArray_GetTest() { BitArray ba2 = new BitArray(6, false); ba2.Set(0, true); ba2.Set(1, false); ba2.Set(2, true); ba2.Set(5, true); Assert.True(ba2.Get(0)); //"Err_1! Expected ba4.Get(0) to be true" Assert.False(ba2.Get(1)); //"Err_2! Expected ba4.Get(1) to be false" Assert.True(ba2.Get(2)); //"Err_3! Expected ba4.Get(2) to be true" Assert.False(ba2.Get(3)); //"Err_4! Expected ba4.Get(3) to be false" Assert.False(ba2.Get(4)); //"Err_5! Expected ba4.Get(4) to be false" Assert.True(ba2.Get(5)); //"Err_6! Expected ba4.Get(5) to be true" }
public static int[] ESieve(int upperLimit) { int sieveBound = (int)(upperLimit - 1) / 2; int upperSqrt = ((int)Math.Sqrt(upperLimit) - 1) / 2; BitArray PrimeBits = new BitArray(sieveBound + 1, true); for (int i = 1; i <= upperSqrt; i++) { if (PrimeBits.Get(i)) { for (int j = i * 2 * (i + 1); j <= sieveBound; j += 2 * i + 1) { PrimeBits.Set(j, false); } } } List<int> numbers = new List<int>((int)(upperLimit / (Math.Log(upperLimit) - 1.08366))); numbers.Add(2); for (int i = 1; i <= sieveBound; i++) { if (PrimeBits.Get(i)) { numbers.Add(2 * i + 1); } } return numbers.ToArray(); }
public AudioFile DecodeHiddenMessage(AudioFile containerAudioFile) { var hiddenBitsPerSample = containerAudioFile.waveFile.bitsPerSample / CHANGING_SAMPLES_FACTOR; var hiddenMessageBits = new BitArray((int)(containerAudioFile.waveFile.samples.Length * hiddenBitsPerSample)); var maxNumberOfDecodingSteps = containerAudioFile.waveFile.samples.Length; for (int i = 0; i < maxNumberOfDecodingSteps; i++) { var uintValue = containerAudioFile.waveFile.samples[i]; var intFromBitsToRead = uintValue.GetLastNBitsIntValue((int) hiddenBitsPerSample); var hiddenIntBits = new BitArray(new[] { intFromBitsToRead }).GetBitArrayFromBitArrayRange(0, (int) hiddenBitsPerSample); for(int j = 0; j < hiddenIntBits.Length; j++) { hiddenMessageBits.Set(i * (int) hiddenBitsPerSample + j, hiddenIntBits[j]); } } containerAudioFile.waveFile.Save(); var messageBytes = new byte[hiddenMessageBits.Count]; hiddenMessageBits.CopyTo(messageBytes, 0); return new AudioFile(containerAudioFile.bytes, messageBytes); }
public static void BitArray_NotTest() { // [] Standard cases BitArray ba2 = null; BitArray ba4 = null; ba2 = new BitArray(6, false); ba2.Set(0, true); ba2.Set(1, true); ba4 = ba2.Not(); for (int i = 0; i < ba4.Length; i++) { if (i <= 1) Assert.False(ba4.Get(i)); //"Err_2! ba4.Get(" + i + ") should be false" else Assert.True(ba4.Get(i)); //"Err_3! ba4.Get(" + i + ") should be true" } // [] Size stress cases. ba2 = new BitArray(0x1000F, false); ba2.Set(0, true); ba2.Set(1, true); ba2.Set(0x10000, true); ba2.Set(0x10001, true); ba4 = ba2.Not(); Assert.False(ba4.Get(1)); //"Err_4! ba4.Get(1) should be false" Assert.True(ba4.Get(2)); //"Err_5! ba4.Get(2) should be true" for (int i = 0x10000; i < ba2.Length; i++) { if (i <= 0x10001) Assert.False(ba4.Get(i)); //"Err_6! ba4.Get(" + i + ") should be false" else Assert.True(ba4.Get(i)); //"Err_7! ba4.Get(" + i + ") should be true" } }
public long[] SieveOfAtkin() { var primeBits = new BitArray(_limit + 1, false); var upperSqrt = (int)Math.Sqrt(_limit); for (var i = 1; i <= upperSqrt; i++) { for (var j = 1; j <= upperSqrt; j++) { var n = 4 * i * i + j * j; if (n <= _limit && (n % 12 == 1 || n % 12 == 5)) primeBits.Set(n, !primeBits.Get(n)); n = 3 * i * i + j * j; if (n <= _limit && (n % 12 == 7)) primeBits.Set(n, !primeBits.Get(n)); n = 3 * i * i - j * j; if (i > j && n <= _limit && (n % 12 == 11)) primeBits.Set(n, !primeBits.Get(n)); } } for (var i = 5; i <= upperSqrt; i++) { if (primeBits.Get(i)) { for (var j = i * i; j <= _limit; j += i * i) { primeBits.Set(j, false); } } } var numbers = new List<long> {2, 3}; for (var i = 5; i <= _limit; i += 2) { if (primeBits.Get(i)) numbers.Add(i); } return numbers.ToArray(); }
public UncompressedBitArray(int[] indices, int capacity) { int length = capacity; array = new BitArray(length); foreach (int index in indices) { array.Set(index, true); } }
public Node() { attrCount = Globals.attrCount; availableAttrs = new BitArray(attrCount); availableAttrs.SetAll(true); availableAttrs.Set(attrCount-1, false); tuples = new List<Tuple>(); childNodes = new List<Node>(); }
public static void ComputePrimes(int limit) { // Sieve of Erathosthenes primes = new BitArray(limit); primes.SetAll(true); primes.Set(0, false); primes.Set(1, false); for (int i = 0; i * i < limit; i++) { if (primes.Get(i)) { for (int j = i * i; j < limit; j += i) { primes.Set(j, false); } } } }
static RowAtom() { binaryOperatorChangeSet = new BitArray(16); binaryOperatorChangeSet.Set((int)TexAtomType.BinaryOperator, true); binaryOperatorChangeSet.Set((int)TexAtomType.BigOperator, true); binaryOperatorChangeSet.Set((int)TexAtomType.Relation, true); binaryOperatorChangeSet.Set((int)TexAtomType.Opening, true); binaryOperatorChangeSet.Set((int)TexAtomType.Punctuation, true); ligatureKernChangeSet = new BitArray(16); ligatureKernChangeSet.Set((int)TexAtomType.Ordinary, true); ligatureKernChangeSet.Set((int)TexAtomType.BigOperator, true); ligatureKernChangeSet.Set((int)TexAtomType.BinaryOperator, true); ligatureKernChangeSet.Set((int)TexAtomType.Relation, true); ligatureKernChangeSet.Set((int)TexAtomType.Opening, true); ligatureKernChangeSet.Set((int)TexAtomType.Closing, true); ligatureKernChangeSet.Set((int)TexAtomType.Punctuation, true); }
public void Combinations_count_correct() { List<string> strs = new List<string>{ "a", "b", "c", "d"}; List<BitArray> bitArrays = new List<BitArray>(); for (int i = 0; i < strs.Count; i++) { for (int j = strs.Count - 1; j > i; j--) { BitArray bitArray = new BitArray(strs.Count); bitArray.Set(i, true); bitArray.Set(j, true); bitArrays.Add(bitArray); } } Assert.AreEqual(24, Factorial(4)); Assert.AreEqual(Combinations(strs.Count, 2), bitArrays.Count); }
public static BitArray StringToBits(string bits) { bits = Regex.Replace( bits, @"\s", String.Empty ); int count=bits.Length; BitArray result=new BitArray(count); for(int index=0; index<count; index++) result.Set(index,bits[count-index-1]=='1'); return result; }
protected static byte[] CalculateSize(long payload) { // // Transform to binary. // var binCoding = new BitArray(28); int bitPos = 0; long curValue = payload; while (curValue != 0) { long remainder = curValue%2; curValue = curValue/2; if (remainder == 1) { binCoding.Set(bitPos, true); } else { binCoding.Set(bitPos, false); } bitPos++; } // // Convert to byte[] structure // var sizeBytes = new byte[4]; byte b4 = CalculateFromBitSet(binCoding, 0, 6); byte b3 = CalculateFromBitSet(binCoding, 7, 13); byte b2 = CalculateFromBitSet(binCoding, 14, 20); byte b1 = CalculateFromBitSet(binCoding, 21, 27); sizeBytes[3] = b4; sizeBytes[2] = b3; sizeBytes[1] = b2; sizeBytes[0] = b1; return sizeBytes; }
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - public SpeciesList(IEnumerable<ISpecies> speciesList, ISpeciesDataset speciesDataset) { bitArray = new BitArray(speciesDataset.Count); if (speciesList != null) { foreach (ISpecies species in speciesList) { bitArray.Set(species.Index, true); } } }
private static void AddToBitArray(BitArray bitArray, int bitArrayIndex, byte byteData, int byteDataIndex, int length) { var localBitArray = new BitArray(new[] { byteData }); for (var i = byteDataIndex + length - 1; i >= byteDataIndex; i--) { bitArray.Set(bitArrayIndex, localBitArray.Get(i)); bitArrayIndex++; } }
public int[] ASieve(int upperLimit) { BitArray PrimeBits = new BitArray(upperLimit + 1, false); int upperSqrt = (int)Math.Sqrt(upperLimit); for (int i = 1; i <= upperSqrt; i++) { for (int j = 1; j <= upperSqrt; j++) { int n = 4 * i * i + j * j; if (n <= upperLimit && (n % 12 == 1 || n % 12 == 5)) { PrimeBits.Set(n, !PrimeBits.Get(n)); } n = 3 * i * i + j * j; if (n <= upperLimit && (n % 12 == 7)) { PrimeBits.Set(n, !PrimeBits.Get(n)); } n = 3 * i * i - j * j; if (i > j && n <= upperLimit && (n % 12 == 11)) { PrimeBits.Set(n, !PrimeBits.Get(n)); } } } for (int i = 5; i <= upperSqrt; i++) { if (PrimeBits.Get(i)) { for (int j = i * i; j <= upperLimit; j += i * i) { PrimeBits.Set((int)j, false); } } } List<int> numbers = new List<int>(); numbers.Add(2); numbers.Add(3); for (int i = 5; i <= upperLimit; i += 2) { if (PrimeBits.Get(i)) { numbers.Add(i); } } return numbers.ToArray(); }
public override BitArray Bits(IndexReader reader) { BitArray bitArray = new BitArray(reader.MaxDoc()); TermDocs termDocs = reader.TermDocs(new Term("score", "5")); while (termDocs.Next()) { bitArray.Set(termDocs.Doc(), true); } return bitArray; }
static void Main() { //input int arraySize = int.Parse(Console.ReadLine()); //get array int[] toSearch = new int[arraySize]; for (int i = 0; i < arraySize; i++) { toSearch[i] = int.Parse(Console.ReadLine()); } // variables BitArray sumFlags = new BitArray(arraySize); BitArray maxFlags = new BitArray(arraySize); int curSum = 0; int maxSum = toSearch.Sum(); for (int curNumb = 0; curNumb < toSearch.Length; curNumb++) { // Step 1: Get Current Sum curSum += toSearch[curNumb]; sumFlags.Set(curNumb, true); if (curSum > maxSum) { // Store the Sum maxSum = curSum; // Flag the indexes maxFlags.SetAll(false); maxFlags.Or(sumFlags); } else { if (curSum < 0) { // discard and start summing again curSum = 0; sumFlags.SetAll(false); } else { // keep going continue; } } } // output Console.WriteLine(maxSum); }
public Tile(BitArray tileType = null, Sprite sprite = null) { if (tileType == null) { tileType = TileInfo.CreateTileType(); tileType.Set((int)TileInfo.TileFlag.Empty, true); } this.tileType = tileType; this.sprite = sprite; }
static public int Set(IntPtr l) { try { System.Collections.BitArray self = (System.Collections.BitArray)checkSelf(l); System.Int32 a1; checkType(l, 2, out a1); System.Boolean a2; checkType(l, 3, out a2); self.Set(a1, a2); pushValue(l, true); return(1); } catch (Exception e) { return(error(l, e)); } }
// Sieve ref: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes public void GeneratePrimesSieve() { isPrime = new System.Collections.BitArray(n + 1, true); for (int i = 3; i *i <= n; i += 2) { if (isPrime.Get(i)) { for (int j = i * i; j <= n; j += i) { isPrime.Set(j, false); } } } primes = new List <int>(new int[] { 2 }); for (int i = 3; i <= n; i += 2) { if (isPrime.Get(i)) { primes.Add(i); } } }
protected void CopyBits(int srcRecordNo, int dstRecordNo) { _dbNullBits.Set(dstRecordNo, _dbNullBits.Get(srcRecordNo)); }
public static void Main() { Cons.WriteLine($"Chapter 10 - Collections..."); //Play._Time(1); //Play._Time(2); //Collection Initializers var intList = new List <int>() { 1, 2, 3, 4, 5 }; //Racers Racer GHill = new Racer(2, "Graham", "Hill", "UK", 10); Racer DHill = new Racer(7, "Dameon", "Hill", "UK", 14); var racers = new List <Racer>(10) { GHill, DHill }; Cons.WriteLine($"{racers.Count} racers so far."); racers.Add(new Racer(24, "Michael", "Schumacher", "Germany", 91)); racers.Insert(0, new Racer(22, "Ayrton", "Senna", "Brazil", 41)); //Accessing elements var a1 = racers[0]; Cons.WriteLine("Print list with a foreach loop........................................."); foreach (var r in racers) { Cons.WriteLine(r.ToString("N", null)); } //Delagates again! Cons.WriteLine("Now using a delegate........................................."); racers.ForEach(Cons.WriteLine); Cons.WriteLine("Now using lambda to format........................................."); racers.ForEach(r => Cons.WriteLine($"{r:w}")); Racer R1 = new Racer(22, "Ayrton", "Senna", "Brazil", 41); if (!racers.Remove(R1)) { Cons.WriteLine($"Racer {R1.Id} not found to remove."); } R1 = DHill; if (!racers.Remove(R1)) { Cons.WriteLine($"Racer {DHill.Id} not found to remove."); } racers.Add(R1); //Using Find Predicate //int i2 = racers.FindIndex(new FindCountry("Finland").FindCountryPredicate); This works but has a bugget, not my code! int i3 = racers.FindIndex(r => r.Country == "UK"); //Sane as line above and more likely to be used... i3 = racers.FindLastIndex(r => r.Country == "UK"); //Sane as line above and more likely to be used... var R2 = racers.FindLast(r => r.LastName == "Louder"); var someWins = racers.FindAll(r => r.Wins < 20); someWins.Sort(); var bigWiners = racers.FindAll(r => r.Wins > 20); bigWiners.Sort(); racers.Sort(new RacerComp(RacerComp.CompareType.LastName)); racers.Sort(new RacerComp(RacerComp.CompareType.Country)); //Sort using delagte and Lambda expression. racers.Sort((r1, r2) => r2.Wins.CompareTo(r1.Wins)); racers.Reverse(); //Type Conversion... var rPeople = racers.ConvertAll <Person>(r => new Person(r.FirstName + ',' + r.LastName)); //Read-Only Collections var roRacers = racers.AsReadOnly(); //Queues var dm = new DocsManager(); ProcessDocs.Start(dm); //Create docs and add too dm for (int i = 0; i < 100; i++) { var doc = new Doc("Doc" + i.ToString(), "AID" + new Random().Next(20).ToString()); dm.AddDoc(doc); Console.WriteLine($"Added Document: {doc.Title} by {doc.Auther} to queue."); Thread.Sleep(new Random().Next(20)); } Thread.Sleep(2000); ProcessDocs.Stop(); //Stacks Quick one... var lets = new Stack <char>(); lets.Push('A'); lets.Push('B'); lets.Push('C'); foreach (var l in lets) { Cons.Write(l); } Cons.WriteLine(); while (lets.Count > 0) { Cons.Write(lets.Pop()); } Cons.WriteLine($"Next..."); //Linked Lists... var pDM = new PDocManager(); pDM.AddPDoc(new PDoc("Adoc", "AAAdams", 4)); pDM.AddPDoc(new PDoc("Bdoc", "BBabs", 8)); pDM.AddPDoc(new PDoc("Cdoc", "CCock", 4)); pDM.AddPDoc(new PDoc("Ddoc", "AAAdams", 8)); pDM.AddPDoc(new PDoc("Edoc", "CCock", 8)); pDM.DisplayAllNodes(); //Simple Sorted List var boots = new SortedList <int, string>(); boots.Add(18, "Knee High"); boots.Add(27, "Thigh Length"); boots[12] = "Calfe"; boots[6] = "Ankle"; foreach (var b in boots) { Cons.WriteLine($"{b.Key}, {b.Value}"); } boots[27] = "Thigh High"; foreach (var b in boots) { Cons.WriteLine($"{b.Key}, {b.Value}"); } //What Next....for DCoates var employees = new Dictionary <EmployeeId, DicEmployee>(); var idCat = new EmployeeId("A000001"); var eCat = new DicEmployee(idCat, "Cat", 100000.00m); employees.Add(idCat, eCat); var idAnt = new EmployeeId("A012345"); var eAnt = new DicEmployee(idAnt, "Ant", 23000.00m); employees.Add(idAnt, eAnt); var idBee = new EmployeeId("B000001"); var eBee = new DicEmployee(idBee, "Bee", 40000.00m); employees.Add(idBee, eBee); var idDog = new EmployeeId("A000002"); var eDog = new DicEmployee(idDog, "Dog", 10000.00m); employees.Add(idDog, eDog); foreach (var e in employees) { Cons.WriteLine(e.ToString()); } while (true) { Cons.Write("Enter am Empolyee Id: (X to exit)>"); var uIn = Cons.ReadLine(); if (uIn.ToLower() == "x") { break; } EmployeeId eId; try { eId = new EmployeeId(uIn); DicEmployee dEmp; if (!employees.TryGetValue(eId, out dEmp)) { Cons.WriteLine($"Employee with {eId} does not exist."); } else { Cons.WriteLine(dEmp); } } catch (EmployeeIdException ee) { Cons.WriteLine(ee.Message); } } //Lookups from System.core //Use the racers list from above var lookupRacers = racers.ToLookup(r => r.Country); foreach (var r in lookupRacers["UK"]) { Cons.WriteLine($"name:{r.LastName}, {r.FirstName}"); } //Nice but not sorted! //Sorted Dics.... //Simple Sorted List var sdBoots = new SortedDictionary <int, string> { { 18, "Knee High" }, { 27, "Thigh Length" } }; sdBoots[12] = "Calfe"; sdBoots[6] = "Ankle"; foreach (var b in sdBoots) { Cons.WriteLine($"{b.Key}, {b.Value}"); } //Sets... var allTeams = new HashSet <string>() { "Ferrari", "Lotus", "McLaren", "Honda", "BRM", "Aston Martin", "Red Bull", "Force India", "Sauber", "Williams" }; var coTeams = new HashSet <string>() { "Ferrari", "Lotus", "McLaren", "Honda" }; var oldTeams = new HashSet <string>() { "Ferrari", "Lotus", "BRM", "Aston Martin" }; var newTeams = new HashSet <string>() { "Red Bull", "Force India", "Sauber" }; var res = coTeams.Add("Williams"); res = coTeams.Add("Williams"); res = coTeams.IsSubsetOf(allTeams); res = allTeams.IsSupersetOf(coTeams); res = oldTeams.Overlaps(coTeams); res = newTeams.Overlaps(coTeams); var allTeams2 = new SortedSet <string>(coTeams); allTeams2.UnionWith(oldTeams); allTeams2.UnionWith(newTeams); res = allTeams2.SetEquals(allTeams); var tTeams = new SortedSet <string>(allTeams); tTeams.SymmetricExceptWith(oldTeams); var yTeams = new SortedSet <string>(allTeams); var yI = new SortedSet <string>(yTeams.Intersect(oldTeams)); //Observable Collections Cons.Clear(); Cons.WriteLine("Observable Collections...."); var data = new ObservableCollection <string>(); data.CollectionChanged += Data_CollectionChanged; data.Add("First"); data.Add("Second"); data.Insert(1, "Three"); data.Remove("Three"); //Bits and bobs.... Cons.WriteLine("Bits and Bobs...."); var bitsA = new Col.BitArray(8); bitsA.SetAll(true); bitsA.Set(1, false); DisplayBits(bitsA); Cons.WriteLine(); bitsA.Not(); DisplayBits(bitsA); byte[] aI = { 22 }; var bitsB = new Col.BitArray(aI); DisplayBits(bitsB); bitsA.Or(bitsB); DisplayBits(bitsA); //BitVector32 Struct var vBits = new Col.Specialized.BitVector32(); int m1 = BitVector32.CreateMask(); int m2 = BitVector32.CreateMask(m1); int m3 = BitVector32.CreateMask(m2); int m4 = BitVector32.CreateMask(m3); int m5 = BitVector32.CreateMask(128); vBits[m1] = true; vBits[m3] = true; vBits[m4] = true; vBits[m5] = true; Cons.WriteLine(vBits); int rec = 0x88abcde; var vBitRSet = new BitVector32(rec); Cons.WriteLine(vBitRSet); //Immutable Collections ImmutabeThings.ImmutableTing1(); Cons.ReadKey(); }
} // End Read Function /// <summary> /// Write data to the Server Device.</summary> public bool Write(DataExtClass[] DataIn) { bool retVar = false; int i, j, jj, SAddress, boolReg, boolBit; uint intFloat; DAConfClass thisArea; var bitArray = new System.Collections.BitArray(16); var BitInt = new int[1]; //If is not initialized and not connected return error if (!(isInitialized && (DataIn != null))) { Status.NewStat(StatType.Bad, "Not Ready for Writing"); return false; } //If the DataIn and Internal data doesnt have the correct amount of data areas return error. if (!((DataIn.Length == MasterDriverConf.NDataAreas) && (IntData.Length == MasterDriverConf.NDataAreas))) { Status.NewStat(StatType.Bad, "Data Containers Mismatch"); return false; } if (!(isConnected && ModTCPObj.Connected)) { Status.NewStat(StatType.Bad, "Connection Error..."); this.Disconect(); return false; } for (i = 0; i < MasterDriverConf.NDataAreas; i++) { thisArea = MasterDataAreaConf[i]; SAddress = int.Parse(thisArea.StartAddress); if (thisArea.Enable && thisArea.Write) { jj = 0; //Index reinitialize for (j = 0; j < thisArea.Amount; j++) { switch (thisArea.dataType) { case DriverConfig.DatType.Bool: if (thisArea.DBnumber == 1) { if ((IntData[i].dBool.Length > j) && (DataIn[i].Data.dBoolean.Length > j)) { IntData[i].dBool[j] = DataIn[i].Data.dBoolean[j]; } } else if (thisArea.DBnumber == 3) { boolReg = Math.DivRem(j, 16, out boolBit); if ((IntData[i].dInt.Length > boolReg) && (DataIn[i].Data.dBoolean.Length > j)) { if (boolBit == 0) { bitArray.SetAll(false); BitInt[0] = 0; } bitArray.Set(boolBit, DataIn[i].Data.dBoolean[j]); bitArray.CopyTo(BitInt, 0); IntData[i].dInt[boolReg] = BitInt[0]; } } break; case DriverConfig.DatType.Byte: IntData[i].dInt[j] = DataIn[i].Data.dByte[j]; break; case DriverConfig.DatType.Word: IntData[i].dInt[j] = DataIn[i].Data.dWord[j]; break; case DriverConfig.DatType.DWord: //Endianess of the double word. if (RegOrder == ModbusClient.RegisterOrder.HighLow) { IntData[i].dInt[jj] = (int)((DataIn[i].Data.dDWord[j] & MaskHWord) >> 16); IntData[i].dInt[(jj + 1)] = (int)(DataIn[i].Data.dDWord[j] & MaskWord); } else { IntData[i].dInt[jj] = (int)(DataIn[i].Data.dDWord[j] & MaskWord); IntData[i].dInt[(jj + 1)] = (int)((DataIn[i].Data.dDWord[j] & MaskHWord) >> 16); } jj = jj + 2; break; case DriverConfig.DatType.Real: //Float point decimal. //Convert the intFloat = (uint)Math.Abs(Math.Round(DataIn[i].Data.dReal[j] * 1000.0)); //Turn ON/OFF the sign bit. if (DataIn[i].Data.dReal[j] < 0) { intFloat = intFloat | MaskNeg; } else { intFloat = intFloat & MaskiNeg; } //Endianess of the double word. if (RegOrder == ModbusClient.RegisterOrder.HighLow) { IntData[i].dInt[jj] = (int)((intFloat & MaskHWord) >> 16); IntData[i].dInt[(jj + 1)] = (int)(intFloat & MaskWord); } else { IntData[i].dInt[jj] = (int)(intFloat & MaskWord); IntData[i].dInt[(jj + 1)] = (int)((intFloat & MaskHWord) >> 16); } jj = jj + 2; break; default: Status.NewStat(StatType.Warning, "Wrong DataArea Type, Check Config."); break; } } // For j try { //Write the data to the device if ((thisArea.DBnumber == 1) && (thisArea.dataType == DriverConfig.DatType.Bool)) { ModTCPObj.WriteMultipleCoils(SAddress, IntData[i].dBool); retVar = true; } else if (thisArea.DBnumber == 3) { ModTCPObj.WriteMultipleRegisters(SAddress, IntData[i].dInt); retVar = true; } else { retVar = false; Status.NewStat(StatType.Warning, "Wrong FC for Write, Check Config."); } //Report Good if (retVar) Status.NewStat(StatType.Good); } catch (Exception e) { Status.NewStat(StatType.Bad, e.Message); return false; } }// Area Enable } //For Data Areas. return retVar; }// END Write Function