Inheritance: MonoBehaviour
Beispiel #1
0
 public void startTimer(Double seconds)
 {
     Timer gameTimer = new Timer();
     gameTimer.Elapsed += new ElapsedEventHandler(TimerGameEvent);
     gameTimer.Interval = seconds;
     gameTimer.Enabled = true;
 }
        private static void RunTests_PowComplex(Double a, Double b)
        {
            //if (!Support.IsARM || !m_randomValues)
            //{
            //	VerifyPow(a, b, -1.0, 0.0);
            //}
            VerifyPow(a, b, 0.0, -1.0);
            VerifyPow(a, b, 0.0, 0.0);
            VerifyPow(a, b, 0.0, 1.0);
            VerifyPow(a, b, 1.0, 0.0);

            Double real = Support.GetSmallRandomDoubleValue(false);
            Double imaginary = Support.GetSmallRandomDoubleValue(false);
            VerifyPow(a, b, real, imaginary);

            real = Support.GetSmallRandomDoubleValue(true);
            imaginary = Support.GetSmallRandomDoubleValue(false);
            VerifyPow(a, b, real, imaginary);

            real = Support.GetSmallRandomDoubleValue(true);
            imaginary = Support.GetSmallRandomDoubleValue(true);
            VerifyPow(a, b, real, imaginary);

            real = Support.GetSmallRandomDoubleValue(false);
            imaginary = Support.GetSmallRandomDoubleValue(true);
            VerifyPow(a, b, real, imaginary);
        }
        private static void VerifyPow(Double a, Double b, Double doubleVal)
        {
            Complex x = new Complex(a, b);
            Complex powComplex = Complex.Pow(x, doubleVal);

            Double expectedReal = 0;
            Double expectedImaginary = 0;
            if (0 == doubleVal)
                expectedReal = 1;
            else if (!(0 == a && 0 == b))
            {
                //pow(x, y) = exp(y·log(x))
                Complex y = new Complex(doubleVal, 0);
                Complex expected = Complex.Exp(y * Complex.Log(x));
                expectedReal = expected.Real;
                expectedImaginary = expected.Imaginary;
            }

            if (false == Support.VerifyRealImaginaryProperties(powComplex, expectedReal, expectedImaginary))
            {
                Console.WriteLine("Error pOw-Err2534! Pow (({0}, {1}), {2})", a, b, doubleVal);

                Assert.True(false, "Verification Failed");
            }
        }
        private static void VerifyBinaryPlusResult(Double realFirst, Double imgFirst, Double realSecond, Double imgSecond)
        {
            // Create complex numbers
            Complex cFirst = new Complex(realFirst, imgFirst);
            Complex cSecond = new Complex(realSecond, imgSecond);

            // calculate the expected results
            Double realExpectedResult = realFirst + realSecond;
            Double imgExpectedResult = imgFirst + imgSecond;

            //local variable
            Complex cResult;

            // arithmetic addition operation
            cResult = cFirst + cSecond;

            // verify the result
            if (!Support.VerifyRealImaginaryProperties(cResult, realExpectedResult, imgExpectedResult))
            {
                Console.WriteLine("ErRoR! Binary Plus Error!");
                Console.WriteLine("Binary Plus test = ({0}, {1}) + ({2}, {3})", realFirst, imgFirst, realSecond, imgSecond);
                Assert.True(false, "Verification Failed");
            }

            // arithmetic static addition operation
            cResult = Complex.Add(cFirst, cSecond);

            // verify the result
            if (!Support.VerifyRealImaginaryProperties(cResult, realExpectedResult, imgExpectedResult))
            {
                Console.WriteLine("ErRoR! Add Error!");
                Console.WriteLine("Add test = ({0}, {1}) + ({2}, {3})", realFirst, imgFirst, realSecond, imgSecond);
                Assert.True(false, "Verification Failed");
            }
        }
Beispiel #5
0
 public static Int32 OnProgress(Object extraData, Double dlTotal,
     Double dlNow, Double ulTotal, Double ulNow)
 {
     Console.WriteLine("Progress: {0} {1} {2} {3}",
         dlTotal, dlNow, ulTotal, ulNow);
     return 0; // standard return from PROGRESSFUNCTION
 }
        private static void VerifyBinaryMinusResult(Double realFirst, Double imgFirst, Double realSecond, Double imgSecond)
        {
            // Create complex numbers
            Complex cFirst = new Complex(realFirst, imgFirst);
            Complex cSecond = new Complex(realSecond, imgSecond);

            // calculate the expected results
            Double realExpectedResult = realFirst - realSecond;
            Double imgExpectedResult = imgFirst - imgSecond;

            // local varuables
            Complex cResult;

            // arithmetic binary minus operation
            cResult = cFirst - cSecond;

            // verify the result
            if (false == Support.VerifyRealImaginaryProperties(cResult, realExpectedResult, imgExpectedResult))
            {
                Console.WriteLine("ErRoR! Binary Minus Error!");
                Console.WriteLine("Binary Minus test = ({0}, {1}) - ({2}, {3})", realFirst, imgFirst, realSecond, imgSecond);
                Assert.True(false, "Verification Failed");
            }

            // arithmetic substract operation
            cResult = Complex.Subtract(cFirst, cSecond);

            // verify the result
            if (false == Support.VerifyRealImaginaryProperties(cResult, realExpectedResult, imgExpectedResult))
            {
                Console.WriteLine("ErRoR! Substract Error!");
                Console.WriteLine("Substract test = ({0}, {1}) - ({2}, {3})", realFirst, imgFirst, realSecond, imgSecond);
                Assert.True(false, "Verification Failed");
            }
        }
 public static Double ToDouble(string valueToParse, Double defaultValue)
 {
     Double returnValue;
     if (!Double.TryParse(valueToParse, out returnValue))
         returnValue = defaultValue;
     return returnValue;
 }
Beispiel #8
0
 //Test the initial posture of the hand to start the gesture
 protected override void TestInitialGesture(Hand hand)
 {
     InitialPosition = hand.PalmPosition.x;
     PreviousHand = hand;
     ListeGesture[0].TestGesture(hand);
     //ReceiveBeginningRightMoveEvent();
 }
Beispiel #9
0
 public String init()
 {
     this.sof = 0.0;
     this.drivercount = 0;
     this.points = new List<Double>();
     return "sof";
 }
    public static Vector3 Div(Vector3 v1, Double _x)
    {
        v1.x /= (float)_x;
        v1.z /= (float)_x;

        return v1;
    }
Beispiel #11
0
    //method to insert invoice
    public void insertInvoice(Guid _pID, DateTime _createdOn, string _createdBy, string _reason, string _status, DateTime _dueOn, Double _total)
    {
        InvoicesDataContext objInvoiceDC = new InvoicesDataContext();
        try
        {
            Guid invoiceID = Guid.NewGuid();
            Console.Write(invoiceID);
            brdhc_Invoice objInv = new brdhc_Invoice();
            objInv.InvoiceID = invoiceID;
            objInv.PatientID = _pID;
            objInv.CreatedOn = _createdOn;
            objInv.CreatedBy = _createdBy;
            objInv.Reason = _reason;
            objInv.Status = _status;
            objInv.DueOn = _dueOn;
            objInv.TotalAmt = _total;

            objInvoiceDC.brdhc_Invoices.InsertOnSubmit(objInv);
            objInvoiceDC.SubmitChanges();

        }
        catch (Exception e)
        {
            clsCommon.saveError(e);
        }
    }
        private static void VerifyBinaryMultiplyResult(Double realFirst, Double imgFirst, Double realSecond, Double imgSecond)
        {
            // calculate the expected results
            Double realExpectedResult = realFirst * realSecond - imgFirst * imgSecond;
            Double imaginaryExpectedResult = realFirst * imgSecond + imgFirst * realSecond;

            // Create complex numbers
            Complex cFirst = new Complex(realFirst, imgFirst);
            Complex cSecond = new Complex(realSecond, imgSecond);

            // arithmetic multiply (binary) operation
            Complex cResult = cFirst * cSecond;

            // verify the result
            if (false == Support.VerifyRealImaginaryProperties(cResult, realExpectedResult, imaginaryExpectedResult))
            {
                Console.WriteLine("ErRoR! Binary Multiply Error!");
                Console.WriteLine("Binary Multiply test = ({0}, {1}) * ({2}, {3})", realFirst, imgFirst, realSecond, imgSecond);
                Assert.True(false, "Verification Failed");
            }

            // arithmetic multiply (static) operation
            cResult = Complex.Multiply(cFirst, cSecond);

            // verify the result
            if (false == Support.VerifyRealImaginaryProperties(cResult, realExpectedResult, imaginaryExpectedResult))
            {
                Console.WriteLine("ErRoR! Multiply (Static) Error!");
                Console.WriteLine("Multiply (Static) test = ({0}, {1}) * ({2}, {3})", realFirst, imgFirst, realSecond, imgSecond);
                Assert.True(false, "Verification Failed");
            }
        }
Beispiel #13
0
    public win()
    {
        try {
        this.Text="Calculator";
        panCalc=new Panel();
        txtCalc = new TextBox();

        txtCalc.Location = new Point(10,10);
        txtCalc.Size=new Size(150,10);
        txtCalc.ReadOnly=true;
        txtCalc.RightToLeft=RightToLeft.Yes;
        panCalc.Size=new Size(200,200);
        panCalc.BackColor=Color.Aqua;
        panCalc.Controls.Add(txtCalc);
        addButtons(panCalc);
        this.Size=new Size(200,225);
        this.Controls.Add(panCalc);

        dblAcc=0;
        dblSec=0;
        blnFrstOpen=true;
        blnClear=false;
        strOper=new String('=',1);
        }
        catch (Exception e) {
        Console.WriteLine("error ......  " + e.StackTrace);
        }
    }
Beispiel #14
0
    static void Main(String[] args)
    {
        Console.WriteLine("Enter numbers separated by comma: ");
          string lineofnumbers = Console.ReadLine();

          string answer = "default";
          while(true)
        {
          Console.WriteLine("Default is sorting by ascending order. Sort by descending order ? (y, n): ");
          answer = Console.ReadLine();
          if("y" == answer)
        {
          Console.WriteLine("Yes");
          break;
        }
          else
        {
          Console.WriteLine("Default");
          break;
        }
        }
          string[] tokens = lineofnumbers.Split(',');

          Double[] array = new Double[tokens.Length];

          for(int i = 0; i < tokens.Length; i++)
        array[i] = Double.Parse(tokens[i]);

          double[] sorted = QuickSort(array, 0, array.Length - 1);
          foreach(Double i in sorted)
        Console.WriteLine(i);
    }
 public SetAttributes createSet(Int32 rep, Int32 time, Int32 weight, Double distance, Int64 logID)
 {
     using (var context = new Layer2Container())
     {
         LoggedExercise existingLog = context.LoggedExercises.Where(log => log.id == logID).FirstOrDefault();
         if (existingLog != null)
         {
             SetAttributes set;
             set = new SetAttributes();
             set.reps = rep;
             set.time = time;
             set.weight = weight;
             set.distance = distance;
             set.timeLogged = DateTime.Now;
             set.LoggedExercise = existingLog;
             context.SetAttributes.AddObject(set);
             context.SaveChanges();
             return set;
         }
         else
         {
             return null;
         }
     }
 }
Beispiel #16
0
 public static Double[] QuickSort(Double[] a, Double left, Double right)
 {
     Double i = left;
       Double j = right;
       Double randcentre = ((left + right) / 2);
       Double x = a[Convert.ToInt32(randcentre)];
       Double w = 0;
       while (i <= j)
     {
       while (a[Convert.ToInt32(i)] < x)
     {
       i++;
     }
       while (x < a[Convert.ToInt32(j)])
     {
       j--;
     }
       if (i <= j)
     {
       w = a[Convert.ToInt32(i)];
       a[Convert.ToInt32(i++)] = a[Convert.ToInt32(j)];
       a[Convert.ToInt32(j--)] = w;
     }
     }
       if (left < j)
     {
       QuickSort(a, left, j);
     }
       if (i < right)
     {
       QuickSort(a, i, right);
     }
       return a;
 }
Beispiel #17
0
    protected void Calculate(object sender, EventArgs e)
    {
        Double resistance = 0;

        // Tracks
        width = ToMicrons (WidthEntry.Text, WidthCombo);
        thickness = ToMicrons (ThicknessEntry.Text, ThicknessCombo);
        length = ToMicrons (LengthEntry.Text, LengthCombo);

        // Vias
        vias = -1;
        if (ViaEntry.Text != "") {
            if (Int32.TryParse (ViaEntry.Text, out vias)) {
                plating = ToMicrons (PlatingEntry.Text, PlatingCombo);
                diameter = ToMicrons (DrillEntry.Text, DrillCombo);
                via_length = ToMicrons (ViaLengthEntry.Text, ViaLengthCombo);
            }
        } else
            vias = 0;

        // Calculate and display resistance
        if (ValuesValid ()) {
            resistance = rho_foil * length / (width * thickness);
            if (vias > 0){
                Double radius = diameter / 2.0;
                Double area = (Math.PI * Math.Pow(radius,2.0)) - (Math.PI * Math.Pow(radius-plating, 2.0));
                resistance += vias * rho_plated * via_length / area;
            }
            ResistanceLabel.Text = String.Format ("Resistance = {0:G4} Ω", resistance);
        }
        else
            ResistanceLabel.Text = "Error";
    }
    protected void grdDealerPromotInfo_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                HiddenField hdnPackName = (HiddenField)e.Row.FindControl("hdnPackName");
                HiddenField hdnPackCost = (HiddenField)e.Row.FindControl("hdnPackCost");
                Label lblPackage = (Label)e.Row.FindControl("lblPackage");
                Label lblPhone = (Label)e.Row.FindControl("lblPhone");
                HiddenField hdnPhoneNum = (HiddenField)e.Row.FindControl("hdnPhoneNum");

                Double PackCost = new Double();
                PackCost = Convert.ToDouble(hdnPackCost.Value.ToString());
                string PackAmount = string.Format("{0:0.00}", PackCost).ToString();
                string PackName = hdnPackName.Value.ToString();
                lblPackage.Text = PackName + "($" + PackAmount + ")";
                if (hdnPhoneNum.Value.ToString() == "")
                {
                    lblPhone.Text = "";
                }
                else
                {
                    lblPhone.Text = objGeneralFunc.filPhnm(hdnPhoneNum.Value);
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
        private static void VerifyExpWithAddition(Double real, Double imaginary)
        {
            // verify with e(x+y) = e(x)*e(y) if xy == yx
            Complex realComplex = new Complex(real, 0.0);
            Complex imgComplex = new Complex(0.0, imaginary);

            Complex ri = realComplex * imgComplex;
            Complex ir = imgComplex * realComplex;
            if (!ri.Equals(ir))
            {
                return;
            }

            Complex realExp = Complex.Exp(realComplex);
            Complex imgExp = Complex.Exp(imgComplex);
            Complex expectedExp = realExp * imgExp;

            Complex complex = new Complex(real, imaginary);
            Complex complexExp = Complex.Exp(complex);

            if (false == Support.VerifyRealImaginaryProperties(complexExp, expectedExp.Real, expectedExp.Imaginary))
            {
                Console.WriteLine("Error eXp-Err3521! Exp({0}):{1} != {2})", complex, complexExp, expectedExp);
                Assert.True(false, "Verification Failed");
            }
        }
        private static void VerifySqrtWithRectangularForm(Double real, Double imaginary)
        {
            // sqrt(a+bi) = +- (sqrt(r + a) + i sqrt(r - a) sign(b)) sqrt(2) / 2, unless a=-r and y = 0
            Complex complex = new Complex(real, imaginary);

            Double expectedReal = 0.0;
            Double expectedImaginary = 0.0;

            if (0 == imaginary)
            {
                if (real == -complex.Magnitude)
                    expectedImaginary = Math.Sqrt(-real);
                else
                    expectedReal = Math.Sqrt(real);
            }
            else
            {
                Double scale = 1 / Math.Sqrt(2);
                expectedReal = scale * Math.Sqrt(complex.Magnitude + complex.Real);
                expectedImaginary = scale * Math.Sqrt(complex.Magnitude - complex.Real);
                if (complex.Imaginary < 0)
                {
                    expectedImaginary = -expectedImaginary;
                }
            }
            VerifySqrtWithRectangularForm(real, imaginary, expectedReal, expectedImaginary);
        }
 public Double ValueAtRetirement(Double StartingBalance, Double MonthlyAddition)
 {
     if (StartingBalance < 0)
         throw new ArgumentOutOfRangeException("Starting Balance cannot be less than 0");
     if (MonthlyAddition < 0)
         throw new ArgumentOutOfRangeException("MonthlyAddition cannot be less than 0");
     return MyCalc.valueAtRetierment(StartingBalance, MonthlyAddition);
 }
Beispiel #22
0
 public String init(IHost parent)
 {
     Parent = parent;
     this.sof = 0.0;
     this.drivercount = 0;
     this.points = new List<Double>();
     return "sof";
 }
Beispiel #23
0
 public static Double GetBigEndian(Double value)
 {
     if(BitConverter.IsLittleEndian) {
     return swapByteOrder(value);
     } else {
     return value;
     }
 }
Beispiel #24
0
 protected void btnDelete_Click(object sender, EventArgs e)
 {
     m_SId = Convert.ToInt32(txtId.Text.ToString());
     clsDb.InsertUpdate("delete from SubjectMaster where SId=" + m_SId + "");
     Reset();
     lblmsg.Visible = true;
     lblmsg.ForeColor = System.Drawing.Color.Red;
     lblmsg.Text = "Video deleted successfully....!!!";
 }
    protected void grdPDPayData_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                HiddenField hdnPackName = (HiddenField)e.Row.FindControl("hdnPackName");
                HiddenField hdnPackCost = (HiddenField)e.Row.FindControl("hdnPackCost");
                Label lblPackage = (Label)e.Row.FindControl("lblPackage");
                Label lblPhone = (Label)e.Row.FindControl("lblPhone");
                HiddenField hdnPhoneNum = (HiddenField)e.Row.FindControl("hdnPhoneNum");
                HiddenField hdnStatus = (HiddenField)e.Row.FindControl("hdnStatus");
                Image ImgStatus = (Image)e.Row.FindControl("ImgStatus");
                Double PackCost = new Double();
                PackCost = Convert.ToDouble(hdnPackCost.Value.ToString());
                string PackAmount = string.Format("{0:0.00}", PackCost).ToString();
                string PackName = hdnPackName.Value.ToString();
                lblPackage.Text = PackName + "($" + PackAmount + ")";
                if (hdnPhoneNum.Value.ToString() == "")
                {
                    lblPhone.Text = "";
                }
                else
                {
                    lblPhone.Text = objGeneralFunc.filPhnm(hdnPhoneNum.Value);
                }
                if (hdnStatus.Value.ToString() == "1")
                {

                    ImgStatus.ImageUrl = "~/images/check.gif";
                }
                else if (hdnStatus.Value.ToString() == "2")
                {

                    ImgStatus.ImageUrl = "~/images/lock.gif";
                }
                else if (hdnStatus.Value.ToString() == "3")
                {

                    ImgStatus.ImageUrl = "~/images/icon13.png";
                }
                else if (hdnStatus.Value.ToString() == "4")
                {
                    ImgStatus.ImageUrl = "~/images/icon14.gif";
                }
                else if (hdnStatus.Value.ToString() == "5")
                {
                    ImgStatus.ImageUrl = "~/images/red_x.png";
                }

            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
Beispiel #26
0
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        m_LId = Convert.ToInt32(txtId.Text.ToString());
        clsDb.InsertUpdate("delete from Comments where Id=" + m_LId + "");
        Reset();
        lblmsg.Visible = true;

        lblmsg.Text = "Comment deleted successfully....!!!";
    }
 private static void VerifySqrtWithRectangularForm(Double real, Double imaginary, Double expectedReal, Double expectedImaginary)
 {
     Complex complex = new Complex(real, imaginary);
     Complex sqrtComplex = Complex.Sqrt(complex);
     if (false == Support.VerifyRealImaginaryProperties(sqrtComplex, expectedReal, expectedImaginary))
     {
         Console.WriteLine("Error sQRt-Err2534! Sqrt({0}):{1} != ({2},{3})", complex, sqrtComplex, expectedReal, expectedImaginary);
         Assert.True(false, "Verification Fail");
     }
 }
Beispiel #28
0
 /// <summary>
 /// Remove border effect
 /// </summary>
 public static void RemoveBorderEffect(Shape shape, BorderStyles borderStyle, Double borderThickness, Brush lineColor)
 {   
     shape.Stroke = lineColor;
     shape.StrokeThickness = borderThickness;
     shape.StrokeStartLineCap = PenLineCap.Flat;
     shape.StrokeEndLineCap = PenLineCap.Flat;
     shape.StrokeDashOffset = 0;
     shape.StrokeLineJoin = PenLineJoin.Bevel;
     shape.StrokeDashArray = Graphics.LineStyleToStrokeDashArray(borderStyle.ToString());
 }
Beispiel #29
0
    /// <summary>
    /// Remove border effect
    /// </summary>
    public static void RemoveBorderEffect(Shape shape, BorderStyles borderStyle, Double borderThickness, Brush lineColor, Brush fillColor, Double width, Double height)
    {
        RemoveBorderEffect(shape, borderStyle, borderThickness, lineColor);
        shape.Fill = fillColor;
        shape.Height = height;
        shape.Width = width;

        shape.SetValue(Canvas.TopProperty, -shape.Height / 2);
        shape.SetValue(Canvas.LeftProperty, -shape.Width / 2);
    }
Beispiel #30
0
    /// <summary>
    /// Apply border effect
    /// </summary>
    public static void ApplyBorderEffect(Shape shape, BorderStyles borderStyles, Brush fillColor, Double scaleFactor, Double borderThickness, Brush borderColor)
    {
        ApplyBorderEffect(shape, borderStyles, borderThickness, borderColor);
        shape.Fill = fillColor;
        shape.Height *= scaleFactor;
        shape.Width *= scaleFactor;

        shape.SetValue(Canvas.TopProperty, -shape.Height / 2);
        shape.SetValue(Canvas.LeftProperty, -shape.Width / 2);
    }
        public void OnGet()
        {
            PO = "Idle No PO";
            List <string> headData = new List <string>();
            Dictionary <string, List <string> > Heads = new Dictionary <string, List <string> >();

            try
            {
                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
                builder.ConnectionString = _configuration.GetConnectionString("B61");
                using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
                {
                    connection.Open();
                    string spName = @"dbo.[sp_4B_GetToteInfo]";
                    using (SqlCommand command = new SqlCommand(spName, connection))
                    {
                        command.CommandType    = CommandType.StoredProcedure;
                        command.CommandTimeout = 60;
                        using (SqlDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                headData.Add(reader.GetInt32(1).ToString());    //tote             0
                                headData.Add(reader.GetInt32(2).ToString());    //material         1
                                headData.Add(reader.GetDouble(3).ToString());   //target         2
                                headData.Add(reader.GetDateTime(4).ToString()); //last drop     3
                                headData.Add(reader.GetInt32(5).ToString());    //quantity         4

                                if (reader[10] != DBNull.Value)
                                {
                                    PO = reader.GetString(10);
                                    headData.Add(reader.GetInt32(6).ToString()); //drops            5
                                    if (reader.GetInt32(6) > 200)
                                    {
                                        headData.Add("green");                          //colours   6
                                    }
                                    else if (reader.GetInt32(6) > 75)
                                    {
                                        headData.Add("orange");
                                    }
                                    else
                                    {
                                        headData.Add("red");
                                    }
                                    //headData.Add(DateTime.Now.AddSeconds(reader.GetInt32(7)).ToString("h:mm tt")); //Time Left 7 TimeSpan.FromSeconds(reader.GetInt32(8)).ToString()
                                    headData.Add(TimeSpan.FromSeconds(reader.GetInt32(7)).ToString(@"hh\:mm\:ss"));
                                    headData.Add(reader.GetInt32(9).ToString()); //Total_Bags_Dropped 8
                                    headData.Add(reader.GetString(10));          //PO 9
                                }
                                else
                                {
                                    headData.Add("0");
                                    headData.Add("grey");
                                    headData.Add("Not In Use");
                                    headData.Add("0");
                                    headData.Add("Not In Current PO");
                                }
                                Heads.Add(reader.GetString(0), new List <string>(headData));
                                headData.Clear();
                            }
                            reader.Close();
                        }
                        connection.Close();
                    }
                }
            }
            catch (SqlException e)
            {
                Console.WriteLine(e.ToString());
            }

            if (PO != "Idle No PO")
            {
                try
                {
                    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
                    builder.ConnectionString = _configuration.GetConnectionString("B106");
                    using (SqlConnection connection106 = new SqlConnection(builder.ConnectionString))
                    {
                        string spName = @"dbo.[spDPGetBagQuantityOrdered]";
                        connection106.Open();
                        using (SqlCommand command = new SqlCommand(spName, connection106))
                        {
                            command.Parameters.AddWithValue("@PO", PO);
                            command.CommandType = CommandType.StoredProcedure;
                            using (SqlDataReader reader = command.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    Current_PO_Bags = reader.GetInt32(1);
                                }
                                reader.Close();
                            }
                        }
                        connection106.Close();
                    }
                }
                catch (SqlException e)
                {
                    Console.WriteLine(e.ToString());
                }
            }
            else
            {
                Current_PO_Bags = 0;
            }
            // Ref: https://www.chartjs.org/docs/latest/

            int           Total_Kg_Rem;
            decimal       temp;
            int           Totes_Rem;
            List <string> head;
            int           i;
            string        headName;

            for (i = 0; i < Heads.Count; i++)
            {
                head         = Heads.Values.ElementAt(i);
                headName     = Heads.Keys.ElementAt(i);
                Total_Kg_Rem = (int)(Double.Parse(head[2]) * (Current_PO_Bags - Int32.Parse(head[8])));
                if (Total_Kg_Rem < 0)
                {
                    Total_Kg_Rem = 0;
                }
                temp = Decimal.Divide((Total_Kg_Rem - Int32.Parse(head[4])), 1000);
                if (temp < 0)
                {
                    temp = 0;
                }
                Totes_Rem = (int)Math.Ceiling(temp);
                if (head[9] != "Not In Current PO")
                {
                    Heads[headName].Add(Totes_Rem.ToString());
                }
            }


            Chart1 = chartPop("4BH1", Heads);
            Chart2 = chartPop("4BH2", Heads);
            Chart3 = chartPop("4BH3", Heads);
            Chart4 = chartPop("4BH4", Heads);
            Chart5 = chartPop("4BH5", Heads);
            Chart6 = chartPop("4BH6", Heads);

            ChartJson1 = JsonConvert.SerializeObject(Chart1, new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore,
            });
            ChartJson2 = JsonConvert.SerializeObject(Chart2, new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore,
            });
            ChartJson3 = JsonConvert.SerializeObject(Chart3, new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore,
            });
            ChartJson4 = JsonConvert.SerializeObject(Chart4, new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore,
            });
            ChartJson5 = JsonConvert.SerializeObject(Chart5, new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore,
            });
            ChartJson6 = JsonConvert.SerializeObject(Chart6, new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore,
            });
        }
Beispiel #32
0
        /// <summary>
        /// Bootstraps the specified priceable assets.
        /// </summary>
        /// <param name="priceableAssets">The priceable assets.</param>
        /// <param name="baseDate">The base date.</param>
        /// <param name="extrapolationPermitted">The extrapolationPermitted flag.</param>
        /// <param name="interpolationMethod">The interpolationMethod.</param>
        /// <param name="tolerance">Solver tolerance to use.</param>
        /// <returns></returns>
        public static TermPoint[] Bootstrap(List <IPriceableCommodityAssetController> priceableAssets,
                                            DateTime baseDate, Boolean extrapolationPermitted,
                                            InterpolationMethod interpolationMethod, Double tolerance)
        {
            //const Double cSolveRateGap = 0.015d;//should we need more precising perhaps???
            //const double Min = 0.000000001;
            //const double max = 2;
            const double defaultGuess = 0.9;

            //const Double accuracy = 0.000001d;
            priceableAssets.Sort
            (
                (priceableAssetController1, priceableAssetController2) =>
                priceableAssetController1.GetRiskMaturityDate().CompareTo(priceableAssetController2.GetRiskMaturityDate())
            );
            //  Add the first element (date : discount factor) to the list
            //
            //  Add the first element (date : discount factor) to the list
            var points = new Dictionary <DateTime, double>();           //{ { baseDate, 1d } }
            var items
                = new Dictionary <DateTime, Pair <string, decimal> >(); //{ { baseDate, new Pair<string, decimal>("", 1m) } }
            bool first = true;

            foreach (var priceableAsset in priceableAssets)
            {
                //TODO check if the maturity date is already in the list. If not contimue.
                var assetMaturityDate = priceableAsset.GetRiskMaturityDate();
                if (points.Keys.Contains(assetMaturityDate))
                {
                    continue;
                }
                // do we really need that guess step??? I don't think so...
                //
                //if (assetMaturityDate < points.Keys.Last())
                //{
                //    throw new InvalidOperationException("The maturity dates of the assets must be consecutive order");
                //}
                //only works for linear on zero.
                var     interp = InterpolationMethodHelper.Parse("LinearInterpolation");
                decimal dfam;
                if (first)
                {
                    first = false;
                    // Add the first point
                    points.Add(assetMaturityDate, defaultGuess);
                    var curve = new SimpleCommodityCurve(baseDate, interp, extrapolationPermitted, points);
                    dfam = priceableAsset.CalculateImpliedQuote(curve);
                    points[assetMaturityDate] = (double)dfam;
                }
                else
                {
                    //The first guess, which should be correct for all priceable assets with analytical solutions that have been implemented.
                    //So far this is only wrt Depos and Futures...This now should automatically extrapolate the required discount factor on a flat rate basis.
                    var curve = new SimpleCommodityCurve(baseDate, interp, extrapolationPermitted, points);
                    //The first guess, which should be correct for all priceable assets with analytical solutions that have been implemented.
                    dfam = priceableAsset.CalculateImpliedQuote(curve);
                    points.Add(assetMaturityDate, (double)dfam);
                }
                //Add a check on the dfam so that the solver is only called if outside tyhe tolerance.
                //var objectiveFunction = new CommodityAssetQuote(priceableAsset, baseDate, interpolationMethod,
                //                                         extrapolationPermitted, points, tolerance);
                //// Check whether the guess was close enough
                //if (!objectiveFunction.InitialValue())
                //{
                //    var timeInterval = Actual365.Instance.YearFraction(baseDate, assetMaturityDate);
                //    var cSolveInterval = Math.Exp(-cSolveRateGap * timeInterval);
                //    var min = Math.Max(0,(double)dfam * cSolveInterval);
                //    var max = (double)dfam / cSolveInterval;
                //    double guess = Math.Max(min, points[assetMaturityDate]);
                //    var solver = new Brent();
                //    points[assetMaturityDate] = solver.Solve(objectiveFunction, tolerance, guess, min, max);
                //}
                items.Add(assetMaturityDate, new Pair <string, decimal>(priceableAsset.Id, (decimal)points[assetMaturityDate]));
            }
            return(TermPointsFactory.Create(items));
        }
Beispiel #33
0
        public static string GetAreaBound()
        {
            Document doc = AcAp.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            //PromptKeywordOptions pkOp = new PromptKeywordOptions("");
            //pkOp.Message = "\nUse Island Detection ";
            //pkOp.Keywords.Add("Yes");
            //pkOp.Keywords.Add("No");
            //pkOp.AllowNone = false;
            //PromptResult pr = ed.GetKeywords(pkOp);
            //if (pr.Status == PromptStatus.Cancel)
            //{
            //    return null;
            //}
            //string pkostr = pr.StringResult;
            //bool flagIsland = false;
            //if (pkostr == "Yes") { flagIsland = true; } else { flagIsland = false; }
            PromptPointResult ppr = ed.GetPoint("\nSelect Internal Point on Closed Area: ");
            if (ppr.Status != PromptStatus.OK)
            {
                ed.WriteMessage("\n" + ppr.StringResult);
            }
            string value = null;
            DBObjectCollection dbObjColl = ed.TraceBoundary(ppr.Value, false);
            Double area = 0;
            try
            {
                if (dbObjColl.Count > 0)
                {
                    Transaction tr = doc.TransactionManager.StartTransaction();
                    using (tr)
                    {
                        BlockTable bt = (BlockTable)
                           tr.GetObject(doc.Database.BlockTableId, OpenMode.ForRead);
                        BlockTableRecord btr = (BlockTableRecord)
                            tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);
                        ObjectIdCollection objIds = new ObjectIdCollection();
                        foreach (DBObject Obj in dbObjColl)
                        {
                            Entity ent = Obj as Entity;
                            if (ent != null)
                            {
                                // ent.GetField("Area");
                                if (ent is Polyline)
                                {
                                    Polyline p = (Polyline)ent;
                                    if (p.Closed)
                                    {
                                        area = p.Area;
                                        string presisi = "#";
                                        switch (db.Auprec)
                                        {
                                            case 0:
                                                presisi = "#";
                                                break;
                                            case 1:
                                                presisi = "#0.0";
                                                break;
                                            case 2:
                                                presisi = "#0.00";
                                                break;
                                            case 3:
                                                presisi = "#0.000";
                                                break;
                                            case 4:
                                                presisi = "#0.0000";
                                                break;
                                            case 5:
                                                presisi = "#0.00000";
                                                break;
                                            default:
                                                presisi = "#0.00";
                                                break;
                                        }
                                        value = area.ToString(presisi);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch
            {

                throw;
            }
            return value;
        }
Beispiel #34
0
        private void LaunchAppViewLoad(String str)
        {
            try { jstr = Web.ReplaceHtml(Regex.Split(Regex.Split(Regex.Split(str, "应用简介</p>")[1], @"<div class=""apk_left_title_info"">")[1], "</div>")[0].Trim()); } catch (Exception) { }
            try { vmstr = Web.ReplaceHtml(Regex.Split(Regex.Split(str, @"<p class=""apk_left_title_info"">")[2], "</p>")[0].Replace("<br />", "").Replace("<br/>", "").Trim()); } catch (Exception) { }
            try { dstr = Web.ReplaceHtml(Regex.Split(Regex.Split(str, @"<p class=""apk_left_title_info"">")[1], "</p>")[0].Replace("<br />", "").Replace("<br/>", "").Trim()); } catch (Exception) { }
            vstr = Regex.Split(str, @"<p class=""detail_app_title"">")[1].Split('>')[1].Split('<')[0].Trim();
            mstr = Regex.Split(str, @"<p class=""apk_topba_message"">")[1].Split('<')[0].Trim().Replace("\n", "").Replace(" ", "");
            nstr = Regex.Split(str, @"<p class=""detail_app_title"">")[1].Split('<')[0].Trim();
            iurl = Regex.Split(str, @"<div class=""apk_topbar"">")[1].Split('"')[1].Trim();
            vtstr = Regex.Split(str, "更新时间:")[1].Split('<')[0].Trim();
            rstr = Regex.Split(str, @"<p class=""rank_num"">")[1].Split('<')[0].Trim();
            pstr = Regex.Split(str, @"<p class=""apk_rank_p1"">")[1].Split('<')[0].Trim();

            //Download URI
            ddstr = Regex.Split(Regex.Split(Regex.Split(str, "function onDownloadApk")[1], "window.location.href")[1], @"""")[1];

            AppIconImage.Source = new BitmapImage(new Uri(iurl, UriKind.RelativeOrAbsolute));
            TitleTextBlock.Text = AppTitleText.Text = nstr;
            AppVTText.Text = vtstr;
            AppV2Text.Text = vstr;
            AppVText.Text = vstr;
            AppMText.Text = Regex.Split(mstr, "/")[2] + " " + Regex.Split(mstr, "/")[3] + " " + rstr + "分";
            AppXText.Text = Regex.Split(mstr, "/")[1] + " · " + Regex.Split(mstr, "/")[0];

            if (Regex.Split(str, @"<p class=""apk_left_title_info"">").Length > 3)
            {
                //当应用有点评
                AppVMText.Text = vmstr;
                AppDText.Text = dstr;
                DPanel.Visibility = Visibility.Visible;
            }
            else
            {
                //当应用无点评的时候(小编要是一个一个全好好点评我就不用加判断了嘛!)
                AppVMText.Text = dstr;
                AppDText.Text = "";
            }
            if (dstr.Contains("更新时间") && dstr.Contains("ROM") && dstr.Contains("名称")) UPanel.Visibility = Visibility.Collapsed;


            //加载截图!
            String images = Regex.Split(Regex.Split(str, @"<div class=""ex-screenshot-thumb-carousel"">")[1], "</div>")[0];
            String[] imagearray = Regex.Split(images, "<img");
            for (int i = 0; i < imagearray.Length - 1; i++)
            {
                String imageUrl = imagearray[i + 1].Split('"')[1];
                if (!imageUrl.Equals(""))
                {
                    Image newImage = new Image
                    {
                        Height = 100,
                        //获得图片
                        Source = new BitmapImage(new Uri(imageUrl, UriKind.RelativeOrAbsolute))
                    };
                    //添加到缩略视图
                    ScreenShotView.Items.Add(newImage);
                }
            }
            images = Regex.Split(Regex.Split(str, @"<div class=""carousel-inner"">")[1], @"<a class=""left carousel-control""")[0];
            imagearray = Regex.Split(images, "<img");
            for (int i = 0; i < imagearray.Length - 1; i++)
            {
                String imageurl = imagearray[i + 1].Split('"')[1];
                Image newImage = new Image
                {
                    //获得图片
                    Source = new BitmapImage(new Uri(imageurl, UriKind.RelativeOrAbsolute))
                };
                //添加到视图
                ScreenShotFlipView.Items.Add(newImage);
            }

            //还有简介(丧心病狂啊)
            AppJText.Text = jstr;

            //评分。。
            AppRText.Text = rstr;
            AppPText.Text = pstr;
            //星星
            double rdob = Double.Parse(rstr);
            if (rdob > 4.5)
            {

            }
            else if (rdob > 3.0)
            {
                star5.Symbol = Symbol.OutlineStar;
            }
            else if (rdob > 4.0)
            {
                star4.Symbol = Symbol.OutlineStar;
                star5.Symbol = Symbol.OutlineStar;
            }
            else if (rdob > 3.0)
            {
                star3.Symbol = Symbol.OutlineStar;
                star4.Symbol = Symbol.OutlineStar;
                star5.Symbol = Symbol.OutlineStar;
            }
            else if (rdob < 2.0)
            {
                //没有评分那么差的应用吧233
                star2.Symbol = Symbol.OutlineStar;
                star3.Symbol = Symbol.OutlineStar;
                star4.Symbol = Symbol.OutlineStar;
                star5.Symbol = Symbol.OutlineStar;
            }


            /*
            //获取开发者
            string knstr = Web.ReplaceHtml(Regex.Split(Regex.Split(str, "开发者名称:")[1], "</p>")[0]);
            try
            {
                AppKNText.Text = knstr;
                AppKImage.Source = new BitmapImage(new Uri(await CoolApkSDK.GetCoolApkUserFaceUri(knstr), UriKind.RelativeOrAbsolute));
            }
            catch (Exception)
            {
                KPanel.Visibility = Visibility.Collapsed;
            }*/
            mainPage.DeactiveProgressRing();
        }
Beispiel #35
0
        // This method is for the the ACTUAL graph, not the table.

        // The reason why I can't sync the graph and the table by calling them at the same time is because I don't
        // know what graph the user wants to see first. So I have to wait for them to call the graph in.

        // However, I could modify the program to force the update table background worker to emit an event every time it
        // completes updating. I could emit it, and just not have anything listening quite yet,
        //
        //
        //


        public static void chartdelegatemethodplotpoint(String[] information, int i)
        {
            //foreach ( String inf in information ) { Console.WriteLine("THIS IS THE TEST!!!!" + inf);  } // BUG SQAUSHING COMMENT

            double deltaautoscale       = 5; //how many points to scale for auto resize
            double millisecondtimestamp = Double.Parse(information[1]);
            // I think the temp varaible is way too large and slowing down the update time of the graph, and the
            // response time of the graph. We'll lower the number and see what happens 5/15/17
            double temp         = ((((((Double.Parse(information[1])) / 1000) / 60) / 60) / 60) / 60);
            double bidbigfigure = Double.Parse(information[2]);
            String bidbigfigurestring;
            double bidpoints = double.Parse(information[3]);
            String bidpointsstring;
            double bidprice = (Double.Parse(information[2] + information[3]));

            //int minutes = (int)(((millisecondtimestamp / 1000) / 60) % 60);
            //String minutesstring = minutes.ToString();
            //String minutesrawstring = (((millisecondtimestamp / 1000) / 60) % 60).ToString();
            //int hour = (int)((((millisecondtimestamp / 1000) / 60) / 60) % 24);
            //String hourstring = hour.ToString();
            //double timestamp = Double.Parse(hourstring + "." + minutesstring);
            //String secondsraw = (((Double.Parse(minutesrawstring.Substring(minutesrawstring.IndexOf('.'))) * 6).ToString()).Replace(".", ""));
            //if (!(secondsraw.Length < 2)) { secondsraw = secondsraw.Substring(0, 2); }
            //t seconds = (int)secondsraw;
            //double timestamp = Double.Parse(hourstring + minutesstring + "." + secondsraw);
            //Console.WriteLine(minutesrawstring.Substring(minutesrawstring.IndexOf('.')));
            //Console.WriteLine(secondsraw);
            //timestamp = (timestamp - 700);
            //Console.WriteLine(((millisecondtimestamp / 1000) / 60) % 60);
            //Console.WriteLine(timestamp);

            //Readjustment should happen automatically for the first time no matter whats going on in the program.
            if (/*((Math.Abs(currencychart.ChartAreas[0].AxisY.Maximum - bidprice) > 0.00005)) &&*/ !(didreadjust))
            {
                //On any cuurency where the bidbigfigure has a decimal point in it, it gets lost in the to string, and
                //ends up being a gigantic number on the graph.
                if (!((bidbigfigure.ToString()).Contains(".")))
                {
                    bidbigfigurestring = (bidbigfigure.ToString() + ".");
                }
                else if (bidbigfigure.ToString().Length == 3)
                {
                    bidbigfigurestring = bidbigfigure.ToString() + "0";
                }
                else
                {
                    bidbigfigurestring = bidbigfigure.ToString();
                }
                bidpointsstring = (bidpoints + deltaautoscale).ToString();
                if (bidpointsstring.Length < 3)
                {
                    bidpointsstring = ("0" + bidpointsstring);
                }
                currencychart.ChartAreas[0].AxisY.Maximum = Double.Parse(bidbigfigurestring + bidpointsstring);
                bidpointsstring = (bidpoints - deltaautoscale).ToString();
                if (bidpointsstring.Length < 3)
                {
                    bidpointsstring = ("0" + bidpointsstring);
                }
                currencychart.ChartAreas[0].AxisY.Minimum = Double.Parse(bidbigfigurestring + bidpointsstring);
                didreadjust = true;
            }
            if ((bidprice >= currencychart.ChartAreas[0].AxisY.Maximum))
            {
                if (!((bidbigfigure.ToString()).Contains(".")))
                {
                    bidbigfigurestring = (bidbigfigure.ToString() + ".");
                }
                else if (bidbigfigure.ToString().Length == 3)
                {
                    bidbigfigurestring = bidbigfigure.ToString() + "0";
                }
                else
                {
                    bidbigfigurestring = bidbigfigure.ToString();
                }
                if ((bidpoints + deltaautoscale) > 999)
                {
                    if (!(bidbigfigurestring.EndsWith(".")))
                    {
                        int    count          = ((bidbigfigurestring.Substring(bidbigfigurestring.IndexOf(".")).Length) - 1);
                        String additionstring = "1";
                        for (; count != 0; count--)
                        {
                            additionstring = additionstring.Insert(0, "0");
                        }
                        if (additionstring.Contains("0"))
                        {
                            additionstring = additionstring.Insert((additionstring.IndexOf("0") + 1), ".");
                        }
                        bidbigfigure += Double.Parse(additionstring);
                    }
                    else
                    {
                        bidbigfigure += 1;
                    }
                    //Only works for sane amounts of deltaautoscale
                    bidpoints       = (bidpoints + deltaautoscale) % 1000;
                    bidpointsstring = bidpoints.ToString();
                }
                else
                {
                    bidpointsstring = (bidpoints - deltaautoscale).ToString();
                }
                bidpointsstring = (bidpoints + deltaautoscale).ToString();
                if (bidpointsstring.Length < 3)
                {
                    bidpointsstring = ("0" + bidpointsstring);
                }
                currencychart.ChartAreas[0].AxisY.Maximum = Double.Parse(bidbigfigurestring + bidpointsstring);
            }
            if (bidprice < currencychart.ChartAreas[0].AxisY.Minimum)
            {
                if (!((bidbigfigure.ToString()).Contains(".")))
                {
                    bidbigfigurestring = (bidbigfigure.ToString() + ".");
                }
                else if (bidbigfigure.ToString().Length == 3)
                {
                    bidbigfigurestring = bidbigfigure.ToString() + "0";
                }
                else
                {
                    bidbigfigurestring = bidbigfigure.ToString();
                }
                if ((bidpoints - deltaautoscale) < 0)
                {
                    if (!(bidbigfigurestring.EndsWith(".")))
                    {
                        int    count             = ((bidbigfigurestring.Substring(bidbigfigurestring.IndexOf(".")).Length) - 1);
                        String subtractionstring = "1";
                        for (; count != 0; count--)
                        {
                            subtractionstring = subtractionstring.Insert(0, "0");
                        }
                        if (subtractionstring.Contains("0"))
                        {
                            subtractionstring = subtractionstring.Insert((subtractionstring.IndexOf("0") + 1), ".");
                        }
                        bidbigfigure -= Double.Parse(subtractionstring);
                    }
                    else
                    {
                        bidbigfigure -= 1;
                    }
                    bidpoints       = (999 - Math.Abs(bidpoints - deltaautoscale));
                    bidpointsstring = bidpoints.ToString();
                }
                else
                {
                    bidpointsstring = (bidpoints - deltaautoscale).ToString();
                }
                if (bidpointsstring.Length < 3)
                {
                    bidpointsstring = ("0" + bidpointsstring);
                }
                currencychart.ChartAreas[0].AxisY.Minimum = Double.Parse(bidbigfigurestring + bidpointsstring);
            }
            currencychart.Series[(String)requestedcurrencies[i]].Points.AddXY(temp, bidprice);
            //currencychart.ChartAreas[0].AxisX.CustomLabels
            currencychart.ChartAreas[0].AxisX.Enabled = AxisEnabled.False;
            //currencychart.Series[(String)requestedcurrencies[i]].Label = "1234";
            //currencychart.Series[(String)requestedcurrencies[i]].Points[0].Label = "First Point";
            //currencychart.ChartAreas[0].AxisX.Enabled = AxisEnabled.False;
        }
        static void Main(string[] args)
        {
            double cantidad;
            int cantidad_decimal;
            int cantidad_entera;
            int i;
            int indice_billetes;
            int indice_monedas;
            int numero_billetes;
            int numero_monedas;
            int total;

            // Constantes usadas
            numero_billetes = 7;
            numero_monedas = 8;
            total = numero_billetes + numero_monedas;

            // arreglo de billetes
            double[] billetes = new double[numero_billetes];
            billetes[0] = 500;
            billetes[1] = 200;
            billetes[2] = 100;
            billetes[3] = 50;
            billetes[4] = 20;
            billetes[5] = 10;
            billetes[6] = 5;

            // arreglo de monedas
            double[] monedas = new double[numero_monedas];

            // las cantidades estan en centimos
            monedas[0] = 200;
            monedas[1] = 100;
            monedas[2] = 50;
            monedas[3] = 20;
            monedas[4] = 10;
            monedas[5] = 5;
            monedas[6] = 2;
            monedas[7] = 1;
            int[] cantidad_bill_mon = new int[total];

            // Indices para los arreglos de billetes y monedas
            indice_billetes = 1;
            indice_monedas = 1;

            // Pedimos la cantidad
            Console.WriteLine("Dame una cantidad mayor que 0");
            cantidad = Double.Parse(Console.ReadLine());

            // Comprobamos si la cantidad es mayor que 0
            if (cantidad >= 1)
            {
                // Saco la parte decimal y la entera
                cantidad_entera = (int)Math.Truncate(cantidad);
                cantidad_decimal = (int)Math.Truncate(((cantidad - cantidad_entera) * 100) + 0.1);

                // Recorro la cantidad_bill_mon
                for (i = 1; i <= total; i++)
                {
                    // Si la i esta entre 0 y 6 en este caso, tocamos los billetes
                    if (i <= numero_billetes)
                    {
                        // Ponemos la cantidad de billetes diviendo entre su numero y truncamos
                        cantidad_bill_mon[i - 1] = (int)Math.Truncate(cantidad_entera / billetes[indice_billetes - 1]);

                        // Actualizamos la cantidad entera usando el modulo (lo que sobra)
                        cantidad_entera = (int)(cantidad_entera % billetes[indice_billetes - 1]);

                        // Aumentamos el indice de los billetes
                        indice_billetes = indice_billetes + 1;
                    }
                    else
                    {
                        // Solo para monedas de 1 y 2 euros (caso especial)
                        if (indice_monedas >= 1 && indice_monedas <= 1)
                        {
                            // Ponemos la cantidad de monedas diviendo entre su numero y truncamos
                            cantidad_bill_mon[i - 1] = (int)Math.Truncate(cantidad_entera / (monedas[indice_monedas - 1] / 100));

                            // Actualizamos la cantidad entera usando el modulo (lo que sobra)
                            cantidad_entera = (int)(cantidad_entera % (monedas[indice_monedas - 1] / 100));
                        }
                        else
                        {
                            // Ponemos la cantidad de monedas diviendo entre su numero y truncamos (parte decimla)
                            cantidad_bill_mon[i - 1] = (int)Math.Truncate(cantidad_decimal / monedas[indice_monedas - 1]);

                            // Actualizamos la cantidad entera usando el modulo (lo que sobra)
                            cantidad_decimal = (int)(cantidad_decimal % monedas[indice_monedas - 1]);
                        }
                        // Aumentamos el indice de las monedas
                        indice_monedas = indice_monedas + 1;
                    }
                }
                // reiniciamos los indices
                indice_billetes = 1;
                indice_monedas = 1;

                // Recorremos de nuevo
                for (i = 1; i <= total; i++)
                {
                    // Si la i esta entre 1 y 7 en este caso, tocamos los billetes
                    if (i < numero_billetes)
                    {
                        // Si hemos rellenado una cantidad, la mostramos
                        if (cantidad_bill_mon[i - 1] >= 1)
                        {
                            Console.WriteLine("Cantidad de " + billetes[indice_billetes - 1] + "€ es de: " + cantidad_bill_mon[i - 1]);
                        }
                        // Aumentamos el indice de las billetes
                        indice_billetes = indice_billetes + 1;
                    }
                    else
                    {
                        // Si hemos rellenado una cantidad, la mostramos
                        if (cantidad_bill_mon[i - 1] > 1)
                        {
                            // En este caso, llo volvemos a pasar a su valor original
                            Console.WriteLine("Cantidad de " + (monedas[indice_monedas - 1] / 100) + "€ es de: " + cantidad_bill_mon[i - 1]);
                        }
                        // Aumentamos el indice de las monedas
                        indice_monedas = indice_monedas + 1;
                    }
                }
            }
            else
            {
                Console.WriteLine("La cantidad debe ser mayor que 0");
            }
        }
Beispiel #37
0
        public async Task StartConvert(CommandContext ctx)
        {
            await ctx.TriggerTypingAsync();

            await ctx.RespondAsync($"Starting convert program.");

            Dictionary <string, string> measurements = new Dictionary <string, string>
            {
                { "temp", "temperature" },
                { "len", "length" },
                { "m", "mass" },
                { "spd", "speed" }
            };

            UnitFactory unitFactory = new UnitFactory();
            await ctx.RespondAsync($"The measurement types that can be used:\n" +
                                   $" - Temperature (temp)\n" +
                                   $" - Length (len)\n" +
                                   $" - Mass (m)\n" +
                                   $" - Speed (spd)\n" +
                                   $"\n" +
                                   $"What measurement type do you wish to convert? Type the short name.");

            var interactivity = ctx.Client.GetInteractivityModule();
            var msg           = await interactivity.WaitForMessageAsync(xm => xm.Author.Id ==
                                                                        ctx.User.Id, TimeSpan.FromMinutes(2));

            if (msg != null)
            {
                //await ctx.RespondAsync($"Received: {msg.Message.Content}");
                if (measurements.ContainsKey(msg.Message.Content))
                {
                    //await ctx.RespondAsync($"{measurements[msg.Message.Content]}");
                    Unit unit = unitFactory.GetUnit(measurements[msg.Message.Content]);

                    // Print info of measurement unit selected
                    await ctx.RespondAsync($"Your choices:\n{unit.UnitInfo()}");

                    // Ask for from, to and value
                    await ctx.RespondAsync($"Please give the from unit, to unit and value " +
                                           $"seperated by commas.");

                    var msg2 = await interactivity.WaitForMessageAsync(xm => xm.Author.Id == ctx.User.Id,
                                                                       TimeSpan.FromMinutes(5));

                    if (msg2 != null)
                    {
                        // Put input into string array
                        string[] input = msg2.Message.Content.Split(',');

                        // Replace whitespaces
                        unit.From  = input[0].Replace(" ", "");
                        unit.To    = input[1].Replace(" ", "");
                        unit.Value = Double.Parse(input[2].Replace(" ", ""));

                        // Call convert method
                        double val = unit.Convert();
                        Console.WriteLine("Conversion resulted in: " + val + unit.To + "\n");
                        await ctx.RespondAsync($"Conversion ({unit.Value + unit.From} => " +
                                               $"{unit.To}) resulted in {val + unit.To}");
                    }
                }
                else
                {
                    await ctx.RespondAsync($"Wrong input! Aborting program!");
                }
            }
            else
            {
                await ctx.RespondAsync($"Messsage not received in time! Program aborted!");
            }
        }
Beispiel #38
0
 public Double Double(Double scale)
 {
     return(this.random.NextDouble() * scale);
 }
Beispiel #39
0
        public string Successfull_Unsuccessfull_MessageIN_ParentChild(string Name, string TotalCustCode, string Successfull, string Unsuccessfull, DataTable Data, Double Amount)
        {
            string result = string.Empty;

            string[] SuccessfullArray   = Successfull.Split(',');
            string[] UNSuccessfullArray = Unsuccessfull.Split(',');
            int      A = 0;
            int      U = 0;

            foreach (string Value in SuccessfullArray)
            {
                if (Value != "")
                {
                    A++;
                }
            }
            foreach (string Value in UNSuccessfullArray)
            {
                if (Value != "")
                {
                    U++;
                }
            }

            {
                result = @"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"">
                     <html xmlns=""http://www.w3.org/1999/xhtml"">
                     <head>
                     <meta http-equiv=""Content-Type"" content=""text/html; charset=iso-8859-1"" />
                     </head>
                     <body>
                      Dear Sir ,<br />
                      Thanks for participating an IPO application of “<b>" + Name + @"</b>”  Regarding the IPO of the Company </br>
                      you have been applied application. The Successful & Unsuccessful result to following bellow---<br /><br />
                      <p align=""center"">Application Summery of “<b>" + Name + @"</b>”</p>
                      <table align=""center"" width=""692"" border=""1"" bordercolor=""#999999"">
                        <tr>
                      <td width=""147"" align=""center"" style=""background-color:#CCCCCC""><strong>No. of Application </strong></td>
                      <td width=""140"" align=""center"" style=""background-color:#CCCCCC""><strong> Per  Application price </strong></td>
                      <td width=""151"" align=""center"" style=""background-color:#CCCCCC""><strong>Total  Application price</strong></td>
                      <td width=""138"" align=""center"" style=""background-color:#CCCCCC""><strong>Applied  Money form</strong></td>
                      <td width=""125"" align=""center"" style=""background-color:#CCCCCC""><strong>Refund  to</strong></td>
                       </tr>"
                         + CreateTable(Data, Amount) +
                         @"<tr>
                        <td align=""center"" style=""background-color:#CCCCCC"">Application  &nbsp;ID's</td>
                        <td colspan=""4"" align=""center""> " + TotalCustCode + @"</td>
                        </tr>
                         <tr>
                        <td align=""center"" style=""background-color:#CCCCCC"">Successful  ID&rsquo;s</td>
                        <td colspan=""4"" align=""center"" > " + Successfull + @"  Count : " + A + @"</td>
                        </tr>
                         <tr>
                          <td align=""center"" style=""background-color:#CCCCCC"">Unsuccessful  ID&rsquo;s</td>
                         <td colspan=""4"" align=""center""> " + Unsuccessfull + @"  Count : " + U + @"</td>
                        </tr>
                        </table><br /><br />

                           Thanks a lot for your valuable transaction. <br /><br />
                           K-Securities & Consultants Ltd (KSCL).<br /> 
                           www.ksclbd.com <br /><br /><br /><br />
                           This website's information is based on our actual record. If any of the above details look incorrect,<br />
                           please advise immediately. This is however possible but highly unlikely to find your record inaccurate or missing.<br />
                           This may happened due to malfunction of any/some of web tools that we use to collect and display your data here <br />
                           such as internet connectivity, FTP software, web server malfunction, problem with web database and others.<br /> 
                           We assure you that our master record of actual information is not affected by any of these.<br />

                       </body>
                       </html>
                    ";
            }
            return(result);
        }
Beispiel #40
0
 // Extension Method to check whether the contents of a string is a double
 public static bool IsNumeric(this String x)
 {
     return(Double.TryParse(x, out double i));
 }
Beispiel #41
0
        private void button2_Click(object sender, EventArgs e)
        {
            Agent_Number = textBox1.Text;
            Amount       = textBox2.Text;

            if (textBox1.Text != "" && textBox2.Text != "")
            {
                SqlConnection con = new SqlConnection(cs);
                con.Open();
                SqlCommand cmd = new SqlCommand(" Select balance from user_information where mobile_number='" + Personal_Number + " ' ", con);

                Ppn = Convert.ToDouble(cmd.ExecuteScalar().ToString());

                SqlCommand cmd2 = new SqlCommand(" Select balance from user_information where mobile_number='" + Agent_Number + " ' ", con);


                String A_Balance = cmd2.ExecuteScalar().ToString();

                Aan = Convert.ToDouble(A_Balance);
                A   = Convert.ToDouble(Amount);
                if (Ppn >= A)
                {
                    Ppn = Ppn - A + A * .02;
                    Aan = Aan + A + A * .02;
                    Pn  = (float)Ppn;
                    An  = (float)Aan;

                    String     qurey  = " Update USER_INFORMATION set BALANCE=@Pn where mobile_number='" + Personal_Number + " ' ";
                    String     qurey2 = " Update USER_INFORMATION set BALANCE=@An where mobile_number='" + Agent_Number + "'";
                    SqlCommand cmd3   = new SqlCommand(qurey, con);
                    SqlCommand cmd4   = new SqlCommand(qurey2, con);

                    cmd3.Parameters.AddWithValue("@Pn", Pn);
                    cmd4.Parameters.AddWithValue("@An", An);


                    int a = cmd3.ExecuteNonQuery();
                    int b = cmd4.ExecuteNonQuery();

                    if (a > 0 && b > 0)
                    {
                        MessageBox.Show("Cashout Successful");
                        textBox1.Clear();
                        textBox2.Clear();
                    }
                    else
                    {
                        MessageBox.Show("Cashout UnSuccessful");
                    }
                }
                else
                {
                    MessageBox.Show("Insufficient Balance ");
                    textBox1.Clear();
                    textBox2.Clear();
                }



                con.Close();
            }
            else
            {
                MessageBox.Show("Please fill up the information");
            }
        }
Beispiel #42
0
        private void button2_Click_1(object sender, EventArgs e)
        {
            Agent_Number = textBox1.Text;
            Amount       = textBox2.Text;

            if (textBox1.Text != "" && textBox2.Text != "")
            {
                SqlConnection con = new SqlConnection(cs);

                String     qurey4 = " Select mobile_number from user_information  where mobile_number=@mobile_number and USER_TYPE=@USER_TYPE";
                SqlCommand cmd4   = new SqlCommand(qurey4, con);
                cmd4.Parameters.AddWithValue("@mobile_number", textBox1.Text);
                cmd4.Parameters.AddWithValue("@USER_TYPE", "Admin");
                con.Open();
                bool m = Personal_Number != Agent_Number;
                if (cmd4.ExecuteScalar() != null && m)
                {
                    SqlCommand cmd = new SqlCommand(" Select balance from user_information where mobile_number='" + Personal_Number + " ' ", con);

                    Ppn = Convert.ToDouble(cmd.ExecuteScalar().ToString());

                    SqlCommand cmd2      = new SqlCommand(" Select balance from user_information where mobile_number='" + Agent_Number + " ' ", con);
                    String     A_Balance = cmd2.ExecuteScalar().ToString();

                    Aan = Convert.ToDouble(A_Balance);
                    A   = Convert.ToDouble(Amount);
                    if (Ppn >= A)
                    {
                        Ppn = Ppn - A;
                        Aan = Aan + A;
                        Pn  = (float)Ppn;
                        An  = (float)Aan;

                        String     qurey  = " Update USER_INFORMATION set BALANCE=@Pn where mobile_number='" + Personal_Number + " ' ";
                        String     qurey2 = " Update USER_INFORMATION set BALANCE=@An where mobile_number='" + Agent_Number + "'";
                        SqlCommand cmd3   = new SqlCommand(qurey, con);
                        SqlCommand cmd5   = new SqlCommand(qurey2, con);

                        cmd3.Parameters.AddWithValue("@Pn", Pn);
                        cmd5.Parameters.AddWithValue("@An", An);


                        int a = cmd3.ExecuteNonQuery();
                        int b = cmd5.ExecuteNonQuery();

                        if (a > 0 && b > 0)
                        {
                            String     qurey5 = " Insert into HISTORY_TABLE values  (@DATE,@TYPE,@SENDER,@RECEIVER,@AMOUNT)";
                            SqlCommand cmd6   = new SqlCommand(qurey5, con);
                            cmd6.Parameters.AddWithValue("@DATE", dateTimePicker2.Value);
                            cmd6.Parameters.AddWithValue("@TYPE", " Cash Out ");
                            cmd6.Parameters.AddWithValue("@SENDER", Personal_Number);
                            cmd6.Parameters.AddWithValue("@RECEIVER", Agent_Number);
                            cmd6.Parameters.AddWithValue("@AMOUNT", A);
                            int HISTORY = cmd6.ExecuteNonQuery();

                            MessageBox.Show("Cashout Successful");

                            textBox1.Clear();
                            textBox2.Clear();
                        }
                        else
                        {
                            MessageBox.Show("Cashout UnSuccessful");
                        }
                    }
                    else
                    {
                        MessageBox.Show("Insufficient Balance ");
                        textBox1.Clear();
                        textBox2.Clear();
                    }
                }
                else
                {
                    MessageBox.Show("Invalaid Mobile Number ");
                }


                con.Close();
            }
            else
            {
                MessageBox.Show("Please fill up the information");
            }
        }
Beispiel #43
0
        internal void MeasureChildren(Size availableSize)
        {
            foreach (UIElement child in Children)
            {
                DependencyObject item = child;
                if (item is ContentPresenter && VisualTreeHelper.GetChildrenCount(item) == 1)
                {
                    item = VisualTreeHelper.GetChild(item, 0);
                }

                var xy = GetPoints(item);
                if (xy != null)
                {
                    if (item is Polyline)
                    {
                        var line   = (Polyline)item;
                        var points = new PointCollection();
                        foreach (var point in xy)
                        {
                            points.Add(new Point(LeftFromX(XDataTransform.DataToPlot(point.X)), TopFromY(YDataTransform.DataToPlot(point.Y))));
                        }
                        line.Points = points;
                    }
                    else if (item is Polygon)
                    {
                        var p      = (Polygon)item;
                        var points = new PointCollection();
                        foreach (var point in xy)
                        {
                            points.Add(new Point(LeftFromX(XDataTransform.DataToPlot(point.X)), TopFromY(YDataTransform.DataToPlot(point.Y))));
                        }
                        p.Points = points;
                    }
                }
                if (item is Line)
                {
                    var    line = (Line)item;
                    double v;
                    v = GetX1(line);
                    if (!double.IsNaN(v))
                    {
                        if (Double.IsNegativeInfinity(v))
                        {
                            line.X1 = 0;
                        }
                        else if (Double.IsPositiveInfinity(v))
                        {
                            line.X1 = availableSize.Width;
                        }
                        else
                        {
                            line.X1 = LeftFromX(XDataTransform.DataToPlot(v));
                        }
                    }
                    v = GetX2(line);
                    if (!double.IsNaN(v))
                    {
                        if (Double.IsNegativeInfinity(v))
                        {
                            line.X2 = 0;
                        }
                        else if (Double.IsPositiveInfinity(v))
                        {
                            line.X2 = availableSize.Width;
                        }
                        else
                        {
                            line.X2 = LeftFromX(XDataTransform.DataToPlot(v));
                        }
                    }
                    v = GetY1(line);
                    if (!double.IsNaN(v))
                    {
                        if (Double.IsNegativeInfinity(v))
                        {
                            line.Y1 = availableSize.Height;
                        }
                        else if (Double.IsPositiveInfinity(v))
                        {
                            line.Y1 = 0;
                        }
                        else
                        {
                            line.Y1 = TopFromY(YDataTransform.DataToPlot(v));
                        }
                    }
                    v = GetY2(line);
                    if (!double.IsNaN(v))
                    {
                        if (Double.IsNegativeInfinity(v))
                        {
                            line.Y2 = availableSize.Height;
                        }
                        else if (Double.IsPositiveInfinity(v))
                        {
                            line.Y2 = 0;
                        }
                        else
                        {
                            line.Y2 = TopFromY(YDataTransform.DataToPlot(v));
                        }
                    }
                }
                child.Measure(availableSize);
            }
        }
Beispiel #44
0
        private static object ConvertNumericLiteral(ErrorContext errCtx, string numericString)
        {
            var k = numericString.IndexOfAny(_numberSuffixes);

            if (-1 != k)
            {
                var suffix     = numericString.Substring(k).ToUpperInvariant();
                var numberPart = numericString.Substring(0, numericString.Length - suffix.Length);
                switch (suffix)
                {
                case "U":
                {
                    UInt32 value;
                    if (!UInt32.TryParse(numberPart, NumberStyles.Integer, CultureInfo.InvariantCulture, out value))
                    {
                        var message = Strings.CannotConvertNumericLiteral(numericString, "unsigned int");
                        throw EntitySqlException.Create(errCtx, message, null);
                    }
                    return(value);
                }
                    ;

                case "L":
                {
                    long value;
                    if (!Int64.TryParse(numberPart, NumberStyles.Integer, CultureInfo.InvariantCulture, out value))
                    {
                        var message = Strings.CannotConvertNumericLiteral(numericString, "long");
                        throw EntitySqlException.Create(errCtx, message, null);
                    }
                    return(value);
                }
                    ;

                case "UL":
                case "LU":
                {
                    UInt64 value;
                    if (!UInt64.TryParse(numberPart, NumberStyles.Integer, CultureInfo.InvariantCulture, out value))
                    {
                        var message = Strings.CannotConvertNumericLiteral(numericString, "unsigned long");
                        throw EntitySqlException.Create(errCtx, message, null);
                    }
                    return(value);
                }
                    ;

                case "F":
                {
                    Single value;
                    if (!Single.TryParse(numberPart, NumberStyles.Float, CultureInfo.InvariantCulture, out value))
                    {
                        var message = Strings.CannotConvertNumericLiteral(numericString, "float");
                        throw EntitySqlException.Create(errCtx, message, null);
                    }
                    return(value);
                }
                    ;

                case "M":
                {
                    Decimal value;
                    if (
                        !Decimal.TryParse(
                            numberPart, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture,
                            out value))
                    {
                        var message = Strings.CannotConvertNumericLiteral(numericString, "decimal");
                        throw EntitySqlException.Create(errCtx, message, null);
                    }
                    return(value);
                }
                    ;

                case "D":
                {
                    Double value;
                    if (!Double.TryParse(numberPart, NumberStyles.Float, CultureInfo.InvariantCulture, out value))
                    {
                        var message = Strings.CannotConvertNumericLiteral(numericString, "double");
                        throw EntitySqlException.Create(errCtx, message, null);
                    }
                    return(value);
                }
                    ;
                }
            }

            //
            // If hit this point, try default conversion
            //
            return(DefaultNumericConversion(numericString, errCtx));
        }
Beispiel #45
0
 public ResultatsScolaireEleveBE(String matricule, String codeClasse, String periode, int annee, Double moyenne, int rang,
                                 string mention, string decision)
 {
     this.matricule  = matricule;
     this.codeClasse = codeClasse;
     this.periode    = periode;
     this.annee      = annee;
     this.moyenne    = moyenne;
     this.rang       = rang;
     this.mention    = mention;
     this.decision   = decision;
 }
Beispiel #46
0
 public RandomForestLeastSquaresTreeLearner(Dataset trainData, int numLeaves, int minDocsInLeaf, Double entropyCoefficient, Double featureFirstUsePenalty,
                                            Double featureReusePenalty, Double softmaxTemperature, int histogramPoolSize, int randomSeed, Double splitFraction, bool allowEmptyTrees,
                                            Double gainConfidenceLevel, int maxCategoricalGroupsPerNode, int maxCategoricalSplitPointsPerNode, bool quantileEnabled, int quantileSampleCount, IParallelTraining parallelTraining,
                                            double minDocsPercentageForCategoricalSplit, Bundle bundling, int minDocsForCategoricalSplit, double bias)
     : base(trainData, numLeaves, minDocsInLeaf, entropyCoefficient, featureFirstUsePenalty, featureReusePenalty, softmaxTemperature, histogramPoolSize,
            randomSeed, splitFraction, false, allowEmptyTrees, gainConfidenceLevel, maxCategoricalGroupsPerNode, maxCategoricalSplitPointsPerNode, -1, parallelTraining,
            minDocsPercentageForCategoricalSplit, bundling, minDocsForCategoricalSplit, bias)
 {
     _quantileSampleCount = quantileSampleCount;
     _quantileEnabled     = quantileEnabled;
 }
Beispiel #47
0
 public static byte[] GetBytes(Double value)
 {
     return((byte[])BitConverter.GetBytes(value).Reverse().ToArray());
 }
Beispiel #48
0
        public void GiftDick(Double pos_tender, Int32 pos_orno, String pos_terminal, String gc_cardno, Double tx_amount)
        {
            con   = new MySqlConnection();
            dbcon = new Conf.dbs();
            con.ConnectionString = dbcon.getConnectionString();
            String query = "UPDATE pos_store SET crm_custcode = 'WLKIN', pos_customer = 'Walk-In', pos_paymethod = 'Gift Card', ";

            query += "pos_tender = ?pos_tender, pos_park = 0 ";
            query += "WHERE (pos_orno = ?pos_orno) AND (pos_terminal = ?pos_terminal)";
            String query1 = "INSERT INTO pos_gc_tx (pos_orno, pos_terminal, gc_cardno, tx_amount, date_tx, time_tx) VALUES";

            query1 += "(?pos_orno, ?pos_terminal, ?gc_cardno, ?tx_amount, ?date_tx, ?time_tx)";
            try
            {
                con.Open();
                MySqlCommand cmd  = new MySqlCommand(query, con);
                MySqlCommand cmd1 = new MySqlCommand(query1, con);
                //
                cmd.Parameters.AddWithValue("?pos_tender", pos_tender);
                cmd.Parameters.AddWithValue("?pos_orno", pos_orno);
                cmd.Parameters.AddWithValue("?pos_terminal", pos_terminal);
                //
                cmd1.Parameters.AddWithValue("?pos_orno", pos_orno);
                cmd1.Parameters.AddWithValue("?pos_terminal", pos_terminal);
                cmd1.Parameters.AddWithValue("?gc_cardno", gc_cardno);
                cmd1.Parameters.AddWithValue("?tx_amount", tx_amount);
                cmd1.Parameters.AddWithValue("?date_tx", DateTime.Now.ToString("yyyy-MM-dd"));
                cmd1.Parameters.AddWithValue("?time_tx", DateTime.Now.ToString("HH:mm:ss"));
                //
                cmd.ExecuteNonQuery();
                cmd1.ExecuteNonQuery();
                cmd.Dispose();
                cmd1.Dispose();
            }
            finally
            {
                con.Close();
            }
        }
Beispiel #49
0
        private static void tabledelegatemethodaddrow(String currency, String millisecondtimestamp,
                                                      String bidprice, String offerprice, String high,
                                                      String low, String open)
        {
            for (int i = 0; i < table.Rows.Count; i++)
            {
                if (table [0, i].Value.ToString() == currency)
                {
                    if (table [2, i].Value == null)
                    {
                        table[1, i].Value = millisecondtimestamp;
                        table[2, i].Value = bidprice;
                        table[3, i].Value = offerprice;
                        table[4, i].Value = high;
                        table[5, i].Value = low;
                        table[6, i].Value = open;
                        break;
                    }


                    table[1, i].Value = millisecondtimestamp;
                    if (Double.Parse(table[2, i].Value.ToString()) < Double.Parse(bidprice))
                    {
                        table[2, i].Style.BackColor = Color.Green;
                        //table[2, i].Style.ForeColor = Color.Black;
                    }
                    else if (Double.Parse(table[2, i].Value.ToString()) > Double.Parse(bidprice))
                    {
                        table[2, i].Style.BackColor = Color.IndianRed;
                        //table[2, i].Style.ForeColor = Color.Black;
                    }
                    else
                    {
                        table[2, i].Style.ForeColor = Color.Black; table[2, i].Style.BackColor = Color.White;
                    }
                    /////
                    if (Double.Parse(table[3, i].Value.ToString()) < Double.Parse(offerprice))
                    {
                        table[3, i].Style.BackColor = Color.Green;
                        //table[3, i].Style.ForeColor = Color.Black;
                    }
                    else if (Double.Parse(table[3, i].Value.ToString()) > Double.Parse(offerprice))
                    {
                        table[3, i].Style.BackColor = Color.IndianRed;
                        //table[3, i].Style.ForeColor = Color.Black;
                    }
                    else
                    {
                        table[3, i].Style.ForeColor = Color.Black; table[3, i].Style.BackColor = Color.White;
                    }

                    table[2, i].Value = bidprice;
                    table[3, i].Value = offerprice;
                    table[4, i].Value = high;
                    table[5, i].Value = low;
                    table[6, i].Value = open;
                    break;
                }
            }
            //table.Rows.Add(
            //            currency, millisecondtimestamp, bidprice, offerprice, high, low, open);
        }
Beispiel #50
0
        public const char OD_CTR_QUERY_MILE    = 'e'; //查询里程
        //短信定位信息
        //*RS,123456789,V1,181003,A,2233.1055,N,11358.1257,E,51.00,000,070925,FFFFFBFD#
        public static Position GetSMSPos(String src)
        {
            Position pos = new Position();

            try
            {
                //Console.WriteLine(src);
                String[] ss = src.Split(',');
                pos.MNO = ss[0];
                int add = 0;
                if (ss[1] == "V4")
                {
                    if (ss[2] == "S32")
                    {
                        add         = 3;
                        pos.Mileage = (int)(Double.Parse(ss[4]) * 0.51444 / 1000);
                    }/*
                      * else if(ss[2] == "S5")
                      * {
                      * add = 5;
                      * pos.IsPointMsg = true;
                      * }/*/
                    else if (ss[2] == "S26")
                    {
                        pos.IsGetSetMsg = true;
                        pos.SettingStr  = src.Substring(src.IndexOf(ss[5]));
                        return(pos);
                    }
                    else
                    {
                        add = 2;
                    }
                }
                else
                {
                    pos.IsPointMsg = true; //此协议无单独定位指令,只好用v1代替
                }
                try
                {/*
                  * pos.GpsTime = "20" + ss[add + 10].Substring(4) + "-" + ss[add + 10].Substring(2, 2) + "-" + ss[add + 10].Substring(0, 2)
                  + " " + ss[add + 2].Substring(0, 2) + ":" + ss[add + 2].Substring(2, 2) + ":" + ss[add + 2].Substring(4);
                  + DateTime dt = DateTime.Parse(pos.GpsTime);
                  + dt = dt.AddHours(8);
                  + pos.GpsTime = dt.ToString("yyyy-MM-dd HH:mm:ss");*/
                    pos.GpsTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                }
                catch { pos.GpsTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); }

                pos.Pointed = (ss[add + 3] == "A") ? 1 : 0;

                pos.La = Double.Parse(ss[add + 4].Substring(0, 2)) + Double.Parse(ss[add + 4].Substring(2)) / 60;
                if (ss[add + 5] == "S")
                {
                    pos.La = 0 - pos.La;
                }
                pos.Lo = Double.Parse(ss[add + 6].Substring(0, 3)) + Double.Parse(ss[add + 6].Substring(3)) / 60;
                if (ss[add + 7] == "W")
                {
                    pos.Lo = 0 - pos.Lo;
                }
                pos.Speed = Pub.KtsToKms((int)Double.Parse(ss[add + 8]));
                if (ss[add + 9] == "")
                {
                    pos.Direction = 0;
                }
                else
                {
                    pos.Direction = 0;
                    double dir = Double.Parse(ss[add + 9]);
                    if (dir < 90)
                    {
                        pos.Direction = 1;
                    }
                    else if (dir == 90)
                    {
                        pos.Direction = 2;
                    }
                    else if (dir < 180)
                    {
                        pos.Direction = 3;
                    }
                    else if (dir == 180)
                    {
                        pos.Direction = 4;
                    }
                    else if (dir < 270)
                    {
                        pos.Direction = 5;
                    }
                    else if (dir == 270)
                    {
                        pos.Direction = 6;
                    }
                    else if (dir > 270)
                    {
                        pos.Direction = 7;
                    }
                }
                if (ss[add + 11].Length > 8)
                {
                    ss[add + 11] = ss[add + 11].Substring(0, 8);
                }
                String   hex    = Pub.HexToBin(ss[add + 11]);
                String[] status =
                {
                    "低电传感器1搭铁",  "高电传感器2为高",  "高电传感器1为高",  "电瓶拆除报警",
                    "车辆断油电",     "GPRS阻塞报警",  "三次密码错误报警",  "温度报警",
                    "低电传感器2搭铁",  "GPS天线短路",   "GPS天线开路",   "电瓶被拆除",
                    "主机由后备电池供电", "",          "",          "GPS天线故障报警",
                    "超速",        "自定义报警",     "发动机开",      "",
                    "",          "ACC关",      "车辆设防",      "车门开",
                    "禁止驶出越界报警",  "GPS天线短路报警", "GPS天线开路报警", "禁止驶入越界报警",
                    "非法点火报警",    "超速报警",      "劫警",        "盗警"
                };
                for (int i = 0; i < 32; i++)
                {
                    if (hex[i] == '0' && status[i] != "")
                    {
                        if (status[i].IndexOf("警") > 0)
                        {
                            pos.Alarm = pos.Alarm + status[i] + " ";
                        }
                        else
                        {
                            pos.Status = pos.Status + status[i] + " ";
                        }
                    }
                }
                if (pos.Status.IndexOf("ACC关") < 0)
                {
                    pos.Status = pos.Status + "ACC开";
                }
                pos.AlarmHandle = (pos.Alarm == "") ? 0 : 1;
                return(pos);
            }
            catch { }
            return(null);
        }
Beispiel #51
0
        //
        #endregion
        #region Cash Count Module
        public void LogCC(Double thousand, Double fiveh, Double twoh, Double oneh, Double fifty, Double twenty, Double ten, Double five, Double one, Double ctwentyfive, String terminal, String cashier)
        {
            con   = new MySqlConnection();
            dbcon = new Conf.dbs();
            con.ConnectionString = dbcon.getConnectionString();
            String query = "INSERT INTO pos_cashcount (thousand, fivehundred, twohundred, onehundred, fifty, twenty, ten, five, one, ctwentyfive, terminal, cashier) VALUES";

            query += "(?thousand, ?fiveh, ?twoh, ?oneh, ?fifty, ?twenty, ?ten, ?five, ?one, ?ctwentyfive, ?terminal, ?cashier)";
            try
            {
                con.Open();
                MySqlCommand cmd = new MySqlCommand(query, con);
                cmd.Parameters.AddWithValue("?thousand", thousand);
                cmd.Parameters.AddWithValue("?fiveh", fiveh);
                cmd.Parameters.AddWithValue("?twoh", twoh);
                cmd.Parameters.AddWithValue("?oneh", oneh);
                cmd.Parameters.AddWithValue("?fifty", fifty);
                cmd.Parameters.AddWithValue("?twenty", twenty);
                cmd.Parameters.AddWithValue("?ten", ten);
                cmd.Parameters.AddWithValue("?five", five);
                cmd.Parameters.AddWithValue("?one", one);
                cmd.Parameters.AddWithValue("?ctwentyfive", ctwentyfive);
                cmd.Parameters.AddWithValue("?terminal", terminal);
                cmd.Parameters.AddWithValue("?cashier", cashier);
                cmd.ExecuteNonQuery();
                cmd.Dispose();
            }
            finally
            {
                con.Close();
            }
        }
Beispiel #52
0
 private void button5_Click(object sender, EventArgs e)
 {
     textBox_Result.Text = "0";
     resultValue         = 0;
 }
Beispiel #53
0
        internal void ArrangeChildren(Size finalSize)
        {
            foreach (UIElement child in Children)
            {
                DependencyObject item = child;
                if (item is ContentPresenter && VisualTreeHelper.GetChildrenCount(item) == 1)
                {
                    item = VisualTreeHelper.GetChild(item, 0);
                }

                if (item is Line || item is Polyline)
                {
                    child.Arrange(new Rect(0, 0, finalSize.Width, finalSize.Height));
                }
                else
                {
                    double x1 = GetX1(item);
                    double x2 = GetX2(item);
                    double y1 = GetY1(item);
                    double y2 = GetY2(item);

                    Size desiredSize = Size.Empty;
                    if (double.IsNaN(x1) || double.IsNaN(x2) || double.IsNaN(y1) || double.IsNaN(y2))
                    {
                        desiredSize = child.DesiredSize;
                    }

                    double L = 0.0;
                    if (!double.IsNaN(x1))
                    {
                        if (double.IsNegativeInfinity(x1))
                        {
                            L = 0;
                        }
                        else if (double.IsPositiveInfinity(x1))
                        {
                            L = finalSize.Width;
                        }
                        else
                        {
                            L = LeftFromX(XDataTransform.DataToPlot(x1)); // x1 is not Nan and Inf here
                        }
                    }
                    else
                    {
                        L = (double)item.GetValue(Canvas.LeftProperty);
                    }

                    double W    = 0.0;
                    var    elem = item as FrameworkElement;
                    if (!double.IsNaN(x1) && !double.IsNaN(x2))
                    {
                        double L2 = 0.0;
                        if (double.IsNegativeInfinity(x2))
                        {
                            L2 = 0;
                        }
                        else if (double.IsPositiveInfinity(x2))
                        {
                            L2 = desiredSize.Width;
                        }
                        else
                        {
                            L2 = LeftFromX(XDataTransform.DataToPlot(x2)); // x2 is not Nan and Inf here
                        }
                        if (L2 >= L)
                        {
                            W = L2 - L;
                        }
                        else
                        {
                            W = L - L2;
                            L = L2;
                        }
                    }
                    else if (elem != null || double.IsNaN(W = elem.Width) || double.IsInfinity(W))
                    {
                        W = desiredSize.Width;
                    }

                    double T = 0.0;
                    if (!double.IsNaN(y1))
                    {
                        if (double.IsNegativeInfinity(y1))
                        {
                            T = desiredSize.Height;
                        }
                        else if (double.IsPositiveInfinity(y1))
                        {
                            T = 0;
                        }
                        else
                        {
                            T = TopFromY(YDataTransform.DataToPlot(y1)); // y1 is not Nan and Inf here
                        }
                    }
                    else
                    {
                        T = (double)item.GetValue(Canvas.TopProperty);
                    }

                    double H = 0.0;
                    if (!double.IsNaN(y1) && !double.IsNaN(y2))
                    {
                        double T2 = 0.0;
                        if (double.IsNegativeInfinity(y2))
                        {
                            T2 = desiredSize.Height;
                        }
                        else if (double.IsPositiveInfinity(y2))
                        {
                            T2 = desiredSize.Width;
                        }
                        else
                        {
                            T2 = TopFromY(YDataTransform.DataToPlot(y2)); // y2 is not Nan and Inf here
                        }
                        if (T2 >= T)
                        {
                            H = T2 - T;
                        }
                        else
                        {
                            H = T - T2;
                            T = T2;
                        }
                    }
                    else if (elem != null || double.IsNaN(H = elem.Height) || double.IsInfinity(H))
                    {
                        H = desiredSize.Height;
                    }

                    if (Double.IsNaN(L) || Double.IsInfinity(L) || Double.IsNaN(W) || Double.IsInfinity(W)) // Horizontal data to screen transform fails
                    {
                        L = 0;
                        W = desiredSize.Width;
                    }
                    if (Double.IsNaN(T) || Double.IsInfinity(T) || Double.IsNaN(H) || Double.IsInfinity(H)) // Vertical data to screen transform fails
                    {
                        T = 0;
                        H = desiredSize.Height;
                    }
                    child.Arrange(new Rect(L, T, W, H));
                }
            }
        }
Beispiel #54
0
        private void initialconfigs()
        {
            InitializeComponent();

            this.DoubleBuffered        = true;
            this.Text                  = "Venta de Mostrador";
            this.gb1.BorderColor       = Color.DarkGray;
            this.gb2.BorderColor       = Color.DarkGray;
            this.gb3.BorderColor       = Color.DarkGray;
            this.gb4.BorderColor       = Color.DarkGray;
            this.gb5.BorderColor       = Color.DarkGray;
            this.gb6.BorderColor       = Color.DarkGray;
            this.gb7.BorderColor       = Color.DarkGray;
            this.txtcliente.ReadOnly   = true;
            this.txtid.ReadOnly        = true;
            this.txtarticulos.ReadOnly = true;
            this.txtsubtotal.ReadOnly  = true;
            this.txtiva.ReadOnly       = true;
            this.db = new dbop();
            behaviorDefinitions.txtPrice(this.txtdescuentoextra);
            behaviorDefinitions.txtPrice(this.txtidproducto);
            this.descuentos = new List <int>()
            {
                0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50
            };
            this.cbdescuento.DataSource = this.descuentos;
            this.tabla = new DataTable();
            this.tabla.Columns.Add("Codigo Producto", typeof(string));
            this.tabla.Columns.Add("Descripción", typeof(string));
            this.tabla.Columns.Add("Cantidad", typeof(string));
            this.tabla.Columns.Add("Precio", typeof(string));
            this.tabla.Columns.Add("Descuento", typeof(string));
            this.tabla.Columns.Add("Importe", typeof(string));
            this.dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            this.dgv.DataSource          = this.tabla;
            this.cbcantidad.Minimum      = 0;
            this.tmp                = new string[6];
            this.atributos          = new vals(true);
            this.txttotal.ReadOnly  = true;
            this.MaximizeBox        = false;
            this.checkboxCP.Checked = true;

            this.ventatmp = new venta();

            this.txtvendedor.Text = (this.usuarioactual.nombre).ToUpper(); //CARGA DATOS DEL USUARIO DEL SISTEMA ACTUAL

            this.inventario = this.db.getinventarioproductos();            //LLENA INVENTARIO TEMPORAL

            this.FormClosed += (s, g) =>
            {
                this.central.xventa = null;
            };

            this.txtidproducto.KeyUp += (sender, args) =>
            {
                if (args.KeyCode == Keys.Enter && this.txtidproducto.Text.Trim() != "")
                {
                    if (this.rtbCodigos.Checked)
                    {
                        this.addcodeDirect();
                    }
                    else
                    {
                        this.codetxtproducto();
                    }
                }
            };

            this.cbdescuento.KeyUp += (sender, args) =>
            {
                if (args.KeyCode == Keys.Enter)
                {
                    this.additem(this.tmp);
                }
            };

            this.cbcantidad.KeyUp += (sender, args) =>
            {
                if (args.KeyCode == Keys.Enter)
                {
                    this.cbdescuento.Focus();
                }
            };

            this.cbcantidad.ValueChanged += (sender, args) =>
            {
                if (this.cbcantidad.Value > this.cbcantidad.Maximum)
                {
                    this.cbcantidad.Value = this.cbcantidad.Maximum;
                }
            };

            this.dgv.KeyUp += (sender, args) => {
                if (args.KeyCode == Keys.Delete)
                {
                    this.inventario.Find(x => x.idproducto.ToString() == this.dgv.Rows[dgv.CurrentRow.Index].Cells[0].Value.ToString()).stock += int.Parse(this.dgv.Rows[dgv.CurrentRow.Index].Cells[2].Value.ToString());
                    this.tabla.Rows.RemoveAt(this.dgv.CurrentRow.Index);
                    this.updatevalues();
                }
                this.txtidproducto.Focus();
            };

            this.txtdescuentoextra.KeyUp += (sender, args) =>
            {
                if (this.txtdescuentoextra.Text.Trim() != "" && this.txtsubtotal.Text != "0" && args.KeyCode == Keys.Enter)
                {
                    if (Double.Parse(this.txtdescuentoextra.Text, CultureInfo.InvariantCulture) >= Double.Parse(this.txtsubtotal.Text, CultureInfo.InvariantCulture))
                    {
                        genericDefinitions.error("Descuento extra invalido", "Aviso");
                        this.txtdescuentoextra.Focus();
                    }
                    else
                    {
                        this.updatevalues();
                    }
                }
            };
            this.txtdescuentoextra.KeyPress += (x, y) =>
            {
                if (this.txtsubtotal.Text == "0")
                {
                    y.Handled = true;
                }
            };
            this.Resize += (sender, args) =>
            {
                this.pb.Location = new Point(this.Width / 2 - this.pb.Width / 2, this.pb.Location.Y);
            };

            this.btnaccept.GotFocus += (x, y) =>
            {
                this.txtidproducto.Focus();
            };

            this.txtid.TextChanged += (sender, args) =>
            {
                this.clienteactual = this.db.getclientAsobject(int.Parse(this.txtid.Text.Trim()));
            };

            this.blapse.GotFocus += (sender, args) =>
            {
                this.txtidproducto.Focus();
            };

            this.btnsc.GotFocus += (sender, args) =>
            {
                this.txtidproducto.Focus();
            };
            this.stopBounds();
            this.setimage();

            this.LostFocus += (a, b) => { this.Update(); };
            this.GotFocus  += (a, b) => { this.Update(); };

            this.txtidproducto.KeyUp += (sender, args) => { if (args.KeyCode == Keys.F12)
                                                            {
                                                                this.cobrar();
                                                            }
            };

            this.btnBuscaproducto.GotFocus += (a, b) => { this.txtidproducto.Focus(); };
        }
Beispiel #55
0
        public void AR_Basic(String customer, Double pos_tender, Int32 pos_orno, String pos_terminal, String crm_custcode, Double tx_amount)
        {
            con   = new MySqlConnection();
            dbcon = new Conf.dbs();
            con.ConnectionString = dbcon.getConnectionString();
            String query = "UPDATE pos_store SET crm_custcode = ?set_custcode, pos_customer = ?set_customer, pos_vatable = 0, pos_vex = 0, pos_vatz = 0, pos_tax_amt = 0, pos_disc_amt = 0, pos_paymethod = 'Charge to Accounts', pos_total_amt = 0, ";

            query += "pos_tender = ?pos_tender, pos_park = 0 ";
            query += "WHERE (pos_orno = ?pos_orno) AND (pos_terminal = ?pos_terminal)";
            String query1 = "INSERT INTO pos_ar_basic_tx (pos_orno, pos_terminal, crm_custcode, tx_amount, date_tx, time_tx) VALUES";

            query1 += "(?pos_orno, ?pos_terminal, ?crm_custcode, ?tx_amount, ?date_tx, ?time_tx)";
            try
            {
                con.Open();
                MySqlCommand cmd  = new MySqlCommand(query, con);
                MySqlCommand cmd1 = new MySqlCommand(query1, con);
                //
                cmd.Parameters.AddWithValue("?set_custcode", crm_custcode);
                cmd.Parameters.AddWithValue("?set_customer", customer);
                cmd.Parameters.AddWithValue("?pos_tender", pos_tender);
                cmd.Parameters.AddWithValue("?pos_orno", pos_orno);
                cmd.Parameters.AddWithValue("?pos_terminal", pos_terminal);
                //
                cmd1.Parameters.AddWithValue("?pos_orno", pos_orno);
                cmd1.Parameters.AddWithValue("?pos_terminal", pos_terminal);
                cmd1.Parameters.AddWithValue("?crm_custcode", crm_custcode);
                cmd1.Parameters.AddWithValue("?tx_amount", tx_amount);
                cmd1.Parameters.AddWithValue("?date_tx", DateTime.Now.ToString("yyyy-MM-dd"));
                cmd1.Parameters.AddWithValue("?time_tx", DateTime.Now.ToString("HH:mm:ss"));
                //
                cmd.ExecuteNonQuery();
                cmd1.ExecuteNonQuery();
                cmd.Dispose();
                cmd1.Dispose();
            }
            finally
            {
                con.Close();
            }
        }
Beispiel #56
0
        //gprs/cdma压缩信息
        //24 75 50 13 90 79 16 04 33 14 08 08 22 31 46 01 00 11 40 19 44 3C 00 01 92 FF FF FB FF FF 00 03
        //24 75 50 13 90 79 16 04 33 14 08 08 22 31 46 01 00 11 40 19 44 3C 00 01 92 FF FF FB FF FF 00 03
        //24 30 80 72 25 23 04 20 38 15 08 08 24 54 60 96 00 11 83 64 28 5C 00 02 67 FF FF FB FF FF 00 5D
        //char c = 1100
        public static Position GetPosEx(String src)
        {
            Position pos = new Position();

            try
            {
                String ss = Pub.RealHexToHex(src.Substring(1, src.Length - 3));
                Console.WriteLine(ss.Length.ToString());
                if (src[0] == HEAD_HEX_2)
                {
                    pos.Mileage = (int)(Int32.Parse(ss.Substring(0, 10)) * 0.51444 / 1000);
                }
                StringBuilder stb = new StringBuilder();
                pos.MNO = ss.Substring(0, 10);

                /*
                 * GPRS协议2协议停车上传数据时,gps时间不变,所以取服务器时间
                 */
                try
                {/*
                  * stb.Append("20").Append(ss.Substring(20, 2)).Append("-");
                  * stb.Append(ss.Substring(18, 2)).Append("-").Append(ss.Substring(16, 2)).Append(" ");
                  * stb.Append(ss.Substring(10, 2)).Append(":").Append(ss.Substring(12, 2)).Append(":");
                  * stb.Append(ss.Substring(14, 2));
                  * DateTime dt = DateTime.Parse(stb.ToString());
                  * dt = dt.AddHours(8);
                  * pos.GpsTime = dt.ToString("yyyy-MM-dd HH:mm:ss");*/
                    pos.GpsTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                }
                catch { pos.GpsTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); }

                pos.La = Double.Parse(ss.Substring(22, 2)) + Double.Parse(ss.Substring(24, 6).Insert(2, ".")) / 60;
                pos.Lo = Double.Parse(ss.Substring(32, 3)) + Double.Parse(ss.Substring(35, 6).Insert(2, ".")) / 60;

                String temp = Pub.HexToBin(ss.Substring(41, 1));
                if (temp[0] == '0')
                {
                    pos.Lo = 0 - pos.Lo;
                }
                if (temp[1] == '0')
                {
                    pos.La = 0 - pos.La;
                }
                if (temp[2] == '0')
                {
                    pos.Pointed = 0;
                }
                else
                {
                    pos.Pointed = 1;
                }

                pos.Speed     = Pub.KtsToKms(Int32.Parse(ss.Substring(42, 3)));
                pos.Direction = 0;
                int dir = Int32.Parse(ss.Substring(45, 3));
                if (dir < 90)
                {
                    pos.Direction = 1;
                }
                else if (dir == 90)
                {
                    pos.Direction = 2;
                }
                else if (dir < 180)
                {
                    pos.Direction = 3;
                }
                else if (dir == 180)
                {
                    pos.Direction = 4;
                }
                else if (dir < 270)
                {
                    pos.Direction = 5;
                }
                else if (dir == 270)
                {
                    pos.Direction = 6;
                }
                else if (dir > 270)
                {
                    pos.Direction = 7;
                }
                String   hex    = Pub.HexToBin(ss.Substring(48, 8));
                String[] status =
                {
                    "低电传感器1搭铁",  "高电传感器2为高",  "高电传感器1为高",  "电瓶拆除报警",
                    "车辆断油电",     "GPRS阻塞报警",  "三次密码错误报警",  "温度报警",
                    "低电传感器2搭铁",  "GPS天线短路",   "GPS天线开路",   "电瓶被拆除",
                    "主机由后备电池供电", "",          "",          "GPS天线故障报警",
                    "超速",        "自定义报警",     "发动机开",      "",
                    "",          "ACC关",      "车辆设防",      "车门开",
                    "禁止驶出越界报警",  "GPS天线短路报警", "GPS天线开路报警", "禁止驶入越界报警",
                    "非法点火报警",    "超速报警",      "劫警",        "盗警"
                };
                for (int i = 0; i < 32; i++)
                {
                    if (hex[i] == '0' && status[i] != "")
                    {
                        if (status[i].IndexOf("警") > 0)
                        {
                            pos.Alarm = pos.Alarm + status[i] + " ";
                        }
                        else
                        {
                            pos.Status = pos.Status + status[i] + " ";
                        }
                    }
                }
                if (pos.Status.IndexOf("ACC关") < 0)
                {
                    pos.Status = pos.Status + "ACC开";
                }
                pos.AlarmHandle = (pos.Alarm == "") ? 0 : 1;
                return(pos);
            }
            catch { }
            return(null);
        }
Beispiel #57
0
        public void UpdateTrunkSales(Double pos_vatable, Double pos_vex, Double pos_vatz, Double tax_p, Double tax_amt, Double pos_disc_amt, Double pos_total_amt, Int32 pos_orno, String pos_terminal)
        {
            con   = new MySqlConnection();
            dbcon = new Conf.dbs();
            con.ConnectionString = dbcon.getConnectionString();
            String query = "UPDATE pos_store SET pos_vatable = ?vatable, pos_vex = ?vex, pos_vatz = ?zero, pos_tax_perc = ?a, pos_tax_amt = ?b, pos_disc_amt = ?disc, pos_total_amt = ?c ";

            query += "WHERE pos_orno = ?pos_orno AND pos_terminal = ?pos_terminal";
            try
            {
                con.Open();
                MySqlCommand cmd = new MySqlCommand(query, con);
                cmd.Parameters.AddWithValue("?vatable", pos_vatable);
                cmd.Parameters.AddWithValue("?vex", pos_vex);
                cmd.Parameters.AddWithValue("?zero", pos_vatz);
                cmd.Parameters.AddWithValue("?a", tax_p);
                cmd.Parameters.AddWithValue("?b", tax_amt);
                cmd.Parameters.AddWithValue("?disc", pos_disc_amt);
                cmd.Parameters.AddWithValue("?c", pos_total_amt);
                cmd.Parameters.AddWithValue("?pos_orno", pos_orno);
                cmd.Parameters.AddWithValue("?pos_terminal", pos_terminal);
                cmd.ExecuteNonQuery();
                cmd.Dispose();
            }
            finally
            {
                con.Close();
            }
        }
    protected void FillGrid()
    {
        lblparty.Text = ddlparty.SelectedItem.Text;
        DataTable dtGrid = (DataTable)(GridFiltersDatatable());

        if (dtGrid != null)
        {
            if (dtGrid.Rows.Count > 0)
            {
                gridpurchaseregister.DataSource = dtGrid;

                DataView myDataView = new DataView();
                myDataView = dtGrid.DefaultView;

                if (hdnsortExp.Value != string.Empty)
                {
                    myDataView.Sort = string.Format("{0} {1}", hdnsortExp.Value, hdnsortDir.Value);
                }

                gridpurchaseregister.DataBind();
            }
            if (gridpurchaseregister.Rows.Count > 0)
            {
                Double tax1total       = 0;
                Double tax2total       = 0;
                Double tax3total       = 0;
                Double shipchargetotal = 0;
                Double gsttltotal      = 0;
                Double nettotal        = 0;

                foreach (GridViewRow gv in gridpurchaseregister.Rows)
                {
                    int         tid      = Convert.ToInt32(gridpurchaseregister.DataKeys[gv.RowIndex].Value);
                    ImageButton img      = (ImageButton)gv.FindControl("img1");
                    Label       lbldocno = (Label)gv.FindControl("lbldocno");
                    string      tid1     = img.CommandArgument;

                    string scpt = "select * from AttachmentMaster where RelatedTableId='" + tid1 + "'";

                    SqlDataAdapter adp58 = new SqlDataAdapter(scpt, con);
                    DataTable      ds58  = new DataTable();
                    adp58.Fill(ds58);

                    if (ds58.Rows.Count == 0)
                    {
                        img.ImageUrl = "~/ShoppingCart/images/Docimg.png";
                        img.Enabled  = false;

                        lbldocno.Text = "0";
                        img.ToolTip   = "0";
                    }
                    else
                    {
                        img.ImageUrl  = "~/ShoppingCart/images/Docimggreen.jpg";
                        img.Enabled   = true;
                        img.ToolTip   = ds58.Rows.Count.ToString();
                        lbldocno.Text = ds58.Rows.Count.ToString();
                    }

                    double  t1, t2, t3, shipcharge, gsttl, net = 0;
                    DataSet ds   = new DataSet();
                    Label   tax1 = (Label)(gv.FindControl("lblgrdtax1"));
                    if (tax1.Text != "")
                    {
                        if (isnumSelf(tax1.Text) != 0)
                        {
                            //tax1.Text
                            t1 = Convert.ToDouble(tax1.Text);
                        }
                        else
                        {
                            t1 = 0;
                        }
                    }
                    else
                    {
                        t1 = 0;
                    }
                    Label tax2 = (Label)(gv.FindControl("lblgrdtax2"));
                    if (tax2.Text != "")
                    {
                        if (isnumSelf(tax2.Text) != 0)
                        {
                            t2 = Convert.ToDouble(tax2.Text);
                        }
                        else
                        {
                            t2 = 0;
                        }
                    }
                    else
                    {
                        t2 = 0;
                    }
                    Label tax3 = (Label)(gv.FindControl("lblgrdtax3"));
                    if (tax3.Text != "")
                    {
                        if (isnumSelf(tax3.Text) != 0)
                        {
                            //tax1.Text
                            t3 = Convert.ToDouble(tax3.Text);
                        }
                        else
                        {
                            t3 = 0;
                        }
                    }
                    else
                    {
                        t3 = 0;
                    }
                    Label shipingcharge = (Label)(gv.FindControl("lblgrdshippingcharg"));
                    if (shipingcharge.Text != "")
                    {
                        if (isnumSelf(shipingcharge.Text) != 0)
                        {
                            shipcharge = Convert.ToDouble(shipingcharge.Text);
                        }
                        else
                        {
                            shipcharge = 0;
                        }
                    }
                    else
                    {
                        shipcharge = 0;
                    }
                    double total      = (t1 + t2 + t3 + shipcharge);
                    Label  grisstotal = (Label)(gv.FindControl("lblgrdgrosstotal"));
                    if (grisstotal.Text != "")
                    {
                        gsttl = Convert.ToDouble(grisstotal.Text);
                    }
                    else
                    {
                        gsttl = 0;
                    }
                    net = gsttl - total;
                    Label netamt = (Label)(gv.FindControl("lblgrdnetamt"));

                    netamt.Text = Convert.ToString(net);
                    Label lblgrdentrytype = (Label)(gv.FindControl("lblgrdentrytype"));
                    tax1total       = tax1total + t1;
                    tax2total       = tax2total + t2;
                    tax3total       = tax3total + t3;
                    shipchargetotal = shipchargetotal + shipcharge;
                    gsttltotal      = gsttltotal + gsttl;
                    nettotal        = nettotal + net;
                    ds.Reset();
                }


                ViewState["7"]  = nettotal.ToString();
                ViewState["10"] = shipchargetotal.ToString();
                ViewState["8"]  = tax1total.ToString();
                ViewState["9"]  = tax2total.ToString();

                ViewState["ta3"] = tax3total.ToString();
                ViewState["11"]  = gsttltotal.ToString();

                // GridViewRow ft = (GridViewRow)gridpurchaseregister.FooterRow;
                gridpurchaseregister.FooterRow.Cells[4].ForeColor  = System.Drawing.Color.White;
                gridpurchaseregister.FooterRow.Cells[5].ForeColor  = System.Drawing.Color.White;
                gridpurchaseregister.FooterRow.Cells[6].ForeColor  = System.Drawing.Color.White;
                gridpurchaseregister.FooterRow.Cells[7].ForeColor  = System.Drawing.Color.White;
                gridpurchaseregister.FooterRow.Cells[8].ForeColor  = System.Drawing.Color.White;
                gridpurchaseregister.FooterRow.Cells[9].ForeColor  = System.Drawing.Color.White;
                gridpurchaseregister.FooterRow.Cells[10].ForeColor = System.Drawing.Color.White;

                gridpurchaseregister.FooterRow.Cells[4].Text  = "Total :";
                gridpurchaseregister.FooterRow.Cells[5].Text  = String.Format("{0:n}", Math.Round(Convert.ToDecimal(ViewState["7"]), 2));
                gridpurchaseregister.FooterRow.Cells[6].Text  = String.Format("{0:n}", Math.Round(Convert.ToDecimal(ViewState["8"]), 2));
                gridpurchaseregister.FooterRow.Cells[7].Text  = String.Format("{0:n}", Math.Round(Convert.ToDecimal(ViewState["9"]), 2));
                gridpurchaseregister.FooterRow.Cells[8].Text  = String.Format("{0:n}", Math.Round(Convert.ToDecimal(ViewState["ta3"]), 2));
                gridpurchaseregister.FooterRow.Cells[9].Text  = String.Format("{0:n}", Math.Round(Convert.ToDecimal(ViewState["10"]), 2));
                gridpurchaseregister.FooterRow.Cells[10].Text = String.Format("{0:n}", Math.Round(Convert.ToDecimal(ViewState["11"]), 2));
            }
        }
        else
        {
            gridpurchaseregister.DataSource = null;


            gridpurchaseregister.DataBind();
        }
    }
Beispiel #59
0
        public static void testAttributedBlockInsert()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            // change block name to your suit

            PromptEntityOptions pEnOpt = new PromptEntityOptions("\nPick Block Reference:");
            pEnOpt.SetRejectMessage("\nObject Not Block Reference");
            pEnOpt.AddAllowedClass(typeof(BlockReference), true);

            PromptEntityResult pEnRes = ed.GetEntity(pEnOpt);
            ObjectId EntId = pEnRes.ObjectId;
            //PromptResult pr = ed.GetString("\nType Block Name: ");
            //string blockName = pr.StringResult;
            string blockName = null;
            BlockReference UserBlockref = null;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                UserBlockref = (BlockReference)trans.GetObject(EntId, OpenMode.ForRead);
                blockName = UserBlockref.Name;
            }
            Matrix3d ucs = ed.CurrentUserCoordinateSystem;
            //get current UCS matrix
            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    // to force update drawing screen
                    doc.TransactionManager.EnableGraphicsFlush(true);
                    BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForWrite);

                    // if the block table doesn't already exists, exit
                    if (!bt.Has(blockName))
                    {
                        Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Block " + blockName + " does not exist.");
                        return;
                    }

                    // insert the block in the current space
                    PromptPointResult ppr = ed.GetPoint("\nSpecify insertion point: ");
                    if (ppr.Status != PromptStatus.OK)
                    {
                        return;
                    }
                    DBObjectCollection dbobjcoll = ed.TraceBoundary(ppr.Value, false);
                    Double area = 0;
                    try
                    {
                        if (dbobjcoll.Count > 0)
                        {
                            BlockTableRecord blockTableRecmSpace = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);
                            ObjectIdCollection traceObjIds = new ObjectIdCollection();
                            foreach (DBObject obj in dbobjcoll)
                            {
                                Entity EntTrace = obj as Entity;
                                if (EntTrace != null)
                                {
                                    if (EntTrace is Polyline)
                                    {
                                        Polyline p = (Polyline)EntTrace;
                                        if (p.Closed)
                                        {
                                            area = p.Area;
                                        }

                                    }
                                    if (EntTrace is Line)
                                    {
                                        Line Ln = (Line)EntTrace;
                                        if (Ln.Closed)
                                        {
                                            area = Ln.Area;
                                        }

                                    }
                                }
                            }
                        }
                    }
                    catch
                    {
                        throw;
                    }
                    string presisi = "#";
                    switch (db.Auprec)
                    {
                        case 0:
                            presisi = "#";
                            break;
                        case 1:
                            presisi = "#0.0";
                            break;
                        case 2:
                            presisi = "#0.00";
                            break;
                        case 3:
                            presisi = "#0.000";
                            break;
                        case 4:
                            presisi = "#0.0000";
                            break;
                        case 5:
                            presisi = "#0.00000";
                            break;
                        default:
                            presisi = "#0.00";
                            break;
                    }

                    valueAreaBoundary = area.ToString(presisi);

                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                    ObjectContextCollection occ = db.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES");
                    List<string> ListTag = new List<string>();
                    List<string> ListString = new List<string>();

                    Point3d pt = ppr.Value;
                    BlockReference bref = new BlockReference(pt, bt[blockName]);

                    Dictionary<string, string> dic = GetAttributDef(bref.BlockTableRecord, tr);
                    foreach (KeyValuePair<string, string> item in dic)
                    {
                        ListTag.Add(item.Key.ToUpper().ToString());
                        // string[] info = item.Value.Split('|');
                    }
                    formUserInputAttribut frmInput = new formUserInputAttribut();
                    IntPtr handle = AcAp.MainWindow.Handle;
                    if (frmInput.ShowDialog(ListTag) == System.Windows.Forms.DialogResult.OK)
                    {
                        ListString.AddRange(frmInput.InputString);
                    }
                    else { return; }

                    bref.Rotation = frmInput.UseRotation ? UserBlockref.Rotation : 0.0;

                    bref.TransformBy(ucs);
                    bref.AddContext(occ.CurrentContext);
                    //add blockreference to current space
                    btr.AppendEntity(bref);
                    tr.AddNewlyCreatedDBObject(bref, true);
                    // set attributes to desired values

                    ApplyAttibutes(db, tr, bref, ListTag, ListString);

                    bref.RecordGraphicsModified(true);
                    // to force updating a block reference
                    tr.TransactionManager.QueueForGraphicsFlush();
                    tr.Commit();
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(ex.Message);
            }
            finally
            {
                // Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Pokey")
            }
        }
Beispiel #60
0
 public Vector(Double val)
 {
     this.Value = val;
 }