How to use GenY class of B package

Best Nunit code snippet using B.GenY

Program.cs

Source:Program.cs Github

copy

Full Screen

1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using System.Diagnostics;7namespace Genetic_ShortPath8{9    class Program10    {11        static int osobi, cities, geny, StartCity, EndCity;12        static void Main(string[] args)13        {14            var sw = new Stopwatch();15            cities = 300;16            Console.WriteLine("Кол-во городов: " + cities);17            Random rand = new Random();18            int[,] MatrDistance = new int[cities, cities];  //матрица растояний19            for (int i = 0; i < cities; i++)20                for (int j = i + 1; j < cities; j++)21                    MatrDistance[i, j] = rand.Next(5, 150);22            for (int i = 0; i < cities; i++)23                for (int j = 0; j < i; j++)24                    MatrDistance[i, j] = MatrDistance[j, i];2526            /*    Console.WriteLine("Длина пути от одного города к другому: ");27              Console.Write("   | ");28               for (int i = 0; i < cities; i++)29               {30                   if (i < 9)31                       Console.Write("{0}   ", i + 1);32                   else33                       Console.Write("{0}  ", i + 1);34               }353637               Console.WriteLine();38               Console.Write("---");39               for (int i = 0; i < cities; i++)40                   Console.Write("----");414243               Console.WriteLine();44               for (int i = 0; i < cities; i++)45               {46                   if (i < 9)47                       Console.Write("{0}  | ", i + 1);48                   else49                       Console.Write("{0} | ", i + 1);50                   for (int j = 0; j < cities; j++)51                   {52                       if (MatrDistance[i, j] > 9)53                           Console.Write("{0}  ", MatrDistance[i, j]);54                       else55                           Console.Write("{0}   ", MatrDistance[i, j]);56                   }57                   Console.WriteLine();58               }*/5960            StartCity = rand.Next(1, cities);61            EndCity = rand.Next(1, cities);62            if (StartCity == EndCity)63                StartCity = rand.Next(1, cities);64            Console.WriteLine("Город-отправитель: {0}, Город-получатель: {1}", StartCity, EndCity);65            osobi = 8;  66            Console.WriteLine("Кол-во особей в популяции: " + osobi);67            geny = 6;  68            Console.WriteLine("Кол-во генов у особи: " + geny);69            sw.Start();70            int[,] Individi = new int[osobi, geny];  //особи71            for (int i = 0; i < osobi; i++)72                for (int j = 0; j < geny; j++)73                    Individi[i, j] = rand.Next(0, cities);74            int[,] allFitnesses = new int[osobi, 2];  //пригодность каждой особи и её номер75            Console.WriteLine();76            Console.WriteLine("Поколение 1:");77            for (int i = 0; i < osobi; i++)78            {79                int fitness = 0;80                fitness += MatrDistance[StartCity - 1, Individi[i, 0]];81                Console.Write("Особь {0}, её гены: ", i + 1);82                for (int j = 0; j < geny; j++)83                {84                    if (Individi[i, j] < 9)85                        Console.Write("{0},  ", Individi[i, j] + 1);86                    else87                        Console.Write("{0}, ", Individi[i, j] + 1);88                    if (j > 0)89                        fitness += MatrDistance[Individi[i, j - 1], Individi[i, j]];90                }91                fitness += MatrDistance[Individi[i, geny - 1], EndCity - 1];92                Console.WriteLine(" Пригодность: " + fitness);93                allFitnesses[i, 0] = i;94                allFitnesses[i, 1] = fitness;95            }96            Console.WriteLine();97            int iterations = 0;98            do99            {100                iterations++;101                List<int[]> newIndividi = new List<int[]>(); //массив из потомства102                do103                {104                    int[] parent_1 = new int[geny];  //родители105                    int[] parent_2 = new int[geny];106                    //выбор родителей 107                    ViborParents(Individi, allFitnesses, ref parent_1, ref parent_2);108                    int[] child_1 = new int[geny];  //потомоки109                    int[] child_2 = new int[geny];110                    //скрещивание 111                    Crossing(parent_1, parent_2, ref child_1, ref child_2);112                    newIndividi.Add(child_1);113                    newIndividi.Add(child_2);114                } while (newIndividi.Count < osobi);  //формируем новую популяцию115                Mutation(ref newIndividi);  //мутация обменом соседних генов116                for (int i = 0; i < osobi; i++)  //объединение родителей и потомков117                {118                    newIndividi.Add(new int[geny]);119                    for (int j = 0; j < geny; j++)120                        newIndividi.Last()[j] = Individi[i, j];121                }122                Selection(MatrDistance, ref newIndividi);  //отбор особей в новое поколение методом усечения123                Console.WriteLine("Поколение {0}:", iterations + 1);124                OutputPopulation(MatrDistance, ref allFitnesses, newIndividi);125                int counter = 0;126                for (int i = 1; i < osobi; i++)  //подсчёт кол-ва особей с одинаковой пригодностью для остановки алгоритма127                    if (allFitnesses[i, 1] == allFitnesses[0, 1])128                        counter++;129                if (counter >= osobi * 0.75)130                    break;131                for (int i = 0; i < osobi; i++)132                    for (int j = 0; j < geny; j++)133                        Individi[i, j] = newIndividi[i][j];134            } while (iterations < 50);135            Console.WriteLine("Кол-во поколений: " + (iterations + 1));136            Console.Write("Найденный путь: " + StartCity);137            for (int i = 0; i < geny; i++)138                Console.Write(" -> " + (Individi[0, i] + 1));139            Console.WriteLine(" -> {0}, его длина: " + allFitnesses[0, 1], EndCity);140            Console.WriteLine("Длина прямого пути от {0} города к {1}: " + MatrDistance[StartCity - 1, EndCity - 1], StartCity, EndCity);141            142            sw.Stop();143            Console.WriteLine($"Времени потрачено - {sw.ElapsedMilliseconds} млс");144            Console.ReadLine();145        }146        static void Selection(int[,] MatrDistance, ref List<int[]> Individi)  //отбор усечением147        {148            Random rand = new Random();149            double T = 0.4;  //порог для отбора150            int fitness = 0;151            int[,] allFitnesses = new int[Individi.Count, 2];  //пригодность каждой особи и её номер152            for (int i = 0; i < Individi.Count; i++)  //вычисление пригодности каждой особи153            {154                fitness += MatrDistance[StartCity - 1, Individi[i][0]];155                for (int j = 1; j < geny; j++)156                    fitness += MatrDistance[Individi[i][j - 1], Individi[i][j]];157                fitness += MatrDistance[Individi[i][geny - 1], EndCity - 1];158                allFitnesses[i, 0] = i;159                allFitnesses[i, 1] = fitness;160                fitness = 0;161            }162            int[] temp = new int[Individi.Count];  //сортировка особей в порядке убывания их пригодности163            for (int i = 0; i < Individi.Count; i++)164                temp[i] = allFitnesses[i, 1];165            Array.Sort(temp);166            for (int i = 0; i < Individi.Count; i++)167                for (int j = 0; j < Individi.Count; j++)168                    if (temp[i] == allFitnesses[j, 1])169                    {170                        Swap(ref allFitnesses[i, 1], ref allFitnesses[j, 1]);171                        Swap(ref allFitnesses[i, 0], ref allFitnesses[j, 0]);172                        break;173                    }174            int countNewIndividi = (int)(Individi.Count * T);  //кол-во особей, прошедших через отбор175            List<int[]> newIndividi = new List<int[]>();176            int numberNewIndividi = 0;177            do  //отбор особей в новую популяцию178            {179                numberNewIndividi = rand.Next(0, countNewIndividi - 1);180                newIndividi.Add(new int[geny]);181                for (int i = 0; i < geny; i++)182                    newIndividi.Last()[i] = Individi[allFitnesses[numberNewIndividi, 0]][i];183            } while (newIndividi.Count < osobi);184            Individi.Clear();185            Individi = newIndividi;186        }187        static void ViborParents(int[,] Individi, int[,] allFitnesses, ref int[] parent_1, ref int[] parent_2)  //выбор родителей 188        {189            Random rand = new Random();190            int numberParent_1 = rand.Next(0, osobi - 1);  //выбор первого родителя          191            for (int i = 0; i < geny; i++)192                parent_1[i] = Individi[allFitnesses[numberParent_1, 0], i];193            double[] euclidDistance = new double[osobi];194            double mineuclidDistance = double.MaxValue;195            int numberParent_2 = 0;196            for (int i = 0; i < osobi; i++)  //вычисление Евклидова расстояния для выбора второго родителя197            {198                for (int j = 0; j < geny; j++)199                    euclidDistance[i] += Math.Pow(parent_1[j] - Individi[allFitnesses[i, 0], j], 2);200                euclidDistance[i] = Math.Sqrt(euclidDistance[i]);201                if (euclidDistance[i] < mineuclidDistance && euclidDistance[i] != 0)202                {203                    mineuclidDistance = euclidDistance[i];204                    numberParent_2 = i;205                }206            }207            for (int i = 0; i < geny; i++)208                parent_2[i] = Individi[allFitnesses[numberParent_2, 0], i];209        }210        static void Crossing(int[] parent_1, int[] parent_2, ref int[] child_1, ref int[] child_2)  //скрещивание методом дискретной рекомбинации211        {212            Random rand = new Random();213            int[,] mask_for_cross = new int[2, geny];  //маска для замены генов214            for (int i = 0; i < 2; i++)    //выбираем номера особи для замены генов215                for (int j = 0; j < geny; j++)216                    mask_for_cross[i, j] = rand.Next(0, 2);217            for (int i = 0; i < geny; i++)218            {219                if (mask_for_cross[0, i] == 1)  //замена генов для первого потомка220                    child_1[i] = parent_2[i];221                else222                    child_1[i] = parent_1[i];223                if (mask_for_cross[1, i] == 0)   //замена генов для второго потомка224                    child_2[i] = parent_1[i];225                else226                    child_2[i] = parent_2[i];227            }228        }229        static void Mutation(ref List<int[]> newIndividi)  //мутация методом обмена соседних генов230        {231            Random rand = new Random();232            double T = 0.3;  //вероятность мутации - порог233            double[] veroyatnost_mutation = new double[newIndividi.Count];234            for (int i = 0; i < newIndividi.Count; i++)235            {236                veroyatnost_mutation[i] = ((double)rand.Next(1, 100) / 100);  //случайно выбирается вероятность мутации для каждой особи237                if (veroyatnost_mutation[i] <= T)  //если вероятность мутации особи меньше порога238                {239                    int numOFgen = rand.Next(1, geny - 1);  //номер гена для мутации                    240                    if (newIndividi[i][numOFgen - 1] == newIndividi[i][numOFgen + 1])241                        numOFgen = rand.Next(0, geny - 1);242                    if (numOFgen == 0)243                        numOFgen++;244                    Swap(ref newIndividi[i][numOFgen - 1], ref newIndividi[i][numOFgen + 1]);245                }246            }247        }248        static void OutputPopulation(int[,] MatrDistance, ref int[,] allFitnesses, List<int[]> newIndividi)249        {250            int fitness = 0;251            for (int i = 0; i < osobi; i++)252            {253                fitness += MatrDistance[StartCity - 1, newIndividi[i][0]];254                Console.Write("Особь {0}, её гены: ", i + 1);255                for (int j = 0; j < geny; j++)256                {257                    if (newIndividi[i][j] < 9)258                        Console.Write("{0},  ", newIndividi[i][j] + 1);259                    else260                        Console.Write("{0}, ", newIndividi[i][j] + 1);261                    if (j > 0)262                        fitness += MatrDistance[newIndividi[i][j - 1], newIndividi[i][j]];263                }264                fitness += MatrDistance[newIndividi[i][geny - 1], EndCity - 1];265                Console.WriteLine(" пригодность: " + fitness);266                allFitnesses[i, 0] = i;267                allFitnesses[i, 1] = fitness;268                fitness = 0;269            }270            Console.WriteLine();271        }272        static void Swap<T>(ref T a, ref T b)273        {274            T temp = a;275            a = b;276            b = temp;277        }278    }279}...

Full Screen

Full Screen

TrueValuesGen.cs

Source:TrueValuesGen.cs Github

copy

Full Screen

12namespace Zygotine.WebExpo3{4    using System;5    using System.Text;6    using Zygotine.Statistics.Distribution;7    using Zygotine.Util;8    internal class TrueValuesGen9    {10        internal double[] LogY = new double[0];11        internal double[] Y = new double[0];12        internal double[] LogGT { get; set; } = new double[0];13        internal double[] GT { get; set; } = new double[0];14        internal double[] LogLT { get; set; } = new double[0];15        internal double[] LT { get; set; } = new double[0];16        internal double[] LogI { get; set; } = new double[0];17        internal double[] I = new double[0];18        private TrueValuesGen()19        {20        }21        public string Show()22        {23            string fmt = "Y={0}, GT={1}, LT={2}, I={3}";24            string fmt2 = "{0}, **LOG: {1}";25            StringBuilder sb = new StringBuilder();26            sb.AppendFormat(fmt2, string.Format(fmt, Y.ShowR(), GT.ShowR(), LT.ShowR(), I.ShowR()), string.Format(fmt, LogY.ShowR(), LogGT.ShowR(), LogLT.ShowR(), LogLT.ShowR()));27            return sb.ToString();28        }29        private TrueValuesGen(YGen genY, DataSummary data, double mu, double sigma, MeasurementError me, bool logNormalDistrn = true, GenObject o = null)30        {31            if (me.ThroughSD && !logNormalDistrn)32            {33                double meSD = me.Parm;34                double tauStar = 1 / Math.Pow(sigma, 2) + 1 / Math.Pow(meSD, 2);35                double sdStar = 1 / Math.Sqrt(tauStar);36                if (data.YLength > 0)37                {38                    double[] tmpMean = (data.Y.Divide(Math.Pow(meSD, 2)).Add(mu / Math.Pow(sigma, 2))).Divide(tauStar);39                    this.Y = NormalDistribution.RNorm(data.YLength, tmpMean, Tools.Rep(sdStar, tmpMean.Length));40                }41                if (data.GTLength > 0)42                {43                    double[] tmpMean = (genY.GT.Divide(Math.Pow(meSD, 2)).Add(mu / Math.Pow(sigma, 2))).Divide(tauStar);44                    this.Y = NormalDistribution.RNorm(data.GTLength, tmpMean, Tools.Rep(sdStar, tmpMean.Length));45                }46                if (data.LTLength > 0)47                {48                    double[] tmpMean = (genY.LT.Divide(Math.Pow(meSD, 2)).Add(mu / Math.Pow(sigma, 2))).Divide(tauStar);49                    this.Y = NormalDistribution.RNorm(data.GTLength, tmpMean, Tools.Rep(sdStar, tmpMean.Length));50                }51                if (data.IntervalLength > 0)52                {53                    double[] tmpMean = (genY.I.Divide(Math.Pow(meSD, 2)).Add(mu / Math.Pow(sigma, 2))).Divide(tauStar);54                    this.Y = NormalDistribution.RNorm(data.GTLength, tmpMean, Tools.Rep(sdStar, tmpMean.Length));55                }56            }57            else58            {59                o.A.Sigma2 = sigma * sigma;60                this.Y = new double[data.YLength];61                this.GT = new double[data.GTLength];62                this.LT = new double[data.LTLength];63                this.I = new double[data.IntervalLength];64                for (int j = 0; j < data.YLength; j++)65                {66                    this.Y[j] = TrueValueGen(o, me, data.Y[j], mu, logY: logNormalDistrn ? data.LogY[j] : Tools.ND);67                }68                for (int j = 0; j < data.GTLength; j++)69                {70                    this.GT[j] = TrueValueGen(o, me, genY.GT[j], mu, logY: logNormalDistrn ? genY.LogGT[j] : Tools.ND);71                }72                for (int j = 0; j < data.LTLength; j++)73                {74                    this.LT[j] = TrueValueGen(o, me, genY.LT[j], mu, logY: logNormalDistrn ? genY.LogLT[j] : Tools.ND);75                }76                for (int j = 0; j < data.IntervalLength; j++)77                {78                    this.I[j] = TrueValueGen(o, me, genY.I[j], mu, logY: logNormalDistrn ? genY.LogI[j] : Tools.ND);79                }80                if (logNormalDistrn)81                {82                    this.LogY = this.Y.Log();83                    this.LogGT = this.GT.Log();84                    this.LogLT = this.LT.Log();85                    this.LogI = this.I.Log();86                }87            }88        } //# end of truevalues.gen   89        internal static TrueValuesGen GetInstance(YGen genY, DataSummary data, double mu, double sigma, MeasurementError me, bool logNormalDistrn = true, GenObject o = null)90        {91            return new TrueValuesGen(genY, data, mu, sigma, me, logNormalDistrn, o);92        }93        private double TrueValueGen(GenObject genO, MeasurementError me, double y, double mu, double logY)94        {95            SGNFnAParam localA = genO.A.Clone();96            localA.Mu = mu;97            if (genO.LogNormalDistrn)98            {99                localA.LogY = logY;100            }101            localA.Y = y;102            localA.Y2 = y * y;103            if (genO.ThroughSD)104            {105                localA.Ksi = me.Parm;106                localA.Ksi2 = me.Parm * me.Parm;107            }108            else109            {110                localA.CV2 = me.Parm * me.Parm;111            }112            double[] start = genO.Start(localA);113            //start.Any(zz => !zz.IsFinite());114            Icdf icdf = new Icdf(genO, localA, range: genO.Range);115            double x = icdf.Bidon(start, inestLowerLim: !genO.LogNormalDistrn);116            if (genO.LogNormalDistrn)117            {118                x = Math.Exp(x);// # new_0.11119            }120            return x;121        } //# end of truevalue.gen122    }123}...

Full Screen

Full Screen

Form1.cs

Source:Form1.cs Github

copy

Full Screen

1using System;2using System.Collections.Generic;3using System.ComponentModel;4using System.Data;5using System.Drawing;6using System.Linq;7using System.Text;8using System.Threading;9using System.Threading.Tasks;10using System.Windows.Forms;11using System.Windows.Forms.DataVisualization.Charting;12namespace rbfNeuro13{14    public partial class Form1 : Form15    {16        public Form1()17        {18            InitializeComponent();19            generator = new Generator();20        }21        private const int Count = 20;22        private static Generator generator;23        private static double[] genY, genYNotSort,24                                chartVal = new double[Count],25                                chartX = new double[Count];26        double deltaX;27        private void GetXArray(double[] generated, out double[] masX, out double[] masY)28        {29            int i = 0;30            masX = new double[Count];31            masY = new double[Count];32           // generated = generated.Select(o => o / 10).ToArray();33            deltaX = (generated.Max() - generated.Min()) / Count;34            for (double val1 = generated[0], val2 = val1 + deltaX; i < Count; maasss[i] = val1, masX[i] = val1 + deltaX / 2, val1 = val2, val2 += deltaX, i++)35                for (int k = 0; k < generated.Length; k++)36                    if (generated[k] >= val1 && generated[k] < val2)37                        masY[i]++;38            double minY = masY.Min();39            double dif = masY.Max() - minY;40            for (int k = 0; k < masY.Length; k++)41            {42                //masY[k] = masY[k] / masY.Length;43                masY[k] = (masY[k] - minY) / dif;44            }45        }46        double[] maasss = new double[Count];47        Layer layer;48        List<double> errors = new List<double>();49        private void button3_Click(object sender, EventArgs e)50        {51          52            double error = 0;53            layer.Neurons.ForEach(o => o.Impulse = 0);54            layer.Output = 0;55            double[] masX;56            double[] masY;57            GetXArray(generator.Generate(5000, Generator.rand.NextDouble() * 3).OrderBy(o => o).Select(o => o / 1.1).ToArray(), out masX, out masY);58            double[] neuroOutput = new double[Count];59            for (int i = 0; i < masX.Length; i++)60            {61                layer.LinearSum(masX[i]);62                neuroOutput[i] = layer.Output;63                error += (Math.Pow(masY[i] - layer.Output, 2));64            }65            errors.Add(Math.Sqrt(error / (Count - 1)));66            // ToChart(2, masX, masY);67            ToChart(3, masX, neuroOutput);68        }69        private void button2_Click(object sender, EventArgs e)70        {71            layer = new Layer(Count, chartX, deltaX / Math.Sqrt(45));72            double n = 0.0012;///////////////////////////////////////////////73            for (int p = 0; p < 80; p++)74            {75                genYNotSort = generator.Generate(5000, 1 /*Generator.rand.NextDouble() * 3*/);76                genY = genYNotSort.OrderBy(o => o).ToArray();77                GetXArray(genY, out chartX, out chartVal);78                int Iter = 8000;79                double[] err = new double[Iter * Count];80                double[] indexes = new double[Iter * Count];81                for (int i = 0; i < Iter * Count; i++)82                    indexes[i] = i;83                label1.Text = "....";84                ////Thread t = new Thread(() =>85                ////{86                    for (int i = 0; i < Iter; i++)87                    {88                        double[] m = new double[Count];89                        for (int k = 0; k < Count; k++)90                        {91                            layer.GoLearn(n, chartVal[k],/* chartX*/ maasss[k]);92                            layer.CalcE(chartVal[k], 0.00001);93                        /// { label1.Text = "готово"; return; }94                        err[k * i] = layer.E;95                            m[k] = layer.Output;96                        }97                       // chart1.Invoke((MethodInvoker)delegate ()98                        //{99                            ToChart(1, chartX, m);100                       // });101                    }102                    //label1.Invoke((MethodInvoker)delegate ()103                    //{104                        label1.Text = "готово";105                    //});106               // });107                //t.Start();108            }109        }110        private void ToChart(int ind, double[] x, double[] y)111        {112            chart1.Series[0].ChartType = SeriesChartType.Line;113            chart1.Series[0].Points.DataBindXY(x, y);114        }115        private void button1_Click(object sender, EventArgs e)116        {117            genYNotSort = generator.Generate(5000, 1/* Generator.rand.NextDouble() * 3*/);118            genY = genYNotSort.OrderBy(o => o).ToArray();119            GetXArray(genY, out chartX, out chartVal);120            ToChart(0, chartX, chartVal);121        }122    }123}...

Full Screen

Full Screen

ScanrangeCalc.cs

Source:ScanrangeCalc.cs Github

copy

Full Screen

1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using UnityEngine;67public class ScanrangeCalc8{9    public ScanrangeCalc()10    {11        InitializeTables();12    }1314    private sbyte[,,] pTablesOffset = new sbyte[41, 41, 2];15    private int[,] pTablesCost = new int[41, 41];16    public int[,] pTablesVision = new int[41, 41];1718    public byte ScanShift = 7;1920    private bool SetCell(int x, int y, int height_origin, int height_cell)21    {22        int vision_previous = pTablesVision[x + pTablesOffset[x, y, 0], y + pTablesOffset[x, y, 1]];23        int cost = pTablesCost[x, y];24        pTablesVision[x, y] = vision_previous - (height_cell - height_origin + cost);25        return (pTablesVision[x, y] >= 0);26    }2728    public void InitializeTables()29    {30        uint ulScanShifted = 1u << ScanShift;3132        for (int i = 0; i <= 20; ++i)33        {34            for (int j = 0; j <= 20; ++j)35            {36                int v1 =  i > 0 || j > 0 ?  (int)(Math.Pow((j * j + i * i), 0.5) / Math.Max(i,j) * ulScanShifted) : 0;3738                pTablesCost[20 + i, 20 + j] = v1;39                pTablesCost[20 + i, 20 - j] = v1;40                pTablesCost[20 - i, 20 + j] = v1;41                pTablesCost[20 - i, 20 - j] = v1;4243                if (j < (i / 2))44                {45                    pTablesOffset[20 + i, 20 + j, 0] = -1;46                    pTablesOffset[20 + i, 20 + j, 1] = 0;47                    pTablesOffset[20 - i, 20 - j, 0] = 1;48                    pTablesOffset[20 - i, 20 - j, 1] = 0;49                    pTablesOffset[20 + i, 20 - j, 0] = -1;50                    pTablesOffset[20 + i, 20 - j, 1] = 0;51                    pTablesOffset[20 - i, 20 + j, 0] = 1;52                    pTablesOffset[20 - i, 20 + j, 1] = 0;5354                } 55                else if (j > (i * 2))56                {57                    pTablesOffset[20 + i, 20 + j, 0] = 0;58                    pTablesOffset[20 + i, 20 + j, 1] = -1;59                    pTablesOffset[20 - i, 20 - j, 0] = 0;60                    pTablesOffset[20 - i, 20 - j, 1] = 1;61                    pTablesOffset[20 + i, 20 - j, 0] = 0;62                    pTablesOffset[20 + i, 20 - j, 1] = 1;63                    pTablesOffset[20 - i, 20 + j, 0] = 0;64                    pTablesOffset[20 - i, 20 + j, 1] = -1;65                }66                else67                {68                    pTablesOffset[20 + i, 20 + j, 0] = -1;69                    pTablesOffset[20 + i, 20 + j, 1] = -1;70                    pTablesOffset[20 - i, 20 - j, 0] = 1;71                    pTablesOffset[20 - i, 20 - j, 1] = 1;72                    pTablesOffset[20 + i, 20 - j, 0] = -1;73                    pTablesOffset[20 + i, 20 - j, 1] = 1;74                    pTablesOffset[20 - i, 20 + j, 0] = 1;75                    pTablesOffset[20 - i, 20 + j, 1] = -1;76                }77            }78        }7980        pTablesCost[20, 20] = 0;81    }8283    private bool CheckValid(int x, int y)84    {85        return (x >= 8 && y >= 8 && x < MapLogic.Instance.Width - 8 && y < MapLogic.Instance.Height - 8);86    }8788    private int GetHeight(int x, int y)89    {90        if (x < 0 || y < 0 || x >= MapLogic.Instance.Width || y >= MapLogic.Instance.Height)91            return 0;92        return MapLogic.Instance.Nodes[x, y].Height;93    }9495    public void CalculateVision(int x, int y, float scanrangef)96    {97        // we need to make scanshifted scanrange from float.98        int scanrange = (int)scanrangef;99        scanrange = (scanrange << 8) | (int)((scanrangef - scanrange) * 255);100101        for (int ly = 0; ly < 41; ly++)102            for (int lx = 0; lx < 41; lx++)103                pTablesVision[lx, ly] = 0;104105        int vision = scanrange;106        int vision2 = (1 << (ScanShift - 1)) + (vision >> (8 - ScanShift));107108        int genX = x - 20;109        int genY = y - 20;110        int ht_origin = GetHeight(x, y);111112        pTablesVision[20, 20] = vision2;113        for(int i = 1; i < 20; i++)114        {115            bool fdisp = false;116            for(int j = -i; j < i+1; j++)117            {118                if(CheckValid(genX+(20+j), genY+(20-i)) &&119                   SetCell(20+j, 20-i, ht_origin, GetHeight(genX+(20+j), genY+(20-i))))120                    fdisp = true;121                if(CheckValid(genX+(20+j), genY+(20+i)) &&122                   SetCell(20+j, 20+i, ht_origin, GetHeight(genX+(20+j), genY+(20+i))))123                    fdisp = true;124                if(CheckValid(genX+(20-i), genY+(20+j)) &&125                   SetCell(20-i, 20+j, ht_origin, GetHeight(genX+(20-i), genY+(20+j))))126                    fdisp = true;127                if(CheckValid(genX+(20+i), genY+(20-j)) &&128                   SetCell(20+i, 20-j, ht_origin, GetHeight(genX+(20+i), genY+(20-j))))129                    fdisp = true;130            }131132		    if(!fdisp) break;133        }134    }
...

Full Screen

Full Screen

TrelamiumTile.cs

Source:TrelamiumTile.cs Github

copy

Full Screen

1using Terraria;2using Terraria.ID;3using Terraria.ModLoader;4using Microsoft.Xna.Framework;5using TrelamiumTwo.Content.Items.Materials;6using TrelamiumTwo.Helpers;7namespace TrelamiumTwo.Common.Tiles8{9	public class TrelamiumTile : GlobalTile10	{11		private const float nutSpawnChance = 0.05f;12		private const float leafSpawnChance = 0.025f;13		private Player player;14		public override void RandomUpdate(int i, int j, int type)15		{16			if (Main.tile[i, j].nactive())17			{18				if ((type == TileID.Grass || type == TileID.HallowedGrass) && Main.rand.Next(55) == 0)19				{20					TryBloomRose(i, j);21				}22			}23		}24		public override void FloorVisuals(int type, Player player)25		{26			player.GetModPlayer<Players.TrelamiumPlayer>().onSand =27				(TileID.Sets.Conversion.Sand[type] || TileID.Sets.Conversion.Sandstone[type] || TileID.Sets.Conversion.HardenedSand[type]);28		}29		private void TryBloomRose(int genX, int genY)30		{31			int scatteredFlowerRadiusCheck = 5;32			int scatteredFlowerType = ModContent.TileType<Content.Tiles.Ambience.BloomRose>();33			if (genX < 95 || genX > Main.maxTilesX - 95 || genY < 95 || genY > Main.worldSurface)34			{35				return;36			}37			Tile topTile = Framing.GetTileSafely(genX, genY - 1);38			if (topTile.active() && topTile.type != scatteredFlowerType)39			{40				return;41			}42			int minX = Utils.Clamp(genX - scatteredFlowerRadiusCheck, 1, Main.maxTilesX - 2);43			int maxX = Utils.Clamp(genX + scatteredFlowerRadiusCheck, 1, Main.maxTilesX - 2);44			int minY = Utils.Clamp(genY - scatteredFlowerRadiusCheck, 1, Main.maxTilesY - 2);45			int maxY = Utils.Clamp(genY + scatteredFlowerRadiusCheck, 1, Main.maxTilesY - 2);46			for (int x = minX; x < maxX; ++x)47			{48				for (int y = minY; y < maxY; ++y)49				{50					Tile t = Framing.GetTileSafely(x, y);51					if (t.active() && t.type == scatteredFlowerType)52					{53						return;54					}55				}56			}57			WorldGen.PlaceTile(genX, genY - 1, scatteredFlowerType, true);58		}59		public override void KillTile(int i, int j, int type, ref bool fail, ref bool effectOnly, ref bool noItem)60		{61			player = Main.LocalPlayer;62			if (!effectOnly)63			{64				if (player.ZoneForest())65				{66					if (Main.netMode != NetmodeID.MultiplayerClient && type == TileID.Trees)67					{68						TrySpawnLeaf(i, j);69						TrySpawnNut(i, j, fail);70					}71				}72			}73		}74		private void TrySpawnNut(int x, int y, bool fail)75		{76			if (fail || Main.rand.NextFloat() > nutSpawnChance)77			{78				return;79			}80			while (y > 10 && Main.tile[x, y].active() && Main.tile[x, y].type == TileID.Trees)81			{82				y--;83			}84			y++;85			if (!IsTileALeafyTreeTop(x, y) || Collision.SolidTiles(x - 2, x + 2, y - 2, y + 2))86			{87				return;88			}89			Item.NewItem(new Vector2(x * 16, y * 16), ModContent.ItemType<Nut>(), Main.rand.Next(5));90		}91		private void TrySpawnLeaf(int x, int y)92		{93			if (Main.rand.NextFloat() > leafSpawnChance)94			{95				return;96			}97			while (y > 10 && Main.tile[x, y].active() && Main.tile[x, y].type == TileID.Trees)98			{99				y--;100			}101			y++;102			if (!IsTileALeafyTreeTop(x, y) || Collision.SolidTiles(x - 2, x + 2, y - 2, y + 2))103			{104				return;105			}106			int velocityXDir = Main.rand.Next(2) * 2 - 1;107			int projectileType = ModContent.ProjectileType<Content.Projectiles.Typeless.FallingLeaf>();108			Projectile.NewProjectile(x * 16, y * 16, Main.rand.NextFloat(2f) * velocityXDir, 0f, projectileType, 0, 0f, Player.FindClosest(new Vector2(x * 16, y * 16), 16, 16));109		}110		private bool IsTileALeafyTreeTop(int i, int j)111		{112			Tile tileSafely = Framing.GetTileSafely(i, j);113			if (tileSafely.active() && tileSafely.type == TileID.Trees)114			{115				if (tileSafely.frameX == 22 && tileSafely.frameY >= 198 && tileSafely.frameY <= 242)116				{117					return true;118				}119			}120			return false;121		}122	}123}...

Full Screen

Full Screen

MEParmGen.cs

Source:MEParmGen.cs Github

copy

Full Screen

12namespace Zygotine.WebExpo3{4    using System.Linq;5    using Zygotine.Util;6    internal class MEParmGen7    {8        public double Parm { get; private set; }9        private MEParmGen()10        {11        }12        internal static MEParmGen GetInstance(GenObject o, MeasurementError me, DataSummary data, YGen genY, TrueValuesGen genTV)13        {14            MEParmGen instance = new MEParmGen();15            double b;16            double[] tmpY, tmpT;17            if (me.ThroughCV)18            {19                if (o.LogNormalDistrn)20                {21                    tmpY = Tools.Combine(data.LogY, genY.LogGT, genY.LogLT, genY.LogI);22                    tmpT = Tools.Combine(genTV.LogY, genTV.LogGT, genTV.LogLT, genTV.LogI);23                    b = tmpY.Substract(tmpT).Exp().Substract(1.0).Sqr().Sum();24                    b /= 2.0;25                }26                else27                {28                    tmpY = Tools.Combine(data.Y, genY.GT, genY.LT, genY.I);29                    tmpT = Tools.Combine(genTV.Y, genTV.GT, genTV.LT, genTV.I);30                    b = tmpY.Divide(tmpT).Substract(1.0).Sqr().Reverse().Sum();31                    b /= 2.0;32                }33                SGNFnAParam localA = o.A.Clone();34                localA.B = b;35                localA.Range = me.GetRange();36                double[] range = me.GetRange();37                Icdf icdf = new Icdf(o, localA, range);38                instance.Parm = icdf.Bidon(o.Start(localA), inestLowerLim: range[0] == 0);39            }40            else41            {42                tmpY = Tools.Combine(data.Y, genY.GT, genY.LT, genY.I);43                tmpT = Tools.Combine(genTV.Y, genTV.GT, genTV.LT, genTV.I);44                b = tmpY.Substract(tmpT).Sqr().Sum();45                b /= 2.0;46                if (o.LogNormalDistrn)47                {48                    SGNFnAParam localA = o.A.Clone();49                    localA.B = b;50                    localA.Range = me.GetRange();51                    localA.Truevalues = Tools.Copy(tmpT);52                    //me.parm <- dens.gen.icdf(o, A, range=me$range, inestimable.lower.limit=me$range[1]==0)53                    double[] range = me.GetRange();54                    Icdf icdf = new Icdf(o, localA, range);55                    instance.Parm = icdf.Bidon(inestLowerLim: range[0] == 0.0);56                }57                else58                {59                    instance.Parm = WebExpoFunctions3.SqrtInvertedGammaGen(data.N, b, me.GetRange(), o);60                }61            }62            return instance;63        }64    }65}...

Full Screen

Full Screen

OutLogoutMoments.cs

Source:OutLogoutMoments.cs Github

copy

Full Screen

1namespace Zygotine.WebExpo2{3    using System.Linq;4    using Zygotine.Util;5    internal class OutLogoutMoments6    {7        public double Sum { get; private set; }8        public double Sum2 { get; private set; }9        private OutLogoutMoments()10        {11        }12        public static OutLogoutMoments Get(bool anyME, bool logNormalDistrn, DataSummary data, YGen genY, TrueValuesGen genTV)13        {14            OutLogoutMoments olm = new OutLogoutMoments();15            if (anyME)16            {17                double[] y;18                if (logNormalDistrn)19                {20                    y = Tools.Combine(genTV.LogY, genTV.LogGT, genTV.LogLT, genTV.LogI);21                }22                else23                {24                    y = Tools.Combine(genTV.Y, genTV.GT, genTV.LT, genTV.I);25                }26                olm.Sum = y.Sum();27                olm.Sum2 = y.Sqr().Sum();28                return olm;29            }30            else if (logNormalDistrn)31            {32                olm.Sum = data.LogUncensoredSum;33                olm.Sum2 = data.LogUncensoredSum2;34                olm.Sum += genY.LogGT.Sum() + genY.LogLT.Sum() + genY.LogI.Sum();35                olm.Sum2 += genY.LogGT.Sqr().Sum() + genY.LogLT.Sqr().Sum() + genY.LogI.Sqr().Sum();36            }37            else38            {39                olm.Sum = data.UncensoredSum;40                olm.Sum2 = data.UncensoredSum2;41                olm.Sum += genY.GT.Sum() + genY.LT.Sum() + genY.I.Sum();42                olm.Sum2 += genY.GT.Sqr().Sum() + genY.LT.Sqr().Sum() + genY.I.Sqr().Sum();43            }44            return olm;45        }46    }47}...

Full Screen

Full Screen

GenyDriverMethodCaller.cs

Source:GenyDriverMethodCaller.cs Github

copy

Full Screen

1using System;2using System.Collections.Generic;3using System.ComponentModel;4using System.Data;5using System.Drawing;6using System.Text;7using System.Windows.Forms;8namespace MethodCaller9{10    public partial class GenyDriverMethodCaller : MethodCaller.MethodCallerMain11    {12        public GenyDriverMethodCaller()13        {14            InitializeComponent();15            this.Load += new EventHandler(GenyDriverMethodCaller_Load);16        }17        void GenyDriverMethodCaller_Load(object sender, EventArgs e)18        {19            this.label2.Visible = false;20            this.label3.Visible = false;21            this.cbbSerialPorts.Visible = false;22            this.tbSerialPortConfig.Visible = false;23        }24        protected override object GetDriver()25        {26            return new DeviceDriver.Driver(24);27        }28        protected override System.Reflection.MethodInfo[] GetMethods()29        {30            return ReflectUtil.GetMethod(typeof(DeviceDriver.Driver));31        }32    }33}...

Full Screen

Full Screen

GenY

Using AI Code Generation

copy

Full Screen

1using B;2{3    {4        public static void Main()5        {6            GenY gy = new GenY();7            gy.Show();8        }9    }10}11using C;12{13    {14        public void Show()15        {16            GenZ gz = new GenZ();17            gz.Show();18        }19    }20}21using C;22{23    {24        public void Show()25        {26            GenZ gz = new GenZ();27            gz.Show();28        }29    }30}31using C;32{33    {34        public void Show()35        {36            GenZ gz = new GenZ();37            gz.Show();38        }39    }40}41using C;42{43    {44        public void Show()45        {46            GenZ gz = new GenZ();47            gz.Show();48        }49    }50}51using C;52{53    {54        public void Show()55        {56            GenZ gz = new GenZ();57            gz.Show();58        }59    }60}61using C;62{63    {64        public void Show()65        {66            GenZ gz = new GenZ();67            gz.Show();68        }69    }70}71using C;72{73    {74        public void Show()75        {76            GenZ gz = new GenZ();77            gz.Show();78        }79    }80}81using C;82{83    {84        public void Show()85        {86            GenZ gz = new GenZ();

Full Screen

Full Screen

GenY

Using AI Code Generation

copy

Full Screen

1using B;2{3public void show()4{5Console.WriteLine("GenY");6}7}8using C;9{10public void show()11{12Console.WriteLine("GenZ");13}14}15using A;16{17public void show()18{19Console.WriteLine("GenA");20}21}22using B;23{24public void show()25{26Console.WriteLine("GenB");27}28}29using C;30{31public void show()32{33Console.WriteLine("GenC");34}35}36using D;37{38public void show()39{40Console.WriteLine("GenD");41}42}43using E;44{45public void show()46{47Console.WriteLine("GenE");48}49}50using F;51{52public void show()53{54Console.WriteLine("GenF");55}56}57using G;58{59public void show()60{61Console.WriteLine("GenG");62}63}64using H;65{66public void show()67{68Console.WriteLine("GenH");69}70}71using I;72{73public void show()74{75Console.WriteLine("GenI");76}77}78using J;79{80public void show()81{82Console.WriteLine("GenJ");83}84}

Full Screen

Full Screen

GenY

Using AI Code Generation

copy

Full Screen

1using B;2{3public static void Main()4{5GenY obj = new GenY();6obj.print();7}8}9Microsoft (R) Visual C# Compiler version 1.1.4322.240810Microsoft (R) Visual C# Compiler version 1.1.4322.2408

Full Screen

Full Screen

GenY

Using AI Code Generation

copy

Full Screen

1using B;2{3  public static void Main()4  {5    GenY g = new GenY();6  }7}8GenX.Show()9GenY.Show()

Full Screen

Full Screen

GenY

Using AI Code Generation

copy

Full Screen

1using B;2{3    public GenY()4    {5        Console.WriteLine("GenY");6    }7}8using C;9{10    public GenZ()11    {12        Console.WriteLine("GenZ");13    }14}15using C;16{17    public static void Main()18    {19        GenZ obj = new GenZ();20        Console.ReadLine();21    }22}

Full Screen

Full Screen

GenY

Using AI Code Generation

copy

Full Screen

1using B;2{3    static void Main()4    {5        GenY g = new GenY();6        g.ShowXY();7    }8}9{10    public unsafe void ShowXY()11    {12        Console.WriteLine("XY");13    }14}

Full Screen

Full Screen

Nunit tutorial

Nunit is a well-known open-source unit testing framework for C#. This framework is easy to work with and user-friendly. LambdaTest’s NUnit Testing Tutorial provides a structured and detailed learning environment to help you leverage knowledge about the NUnit framework. The NUnit tutorial covers chapters from basics such as environment setup to annotations, assertions, Selenium WebDriver commands, and parallel execution using the NUnit framework.

Chapters

  1. NUnit Environment Setup - All the prerequisites and setup environments are provided to help you begin with NUnit testing.
  2. NUnit With Selenium - Learn how to use the NUnit framework with Selenium for automation testing and its installation.
  3. Selenium WebDriver Commands in NUnit - Leverage your knowledge about the top 28 Selenium WebDriver Commands in NUnit For Test Automation. It covers web browser commands, web element commands, and drop-down commands.
  4. NUnit Parameterized Unit Tests - Tests on varied combinations may lead to code duplication or redundancy. This chapter discusses how NUnit Parameterized Unit Tests and their methods can help avoid code duplication.
  5. NUnit Asserts - Learn about the usage of assertions in NUnit using Selenium
  6. NUnit Annotations - Learn how to use and execute NUnit annotations for Selenium Automation Testing
  7. Generating Test Reports In NUnit - Understand how to use extent reports and generate reports with NUnit and Selenium WebDriver. Also, look into how to capture screenshots in NUnit extent reports.
  8. Parallel Execution In NUnit - Parallel testing helps to reduce time consumption while executing a test. Deep dive into the concept of Specflow Parallel Execution in NUnit.

NUnit certification -

You can also check out the LambdaTest Certification to enhance your learning in Selenium Automation Testing using the NUnit framework.

YouTube

Watch this tutorial on the LambdaTest Channel to learn how to set up the NUnit framework, run tests and also execute parallel testing.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful