/// <summary>
        /// Performs all socket listening actions.
        /// </summary>
        private void Listen()
        {
            try
            {
                while (true)
                {
                    if (!sck.Connected)
                    {
                        throw new SocketException(10054);
                    }

                    localBuffer = new byte[sck.SendBufferSize];

                    int bytesRead = sck.Receive(localBuffer, sck.SendBufferSize, SocketFlags.None);

                    if (bytesRead == 0)
                    {
                        Connected = false;
                        Debug.WriteLine("Server disconnected. Closing socket...");
                        sck.Close();
                        Debug.WriteLine("Socket closed. Successfully disconnected from server.");
                        tsslStatus.Text = "Disconnected from receiver.";
                    }


                    /** Format buffer to take care of whitespace or extra crap*/
                    List <byte> formatted = new List <byte>(bytesRead);
                    for (int i = 0; i < bytesRead; i++)
                    {
                        if (localBuffer[i] != default(byte))
                        {
                            formatted.Add(localBuffer[i]);
                        }
                    }

                    string strData = Encoding.ASCII.GetString(formatted.ToArray()).Trim();
                    if (string.IsNullOrWhiteSpace(strData))
                    {
                        continue;
                    }
                    List <string> toks     = strData.Split(' ').ToList();
                    string        protocol = toks[0];

                    if (Numerics.ContainsKey(protocol))
                    {
                        Numerics[protocol](toks);
                    }
                    else
                    {
                        Debug.WriteLine("Server sent erroneous protocol. Message was '" + strData + "'");
                    }
                }
            }
            catch (SocketException error)
            {
                Debug.WriteLine("Socket error: " + error.Message);
                tsslStatus.Text = "Disconnected from receiver.";
            }
        }
Exemplo n.º 2
0
 public void ClampNoIntrinsics()
 {
     for (int i = 0; i < A.Length; i++)
     {
         ref int x = ref A[i];
         x = Numerics.Clamp(x, 64, 128);
     }
Exemplo n.º 3
0
        public IHttpActionResult GetPc1Province()
        {
            var request    = HttpContext.Current.Request;
            var length     = Numerics.GetInt(request["length"] + "");
            var draw       = request["draw"] + "";
            var start      = Numerics.GetInt(request["start"] + "");
            var orderIndex = Numerics.GetInt(request["order[0][column]"] + "");
            var orderWise  = request["order[0][dir]"] + "";
            var search     = request["search[value]"] + "";
            var rows       = 0;
            var result     = new List <AdpPC1>();

            var year_id = db.tbl_adp.OrderByDescending(x => x.auto_ADP_id).FirstOrDefault().auto_ADP_id;

            result = db.tbl_ADP_Serial.Where(x => x.auto_ADP_id == year_id && x.ProjectName != null && x.Allocation != null && x.serial_no_ADP != null).Select(x => new AdpPC1
            {
                Serial = x.serial_no_ADP,
                Name   = x.ProjectName,
                Cost   = x.Allocation + "",
                Year   = x.auto_ADP_id + ""
            }).ToList();
            var tempList = result.Skip(start).Take(length).ToList();

            return(Json(new
            {
                draw = draw,
                recordsFiltered = result.Count(),
                recordsTotal = result.Count(),
                data = tempList
            }));
        }
Exemplo n.º 4
0
        private void DrawRect()
        {
            Point MinPoint = Numerics.GetMinXY_Tooth(Points);
            Point MaxPoint = Numerics.GetMaxXY_Tooth(Points);

            Border_WrapTooth.Height = MaxPoint.Y - MinPoint.Y + padding;
            Border_WrapTooth.Width  = MaxPoint.X - MinPoint.X + padding;

            Top  = MinPoint.Y - padding / 2;
            Left = MinPoint.X - padding / 2;

            Canvas.SetTop(this, Top);
            Canvas.SetLeft(this, Left);

            //MoveTop.X1 = Border_WrapTooth.Width / 2;
            //MoveTop.Y1 = -50;
            //MoveTop.X2 = Border_WrapTooth.Width / 2;
            //MoveTop.Y2 = -30;

            MoveTop.TopX    = Border_WrapTooth.Width / 2;
            MoveTop.TopY    = -50;
            MoveTop.BottomX = Border_WrapTooth.Width / 2;
            MoveTop.BottomY = -30;
            MoveTop.LeftX   = Border_WrapTooth.Width / 2 - 10;
            MoveTop.LeftY   = -40;
            MoveTop.RightX  = Border_WrapTooth.Width / 2 + 10;
            MoveTop.RightY  = -40;
        }
Exemplo n.º 5
0
        private void DrawTeethBetweenLine(List <List <Point> > points)
        {
            List <double> listX1 = new List <double>();

            double coorX;

            foreach (var teeth in points)
            {
                coorX = Numerics.GetMaxX_Teeth(teeth).X - Left;
                listX1.Add(coorX);
            }
            List <Point> lastTeeth = points[5];  // CanineL

            coorX = Numerics.GetMinX_Teeth(lastTeeth).X - Left;
            listX1.Add(coorX);

            int i = 0;

            foreach (var l in Grid_WrapTooth.Children)
            {
                if (l is Line)
                {
                    Line line = l as Line;
                    line.X1 = listX1[i];
                    line.Y1 = 0;
                    line.X2 = listX1[i++];
                    line.Y2 = Border_WrapTooth.Height;
                }
            }
        }
        }//*/

        public IEnumerable <ProductMatch> GetProductMZs(DBOptions options, GraphML_List <MsMsPeak> peaks)//, List<double> theoretical_product_mzs = null)
        {
            // speed optimizations
            //double[] experimental_masses = Query.spectrum.Masses;
            //GraphML_List<MSPeak> peaks = Query.spectrum.Peaks;
            int num_experimental_peaks = peaks.Count;

            TotalTheoreticalProducts = 0;
            TotalWeightedProducts    = 0;
            //New version that should include charged ions

            //foreach (ProductMatch matchTheo in AllFragmentSearch.ComputeAllFragments(Peptide, Query.precursor.Charge, options))
            foreach (ProductMatch matchTheo in options.fragments.ComputeFragmentsFast(Peptide.GetMasses(), Query.precursor.Charge, options))
            //foreach (ProductMatch matchTheo in options.fragments.ComputeFragments(Peptide, Query.precursor.Charge, options))
            {
                TotalTheoreticalProducts++;
                TotalWeightedProducts += matchTheo.weight;//++;
                //TODO test what is most common between charged ions, and uncharged ions
                //for (int charge = 1; charge <= Query.precursor.Charge; charge++)
                //for (int charge = Query.precursor.Charge; charge >= 1; charge--)
                //{
                double massDiff = options.productMassTolerance.Value;
                double bestMz   = -1;
                double bestInt  = 0;

                foreach (int index in Query.spectrum.GetIndexOfMZInRange(matchTheo.theoMz, options.productMassTolerance))
                {
                    if (peaks[index].Charge <= 0 || peaks[index].Charge == matchTheo.charge)
                    {
                        double diff = Numerics.CalculateMassError(peaks[index].MZ, matchTheo.theoMz, options.productMassTolerance.Units);
                        //double diff = matchTheo.theoMz - peaks[index].MZ;// experimental_masses[index];//TODO DALTON ONLY : add product mass tolerance unit test
                        if (Math.Abs(diff) < options.productMassTolerance.Value)
                        {
                            if (Math.Abs(diff) < Math.Abs(massDiff))//TODO Priority to intensity, or precision?
                            {
                                massDiff = diff;
                                bestMz   = peaks[index].MZ;
                            }
                            //if (peaks[index].Intensity > bestInt)
                            bestInt += peaks[index].Intensity;
                        }
                    }
                }
                if (bestMz >= 0)
                {
                    ProductMatch pMatch = new ProductMatch();
                    pMatch.weight              = matchTheo.weight;
                    pMatch.theoMz              = matchTheo.theoMz; // Utilities.MZFromMzSingleCharge(theoMass, charge);
                    pMatch.obsMz               = bestMz;           // experimental_masses[bestIndex];
                    pMatch.mass_diff           = massDiff;
                    pMatch.obsIntensity        = bestInt;          // Intensities[bestIndex];
                    pMatch.charge              = matchTheo.charge; // peaks[bestIndex].Charge;
                    pMatch.Fragment            = matchTheo.Fragment;
                    pMatch.fragmentPos         = matchTheo.fragmentPos;
                    pMatch.normalizedIntensity = pMatch.obsIntensity / (Query.spectrum.InjectionTime * Query.spectrum.PrecursorIntensityPerMilliSecond);
                    yield return(pMatch);
                    //break;
                }
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Initializes quantization tables.
        /// </summary>
        /// <remarks>
        /// We take quality values in a hierarchical order:
        /// 1. Check if encoder has set quality
        /// 2. Check if metadata has special table for encoding
        /// 3. Check if metadata has set quality
        /// 4. Take default quality value - 75
        /// </remarks>
        /// <param name="componentCount">Color components count.</param>
        /// <param name="metadata">Jpeg metadata instance.</param>
        /// <param name="luminanceQuantTable">Output luminance quantization table.</param>
        /// <param name="chrominanceQuantTable">Output chrominance quantization table.</param>
        private void InitQuantizationTables(int componentCount, JpegMetadata metadata, out Block8x8F luminanceQuantTable, out Block8x8F chrominanceQuantTable)
        {
            int lumaQuality;
            int chromaQuality;

            if (this.quality.HasValue)
            {
                lumaQuality   = this.quality.Value;
                chromaQuality = this.quality.Value;
            }
            else
            {
                lumaQuality   = metadata.LuminanceQuality;
                chromaQuality = metadata.ChrominanceQuality;
            }

            // Luminance
            lumaQuality         = Numerics.Clamp(lumaQuality, 1, 100);
            luminanceQuantTable = Quantization.ScaleLuminanceTable(lumaQuality);

            // Chrominance
            chrominanceQuantTable = default;
            if (componentCount > 1)
            {
                chromaQuality         = Numerics.Clamp(chromaQuality, 1, 100);
                chrominanceQuantTable = Quantization.ScaleChrominanceTable(chromaQuality);

                if (!this.colorType.HasValue)
                {
                    this.colorType = chromaQuality >= 91 ? JpegColorType.YCbCrRatio444 : JpegColorType.YCbCrRatio420;
                }
            }
        }
Exemplo n.º 8
0
        internal void Initialize_SunnyCrossFilter(string name           = "SunnyCross",
                                                  float sampleLength    = 1.0f,
                                                  float attenuation     = 0.88f,
                                                  float longAttenuation = 0.95f,
                                                  float inclination     = 0)
        {
            this.name        = name;
            this.inclination = inclination;
            this.StarLines   = new Starline[8];
            this.rotation    = false;

            float inc = Numerics.ToRadians(360.0f / 8.0f);

            for (int i = 0; i < 8; i++)
            {
                StarLines[i].SampleLength = sampleLength;
                StarLines[i].Inclination  = inc * (float)i;
                StarLines[i].Passes       = 3;
                if (0 == (i % 2))
                {
                    StarLines[i].Attenuation = longAttenuation;    // long
                }
                else
                {
                    StarLines[i].Attenuation = attenuation;
                }
            }
        }
Exemplo n.º 9
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            MDatabaseUtilities.strCurrentConnectionString = Hidden.ExternalConnection;
            List <CStoredProcedureParameter> lclsParameters = new List <CStoredProcedureParameter>();

            lclsParameters.Add(new CStoredProcedureParameter("@intGunID", int.Parse(Request.QueryString["ID"])));
            lclsParameters.Add(new CStoredProcedureParameter("@intGunTypeID", Numerics.Val(cmbGunType.SelectedValue)));
            lclsParameters.Add(new CStoredProcedureParameter("@intAmmoTypeID", Numerics.Val(cmbAmmoType.SelectedValue)));
            lclsParameters.Add(new CStoredProcedureParameter("@strName", txtName.Text));
            lclsParameters.Add(new CStoredProcedureParameter("@strDescription", txtDescription.Text));
            lclsParameters.Add(new CStoredProcedureParameter("@strNotes", txtNotes.Text));
            lclsParameters.Add(new CStoredProcedureParameter("@strScreenshotLocation", txtScreenshot.Text));
            lclsParameters.Add(new CStoredProcedureParameter("@strVisual", txtVisual.Text));
            lclsParameters.Add(new CStoredProcedureParameter("@strAudio", txtAudio.Text));
            lclsParameters.Add(new CStoredProcedureParameter("@strMagMod", txtMagMod.Text));
            lclsParameters.Add(new CStoredProcedureParameter("@strSightMod", txtSightMod.Text));
            lclsParameters.Add(new CStoredProcedureParameter("@strGameID", txtGameID.Text));
            lclsParameters.Add(new CStoredProcedureParameter("@strDefaultMod", txtDefaultMod.Text));
            lclsParameters.Add(new CStoredProcedureParameter("@intDurability", Numerics.Val(txtDurability.Text)));
            lclsParameters.Add(new CStoredProcedureParameter("@intCapacity", Numerics.Val(txtCapacity.Text)));
            lclsParameters.Add(new CStoredProcedureParameter("@intBuyPrice", Numerics.Val(txtBuyPrice.Text)));
            lclsParameters.Add(new CStoredProcedureParameter("@intSellPrice", Numerics.Val(txtSellPrice.Text)));
            lclsParameters.Add(new CStoredProcedureParameter("@intSalvage", Numerics.Val(txtSalvageValue.Text)));
            lclsParameters.Add(new CStoredProcedureParameter("@decWeight", Numerics.Val(txtWeight.Text)));
            lclsParameters.Add(new CStoredProcedureParameter("@blnCanFireSingle", chkSingle.Checked));
            lclsParameters.Add(new CStoredProcedureParameter("@blnCanFireBurst", chkBurst.Checked));
            lclsParameters.Add(new CStoredProcedureParameter("@blnCanFireAuto", chkAuto.Checked));
            lclsParameters.Add(new CStoredProcedureParameter("@blnAcceptsAttachments", chkAcceptsAttachments.Checked));
            lclsParameters.Add(new CStoredProcedureParameter("@blnOneIsTheChamber", chkOneInTheChamber.Checked));
            lclsParameters.Add(new CStoredProcedureParameter("@blnHasSight", chkHasSight.Checked));
            lclsParameters.Add(new CStoredProcedureParameter("@intSubmitterID", ((Classes.Submitter)Session["Submitter"]).intID));
            MDatabaseUtilities.ExecuteStoredProcedure("uspUpsertGun", lclsParameters.ToArray());
            Classes.AllData.IsDirty = true;
            Response.Redirect("Guns.aspx");
        }
Exemplo n.º 10
0
        public void Run()
        {
            const long bound1 = 0L;
            const long bound2 = 100L;
            var        primes = Numerics.Primes(bound1, bound2);

            foreach (var prime in primes)
            {
                Console.WriteLine(prime);
            }

            Console.WriteLine("-------------------------------------------------------------------");

            const long bound3 = 20000000L;
            const long bound4 = 30000000L;

            Console.WriteLine(Numerics.Prime(bound3, bound4));


            Console.WriteLine("-------------------------------------------------------------------");

            Console.WriteLine(Numerics.Prime());
            Console.WriteLine(Numerics.Prime());
            Console.WriteLine(Numerics.Prime());


            Console.ReadLine();
        }
Exemplo n.º 11
0
        protected override IEnumerable <Result <NumberListToken> > Tokenize(TextSpan span)
        {
            var next = SkipWhiteSpace(span);

            if (!next.HasValue)
            {
                yield break;
            }

            do
            {
                var ch = next.Value;
                if (ch >= '0' && ch <= '9')
                {
                    var integer = Numerics.Integer(next.Location);
                    next = integer.Remainder.ConsumeChar();
                    yield return(Result.Value(NumberListToken.Number, integer.Location, integer.Remainder));
                }
                else
                {
                    if (_useCustomErrors)
                    {
                        yield return(Result.Empty <NumberListToken>(next.Location, "list must contain only numbers"));
                    }
                    else
                    {
                        yield return(Result.Empty <NumberListToken>(next.Location, new[] { "digit" }));
                    }
                }

                next = SkipWhiteSpace(next.Location);
            } while (next.HasValue);
        }
Exemplo n.º 12
0
        public float ComputeNextQ()
        {
            float dq;

            if (this.IsFirst)
            {
                dq           = this.Value > this.Target ? -this.Dq : this.Dq;
                this.IsFirst = false;
            }
            else if (this.Value != this.LastValue)
            {
                double slope = (this.Target - this.Value) / (this.LastValue - this.Value);
                dq = (float)(slope * (this.LastQ - this.Q));
            }
            else
            {
                dq = 0.0f;  // we're done?!
            }

            // Limit variable to avoid large swings.
            this.Dq        = Numerics.Clamp(dq, -30.0f, 30.0f);
            this.LastQ     = this.Q;
            this.LastValue = this.Value;
            this.Q         = Numerics.Clamp(this.Q + this.Dq, this.Qmin, this.Qmax);

            return(this.Q);
        }
Exemplo n.º 13
0
 private void renderArea_MouseWheel(object sender, MouseEventArgs e)
 {
     if (e.Delta != 0)
     {
         renderArea.ImageScale *= Numerics.Pow(1.1f, Numerics.Clamp(e.Delta, -2, 2));
     }
 }
Exemplo n.º 14
0
        private async Task FindRecord(epd_search_model model)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    var url    = $"{_url}/select?q=*:*&fq=uid:\"{model.uid}\"&fl=id,uid";
                    var result = await client.GetAsync(url);

                    string resultContent = await result.Content.ReadAsStringAsync();

                    dynamic d        = JsonConvert.DeserializeObject <dynamic>(resultContent);
                    var     response = d.response;
                    var     numFound = Numerics.GetInt(response.numFound);
                    if (numFound > 0)
                    {
                        var docs = Convert.ToString(response.docs);
                        epd_search_response_model[] res = JsonConvert.DeserializeObject <epd_search_response_model[]>(docs);
                        foreach (var item in res)
                        {
                            bool deleted = await DeleteRecord(item.id);
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
        }
Exemplo n.º 15
0
        public void Transform(Igneel.SceneManagement.Frame frame, GlypComponent component,
                              Igneel.Vector2 p0, Igneel.Vector2 p1)
        {
            var disp     = p1 - p0;
            var position = frame.BoundingSphere.Radius > 0?
                           frame.BoundingSphere.Center:
                           frame.GlobalPosition;
            var Tw = Matrix.Translate(-position);

            switch (component.Id)
            {
            case X:
                Tw *= Matrix.RotationX(Numerics.ToRadians(disp.Y));
                break;

            case Y:
                Tw *= Matrix.RotationY(Numerics.ToRadians(disp.X));
                break;

            case Z:
                Tw *= Matrix.RotationZ(Numerics.ToRadians(disp.Y));
                break;
            }

            Tw *= Matrix.Translate(position);
            var localPose = frame.LocalPose;
            var P         = Matrix.Invert(localPose) * frame.GlobalPose;
            var Tl        = P * Tw * Matrix.Invert(P);

            frame.LocalPose *= Tl;
            frame.CommitChanges();
        }
        private void CreateCamera()
        {
            var scene = Engine.Scene;

            //Compute the render target aspect ratio
            float aspect = (float)Engine.Graphics.BackBuffer.Width / (float)Engine.Graphics.BackBuffer.Height;

            //Create a First-Person camera controller. The controller will responds to user inputs and move the camera
            var controller = new FpController()
            {
                MoveScale     = 10.0f,
                RotationScale = 0.5f,
                BreakingTime  = 0.2f,

                //The callback that is called during a frame update ,if it returns true the camera respond to the user input
                UpdateCallback = c => Engine.Mouse.IsButtonPresed(Igneel.Input.MouseButton.Middle) ||
                                 (Engine.Mouse.IsButtonPresed(Igneel.Input.MouseButton.Left) &&
                                  Engine.KeyBoard.IsKeyPressed(Keys.Lalt)),

                //Create the camera and the camera node
                Node = scene.Create("cameraNode", Camera.FromOrientation("camera", zn: 0.05f, zf: 1000f).SetPerspective(Numerics.ToRadians(60), aspect),
                                    localPosition: new Vector3(0, 200, -500),
                                    localRotation: new Euler(0, Numerics.ToRadians(30), 0).ToMatrix())
            };

            scene.Dynamics.Add(new Dynamic(x => controller.Update(x)));
        }
Exemplo n.º 17
0
        private static GraphML_List <MsMsPeak> AssignChargeStatesbkp(GraphML_List <MsMsPeak> peaks, int maxCharge, MassTolerance isotopicMzTolerance)
        {
            GraphML_List <MsMsPeak> new_peaks = new GraphML_List <MsMsPeak>();

            for (int i = 0; i < peaks.Count - 1; i++)
            {
                int        j       = i + 1;
                List <int> charges = new List <int>();
                while (j < peaks.Count)
                {
                    if (peaks[j].MZ > (peaks[i].MZ + Constants.C12_C13_MASS_DIFFERENCE) + isotopicMzTolerance)
                    {
                        break;
                    }

                    for (int c = maxCharge; c >= 1; c--)
                    {
                        if (Math.Abs(Numerics.CalculateMassError(peaks[j].MZ, peaks[i].MZ + Constants.C12_C13_MASS_DIFFERENCE / (double)c, isotopicMzTolerance.Units)) <= isotopicMzTolerance.Value)
                        {
                            new_peaks.Add(new MsMsPeak(peaks[i].MZ, peaks[i].Intensity, c));
                            charges.Add(c);
                        }
                    }

                    j++;
                }
                if (charges.Count == 0)
                {
                    new_peaks.Add(new MsMsPeak(peaks[i].MZ, peaks[i].Intensity, 0));
                }
            }

            return(new_peaks);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Prints output in a single line form
        /// </summary>
        /// <param name="output">Output.</param>
        /// <param name="io_counter">Io_counter.</param>
        public static void PrintOut(string output, int io_counter)
        {
            string prompt   = "Out[" + Numerics.Roman(io_counter) + "]= ";
            int    max_size = Terminal.Width - prompt.Length - 5;
            string result   = "";

            if (output.Length > max_size)
            {
                int counter = 0;
                foreach (var index in output)
                {
                    if (counter < max_size)
                    {
                        result += index;
                        counter++;
                    }
                    else
                    {
                        counter = 0;
                        result += index + "\n" + Utilities.Repeat(" ", prompt.Length);
                    }
                }
            }
            else
            {
                result = output;
            }

            Terminal.Magenta();
            Terminal.Print(prompt);
            Terminal.Reset();
            Terminal.PrintLn(result);
            Terminal.NewLine();
        }
Exemplo n.º 19
0
        public void DivideCeil_DivideZero()
        {
            uint expected = 0;
            uint actual   = Numerics.DivideCeil(0, 100);

            Assert.Equal(expected, actual);
        }
Exemplo n.º 20
0
        public Precursor(Track track, int charge, Sample entry, double massShift = 0, GraphML_List <Precursor> isotopes = null)//double mz, double intensity, int charge = -1, double rt = 0, double massShift = 0, List<Precursor> isotopes = null)
        {
            INDEX       = COMPTEUR++;
            this.Track  = track;
            this.Charge = charge;
            this.sample = entry;

            this.psms_AllPossibilities = new PeptideSpectrumMatches(); // GraphML_List<PeptideSpectrumMatch>();
            this.psms = new PeptideSpectrumMatches();                  // GraphML_List<PeptideSpectrumMatch>();
            //  this.Mz         = mz;
            //  this.Intensity  = intensity;
            //  this.Charge     = charge;
            this.Mass = Numerics.MassFromMZ(track.MZ, charge);
            //  this.Rt         = rt;
            MassShift = massShift;
            if (isotopes == null)
            {
                Isotopes = new GraphML_List <Precursor>();
            }
            else
            {
                Isotopes = isotopes;
            }
            OtherCharges = new GraphML_List <Precursor>();
        }
        protected override IEnumerable <Result <ArithmeticExpressionToken> > Tokenize(TextSpan span)
        {
            var next = SkipWhiteSpace(span);

            if (!next.HasValue)
            {
                yield break;
            }

            do
            {
                ArithmeticExpressionToken charToken;

                var ch = next.Value;
                if (ch >= '0' && ch <= '9')
                {
                    var integer = Numerics.Integer(next.Location);
                    next = integer.Remainder.ConsumeChar();
                    yield return(Result.Value(ArithmeticExpressionToken.Number, integer.Location, integer.Remainder));
                }
                else if (_operators.TryGetValue(ch, out charToken))
                {
                    yield return(Result.Value(charToken, next.Location, next.Remainder));

                    next = next.Remainder.ConsumeChar();
                }
                else
                {
                    yield return(Result.Empty <ArithmeticExpressionToken>(next.Location, new[] { "number", "operator" }));
                }

                next = SkipWhiteSpace(next.Location);
            } while (next.HasValue);
        }
Exemplo n.º 22
0
        private void SetupFilterStrength()
        {
            int filterSharpness = 0; // TODO: filterSharpness is hardcoded
            int filterType      = 1; // TODO: filterType is hardcoded

            // level0 is in [0..500]. Using '-f 50' as filter_strength is mid-filtering.
            int level0 = 5 * this.filterStrength;

            for (int i = 0; i < WebpConstants.NumMbSegments; i++)
            {
                Vp8SegmentInfo m = this.SegmentInfos[i];

                // We focus on the quantization of AC coeffs.
                int qstep        = WebpLookupTables.AcTable[Numerics.Clamp(m.Quant, 0, 127)] >> 2;
                int baseStrength = this.FilterStrengthFromDelta(this.FilterHeader.Sharpness, qstep);

                // Segments with lower complexity ('beta') will be less filtered.
                int f = baseStrength * level0 / (256 + m.Beta);
                m.FStrength = f < WebpConstants.FilterStrengthCutoff ? 0 : f > 63 ? 63 : f;
            }

            // We record the initial strength (mainly for the case of 1-segment only).
            this.FilterHeader.FilterLevel = this.SegmentInfos[0].FStrength;
            this.FilterHeader.Simple      = filterType == 0;
            this.FilterHeader.Sharpness   = filterSharpness;
        }
Exemplo n.º 23
0
        public ActionResult ChangePassword(FormCollection data)
        {
            int AdminID = Numerics.GetInt(Session["AdminID"]);

            if (AdminID > 0)
            {
                if (data.Count > 0)
                {
                    string oldPassword = AesCryptography.Encrypt(data["OldPassword"]);
                    string newPassword = AesCryptography.Encrypt(data["NewPassword"]);
                    GenericRepository <Users> _userRepo = new GenericRepository <Users>(_unitOfWork);

                    Users entity = _userRepo.Repository.Get(p => p.Password == oldPassword && p.UserID == AdminID);
                    if (entity != null)
                    {
                        entity.Password = newPassword;
                        _userRepo.Repository.Update(entity);
                        ViewBag.Message = "Password updated successfully.";
                        ViewBag.Type    = "alert-success";
                    }
                    else
                    {
                        ViewBag.Message = "Old Password is incorrect.";
                        ViewBag.Type    = "alert-danger";
                    }
                }
                return(View());
            }
            else
            {
                return(RedirectToAction("index", "login"));
            }
        }
Exemplo n.º 24
0
        protected override IEnumerable <Result <ArithmeticExpressionToken> > Tokenize(TextSpan span)
        {
            var next = SkipWhiteSpace(span);

            if (!next.HasValue)
            {
                yield break;
            }

            do
            {
                if (char.IsDigit(next.Value))
                {
                    var natural = Numerics.Natural(next.Location);
                    next = natural.Remainder.ConsumeChar();
                    yield return(Result.Value(ArithmeticExpressionToken.Number, natural.Location, natural.Remainder));
                }
                else if (_operators.TryGetValue(next.Value, out var charToken))
                {
                    yield return(Result.Value(charToken, next.Location, next.Remainder));

                    next = next.Remainder.ConsumeChar();
                }
                else
                {
                    yield return(Result.Empty <ArithmeticExpressionToken>(next.Location, new[] { "number", "operator" }));
                }

                next = SkipWhiteSpace(next.Location);
            } while (next.HasValue);
        }
Exemplo n.º 25
0
        public int GetBit(int prob)
        {
            uint range = this.range;

            if (this.bits < 0)
            {
                this.LoadNewBytes();
            }

            int   pos   = this.bits;
            uint  split = (uint)((range * prob) >> 8);
            ulong value = this.value >> pos;
            bool  bit   = value > split;

            if (bit)
            {
                range      -= split;
                this.value -= (ulong)(split + 1) << pos;
            }
            else
            {
                range = split + 1;
            }

            int shift = 7 ^ Numerics.Log2(range);

            range    <<= shift;
            this.bits -= shift;

            this.range = range - 1;

            return(bit ? 1 : 0);
        }
Exemplo n.º 26
0
 public void FromVector4(Vector4 vector)
 {
     vector = Numerics.Clamp(vector, Vector4.Zero, Vector4.One) * Max;
     this.R = (ushort)MathF.Round(vector.X);
     this.G = (ushort)MathF.Round(vector.Y);
     this.B = (ushort)MathF.Round(vector.Z);
 }
Exemplo n.º 27
0
        void SetWrapTeethRectAndLine()
        {
            if (Points == null)
            {
                return;
            }
            var points = new List <Point>();

            Border_WrapTeeth.Visibility    = Visibility.Visible;
            Rectangle_WrapTeeth.Visibility = Visibility.Visible;

            foreach (var point in Points)
            {
                var pointProperties = point.GetType().GetProperties();
                if (pointProperties.All(p => p.Name != "X") ||
                    pointProperties.All(p => p.Name != "Y"))
                {
                    continue;
                }
                var x = (double)point.GetType().GetProperty("X").GetValue(point, new object[] { });
                var y = (double)point.GetType().GetProperty("Y").GetValue(point, new object[] { });
                points.Add(new Point(x, y));
            }

            if (points.Count <= 1)
            {
                return;
            }

            Point minP = new Point(Numerics.GetMinX_Teeth(points).X, Numerics.GetMinY_Teeth(points).Y);
            Point maxP = new Point(Numerics.GetMaxX_Teeth(points).X, Numerics.GetMaxY_Teeth(points).Y);

            DrawRect(minP, maxP);
            DrawLineXY(minP, maxP);
        }
Exemplo n.º 28
0
        protected override IEnumerable <Result <NumberListToken> > Tokenize(TextSpan span)
        {
            var next = SkipWhiteSpace(span);

            if (!next.HasValue)
            {
                yield break;
            }

            do
            {
                if (char.IsDigit(next.Value))
                {
                    var integer = Numerics.Integer(next.Location);
                    next = integer.Remainder.ConsumeChar();
                    yield return(Result.Value(NumberListToken.Number, integer.Location, integer.Remainder));
                }
                else
                {
                    yield return(Result.Empty <NumberListToken>(next.Location, new[] { "digit" }));
                }

                next = SkipWhiteSpace(next.Location);
            } while (next.HasValue);
        }
Exemplo n.º 29
0
 public Cmyk(Vector4 vector)
 {
     vector = Numerics.Clamp(vector, Min, Max);
     this.C = vector.X;
     this.M = vector.Y;
     this.Y = vector.Z;
     this.K = vector.W;
 }
Exemplo n.º 30
0
 private static ushort Pack(ref Vector4 vector)
 {
     vector = Numerics.Clamp(vector, Vector4.Zero, Vector4.One);
     return((ushort)((((int)Math.Round(vector.W * 15F) & 0x0F) << 12)
                     | (((int)Math.Round(vector.X * 15F) & 0x0F) << 8)
                     | (((int)Math.Round(vector.Y * 15F) & 0x0F) << 4)
                     | ((int)Math.Round(vector.Z * 15F) & 0x0F)));
 }
Exemplo n.º 31
0
        /// <summary>
        /// Determines eigenvectors by undoing the symmetric tridiagonalize transformation
        /// </summary>
        /// <param name="dataEv">Data array of matrix V (eigenvectors)</param>
        /// <param name="matrixA">Previously tridiagonalized matrix by <see cref="SymmetricTridiagonalize"/>.</param>
        /// <param name="tau">Contains further information about the transformations</param>
        /// <param name="order">Input matrix order</param>
        /// <remarks>This is derived from the Algol procedures HTRIBK, by
        /// by Smith, Boyle, Dongarra, Garbow, Ikebe, Klema, Moler, and Wilkinson, Handbook for
        /// Auto. Comp., Vol.ii-Linear Algebra, and the corresponding
        /// Fortran subroutine in EISPACK.</remarks>
        internal static void SymmetricUntridiagonalize(Numerics.Complex32[] dataEv, Numerics.Complex32[] matrixA, Numerics.Complex32[] tau, int order)
        {
            for (var i = 0; i < order; i++)
            {
                for (var j = 0; j < order; j++)
                {
                    dataEv[(j*order) + i] = dataEv[(j*order) + i].Real*tau[i].Conjugate();
                }
            }

            // Recover and apply the Householder matrices.
            for (var i = 1; i < order; i++)
            {
                var h = matrixA[i*order + i].Imaginary;
                if (h != 0)
                {
                    for (var j = 0; j < order; j++)
                    {
                        var s = Numerics.Complex32.Zero;
                        for (var k = 0; k < i; k++)
                        {
                            s += dataEv[(j*order) + k]*matrixA[k*order + i];
                        }

                        s = (s/h)/h;

                        for (var k = 0; k < i; k++)
                        {
                            dataEv[(j*order) + k] -= s*matrixA[k*order + i].Conjugate();
                        }
                    }
                }
            }
        }
Exemplo n.º 32
0
        /// <summary>
        /// Symmetric tridiagonal QL algorithm.
        /// </summary>
        /// <param name="dataEv">Data array of matrix V (eigenvectors)</param>
        /// <param name="d">Arrays for internal storage of real parts of eigenvalues</param>
        /// <param name="e">Arrays for internal storage of imaginary parts of eigenvalues</param>
        /// <param name="order">Order of initial matrix</param>
        /// <remarks>This is derived from the Algol procedures tql2, by
        /// Bowdler, Martin, Reinsch, and Wilkinson, Handbook for
        /// Auto. Comp., Vol.ii-Linear Algebra, and the corresponding
        /// Fortran subroutine in EISPACK.</remarks>
        internal static void SymmetricDiagonalize(Numerics.Complex32[] dataEv, float[] d, float[] e, int order)
        {
            const int Maxiter = 1000;

            for (var i = 1; i < order; i++)
            {
                e[i - 1] = e[i];
            }

            e[order - 1] = 0.0f;

            var f = 0.0f;
            var tst1 = 0.0f;
            var eps = Precision.DoubleMachinePrecision;
            for (var l = 0; l < order; l++)
            {
                // Find small subdiagonal element
                tst1 = Math.Max(tst1, Math.Abs(d[l]) + Math.Abs(e[l]));
                var m = l;
                while (m < order)
                {
                    if (Math.Abs(e[m]) <= eps*tst1)
                    {
                        break;
                    }

                    m++;
                }

                // If m == l, d[l] is an eigenvalue,
                // otherwise, iterate.
                if (m > l)
                {
                    var iter = 0;
                    do
                    {
                        iter = iter + 1; // (Could check iteration count here.)

                        // Compute implicit shift
                        var g = d[l];
                        var p = (d[l + 1] - g)/(2.0f*e[l]);
                        var r = SpecialFunctions.Hypotenuse(p, 1.0f);
                        if (p < 0)
                        {
                            r = -r;
                        }

                        d[l] = e[l]/(p + r);
                        d[l + 1] = e[l]*(p + r);

                        var dl1 = d[l + 1];
                        var h = g - d[l];
                        for (var i = l + 2; i < order; i++)
                        {
                            d[i] -= h;
                        }

                        f = f + h;

                        // Implicit QL transformation.
                        p = d[m];
                        var c = 1.0f;
                        var c2 = c;
                        var c3 = c;
                        var el1 = e[l + 1];
                        var s = 0.0f;
                        var s2 = 0.0f;
                        for (var i = m - 1; i >= l; i--)
                        {
                            c3 = c2;
                            c2 = c;
                            s2 = s;
                            g = c*e[i];
                            h = c*p;
                            r = SpecialFunctions.Hypotenuse(p, e[i]);
                            e[i + 1] = s*r;
                            s = e[i]/r;
                            c = p/r;
                            p = (c*d[i]) - (s*g);
                            d[i + 1] = h + (s*((c*g) + (s*d[i])));

                            // Accumulate transformation.
                            for (var k = 0; k < order; k++)
                            {
                                h = dataEv[((i + 1)*order) + k].Real;
                                dataEv[((i + 1)*order) + k] = (s*dataEv[(i*order) + k].Real) + (c*h);
                                dataEv[(i*order) + k] = (c*dataEv[(i*order) + k].Real) - (s*h);
                            }
                        }

                        p = (-s)*s2*c3*el1*e[l]/dl1;
                        e[l] = s*p;
                        d[l] = c*p;

                        // Check for convergence. If too many iterations have been performed, 
                        // throw exception that Convergence Failed
                        if (iter >= Maxiter)
                        {
                            throw new ArgumentException(Resources.ConvergenceFailed);
                        }
                    } while (Math.Abs(e[l]) > eps*tst1);
                }

                d[l] = d[l] + f;
                e[l] = 0.0f;
            }

            // Sort eigenvalues and corresponding vectors.
            for (var i = 0; i < order - 1; i++)
            {
                var k = i;
                var p = d[i];
                for (var j = i + 1; j < order; j++)
                {
                    if (d[j] < p)
                    {
                        k = j;
                        p = d[j];
                    }
                }

                if (k != i)
                {
                    d[k] = d[i];
                    d[i] = p;
                    for (var j = 0; j < order; j++)
                    {
                        p = dataEv[(i*order) + j].Real;
                        dataEv[(i*order) + j] = dataEv[(k*order) + j];
                        dataEv[(k*order) + j] = p;
                    }
                }
            }
        }
Exemplo n.º 33
0
        /// <summary>
        ///     Gets the transform matricies used for printing.
        /// </summary>
        /// <param name="bounds">The bounds.</param>
        /// <param name="transform">The transform.</param>
        /// <param name="inverseTransform">The inverse transform.</param>
        /// <exception cref="System.ArgumentOutOfRangeException"></exception>
        private void GetPrintTransform(
            Numerics.Rectangle bounds,
            out Matrix3x2 transform,
            out Matrix3x2 inverseTransform)
        {
            float minDim = Math.Min(bounds.Width, bounds.Height);

            Vector2 center = bounds.Center;

            Matrix3x2 scale = Matrix3x2.CreateScale((minDim * _zoom) / 10000f, center);
            Matrix3x2 invScale = Matrix3x2.CreateScale(10000f / (minDim * _zoom), center);

            Matrix3x2 centerTranslate = Matrix3x2.CreateTranslation(center);
            Matrix3x2 invCenterTranslate = Matrix3x2.CreateTranslation(-center);

            Matrix3x2 translate, invTranslate;

            switch (_printDocument.PrintMode)
            {
                case TilingPrintMode.TilingFull:
                case TilingPrintMode.TilingLines:
                    translate = Matrix3x2.CreateTranslation(_bounds.Center);
                    invTranslate = Matrix3x2.CreateTranslation(-_bounds.Center);
                    break;

                case TilingPrintMode.SingleTileFull:
                case TilingPrintMode.SingleTileLines:
                    Debug.Assert(_printDocument.Tile != null, "_printDocument.Tile != null");

                    Vector2 centroid = _printDocument.Tile.Centroid;

                    translate = Matrix3x2.CreateTranslation(centroid);
                    invTranslate = Matrix3x2.CreateTranslation(-centroid);
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            transform = centerTranslate * translate * scale;
            inverseTransform = invScale * invTranslate * invCenterTranslate;
        }
Exemplo n.º 34
0
        /// <summary>
        /// Reduces a complex hermitian matrix to a real symmetric tridiagonal matrix using unitary similarity transformations.
        /// </summary>
        /// <param name="matrixA">Source matrix to reduce</param>
        /// <param name="d">Output: Arrays for internal storage of real parts of eigenvalues</param>
        /// <param name="e">Output: Arrays for internal storage of imaginary parts of eigenvalues</param>
        /// <param name="tau">Output: Arrays that contains further information about the transformations.</param>
        /// <param name="order">Order of initial matrix</param>
        /// <remarks>This is derived from the Algol procedures HTRIDI by 
        /// Smith, Boyle, Dongarra, Garbow, Ikebe, Klema, Moler, and Wilkinson, Handbook for 
        /// Auto. Comp., Vol.ii-Linear Algebra, and the corresponding 
        /// Fortran subroutine in EISPACK.</remarks>
        internal static void SymmetricTridiagonalize(Numerics.Complex32[] matrixA, float[] d, float[] e, Numerics.Complex32[] tau, int order)
        {
            float hh;
            tau[order - 1] = Numerics.Complex32.One;

            for (var i = 0; i < order; i++)
            {
                d[i] = matrixA[i*order + i].Real;
            }

            // Householder reduction to tridiagonal form.
            for (var i = order - 1; i > 0; i--)
            {
                // Scale to avoid under/overflow.
                var scale = 0.0f;
                var h = 0.0f;

                for (var k = 0; k < i; k++)
                {
                    scale = scale + Math.Abs(matrixA[k*order + i].Real) + Math.Abs(matrixA[k*order + i].Imaginary);
                }

                if (scale == 0.0f)
                {
                    tau[i - 1] = Numerics.Complex32.One;
                    e[i] = 0.0f;
                }
                else
                {
                    for (var k = 0; k < i; k++)
                    {
                        matrixA[k*order + i] /= scale;
                        h += matrixA[k*order + i].MagnitudeSquared;
                    }

                    Numerics.Complex32 g = (float) Math.Sqrt(h);
                    e[i] = scale*g.Real;

                    Numerics.Complex32 temp;
                    var im1Oi = (i - 1)*order + i;
                    var f = matrixA[im1Oi];
                    if (f.Magnitude != 0.0f)
                    {
                        temp = -(matrixA[im1Oi].Conjugate()*tau[i].Conjugate())/f.Magnitude;
                        h += f.Magnitude*g.Real;
                        g = 1.0f + (g/f.Magnitude);
                        matrixA[im1Oi] *= g;
                    }
                    else
                    {
                        temp = -tau[i].Conjugate();
                        matrixA[im1Oi] = g;
                    }

                    if ((f.Magnitude == 0.0f) || (i != 1))
                    {
                        f = Numerics.Complex32.Zero;
                        for (var j = 0; j < i; j++)
                        {
                            var tmp = Numerics.Complex32.Zero;
                            var jO = j*order;
                            // Form element of A*U.
                            for (var k = 0; k <= j; k++)
                            {
                                tmp += matrixA[k*order + j]*matrixA[k*order + i].Conjugate();
                            }

                            for (var k = j + 1; k <= i - 1; k++)
                            {
                                tmp += matrixA[jO + k].Conjugate()*matrixA[k*order + i].Conjugate();
                            }

                            // Form element of P
                            tau[j] = tmp/h;
                            f += (tmp/h)*matrixA[jO + i];
                        }

                        hh = f.Real/(h + h);

                        // Form the reduced A.
                        for (var j = 0; j < i; j++)
                        {
                            f = matrixA[j*order + i].Conjugate();
                            g = tau[j] - (hh*f);
                            tau[j] = g.Conjugate();

                            for (var k = 0; k <= j; k++)
                            {
                                matrixA[k*order + j] -= (f*tau[k]) + (g*matrixA[k*order + i]);
                            }
                        }
                    }

                    for (var k = 0; k < i; k++)
                    {
                        matrixA[k*order + i] *= scale;
                    }

                    tau[i - 1] = temp.Conjugate();
                }

                hh = d[i];
                d[i] = matrixA[i*order + i].Real;
                matrixA[i*order + i] = new Numerics.Complex32(hh, scale*(float) Math.Sqrt(h));
            }

            hh = d[0];
            d[0] = matrixA[0].Real;
            matrixA[0] = hh;
            e[0] = 0.0f;
        }
Exemplo n.º 35
0
        /// <summary>
        /// Nonsymmetric reduction to Hessenberg form.
        /// </summary>
        /// <param name="dataEv">Data array of matrix V (eigenvectors)</param>
        /// <param name="matrixH">Array for internal storage of nonsymmetric Hessenberg form.</param>
        /// <param name="order">Order of initial matrix</param>
        /// <remarks>This is derived from the Algol procedures orthes and ortran,
        /// by Martin and Wilkinson, Handbook for Auto. Comp.,
        /// Vol.ii-Linear Algebra, and the corresponding
        /// Fortran subroutines in EISPACK.</remarks>
        internal static void NonsymmetricReduceToHessenberg(Numerics.Complex32[] dataEv, Numerics.Complex32[] matrixH, int order)
        {
            var ort = new Numerics.Complex32[order];

            for (var m = 1; m < order - 1; m++)
            {
                // Scale column.
                var scale = 0.0f;
                var mm1O = (m - 1)*order;
                for (var i = m; i < order; i++)
                {
                    scale += Math.Abs(matrixH[mm1O + i].Real) + Math.Abs(matrixH[mm1O + i].Imaginary);
                }

                if (scale != 0.0f)
                {
                    // Compute Householder transformation.
                    var h = 0.0f;
                    for (var i = order - 1; i >= m; i--)
                    {
                        ort[i] = matrixH[mm1O + i]/scale;
                        h += ort[i].MagnitudeSquared;
                    }

                    var g = (float) Math.Sqrt(h);
                    if (ort[m].Magnitude != 0)
                    {
                        h = h + (ort[m].Magnitude*g);
                        g /= ort[m].Magnitude;
                        ort[m] = (1.0f + g)*ort[m];
                    }
                    else
                    {
                        ort[m] = g;
                        matrixH[mm1O + m] = scale;
                    }

                    // Apply Householder similarity transformation
                    // H = (I-u*u'/h)*H*(I-u*u')/h)
                    for (var j = m; j < order; j++)
                    {
                        var f = Numerics.Complex32.Zero;
                        var jO = j*order;
                        for (var i = order - 1; i >= m; i--)
                        {
                            f += ort[i].Conjugate()*matrixH[jO + i];
                        }

                        f = f/h;
                        for (var i = m; i < order; i++)
                        {
                            matrixH[jO + i] -= f*ort[i];
                        }
                    }

                    for (var i = 0; i < order; i++)
                    {
                        var f = Numerics.Complex32.Zero;
                        for (var j = order - 1; j >= m; j--)
                        {
                            f += ort[j]*matrixH[j*order + i];
                        }

                        f = f/h;
                        for (var j = m; j < order; j++)
                        {
                            matrixH[j*order + i] -= f*ort[j].Conjugate();
                        }
                    }

                    ort[m] = scale*ort[m];
                    matrixH[mm1O + m] *= -g;
                }
            }

            // Accumulate transformations (Algol's ortran).
            for (var i = 0; i < order; i++)
            {
                for (var j = 0; j < order; j++)
                {
                    dataEv[(j*order) + i] = i == j ? Numerics.Complex32.One : Numerics.Complex32.Zero;
                }
            }

            for (var m = order - 2; m >= 1; m--)
            {
                var mm1O = (m - 1)*order;
                var mm1Om = mm1O + m;
                if (matrixH[mm1Om] != Numerics.Complex32.Zero && ort[m] != Numerics.Complex32.Zero)
                {
                    var norm = (matrixH[mm1Om].Real*ort[m].Real) + (matrixH[mm1Om].Imaginary*ort[m].Imaginary);

                    for (var i = m + 1; i < order; i++)
                    {
                        ort[i] = matrixH[mm1O + i];
                    }

                    for (var j = m; j < order; j++)
                    {
                        var g = Numerics.Complex32.Zero;
                        for (var i = m; i < order; i++)
                        {
                            g += ort[i].Conjugate()*dataEv[(j*order) + i];
                        }

                        // Double division avoids possible underflow
                        g /= norm;
                        for (var i = m; i < order; i++)
                        {
                            dataEv[(j*order) + i] += g*ort[i];
                        }
                    }
                }
            }

            // Create real subdiagonal elements.
            for (var i = 1; i < order; i++)
            {
                var im1 = i - 1;
                var im1O = im1*order;
                var im1Oi = im1O + i;
                var iO = i*order;
                if (matrixH[im1Oi].Imaginary != 0.0f)
                {
                    var y = matrixH[im1Oi]/matrixH[im1Oi].Magnitude;
                    matrixH[im1Oi] = matrixH[im1Oi].Magnitude;
                    for (var j = i; j < order; j++)
                    {
                        matrixH[j*order + i] *= y.Conjugate();
                    }

                    for (var j = 0; j <= Math.Min(i + 1, order - 1); j++)
                    {
                        matrixH[iO + j] *= y;
                    }

                    for (var j = 0; j < order; j++)
                    {
                        dataEv[(i*order) + j] *= y;
                    }
                }
            }
        }
Exemplo n.º 36
0
        /// <summary>
        /// Nonsymmetric reduction from Hessenberg to real Schur form.
        /// </summary>
        /// <param name="vectorV">Data array of the eigenvectors</param>
        /// <param name="dataEv">Data array of matrix V (eigenvectors)</param>
        /// <param name="matrixH">Array for internal storage of nonsymmetric Hessenberg form.</param>
        /// <param name="order">Order of initial matrix</param>
        /// <remarks>This is derived from the Algol procedure hqr2,
        /// by Martin and Wilkinson, Handbook for Auto. Comp.,
        /// Vol.ii-Linear Algebra, and the corresponding
        /// Fortran subroutine in EISPACK.</remarks>
        internal static void NonsymmetricReduceHessenberToRealSchur(Numerics.Complex32[] vectorV, Numerics.Complex32[] dataEv, Numerics.Complex32[] matrixH, int order)
        {
            // Initialize
            var n = order - 1;
            var eps = (float) Precision.SingleMachinePrecision;

            float norm;
            Numerics.Complex32 x, y, z, exshift = Numerics.Complex32.Zero;

            // Outer loop over eigenvalue index
            var iter = 0;
            while (n >= 0)
            {
                // Look for single small sub-diagonal element
                var l = n;
                while (l > 0)
                {
                    var lm1 = l - 1;
                    var lm1O = lm1*order;
                    var lO = l*order;
                    var tst1 = Math.Abs(matrixH[lm1O + lm1].Real) + Math.Abs(matrixH[lm1O + lm1].Imaginary) + Math.Abs(matrixH[lO + l].Real) + Math.Abs(matrixH[lO + l].Imaginary);
                    if (Math.Abs(matrixH[lm1O + l].Real) < eps*tst1)
                    {
                        break;
                    }

                    l--;
                }

                var nm1 = n - 1;
                var nm1O = nm1*order;
                var nO = n*order;
                var nOn = nO + n;
                // Check for convergence
                // One root found
                if (l == n)
                {
                    matrixH[nOn] += exshift;
                    vectorV[n] = matrixH[nOn];
                    n--;
                    iter = 0;
                }
                else
                {
                    // Form shift
                    Numerics.Complex32 s;
                    if (iter != 10 && iter != 20)
                    {
                        s = matrixH[nOn];
                        x = matrixH[nO + nm1]*matrixH[nm1O + n].Real;

                        if (x.Real != 0.0f || x.Imaginary != 0.0f)
                        {
                            y = (matrixH[nm1O + nm1] - s)/2.0f;
                            z = ((y*y) + x).SquareRoot();
                            if ((y.Real*z.Real) + (y.Imaginary*z.Imaginary) < 0.0)
                            {
                                z *= -1.0f;
                            }

                            x /= y + z;
                            s = s - x;
                        }
                    }
                    else
                    {
                        // Form exceptional shift
                        s = Math.Abs(matrixH[nm1O + n].Real) + Math.Abs(matrixH[(n - 2)*order + nm1].Real);
                    }

                    for (var i = 0; i <= n; i++)
                    {
                        matrixH[i*order + i] -= s;
                    }

                    exshift += s;
                    iter++;

                    // Reduce to triangle (rows)
                    for (var i = l + 1; i <= n; i++)
                    {
                        var im1 = i - 1;
                        var im1O = im1*order;
                        var im1Oim1 = im1O + im1;
                        s = matrixH[im1O + i].Real;
                        norm = SpecialFunctions.Hypotenuse(matrixH[im1Oim1].Magnitude, s.Real);
                        x = matrixH[im1Oim1]/norm;
                        vectorV[i - 1] = x;
                        matrixH[im1Oim1] = norm;
                        matrixH[im1O + i] = new Numerics.Complex32(0.0f, s.Real/norm);

                        for (var j = i; j < order; j++)
                        {
                            var jO = j*order;
                            y = matrixH[jO + im1];
                            z = matrixH[jO + i];
                            matrixH[jO + im1] = (x.Conjugate()*y) + (matrixH[im1O + i].Imaginary*z);
                            matrixH[jO + i] = (x*z) - (matrixH[im1O + i].Imaginary*y);
                        }
                    }

                    s = matrixH[nOn];
                    if (s.Imaginary != 0.0f)
                    {
                        s /= matrixH[nOn].Magnitude;
                        matrixH[nOn] = matrixH[nOn].Magnitude;

                        for (var j = n + 1; j < order; j++)
                        {
                            matrixH[j*order + n] *= s.Conjugate();
                        }
                    }

                    // Inverse operation (columns).
                    for (var j = l + 1; j <= n; j++)
                    {
                        x = vectorV[j - 1];
                        var jO = j*order;
                        var jm1 = j - 1;
                        var jm1O = jm1*order;
                        var jm1Oj = jm1O + j;
                        for (var i = 0; i <= j; i++)
                        {
                            var jm1Oi = jm1O + i;
                            z = matrixH[jO + i];
                            if (i != j)
                            {
                                y = matrixH[jm1Oi];
                                matrixH[jm1Oi] = (x*y) + (matrixH[jm1O + j].Imaginary*z);
                            }
                            else
                            {
                                y = matrixH[jm1Oi].Real;
                                matrixH[jm1Oi] = new Numerics.Complex32((x.Real*y.Real) - (x.Imaginary*y.Imaginary) + (matrixH[jm1O + j].Imaginary*z.Real), matrixH[jm1Oi].Imaginary);
                            }

                            matrixH[jO + i] = (x.Conjugate()*z) - (matrixH[jm1O + j].Imaginary*y);
                        }

                        for (var i = 0; i < order; i++)
                        {
                            y = dataEv[((j - 1)*order) + i];
                            z = dataEv[(j*order) + i];
                            dataEv[jm1O + i] = (x*y) + (matrixH[jm1Oj].Imaginary*z);
                            dataEv[jO + i] = (x.Conjugate()*z) - (matrixH[jm1Oj].Imaginary*y);
                        }
                    }

                    if (s.Imaginary != 0.0f)
                    {
                        for (var i = 0; i <= n; i++)
                        {
                            matrixH[nO + i] *= s;
                        }

                        for (var i = 0; i < order; i++)
                        {
                            dataEv[nO + i] *= s;
                        }
                    }
                }
            }

            // All roots found.  
            // Backsubstitute to find vectors of upper triangular form
            norm = 0.0f;
            for (var i = 0; i < order; i++)
            {
                for (var j = i; j < order; j++)
                {
                    norm = Math.Max(norm, Math.Abs(matrixH[j*order + i].Real) + Math.Abs(matrixH[j*order + i].Imaginary));
                }
            }

            if (order == 1)
            {
                return;
            }

            if (norm == 0.0)
            {
                return;
            }

            for (n = order - 1; n > 0; n--)
            {
                var nO = n*order;
                var nOn = nO + n;
                x = vectorV[n];
                matrixH[nOn] = 1.0f;

                for (var i = n - 1; i >= 0; i--)
                {
                    z = 0.0f;
                    for (var j = i + 1; j <= n; j++)
                    {
                        z += matrixH[j*order + i]*matrixH[nO + j];
                    }

                    y = x - vectorV[i];
                    if (y.Real == 0.0f && y.Imaginary == 0.0f)
                    {
                        y = eps*norm;
                    }

                    matrixH[nO + i] = z/y;

                    // Overflow control
                    var tr = Math.Abs(matrixH[nO + i].Real) + Math.Abs(matrixH[nO + i].Imaginary);
                    if ((eps*tr)*tr > 1)
                    {
                        for (var j = i; j <= n; j++)
                        {
                            matrixH[nO + j] = matrixH[nO + j]/tr;
                        }
                    }
                }
            }

            // Back transformation to get eigenvectors of original matrix
            for (var j = order - 1; j > 0; j--)
            {
                var jO = j*order;
                for (var i = 0; i < order; i++)
                {
                    z = Numerics.Complex32.Zero;
                    for (var k = 0; k <= j; k++)
                    {
                        z += dataEv[(k*order) + i]*matrixH[jO + k];
                    }

                    dataEv[jO + i] = z;
                }
            }
        }
            public static double[] PTCurve(Direct_Sound Direct, ImageSourceData ISData, Environment.Receiver_Bank RTData, double CO_Time_ms, int samplerate, int Octave, int Rec_ID, bool StartAtZero, Numerics.ComplexComponent Output_Type)
            {
                Direct_Sound[] ArrDirect = new Direct_Sound[1];
                    ArrDirect[0] = Direct;
                    ImageSourceData[] ArrIS = new ImageSourceData[1];
                    ArrIS[0] = ISData;
                    Environment.Receiver_Bank[] ArrRT = new Environment.Receiver_Bank[1];
                    ArrRT[0] = RTData;

                    double[] P;
                    PTCurve(ArrDirect, ArrIS, ArrRT, CO_Time_ms*0.001, samplerate, Rec_ID, 0, StartAtZero, out P);

                    double[] Pressure = new double[P.Length];
                    for (int i = 0; i < Pressure.Length; i++) Pressure[i] = P[i];
                    return Pressure;
            }