Exemplo n.º 1
1
        // Retrieve end of day price data from yahoo finance
        public void GetData(string symbol, int period, int observations)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://ichart.yahoo.com/table.csv?s=" + symbol);
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            StreamReader sr = new StreamReader(resp.GetResponseStream());

            DataPointCollection logReturns = new DataPointCollection();

            int i = 0;
            string line = sr.ReadLine();// skip first line (header)
            string[] m = sr.ReadLine().Split(',');

            // The # of items we need to retrieve (make sure right amount)
            int j = period*4 + 1;
            if (j <= observations*4+1)
            {
                j = ((observations * 4) + 1);
            }

            while (i < j)
            {
                string[] n = sr.ReadLine().Split(',');
                double l = Convert.ToDouble(m[4]);
                double k = Convert.ToDouble(n[4]);
                DataPoint t = new DataPoint(Math.Log(l / k), Convert.ToDateTime(m[0]));
                logReturns.Add(t);
                m = n;
                i++;
            }

            // Calculate volatilities
            double annualFactor = Math.Sqrt(252);
            for (i = 0; i < j / 2; ++i)
            {
                double vol = StandardDeviation(logReturns.GetRange(i, period)) * annualFactor;
                DataPoint t = new DataPoint(vol, logReturns[i].Date);
                _vols.Add(t);
            }

            // Calculate std-dev of all volatilities
            for(i = 0; i < observations; ++i)
            {
                double stdDev = StandardDeviation(_vols.GetRange(i, period));
                DataPoint t = new DataPoint(stdDev, _vols[i].Date);
                _volStdDev.Add(t);
            }

            // Take subset so we can plot on graph
            _vols = _vols.GetRange(0, observations);
        }
 public LagarangePolynomialCurveInterpolatedData(PolynomialCurveParam curveParam)
 {
     this.curveType = curveParam.PolynomialCurveType;
     this.lastPoint = curveParam.PointList.RightBorderPoint;
     this.count = curveParam.Count;
     this.curve = GenerateCurve(curveParam);
 }
Exemplo n.º 3
0
        private int GetPaletteEntryIndex(DataPoint dp)
        {
            var series = (ChartSeries)dp.Presenter;
            var cartesianChart = series.Chart as RadCartesianChart;
            var pieChart = series.Chart as RadPieChart;
            int index;

            if (cartesianChart != null)
            {
                BarSeries barSeries = series as BarSeries;
                BubbleSeries bubbleSeries = series as BubbleSeries;
                if ((barSeries != null && barSeries.PaletteMode == SeriesPaletteMode.DataPoint) ||
                    (bubbleSeries != null && bubbleSeries.PaletteMode == SeriesPaletteMode.DataPoint))
                {
                    index = dp.Index;
                }
                else
                {
                    index = cartesianChart.Series.IndexOf((CartesianSeries)series);
                }
            }
            else if (pieChart != null)
            {
                index = pieChart.Series.IndexOf((PieSeries)series);
            }
            else
            {
                index = ((RadPolarChart)series.Chart).Series.IndexOf((PolarSeries)series);
            }

            return index;
        }
        protected override void Add(DataPoint<decimal> dataPoint)
        {
            //TimeSeriesLock.EnterWriteLock();
            try
            {
                TimeSeries.Add(dataPoint);
            }
            finally
            {
               // TimeSeriesLock.ExitWriteLock();
            }

            OnNewDataPoint(dataPoint);

            bool haveToProcess = false;
            //TimeSeriesLock.EnterReadLock();
            try
            {
                haveToProcess = TimeSeries.Count >= _period;
            }
            finally
            {
                //TimeSeriesLock.ExitReadLock();
            }
            // not ideal, value can still change, but it is acceptable for the stats
            if (haveToProcess)
                ProcessNewValue();
        }
        public async void QueryMetricsAsync_uses_sum_aggregator()
        {
            var metricName = GetUniqueMetricName();

            var time = DateTime.UtcNow.MillisecondsSinceEpoch();

            var dataPoint = new DataPoint(time, 10L);
            var dataPoint2 = new DataPoint(time + 1, 30L);

            var metric = new Metric(metricName)
                .AddTag("route_id", "1")
                .AddDataPoint(dataPoint2)
                .AddDataPoint(dataPoint);

            await _client.AddMetricsAsync(new[] { metric });

            var queryMetric = new QueryMetric(metricName)
                .AddAggregator(new SumAggregator(1, TimeUnit.Minutes));

            var query = new QueryBuilder()
                .SetStart(TimeSpan.FromSeconds(10))
                .AddQueryMetric(queryMetric);

            Thread.Sleep(TimeSpan.FromSeconds(2));

            var response = await _client.QueryMetricsAsync(query);

            response.Queries.Should().HaveCount(1);
            response.Queries[0].Results.Should().HaveCount(1);
            response.Queries[0].Results[0].DataPoints.Single().Value.Should().Be(40L);
        }
        public void ValidMessage_ProducesValidJson()
        {
            var name = "foo";
            var value = 1923;
            var instance = "i-349da92";
            var collectedAt = new DateTime(2012, 1, 2);
            var collectedAtEpochSeconds = (long) collectedAt.Subtract(CustomMetricsMessage.EpochTime).TotalSeconds;
            var dp = new DataPoint(name, value, collectedAt, instance);

            var now = DateTime.UtcNow;
            var msg = new CustomMetricsMessage(dp);

            var json = msg.ToJson();
            Assert.NotNull(json);

            var deserialized = (JObject)JsonConvert.DeserializeObject(json);
            Assert.Equal(CustomMetricsMessage.ProtocolVersion, deserialized["proto_version"].Value<int>());
            Assert.True(deserialized["timestamp"].Value<long>() >= CustomMetricsMessage.EpochTime.Subtract(now).TotalSeconds);

            var pointsArray = deserialized["data"].Value<JArray>();
            Assert.NotNull(pointsArray);
            Assert.Equal(1, pointsArray.Count);

            var data0 = (JObject)pointsArray[0];
            Assert.Equal(name, data0["name"].Value<string>());
            Assert.Equal(value, data0["value"].Value<int>());
            Assert.Equal(instance, data0["instance"].Value<string>());
            Assert.Equal(collectedAtEpochSeconds, data0["collected_at"].Value<long>());
        }
        public async void RestClient_posts_metrics()
        {
            var metricName = GetUniqueMetricName();

            var dataPoint = new DataPoint(DateTime.UtcNow.MillisecondsSinceEpoch(), 5L);

            var metric = new Metric(metricName)
                .AddTag("route_id", "1")
                .AddDataPoint(dataPoint);

            await _client.AddMetricsAsync(new[] {metric});

            var query = new QueryBuilder()
                .SetStart(TimeSpan.FromSeconds(5))
                .AddQueryMetric(new QueryMetric(metricName));

            Thread.Sleep(TimeSpan.FromSeconds(2));

            var response = await _client.QueryMetricsAsync(query);

            response.Queries.Should().HaveCount(1);
            response.Queries[0].SampleSize.Should().Be(1);
            response.Queries[0].Results.Should().HaveCount(1);
            response.Queries[0].Results[0].DataPoints.Single().ShouldBeEquivalentTo(dataPoint);
        }
Exemplo n.º 8
0
        // Override the AddChartSeries method to provide the chart data
        protected override void AddChartSeries()
        {
            ChartSeriesData = new List<Series>();
            var series = new Series()
            {
                ChartType = SeriesChartType.Pie,
                BorderWidth = 1
            };

            var shares = chartData.ShareData;
            foreach (var share in shares)
            {
                var point = new DataPoint();
                point.IsValueShownAsLabel = true;
                point.AxisLabel = share.Name;
                point.ToolTip = share.Name + " " +
                      share.Share.ToString("#0.##%");
                if (share.Url != null)
                {
                    point.MapAreaAttributes = "href=\"" +
                          share.Url + "\"";
                }
                point.YValues = new double[] { share.Share };
                point.LabelFormat = "P1";
                series.Points.Add(point);
            }

            ChartSeriesData.Add(series);
        }
Exemplo n.º 9
0
        protected void uxGamesRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            UserMeanGameScore mgs = (UserMeanGameScore)e.Item.DataItem;
            //e.Item.FindControl("uxIndividualCharge");

            if (Session["SessionId"] != null)
            {
                Guid sessionId = new Guid(Session["SessionId"].ToString());
                GamesScoreWS.GameScoreService gsClient = new GamesScoreWS.GameScoreService();
                IndividualGameResults igResults = gsClient.FetchIndividualGames(sessionId, mgs.GameId);
                if (igResults.Success)
                {
                    Chart createChart = (Chart)e.Item.FindControl("uxIndividualCharge");
                    createChart.Titles.Add(mgs.Game);
                    Series resultsSeries = createChart.Series["GameScores"];
                    foreach (t_GameResults gr in igResults.GameResultList)
                    {
                        DataPoint dp = new DataPoint();
                        decimal indexical = ((decimal)gr.Score / (decimal)gr.Total) * 100;
                        dp.SetValueXY(gr.Created.ToShortDateString(), indexical);
                        dp.ToolTip = string.Format("{0} out of {1} in {2} seconds", gr.Score, gr.Total, gr.TestDuration);
                        resultsSeries.Points.Add(dp);
                    }
                }
            }
        }
Exemplo n.º 10
0
 public void PointsTest(int i, double x, double y)
 {
     var s = GetSpectrum();
     var expected = new DataPoint(i, x, y);
     var actual = s.Points.ToArray()[i];
     Assert.AreEqual(expected, actual);
 }
Exemplo n.º 11
0
        public static void CreateChart(string imagePath,string name, IEnumerable<BenchResult> results, Func<BenchResult,double> selector)
        {
            Chart chart = new Chart();
            chart.Width = 500;
            chart.Height = 400;
            chart.Titles.Add(name);
            var area = new ChartArea("Default");
            chart.ChartAreas.Add(area);
            var series = new Series("Default");
            chart.Series.Add(series);
            area.AxisX.LabelAutoFitStyle = LabelAutoFitStyles.LabelsAngleStep90;
            area.AxisX.LabelStyle.TruncatedLabels = false;
            area.AxisX.Interval = 1;
            series.ChartType = SeriesChartType.Column;
            series.IsValueShownAsLabel = true;
            series.XValueType = ChartValueType.String;

            series.YValueType = ChartValueType.Int32;

            foreach(var r in results.OrderBy( r => selector(r)))
            {
                DataPoint point = new DataPoint();
                point.SetValueXY(r.Serializer.Replace("Adapter",""),(int)Math.Round(selector(r)));
                point.AxisLabel = r.Serializer.Replace("Adapter", "");
                series.Points.Add(point);
            }

            chart.SaveImage(imagePath, ChartImageFormat.Png);
        }
Exemplo n.º 12
0
    public void BindProductSalesChart(int year)
    {
        using (CartDataClassesDataContext context = new CartDataClassesDataContext())
        {
            var productSales = from o in context.Orders
                               where o.DatePlaced.Value.Year == year
                               group o by o.DatePlaced.Value.Month into g
                               orderby g.Key
                               select new
                               {
                                   Month = g,
                                   TopProducts = (from op in context.OrderProducts
                                                  where op.OrderDate.Value.Year == year && op.OrderDate.Value.Month == g.Key
                                                  group op by op.ProductID into opg
                                                  orderby opg.Count() descending
                                                  select new { ProductName = context.Products.Where(p => p.ProductID == opg.Key).Single().ProductName, ProductCount = opg.Count() }).Take(5)
                               };

            foreach (var sale in productSales)
            {
                Series series = new Series(Enum.Parse(typeof(Month), sale.Month.FirstOrDefault().DatePlaced.Value.Month.ToString()).ToString()) { ChartType = SeriesChartType.Bubble};
                foreach (var topProduct in sale.TopProducts){
                    DataPoint point = new DataPoint() { XValue = sale.Month.Key, YValues = new double[] { (double)topProduct.ProductCount }, Label = topProduct.ProductName };
                    series.Points.Add(point);

                }
                ProductSalesChart.Series.Add(series);
            }
        }
    }
Exemplo n.º 13
0
        public static double Slope(DataPoint[] points)
        {
            double xAvg = 0, yAvg = 0;

            for (int i = 0; i < points.Length; i++)
            {
                xAvg += points[i].temperature;
                yAvg += points[i].position;
            }

            xAvg = xAvg / points.Length;
            yAvg = yAvg / points.Length;

            double v1 = 0;
            double v2 = 0;

            for (int i = 0; i < points.Length; i++)
            {
                v1 += (points[i].temperature - xAvg) * (points[i].position - yAvg);
                v2 += Math.Pow(points[i].temperature - xAvg, 2);
            }

            double a = v1 / v2;

            return a;
        }
 public void addPoint(DataPoint point)
 {
     lock (this.theLock)
     {
         points.Add(point);
         dataPoints.Add(point.AsDataObject());
     }
 }
Exemplo n.º 15
0
 public static DataPoint operator +(DataPoint d1, DataPoint d2)
 {
     DataPoint temp = new DataPoint();
     temp.Commits = d1.Commits + d2.Commits;
     temp.AddedLines = d1.AddedLines + d2.AddedLines;
     temp.DeletedLines = d1.DeletedLines + d2.DeletedLines;
     return temp;
 }
Exemplo n.º 16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MetricTelemetry"/> class with empty 
        /// properties.
        /// </summary>
        public MetricTelemetry()
        {
            this.Data = new MetricData();
            this.Metric = new DataPoint();
            this.context = new TelemetryContext(this.Data.properties, new Dictionary<string, string>());

            // We always have a single 'metric'.
            this.Data.metrics.Add(this.Metric);
        }
Exemplo n.º 17
0
 public DataVector(DataPoint pt1, DataPoint pt2)
 {
     xDiff = pt2.X - pt1.X;
     yDiff = pt2.Y - pt1.Y;
     if (xDiff != 0 || yDiff != 0)
     {
         isZero = false;
     }
 }
        public override RadRect GetLabelLayoutSlot(DataPoint point, FrameworkElement visual, int labelIndex)
        {
            visual.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));

            double x = point.LayoutSlot.X + ((point.LayoutSlot.Width - visual.ActualWidth) / 2);
            double y = point.LayoutSlot.Y + ((point.LayoutSlot.Height - visual.ActualHeight) / 2);

            return new RadRect(x, y, visual.ActualWidth, visual.ActualHeight);
        }
Exemplo n.º 19
0
        public override RadRect GetLabelLayoutSlot(DataPoint point, FrameworkElement visual, int labelIndex)
        {
            var size = new Size(visual.ActualWidth + visual.Margin.Left + visual.Margin.Right, visual.ActualHeight + visual.Margin.Top + visual.Margin.Bottom);

            var series = (ChartSeries)point.Presenter;
            double top = point.LayoutSlot.Center.Y - (size.Height / 2);
            double left = series.Chart.PlotAreaClip.Right - size.Width + Offset;

            return new RadRect(left, top, size.Width, size.Height);
        }
        public void addDataPoint(DataContainer container, DataPoint point)
        {
            //Add data point to container
            container.addPoint(point);

            //If the container is full, push to the server
            if (container.count() >= MAX_DATA_POINTS)
            {
                pushData(container);
            }
        }
Exemplo n.º 21
0
 public virtual void ReceivedData(DataPoint data)
 {
     GetComponent<Pulse>().ScaleSecond();
     if(imSpecial) {
         imSpecial.OnReceivedData(data);
     }
     else {
         nodeState = NodeState.active;
         data.FindNewTarget(this);
         timeToLoneliness = 2.3f;
     }
 }
Exemplo n.º 22
0
 protected override void Add(DataPoint<decimal> dataPoint)
 {
     //TimeSeriesLock.EnterWriteLock();
     try
     {
         TimeSeries.Add(dataPoint);
     }
     finally
     {
         //TimeSeriesLock.ExitWriteLock();
     }
     OnNewDataPoint(dataPoint);
 }
Exemplo n.º 23
0
 public ImageAnnotation(
     OxyImage image,
     DataPoint position,
     HorizontalAlignment horizontalAlignment = HorizontalAlignment.Center,
     VerticalAlignment verticalAlignment = VerticalAlignment.Middle)
     : this()
 {
     this.ImageSource = image;
     this.X = new PlotLength(position.X, PlotLengthUnit.Data);
     this.Y = new PlotLength(position.Y, PlotLengthUnit.Data);
     this.HorizontalAlignment = horizontalAlignment;
     this.VerticalAlignment = verticalAlignment;
 }
Exemplo n.º 24
0
        private void InitData()
        {
            string mDeviceID= Request.QueryString["id"];
            PerfNetDetailOR _Obj = new PerfNetDA().SelectDeviceDetail(mDeviceID);
            DeviceOR _objDev = new DeviceDA().SelectDeviceORByID(mDeviceID);
            DeviceOREx _objDevEx = new DeviceDA().SelectDeviceORExByID(mDeviceID);
            switch (_objDevEx.State)
            {
                case "正常":
                    State = "1";
                    break;
                case "故障":
                    State = "0";
                    break;
            }
            lblClass.Text = _objDevEx.ClassName;
            lblType.Text = _objDevEx.TypeName;

            lblDeviceName.Text = _objDev.DeviceName;

            lblIP.Text = _objDev.IP;
            lblFirm.Text = _Obj.Firm;
            lblFlowCalculator.Text = _Obj.FlowCalculator;
            lblDependence.Text = _Obj.Dependence;
            lblPollingProtocol.Text = _Obj.PollingProtocol;
            lblMonitor.Text = _Obj.Monitor;
            lblSystemDescription.Text = _objDev.Describe;
            lblResponseTime.Text = _Obj.ResponseTime;
            lblPacketLossRate.Text = _Obj.LoseRate;

            #region 绑定 今天的使用率
            DataPoint dp = new DataPoint();
            dp.LegendText = string.Format("{0}({1}%)", "今天的使用率", _Obj.NetUtilityRate);
            double[] d = { Convert.ToDouble(_Obj.NetUtilityRate) };
            dp.Color = Color.Green;
            dp.YValues = d;
            chtPerf.Series["Series1"].Points.Add(dp);

            dp = new DataPoint();
            dp.LegendText = string.Format("{0}({1}%)", "今天的未使用率", 100 - _Obj.NetUtilityRate);
            double[] dno = { Convert.ToDouble(100 - _Obj.NetUtilityRate) };
            dp.Color = Color.Red;
            dp.YValues = dno;
            chtPerf.Series["Series1"].Points.Add(dp);
            #endregion

            //接口列表
            gvPortList.DataSource = _Obj.SubProts;
            gvPortList.DataBind();
        }
Exemplo n.º 25
0
        public static Readings GetAllCollectionData()
        {
            UdpClient udpClient = new UdpClient(7000);

            IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 7000);

            try
            {
                while (true)
                {

                    Byte[] receiveBytes = udpClient.Receive(ref remoteIpEndPoint);

                    string receivedData = Encoding.ASCII.GetString(receiveBytes);

                    string[] data = receivedData.Split();
                    int potentiometer = int.Parse(data[14]);
                    int lightSensor = int.Parse(data[18]);
                    int temperature = int.Parse(data[21]);

                    //Indsæt DataPoint i databasen
                    var dp = new DataPoint()
                    {
                        Humidity = potentiometer,
                        Light = lightSensor,
                        Temp = temperature,
                        Ph = 100,
                        PlantId = 4,
                        TimeStamp = DateTime.Now
                    };
                    DbRepository.InsertDataPoint(dp);

                    udpClient.Close();

                    return new Readings()
                    {
                        Humidity = potentiometer,
                        Light = lightSensor,
                        Ph = 100,
                        Temp = temperature
                    };

                }

            }
            catch (Exception)
            {
                throw new Exception("Could not connect to sensors.");
            }
        }
Exemplo n.º 26
0
 public override void OnMouseMove(System.Windows.Point pt, bool control, bool shift)
 {
     if (!isPanning)
         return;
     var currentPoint = pc.InverseTransform(pt, xaxis, yaxis);
     double dx = currentPoint.X - previousPoint.X;
     double dy = currentPoint.Y - previousPoint.Y;
     if (xaxis != null)
         pc.Pan(xaxis, -dx);
     if (yaxis != null)
         pc.Pan(yaxis, -dy);
     pc.Refresh();
     previousPoint = pc.InverseTransform(pt, xaxis, yaxis);
 }
Exemplo n.º 27
0
        /// <summary>
        /// Gets the point on the series that is nearest the specified point.
        /// </summary>
        /// <param name="point">The point.</param>
        /// <param name="interpolate">Interpolate the series if this flag is set to <c>true</c>.</param>
        /// <returns>A TrackerHitResult for the current hit.</returns>
        public override TrackerHitResult GetNearestPoint(ScreenPoint point, bool interpolate)
        {
            if (this.XAxis == null || this.YAxis == null)
            {
                return null;
            }

            if (interpolate)
            {
                return null;
            }

            TrackerHitResult result = null;

            // http://paulbourke.net/geometry/pointlineplane/
            double minimumDistance = double.MaxValue;
            var points = this.ActualPoints;

            for (int i = 0; i < points.Count; i++)
            {
                var p1 = points[i];
                var basePoint = new DataPoint(p1.X, this.Base);
                var sp1 = this.Transform(p1);
                var sp2 = this.Transform(basePoint);
                var u = ScreenPointHelper.FindPositionOnLine(point, sp1, sp2);

                if (double.IsNaN(u))
                {
                    continue;
                }

                if (u < 0 || u > 1)
                {
                    continue; // outside line
                }

                var sp = sp1 + ((sp2 - sp1) * u);
                double distance = (point - sp).LengthSquared;

                if (distance < minimumDistance)
                {
                    result = new TrackerHitResult(
                        this, new DataPoint(p1.X, p1.Y), new ScreenPoint(sp1.x, sp1.y), this.GetItem(i));
                    minimumDistance = distance;
                }
            }

            return result;
        }
Exemplo n.º 28
0
            public void Update(DateTime sent, DateTime processingStarted, DateTime processingEnded)
            {
                var dataPoint = new DataPoint(processingEnded - sent, processingEnded, processingEnded - processingStarted);

                lock (dataPoints)
                {
                    dataPoints.Add(dataPoint);
                    if (dataPoints.Count > MaxDataPoints)
                    {
                        dataPoints.RemoveRange(0, dataPoints.Count - MaxDataPoints);
                    }
                }

                UpdateTimeToSLABreach();
            }
Exemplo n.º 29
0
 public override void OnReceivedData(DataPoint data)
 {
     audio.Stop();
     if(data.contaminated) {
         audio.clip = GameHandler.instance.badGatheredSound;
         audio.Play();
         GameHandler.instance.contaminatedDataCollected++;
     }
     else {
         audio.clip = GameHandler.instance.dataGatheredSound;
         audio.Play();
         GameHandler.instance.dataCollected++;
     }
     Destroy(data.gameObject);
 }
Exemplo n.º 30
0
    public override void OnReceivedData(DataPoint data)
    {
        base.OnReceivedData(data);

        audio.Stop();
        audio.Play();

        if(!data.contaminated) {
            data.contaminated = true;
            data.renderer.material.color = Color.red;
            GameHandler.instance.dataContaminated++;
        }
        myNode.nodeState = Node.NodeState.nsa;
        myNode.timeToLoneliness = 2.3f;
    }
Exemplo n.º 31
0
 /// <summary>
 /// A callback, raised by a data point visualized by this instance. Intended for internal use.
 /// </summary>
 void IChartSeries.OnDataPointIsSelectedChanged(DataPoint point)
 {
     this.OnDataPointSelectionChanged(point);
 }
Exemplo n.º 32
0
 internal virtual int GetPaletteIndexForPoint(DataPoint point)
 {
     return(this.ActualPaletteIndex);
 }
Exemplo n.º 33
0
        // serialization is needed by OnSerialize and by manual sending from authority
        void DeserializeFromReader(NetworkReader reader)
        {
            // put it into a data point immediately
            DataPoint temp = new DataPoint();

            // deserialize position
            temp.position = reader.ReadVector3();

            // deserialize rotation
            if (compressRotation == Compression.None)
            {
                // read 3 floats = 16 byte
                float x = reader.ReadSingle();
                float y = reader.ReadSingle();
                float z = reader.ReadSingle();
                temp.rotation = Quaternion.Euler(x, y, z);
            }
            else if (compressRotation == Compression.Much)
            {
                // read 3 byte. scaling [0,255] to [0,360]
                float x = Utils.ScaleByteToFloat(reader.ReadByte(), byte.MinValue, byte.MaxValue, 0, 360);
                float y = Utils.ScaleByteToFloat(reader.ReadByte(), byte.MinValue, byte.MaxValue, 0, 360);
                float z = Utils.ScaleByteToFloat(reader.ReadByte(), byte.MinValue, byte.MaxValue, 0, 360);
                temp.rotation = Quaternion.Euler(x, y, z);
            }
            else if (compressRotation == Compression.Lots)
            {
                // read 2 byte, 5 bits per float
                float[] xyz = Utils.UnpackUShortIntoThreeFloats(reader.ReadUInt16(), 0, 360);
                temp.rotation = Quaternion.Euler(xyz[0], xyz[1], xyz[2]);
            }

            // timestamp
            temp.timeStamp = Time.time;

            // movement speed: based on how far it moved since last time
            // has to be calculated before 'start' is overwritten
            temp.movementSpeed = EstimateMovementSpeed(goal, temp, targetComponent.transform, syncInterval);

            // reassign start wisely
            // -> first ever data point? then make something up for previous one
            //    so that we can start interpolation without waiting for next.
            if (start == null)
            {
                start = new DataPoint {
                    timeStamp     = Time.time - syncInterval,
                    position      = targetComponent.transform.position,
                    rotation      = targetComponent.transform.rotation,
                    movementSpeed = temp.movementSpeed
                };
            }
            // -> second or nth data point? then update previous, but:
            //    we start at where ever we are right now, so that it's
            //    perfectly smooth and we don't jump anywhere
            //
            //    example if we are at 'x':
            //
            //        A--x->B
            //
            //    and then receive a new point C:
            //
            //        A--x--B
            //              |
            //              |
            //              C
            //
            //    then we don't want to just jump to B and start interpolation:
            //
            //              x
            //              |
            //              |
            //              C
            //
            //    we stay at 'x' and interpolate from there to C:
            //
            //           x..B
            //            \ .
            //             \.
            //              C
            //
            else
            {
                float oldDistance = Vector3.Distance(start.position, goal.position);
                float newDistance = Vector3.Distance(goal.position, temp.position);

                start = goal;

                // teleport / lag / obstacle detection: only continue at current
                // position if we aren't too far away
                if (Vector3.Distance(targetComponent.transform.position, start.position) < oldDistance + newDistance)
                {
                    start.position = targetComponent.transform.position;
                    start.rotation = targetComponent.transform.rotation;
                }
            }

            // set new destination in any case. new data is best data.
            goal = temp;
        }
Exemplo n.º 34
0
        // CONTROL ADDITION -------------------------------------------------------------------------------------------------------------

        Control addcontrol(string[, ,] controlarray, HtmlTableCell cell, HtmlTableRow row, int col_traverse, int row_traverse)
        {
            // Generic return object
            Control returncontrol = new Control();

            // Specific object generation methods
            switch (controlarray[col_traverse, row_traverse, 0])
            {
            case "LABEL":       // Label control
            {
                // Create new control
                Label newlabel = new Label();

                // Set control properties
                newlabel.Font.Name = "Arial"; newlabel.Font.Size = 11;
                newlabel.ID        = "control_" + col_traverse + "_" + row_traverse;

                // Add control
                cell.Controls.Add(newlabel);
                returncontrol = newlabel;

                break;
            }

            case "TEXTBOX":
            {
                // Create new control
                TextBox newtextbox = new TextBox();
                Label   newlabel   = new Label();

                // Set textbox control properties
                newtextbox.Font.Name = "Arial"; newtextbox.Font.Size = 11;
                newtextbox.ID        = "control_" + col_traverse + "_" + row_traverse;
                newtextbox.Width     = Unit.Pixel(Convert.ToInt16(cell.Width.Substring(0, cell.Width.Length - 2)) * cell.ColSpan - 2 * (layouttable.Border + layouttable.CellPadding));

                // Set label control properties
                newlabel.Font.Name = "Arial"; newlabel.Font.Size = 11;

                // Add control
                cell.Controls.Add(newlabel);
                cell.Controls.Add(new LiteralControl("<br><br>"));
                cell.Controls.Add(newtextbox);

                // Return label for text fill
                //returncontrol = newtextbox;
                returncontrol = newlabel;
                break;
            }

            case "MULTISELECT":
            {
                // Create new control
                ListBox newlistbox = new ListBox();
                Label   newlabel   = new Label();

                // Set listbox control properties
                newlistbox.Font.Name     = "Arial"; newlistbox.Font.Size = 11;
                newlistbox.ID            = "control_" + col_traverse + "_" + row_traverse;
                newlistbox.Width         = Unit.Pixel(Convert.ToInt16(cell.Width.Substring(0, cell.Width.Length - 2)) * cell.ColSpan - 2 * (layouttable.Border + layouttable.CellPadding));
                newlistbox.SelectionMode = ListSelectionMode.Multiple;

                // Set label control properties
                newlabel.Font.Name = "Arial"; newlabel.Font.Size = 11;
                newlabel.ID        = "control_" + col_traverse + "_" + row_traverse + "_label";

                // Add control
                cell.Controls.Add(newlabel);
                cell.Controls.Add(new LiteralControl("<br><br>"));
                cell.Controls.Add(newlistbox);

                // Return label for text fill
                //returncontrol = newtextbox;
                returncontrol = newlistbox;
                break;
            }

            case "IMAGE":
            {
                // Create new control
                Image newimage = new Image();

                // Set control properties
                newimage.ID     = "control_" + col_traverse + "_" + row_traverse;
                newimage.Width  = Unit.Pixel(Convert.ToInt16(cell.Width.Substring(0, cell.Width.Length - 2)) * cell.ColSpan - 2 * (layouttable.Border + layouttable.CellPadding));
                newimage.Height = Unit.Pixel(Convert.ToInt16(row.Height.Substring(0, row.Height.Length - 2)) * cell.RowSpan - 2 * (layouttable.Border + layouttable.CellPadding));

                // Add control
                cell.Controls.Add(newimage);
                returncontrol = newimage;

                break;
            }

            case "TABLE":
            {
                // Enclose table in panel
                Panel tablepanel = new Panel();
                tablepanel.ScrollBars = ScrollBars.Both;
                tablepanel.Width      = Unit.Pixel(Convert.ToInt16(cell.Width.Substring(0, cell.Width.Length - 2)) * cell.ColSpan - (layouttable.Border + layouttable.CellPadding));
                tablepanel.Height     = Unit.Pixel(Convert.ToInt16(row.Height.Substring(0, row.Height.Length - 2)) * cell.RowSpan - (layouttable.Border + layouttable.CellPadding));

                // Create new control
                GridView newtable = new GridView();

                // Set control properties
                newtable.ID                       = "control_" + col_traverse + "_" + row_traverse;
                newtable.Width                    = Unit.Pixel((int)(tablepanel.Width.Value - 17));
                newtable.Height                   = Unit.Pixel((int)(tablepanel.Height.Value - 17));
                newtable.Font.Name                = "Arial"; newtable.Font.Size = 11;
                newtable.HeaderStyle.BackColor    = System.Drawing.Color.Silver;
                newtable.RowStyle.BackColor       = System.Drawing.Color.White;
                newtable.RowStyle.HorizontalAlign = HorizontalAlign.Center;

                // Add control
                tablepanel.Controls.Add(newtable);
                cell.Controls.Add(tablepanel);
                returncontrol = tablepanel;

                break;
            }

            case "SCATTERPLOT":
            {
                Chart  Projection = new Chart();
                Series newseries  = new Series();
                newseries.ChartType = SeriesChartType.Point;
                Projection.ChartAreas.Add(new ChartArea());
                Projection.ChartAreas[0].AxisY.Title = "Second Principal Component";
                Projection.ChartAreas[0].AxisX.Title = "First Principal Component";

                Projection.Width  = Unit.Pixel(Convert.ToInt16(cell.Width.Substring(0, cell.Width.Length - 2)) * cell.ColSpan - 2 * (layouttable.Border + layouttable.CellPadding));
                Projection.Height = Unit.Pixel(Convert.ToInt16(row.Height.Substring(0, row.Height.Length - 2)) * cell.RowSpan - 2 * (layouttable.Border + layouttable.CellPadding));

                DataMiningApp.Analysis.ParameterStream stream;
                Registry.Registry registry;

                stream   = DataMiningApp.Analysis.ParameterStream.getStream(Session);
                registry = Registry.Registry.getRegistry(Session);

                Matrix   PCmatrix = (Matrix)stream.get("PCmatrix");
                String[] features = (String[])stream.get("selectedFeatures");

                System.Data.DataSet ds = (System.Data.DataSet)registry.GetDataset((string)stream.get("dataSetName"));

                //retrieve dataset table (assume one for now)
                System.Data.DataTable dt = ds.Tables[0];

                //raw data
                double[,] rawData = new double[dt.Rows.Count, features.Count()];
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    for (int j = 0; j < features.Count(); j++)
                    {
                        rawData[i, j] = (double)dt.Rows[i].ItemArray.ElementAt(dt.Columns[features[j]].Ordinal);
                    }
                }

                //Create matrix to hold data for PCA
                Matrix X = new Matrix(rawData);

                //Remove mean
                Vector columnVector;
                for (int i = 0; i < X.ColumnCount; i++)
                {
                    columnVector = X.GetColumnVector(i);
                    X.SetColumnVector(columnVector.Subtract(columnVector.Average()), i);
                }

                //get first two PCs
                Matrix xy = new Matrix(PCmatrix.RowCount, 2);
                xy.SetColumnVector(PCmatrix.GetColumnVector(0), 0);
                xy.SetColumnVector(PCmatrix.GetColumnVector(1), 1);

                //project
                Matrix projected = X.Multiply(xy);

                DataPoint point;
                Projection.Series.Clear();
                Projection.Legends.Clear();


                //if a label column is selected
                String LabelColumnName = "Species";

                if (!LabelColumnName.Equals(""))
                {
                    //get labels
                    int           labelColumnIndex = dt.Columns[LabelColumnName].Ordinal;
                    List <String> labels           = new List <String>();
                    String        item;

                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        item = (String)dt.Rows[i].ItemArray.ElementAt(labelColumnIndex);
                        if (!labels.Contains(item))
                        {
                            labels.Add(item);
                        }
                    }
                    Legend mylegend = Projection.Legends.Add(LabelColumnName);
                    mylegend.TableStyle = LegendTableStyle.Wide;

                    Projection.Legends[0].Docking = Docking.Bottom;
                    System.Drawing.Font font = Projection.Legends[LabelColumnName].Font = new System.Drawing.Font(Projection.Legends[LabelColumnName].Font.Name, 14);

                    //Configure series
                    foreach (String label in labels)
                    {
                        Projection.Series.Add(label);
                        Projection.Series[label].LegendText      = label;
                        Projection.Series[label].IsXValueIndexed = false;
                        Projection.Series[label].ChartType       = SeriesChartType.Point;
                        Projection.Series[label].MarkerSize      = 8;
                    }

                    //Add points
                    for (int i = 0; i < projected.RowCount; i++)
                    {
                        point = new DataPoint(projected[i, 0], projected[i, 1]);
                        String label = dt.Rows[i].ItemArray[labelColumnIndex].ToString();
                        Projection.Series[label].Points.Add(point);
                    }
                }
                else
                {
                    //Single plot graph
                    Projection.Series.Add("series1");
                    Projection.Series[0].IsXValueIndexed = false;
                    Projection.Series[0].ChartType       = SeriesChartType.Point;
                    Projection.Series[0].MarkerSize      = 8;

                    for (int i = 0; i < projected.RowCount; i++)
                    {
                        point = new DataPoint(projected[i, 0], projected[i, 1]);
                        Projection.Series[0].Points.Add(point);
                    }
                }
                cell.Controls.Add(Projection);
                returncontrol = Projection;

                /*
                 * // Create new control
                 * Chart chartcontrol = new Chart();
                 *
                 * // Set chart width and height
                 * chartcontrol.Width = Unit.Pixel(Convert.ToInt16(cell.Width.Substring(0, cell.Width.Length - 2)) * cell.ColSpan - 2 * (layouttable.Border + layouttable.CellPadding));
                 * chartcontrol.Height = Unit.Pixel(Convert.ToInt16(row.Height.Substring(0, row.Height.Length - 2)) * cell.RowSpan - 2 * (layouttable.Border + layouttable.CellPadding));
                 *
                 * // Needed so server knows where to store temporary image
                 * chartcontrol.ImageStorageMode = ImageStorageMode.UseImageLocation;
                 *
                 * ChartArea mychartarea = new ChartArea();
                 * chartcontrol.ChartAreas.Add(mychartarea);
                 *
                 * Series myseries = new Series();
                 * myseries.Name = "Series";
                 * chartcontrol.Series.Add(myseries);
                 *
                 * chartcontrol.Series["Series"].ChartType = SeriesChartType.Point;
                 *
                 * // Add control
                 * cell.Controls.Add(chartcontrol);
                 * returncontrol = chartcontrol;
                 */
                break;
            }

            case "LINEPLOT":
            {
                DataMiningApp.Analysis.ParameterStream stream = DataMiningApp.Analysis.ParameterStream.getStream(Session);
                Vector Weights = (Vector)stream.get("Weights");

                Chart VariancePlot = new Chart();

                VariancePlot.Width  = Unit.Pixel(Convert.ToInt16(cell.Width.Substring(0, cell.Width.Length - 2)) * cell.ColSpan - 2 * (layouttable.Border + layouttable.CellPadding));
                VariancePlot.Height = Unit.Pixel(Convert.ToInt16(row.Height.Substring(0, row.Height.Length - 2)) * cell.RowSpan - 2 * (layouttable.Border + layouttable.CellPadding));

                VariancePlot.Palette = ChartColorPalette.EarthTones;
                Series dataseries = new Series();
                dataseries.ChartType         = SeriesChartType.Line;
                dataseries.MarkerColor       = System.Drawing.Color.Black;
                dataseries.MarkerBorderWidth = 3;
                dataseries.MarkerBorderColor = System.Drawing.Color.Black;
                VariancePlot.Series.Add(dataseries);
                VariancePlot.ChartAreas.Add(new ChartArea());
                VariancePlot.ChartAreas[0].AxisY.Title = "Variance Explained";
                VariancePlot.ChartAreas[0].AxisX.Title = "Principal Component";

                for (int i = 0; i < Weights.Length; i++)
                {
                    VariancePlot.Series[0].Points.InsertY(i, Weights[i]);
                }

                cell.Controls.Add(VariancePlot);
                returncontrol = VariancePlot;

                break;
            }

            case "UPLOAD":
            {
                // Create new controls
                Label       uploadlabel = new Label();
                FileUpload  uploadcontrol = new FileUpload();
                HiddenField savedfile = new HiddenField(); HiddenField savedpath = new HiddenField();
                Button      uploadbutton = new Button();
                GridView    uploadtable  = new GridView();

                // Create panel to enclose table to it can scroll without having to scroll entire window
                Panel tablepanel = new Panel();
                tablepanel.ScrollBars = ScrollBars.Both;
                tablepanel.Width      = Unit.Pixel(Convert.ToInt16(cell.Width.Substring(0, cell.Width.Length - 2)) * cell.ColSpan - (layouttable.Border + layouttable.CellPadding));
                tablepanel.Height     = Unit.Pixel(Convert.ToInt16(row.Height.Substring(0, row.Height.Length - 2)) * cell.RowSpan - (layouttable.Border + layouttable.CellPadding));

                // Set IDs for all controls (necessary to get information after postback on upload)
                uploadlabel.ID   = "control_" + col_traverse + "_" + row_traverse + "_label";
                savedfile.ID     = "control_" + col_traverse + "_" + row_traverse + "_savedfile";
                savedpath.ID     = "control_" + col_traverse + "_" + row_traverse + "_savedpath";
                uploadcontrol.ID = "control_" + col_traverse + "_" + row_traverse;
                uploadtable.ID   = "control_" + col_traverse + "_" + row_traverse + "_table";
                uploadbutton.ID  = "control_" + col_traverse + "_" + row_traverse + "_button";

                // Set control properties
                uploadbutton.Text                    = "Load File";
                uploadbutton.Font.Name               = "Arial"; uploadbutton.Font.Size = 10;
                uploadbutton.Width                   = 100;
                uploadbutton.Click                  += new System.EventHandler(uploadbutton_Click);
                uploadlabel.Font.Name                = "Arial"; uploadlabel.Font.Size = 11;
                uploadlabel.ForeColor                = System.Drawing.Color.Black;
                uploadcontrol.Width                  = Unit.Pixel((int)(tablepanel.Width.Value - 17) - (int)uploadbutton.Width.Value);
                uploadtable.Width                    = Unit.Pixel((int)(tablepanel.Width.Value - 17));
                uploadtable.Height                   = Unit.Pixel((int)(tablepanel.Height.Value - 17));
                uploadtable.Font.Name                = "Arial"; uploadtable.Font.Size = 11;
                uploadtable.HeaderStyle.BackColor    = System.Drawing.Color.Silver;
                uploadtable.RowStyle.BackColor       = System.Drawing.Color.White;
                uploadtable.RowStyle.HorizontalAlign = HorizontalAlign.Center;

                // Add controls to form and format
                tablepanel.Controls.Add(uploadlabel);
                tablepanel.Controls.Add(new LiteralControl("<br><br>"));
                tablepanel.Controls.Add(uploadcontrol);
                tablepanel.Controls.Add(uploadbutton);
                tablepanel.Controls.Add(new LiteralControl("<br><br>"));
                tablepanel.Controls.Add(uploadtable);

                // Add controls to scrollable panel
                cell.Controls.Add(tablepanel);

                // Return uploadcontrol, even though this control itself does not need to be filled (need control type)
                returncontrol = uploadcontrol;

                break;
            }
            }
            return(returncontrol);
        }
Exemplo n.º 35
0
 /// <summary>
 /// Gets the x coordinate of a DataPoint.
 /// </summary>
 /// <param name="point">Data point.</param>
 /// <returns>X coordinate.</returns>
 protected double GetPointX(DataPoint point)
 {
     return(point.x);
 }
Exemplo n.º 36
0
        /// <summary>
        /// Gets the point on the curve that is nearest the specified point.
        /// </summary>
        /// <param name="points">The point list.</param>
        /// <param name="point">The point.</param>
        /// <returns>A tracker hit result if a point was found.</returns>
        /// <remarks>The Text property of the result will not be set, since the formatting depends on the various series.</remarks>
        protected TrackerHitResult GetNearestInterpolatedPointInternal(List <DataPoint> points, ScreenPoint point)
        {
            if (this.XAxis == null || this.YAxis == null || points == null)
            {
                return(null);
            }

            var    spn   = default(ScreenPoint);
            var    dpn   = default(DataPoint);
            double index = -1;

            double minimumDistance = double.MaxValue;

            for (int i = 0; i + 1 < points.Count; i++)
            {
                var p1 = points[i];
                var p2 = points[i + 1];
                if (!this.IsValidPoint(p1) || !this.IsValidPoint(p2))
                {
                    continue;
                }

                var sp1 = this.Transform(p1);
                var sp2 = this.Transform(p2);

                // Find the nearest point on the line segment.
                var spl = ScreenPointHelper.FindPointOnLine(point, sp1, sp2);

                if (ScreenPoint.IsUndefined(spl))
                {
                    // P1 && P2 coincident
                    continue;
                }

                double l2 = (point - spl).LengthSquared;

                if (l2 < minimumDistance)
                {
                    double segmentLength = (sp2 - sp1).Length;
                    double u             = segmentLength > 0 ? (spl - sp1).Length / segmentLength : 0;
                    dpn             = new DataPoint(p1.X + (u * (p2.X - p1.X)), p1.Y + (u * (p2.Y - p1.Y)));
                    spn             = spl;
                    minimumDistance = l2;
                    index           = i + u;
                }
            }

            if (minimumDistance < double.MaxValue)
            {
                var item = this.GetItem((int)Math.Round(index));
                return(new TrackerHitResult
                {
                    Series = this,
                    DataPoint = dpn,
                    Position = spn,
                    Item = item,
                    Index = index
                });
            }

            return(null);
        }
        private void DischargeChart_MouseMove(object sender, MouseEventArgs e)
        {
            if (m_isDragginPoint && m_pointUnderCursor != null)
            {
                var xValueUnderCursor = DischargeChart.ChartAreas[0].AxisX.PixelPositionToValue(e.X);
                var yValueUnderCursor = DischargeChart.ChartAreas[0].AxisY.PixelPositionToValue(e.Y);

                var leftBound  = m_pointUnderCursorIndex == m_battery.Data.Length - 1 ? MaxPrc : DischargeChart.Series[0].Points[m_pointUnderCursorIndex + 1].XValue - 1;
                var rightBound = m_pointUnderCursorIndex == 0 ? MinPrc : DischargeChart.Series[0].Points[m_pointUnderCursorIndex - 1].XValue + 1;

                var upperBound = m_pointUnderCursorIndex == m_battery.Data.Length - 1 ? (double)MaxVolts : DischargeChart.Series[0].Points[m_pointUnderCursorIndex + 1].YValues[0] - 0.01;
                var lowerBound = m_pointUnderCursorIndex == 0 ? (double)MinVolts : DischargeChart.Series[0].Points[m_pointUnderCursorIndex - 1].YValues[0] + 0.01;

                double tempXValue;
                if (xValueUnderCursor >= leftBound)
                {
                    tempXValue = leftBound;
                }
                else if (xValueUnderCursor <= rightBound)
                {
                    tempXValue = rightBound;
                }
                else
                {
                    tempXValue = xValueUnderCursor;
                }

                double tempYValue;
                if (yValueUnderCursor >= upperBound)
                {
                    tempYValue = upperBound;
                }
                else if (yValueUnderCursor <= lowerBound)
                {
                    tempYValue = lowerBound;
                }
                else
                {
                    tempYValue = yValueUnderCursor;
                }

                tempXValue = Math.Round(tempXValue, 0);
                tempYValue = Math.Round(tempYValue, 2);

                m_curveControls[m_pointUnderCursorIndex].VoltsUpDown.Value    = (decimal)tempYValue;
                m_curveControls[m_pointUnderCursorIndex].PercentsUpDown.Value = (decimal)tempXValue;
            }
            else
            {
                var results = DischargeChart.HitTest(e.X, e.Y, false, ChartElementType.DataPoint);

                DataPoint point = null;
                foreach (var result in results)
                {
                    if (result.ChartElementType != ChartElementType.DataPoint)
                    {
                        continue;
                    }

                    var tmpPoint = result.Object as DataPoint;
                    if (tmpPoint == null)
                    {
                        continue;
                    }
                    if (!Equals(tmpPoint.Tag, "draggable"))
                    {
                        continue;
                    }

                    var pointX = DischargeChart.ChartAreas[0].AxisX.ValueToPixelPosition(tmpPoint.XValue);
                    var pointY = DischargeChart.ChartAreas[0].AxisY.ValueToPixelPosition(tmpPoint.YValues[0]);

                    if (Math.Abs(e.X - pointX) <= 12 && Math.Abs(e.Y - pointY) <= 12)
                    {
                        point = tmpPoint;
                        m_pointUnderCursorIndex = result.PointIndex;
                        break;
                    }
                }

                if (m_pointUnderCursor != null)
                {
                    m_pointUnderCursor.MarkerSize = 7;
                }
                m_pointUnderCursor = point;
                if (m_pointUnderCursor != null)
                {
                    m_pointUnderCursor.MarkerSize = 10;
                }
            }
        }
Exemplo n.º 38
0
 internal override FrameworkElement CreateDefaultDataPointVisual(DataPoint point)
 {
     return(new Candlestick());
 }
Exemplo n.º 39
0
 internal override void UpdateLegendItem(FrameworkElement visual, DataPoint dataPoint)
 {
     // Implement this when the legend start to makes sense for this series.
 }
Exemplo n.º 40
0
        public void DBClaimBonusCoupons(string mobile, int promotionID)
        {
            try
            {
                PromotionID = promotionID;
                string              CMSPlayerID = ServerSide.DBGetCMSPlayerID(mobile);
                DataSet             result      = new DataSet();
                List <SqlParameter> spParams    = new List <SqlParameter>();
                spParams.Add(new SqlParameter("@CMSPlayerID", CMSPlayerID));
                spParams.Add(new SqlParameter("@PromotionID", PromotionID));
                result = DataAcess.ExecuteQuerySP("PEC.TODO", spParams);

                if (result.Tables[0].Rows.Count > 0)
                {
                    ClaimButtonRemainsVisible = Convert.ToBoolean(result.Tables[0].Rows[0][""].ToString());
                    ClaimButtonRemainsActive  = Convert.ToBoolean(result.Tables[0].Rows[0][""].ToString());
                    ClaimButtonNewCaption     = result.Tables[0].Rows[0][""].ToString();

                    MemoryStream ms    = new MemoryStream((byte[])result.Tables[0].Rows[0]["Image"]);
                    byte[]       bytes = ms.ToArray();
                    ClaimButtonNewImage = bytes;

                    DataSet             descDS     = new DataSet();
                    List <SqlParameter> descParams = new List <SqlParameter>();
                    descParams.Add(new SqlParameter("@CMSPlayerID", CMSPlayerID));
                    descParams.Add(new SqlParameter("@PromotionID", PromotionID));
                    descDS = DataAcess.ExecuteQuerySP("PEC.TODO", descParams);


                    if (descDS.Tables[0].Rows.Count > 0)
                    {
                        for (int i = 0; i < descDS.Tables[0].Rows.Count; i++)
                        {
                            ResultDescriptionBonus newRDB = new ResultDescriptionBonus();
                            newRDB.ResultCaption        = descDS.Tables[0].Rows[i][""].ToString();
                            newRDB.ResultUpdatedElement = descDS.Tables[0].Rows[i][""].ToString();

                            MemoryStream msResult    = new MemoryStream((byte[])descDS.Tables[0].Rows[i]["Image"]);
                            byte[]       resultBytes = msResult.ToArray();
                            newRDB.ResultImage = resultBytes;

                            DataSet             dP           = new DataSet();
                            List <SqlParameter> pointsParams = new List <SqlParameter>();
                            pointsParams.Add(new SqlParameter("@CMSPlayerID", CMSPlayerID));
                            pointsParams.Add(new SqlParameter("@PromotionID", PromotionID));
                            dP = DataAcess.ExecuteQuerySP("PEC.TODO", pointsParams);
                            if (dP.Tables[0].Rows.Count > 0)
                            {
                                for (int j = 0; j < dP.Tables[0].Rows.Count; j++)
                                {
                                    DataPoint newPoint = new DataPoint();
                                    newPoint.DataPointCaption = dP.Tables[0].Rows[i]["DataPointCaption"].ToString();
                                    newPoint.DataPointData    = dP.Tables[0].Rows[i]["DataPointData"].ToString();
                                    newRDB.DataPoints.Add(newPoint);
                                }
                            }
                            else
                            {
                                newRDB.DataPoints = null;
                            }
                        }
                    }
                    else
                    {
                        ResultDescriptions = null;
                    }
                }
                else
                {
                    RemoveData();
                }
            }
            catch (SqlException ex)
            {
                string errorMessage = ex.Message;
                RemoveData();
            }
        }
Exemplo n.º 41
0
        /// <summary>
        /// Renders the point labels.
        /// </summary>
        /// <param name="rc">The render context.</param>
        /// <param name="clippingRect">The clipping rectangle.</param>
        protected void RenderPointLabels(IRenderContext rc, OxyRect clippingRect)
        {
            var actualPoints = this.ActualPointsList;

            if (actualPoints == null || actualPoints.Count == 0)
            {
                return;
            }

            // TODO: share code with LineSeries
            int index = -1;

            foreach (var point in actualPoints)
            {
                index++;
                var dataPoint = new DataPoint(point.X, point.Y);
                if (!this.IsValidPoint(dataPoint))
                {
                    continue;
                }

                var pt = this.Transform(dataPoint) + new ScreenVector(0, -this.LabelMargin);

                if (!clippingRect.Contains(pt))
                {
                    continue;
                }

                var item = this.GetItem(index);
                var s    = StringHelper.Format(this.ActualCulture, this.LabelFormatString, item, point.X, point.Y);

#if SUPPORTLABELPLACEMENT
                switch (this.LabelPlacement)
                {
                case LabelPlacement.Inside:
                    pt = new ScreenPoint(rect.Right - this.LabelMargin, (rect.Top + rect.Bottom) / 2);
                    ha = HorizontalAlignment.Right;
                    break;

                case LabelPlacement.Middle:
                    pt = new ScreenPoint((rect.Left + rect.Right) / 2, (rect.Top + rect.Bottom) / 2);
                    ha = HorizontalAlignment.Center;
                    break;

                case LabelPlacement.Base:
                    pt = new ScreenPoint(rect.Left + this.LabelMargin, (rect.Top + rect.Bottom) / 2);
                    ha = HorizontalAlignment.Left;
                    break;

                default:         // Outside
                    pt = new ScreenPoint(rect.Right + this.LabelMargin, (rect.Top + rect.Bottom) / 2);
                    ha = HorizontalAlignment.Left;
                    break;
                }
#endif

                rc.DrawClippedText(
                    clippingRect,
                    pt,
                    s,
                    this.ActualTextColor,
                    this.ActualFont,
                    this.ActualFontSize,
                    this.ActualFontWeight,
                    0,
                    HorizontalAlignment.Center,
                    VerticalAlignment.Bottom);
            }
        }
Exemplo n.º 42
0
        /// <summary>
        /// Renders the series on the specified rendering context.
        /// </summary>
        /// <param name="rc">The rendering context.</param>
        public override void Render(IRenderContext rc)
        {
            var actualPoints = this.ActualPointsList;

            if (actualPoints == null || actualPoints.Count == 0)
            {
                return;
            }

            var clippingRect = this.GetClippingRect();

            int n                   = actualPoints.Count;
            var allPoints           = new List <ScreenPoint>(n);
            var allMarkerSizes      = new List <double>(n);
            var selectedPoints      = new List <ScreenPoint>();
            var selectedMarkerSizes = new List <double>(n);
            var groupPoints         = new Dictionary <int, IList <ScreenPoint> >();
            var groupSizes          = new Dictionary <int, IList <double> >();

            // check if any item of the series is selected
            bool isSelected = this.IsSelected();

            // Transform all points to screen coordinates
            for (int i = 0; i < n; i++)
            {
                var dp = new DataPoint(actualPoints[i].X, actualPoints[i].Y);

                // Skip invalid points
                if (!this.IsValidPoint(dp))
                {
                    continue;
                }

                double size  = double.NaN;
                double value = double.NaN;

                var scatterPoint = actualPoints[i];
                if (scatterPoint != null)
                {
                    size  = scatterPoint.Size;
                    value = scatterPoint.Value;
                }

                if (double.IsNaN(size))
                {
                    size = this.MarkerSize;
                }

                // Transform from data to screen coordinates
                var screenPoint = this.XAxis.Transform(dp.X, dp.Y, this.YAxis);

                if (isSelected && this.IsItemSelected(i))
                {
                    selectedPoints.Add(screenPoint);
                    selectedMarkerSizes.Add(size);
                    continue;
                }

                if (this.ColorAxis != null)
                {
                    if (double.IsNaN(value))
                    {
                        // The value is not defined, skip this point.
                        continue;
                    }

                    int group = this.ColorAxis.GetPaletteIndex(value);
                    if (!groupPoints.ContainsKey(group))
                    {
                        groupPoints.Add(group, new List <ScreenPoint>());
                        groupSizes.Add(group, new List <double>());
                    }

                    groupPoints[group].Add(screenPoint);
                    groupSizes[group].Add(size);
                }
                else
                {
                    allPoints.Add(screenPoint);
                    allMarkerSizes.Add(size);
                }
            }

            // Offset of the bins
            var binOffset = this.XAxis.Transform(this.MinX, this.MaxY, this.YAxis);

            rc.SetClip(clippingRect);

            if (this.ColorAxis != null)
            {
                // Draw the grouped (by color defined in ColorAxis) markers
                var markerIsStrokedOnly = this.MarkerType == MarkerType.Plus || this.MarkerType == MarkerType.Star || this.MarkerType == MarkerType.Cross;
                foreach (var group in groupPoints)
                {
                    var color = this.ColorAxis.GetColor(group.Key);
                    rc.DrawMarkers(
                        clippingRect,
                        group.Value,
                        this.MarkerType,
                        this.MarkerOutline,
                        groupSizes[group.Key],
                        this.MarkerFill.GetActualColor(color),
                        markerIsStrokedOnly ? color : this.MarkerStroke,
                        this.MarkerStrokeThickness,
                        this.BinSize,
                        binOffset);
                }
            }

            // Draw unselected markers
            rc.DrawMarkers(
                clippingRect,
                allPoints,
                this.MarkerType,
                this.MarkerOutline,
                allMarkerSizes,
                this.ActualMarkerFillColor,
                this.MarkerStroke,
                this.MarkerStrokeThickness,
                this.BinSize,
                binOffset);

            // Draw the selected markers
            rc.DrawMarkers(
                clippingRect,
                selectedPoints,
                this.MarkerType,
                this.MarkerOutline,
                selectedMarkerSizes,
                this.PlotModel.SelectionColor,
                this.PlotModel.SelectionColor,
                this.MarkerStrokeThickness,
                this.BinSize,
                binOffset);

            if (this.LabelFormatString != null)
            {
                // render point labels (not optimized for performance)
                this.RenderPointLabels(rc, clippingRect);
            }

            rc.ResetClip();
        }
Exemplo n.º 43
0
        public void CreateChartSpline(string name = null, List <DateTime> LsTime = null, List <string> cherry1 = null, List <string> pineapple1 = null)
        {
            List <string[]> temperatureValue = new BLL.Environment().getValue(classroomID, "温度传感器");
            List <string[]> humidityValue    = new BLL.Environment().getValue(classroomID, "湿度传感器");
            List <DateTime> lsTime           = new List <DateTime>();
            List <string>   cherry           = new List <string>();
            List <string>   pineapple        = new List <string>();

            foreach (string[] str in temperatureValue)
            {
                lsTime.Add(Convert.ToDateTime(str[1]));
                cherry.Add(str[0]);
            }
            foreach (string[] str in humidityValue)
            {
                pineapple.Add(str[0]);
            }


            //创建一个图标
            Chart chart = new Chart();

            //设置图标的宽度和高度
            chart.Width  = chartGrid.Width;
            chart.Height = chartGrid.Height;
            chart.Margin = new Thickness(0, 0, 0, 0);
            //是否启用打印和保持图片
            chart.ToolBarEnabled = false;

            //设置图标的属性
            chart.ScrollingEnabled = false; //是否启用或禁用滚动
            chart.View3D           = false; //3D效果显示

            //创建一个标题的对象
            Title title = new Title();

            //设置标题的名称
            title.Text       = "温湿度曲线图";
            title.Padding    = new Thickness(0, 10, 5, 0);
            chart.Background = new SolidColorBrush(Color.FromArgb(100, 100, 100, 100));

            //向图标添加标题
            chart.Titles.Add(title);

            //X轴

            //初始化一个新的Axis
            Axis xaxis = new Axis();

            //设置Axis的属性
            //图表的X轴坐标按什么来分类,如时分秒
            xaxis.IntervalType = IntervalTypes.Hours;
            //图表的X轴坐标间隔如2,3,20等,单位为xAxis.IntervalType设置的时分秒。
            xaxis.Interval = 1;
            //设置X轴的时间显示格式为7-10 11:20
            xaxis.ValueFormatString = "HH:00";
            //给图标添加Axis
            chart.AxesX.Add(xaxis);


            //Y轴

            Axis yAxis = new Axis();

            //设置图标中Y轴的最小值为-20
            yAxis.AxisMinimum = -20;
            //设置图标中Y轴的最大值为100
            yAxis.AxisMaximum = 100;
            //设置间隔为10
            yAxis.Interval = 10;
            //设置图表中Y轴的后缀
            yAxis.Suffix = "℃";
            chart.AxesY.Add(yAxis);


            // 创建一个新的数据线。
            DataSeries dataSeries = new DataSeries();

            // 设置数据线的格式。
            dataSeries.LegendText = "温度";

            dataSeries.RenderAs = RenderAs.Spline;//折线图

            dataSeries.XValueType = ChartValueTypes.DateTime;
            // 设置数据点
            DataPoint dataPoint;

            for (int i = 0; i < cherry.Count; i++)
            {
                // 创建一个数据点的实例。
                dataPoint = new DataPoint();
                // 设置X轴点
                dataPoint.XValue = lsTime[i];
                //设置Y轴点
                dataPoint.YValue     = double.Parse(cherry[i]);
                dataPoint.MarkerSize = 8;
                //dataPoint.Tag = tableName.Split('(')[0];
                //设置数据点颜色
                // dataPoint.Color = new SolidColorBrush(Colors.LightGray);
                //dataPoint.MouseLeftButtonDown += new MouseButtonEventHandler(dataPoint_MouseLeftButtonDown);
                //添加数据点
                dataSeries.DataPoints.Add(dataPoint);
            }

            // 添加数据线到数据序列。
            chart.Series.Add(dataSeries);


            // 创建一个新的数据线。
            DataSeries dataSeriesPineapple = new DataSeries();

            // 设置数据线的格式。
            dataSeriesPineapple.LegendText = "湿度";

            dataSeriesPineapple.RenderAs = RenderAs.Spline;//折线图

            dataSeriesPineapple.XValueType = ChartValueTypes.DateTime;
            // 设置数据点

            DataPoint dataPoint2;

            for (int i = 0; i < pineapple.Count; i++)
            {
                // 创建一个数据点的实例。
                dataPoint2 = new DataPoint();
                // 设置X轴点
                dataPoint2.XValue = lsTime[i];
                //设置Y轴点
                dataPoint2.YValue     = double.Parse(pineapple[i]);
                dataPoint2.MarkerSize = 8;
                //dataPoint2.Tag = tableName.Split('(')[0];
                //设置数据点颜色
                // dataPoint.Color = new SolidColorBrush(Colors.LightGray);
                //dataPoint2.MouseLeftButtonDown += new MouseButtonEventHandler(dataPoint_MouseLeftButtonDown);
                //添加数据点
                dataSeriesPineapple.DataPoints.Add(dataPoint2);
            }
            // 添加数据线到数据序列。
            chart.Series.Add(dataSeriesPineapple);

            //将生产的图表增加到Grid,然后通过Grid添加到上层Grid.
            Grid gr = new Grid();

            gr.Children.Add(chart);

            chartGrid.Children.Add(gr);
        }
Exemplo n.º 44
0
        private void OnRFE_UpdateData(object sender, EventArgs e)
        {
            labelSweeps.Text = "Sweeps: " + m_objRFE.SweepData.Count.ToString();


            RFESweepData objData = m_objRFE.SweepData.GetData(m_objRFE.SweepData.Count - 1);

            if (objData != null)
            {
                UInt16 nPeak = objData.GetPeakStep();
                labelFrequency.Text = objData.GetFrequencyMHZ(nPeak).ToString("f3") + " MHZ";
                labelAmplitude.Text = objData.GetAmplitudeDBM(nPeak).ToString("f2") + " dBm";


                for (ushort i = 0; i < objData.TotalSteps; i++)
                {
                    DataPoint point = new DataPoint();
                    point.freq = objData.GetFrequencyMHZ(i);
                    point.amp  = objData.GetAmplitudeDBM(i);

                    if (currentData.Count < objData.TotalSteps)
                    {
                        currentData.Add(point);
                    }
                    else
                    {
                        currentData[i] = point;
                    }

                    if (peakHoldData.Count < objData.TotalSteps)
                    {
                        peakHoldData.Add(point);
                    }
                    else
                    {
                        if (point.amp > peakHoldData[i].amp)
                        {
                            peakHoldData[i] = point;
                        }
                    }
                }

                for (ushort i = 0; i < objData.TotalSteps; i++)
                {
                    if (ScanPlot.Series[0].Points.Count < currentData.Count)
                    {
                        ScanPlot.Series[0].Points.AddXY(currentData[i].freq, currentData[i].amp);
                    }
                    else
                    {
                        ScanPlot.Series[0].Points[i].SetValueXY(currentData[i].freq, currentData[i].amp);
                    }
                    if (ScanPlot.Series[1].Points.Count < peakHoldData.Count)
                    {
                        ScanPlot.Series[1].Points.AddXY(peakHoldData[i].freq, peakHoldData[i].amp);
                    }
                    else
                    {
                        ScanPlot.Series[1].Points[i].SetValueXY(peakHoldData[i].freq, peakHoldData[i].amp);
                    }
                }
                ScanPlot.Refresh();
            }
        }
Exemplo n.º 45
0
        private static PreparedDataPoints VerifyAndCompute(IEnumerable <Line> graphLines, DataPointFormat format)
        {
            // Find the y-values and the labels for those

            HashSet <decimal> allDistinctValues = GetDistinctXValuesForAllDataSeries(graphLines.Select(line => line.DataSeries));

            List <decimal> sortedValues = new List <decimal>(allDistinctValues);

            sortedValues.Sort();

            decimal minXValue = sortedValues[0];
            decimal maxXValue = sortedValues[sortedValues.Count - 1];

            List <decimal> allPossibleXValues = null;

            List <string> labels = ComputeLabelNames(format, minXValue, maxXValue, ref allPossibleXValues);

            List <DataSet> dataSets = new List <DataSet>(labels.Count);

            foreach (Line line in graphLines)
            {
                DataSeries series = line.DataSeries;

                int seriesIdx = 0;

                List <decimal?> dataSetValues = new List <decimal?>();

                foreach (decimal value in allPossibleXValues)
                {
                    if (seriesIdx < series.DataPoints.Count)
                    {
                        DataPoint dataPoint       = series.DataPoints[seriesIdx];
                        decimal   dataPointXValue = dataPoint.XValue;

                        if (dataPointXValue == value)
                        {
                            dataSetValues.Add(dataPoint.YValue);

                            ++seriesIdx;
                        }
                        else
                        {
                            dataSetValues.Add(null);
                        }
                    }
                    else
                    {
                        dataSetValues.Add(null);
                    }
                }

                if (seriesIdx != series.DataPoints.Count)
                {
                    throw new InvalidOperationException();
                }

                if (dataSetValues.Count != allPossibleXValues.Count)
                {
                    throw new InvalidOperationException();
                }

                dataSets.Add(new DataSet(line.Label, line.Color, dataSetValues));
            }

            return(new PreparedDataPoints(labels, dataSets));
        }
Exemplo n.º 46
0
 public Line(DataPoint p1, DataPoint p2)
 {
     dp1 = p1;
     dp2 = p2;
 }
Exemplo n.º 47
0
 /// <summary>
 /// Determines whether the specified point is valid.
 /// </summary>
 /// <param name="pt">The point.</param>
 /// <returns><c>true</c> if the point is valid; otherwise, <c>false</c> .</returns>
 protected virtual bool IsValidPoint(DataPoint pt)
 {
     return
         (this.XAxis != null && this.XAxis.IsValidValue(pt.X) &&
          this.YAxis != null && this.YAxis.IsValidValue(pt.Y));
 }
Exemplo n.º 48
0
 //EXPERIMENTAL
 public static double YValue(this DataPoint dp, int idx = 0)
 {
     return(dp.YValues[idx]);
 }
Exemplo n.º 49
0
 /// <summary>
 /// Transforms the specified data point to a screen point by the axes of this series.
 /// </summary>
 /// <param name="p">The point.</param>
 /// <returns>A screen point.</returns>
 public ScreenPoint Transform(DataPoint p)
 {
     return(this.XAxis.Transform(p.X, p.Y, this.YAxis));
 }
Exemplo n.º 50
0
        //Trig Intersects
        public static double sub_Diference_intersect(this Series series, double xCursorPos, DataPoint p2, DataPoint p1)
        {
            //LETS DO TRIG!!!!!!

            //side 1

            var AM = p2.XValue - p1.XValue;
            //side 2
            var BM = p2.YValues[0] - p1.YValues[0];

            if (AM < 0)
            {
                AM = AM * (-1);
            }
            if (BM < 0)
            {
                BM = BM * (-1);
            }

            //hypotenuse of s1 and s2
            var CM = Math.Sqrt(AM * AM + BM * BM);

            //set cursor value
            var XC = xCursorPos;

            var    A1 = XC - p1.XValue;
            double B1;
            var    angle = Math.Atan2(AM, BM) * 180 / Math.PI;

            angle = 180 - 90 - angle;
            B1    = A1 * Math.Tan(angle * Math.PI / 180);

            //check for negative value

            return(B1);
        }
Exemplo n.º 51
0
 internal override void UpdateLegendItem(FrameworkElement visual, DataPoint dataPoint)
 {
     this.UpdateLegendItemProperties((Brush)visual.GetValue(Path.FillProperty) ?? (Brush)visual.GetValue(Path.StrokeProperty), (Brush)visual.GetValue(Path.StrokeProperty));
 }
Exemplo n.º 52
0
 private bool IsInterruption(DataPoint dataPoint)
 {
     return(dataPoint.Value <= 0.1D);
 }
Exemplo n.º 53
0
 static void DrawLineBetweenDataPoints(DataPoint data1, DataPoint data2, Color color)
 {
     Gizmos.color = Color.white;
     Gizmos.DrawLine(data1.position, data2.position);
 }
Exemplo n.º 54
0
 public TreeMapNode(DataPoint dataPoint)
 {
     this.DataPoint = dataPoint;
     this.Value     = Math.Abs(dataPoint.YValues[0]);
 }
Exemplo n.º 55
0
        /// <summary>
        /// Create handler for metric telemetry.
        /// </summary>
        private Action <ITelemetry> CreateHandlerForMetricTelemetry(EventSource eventSource, MethodInfo writeGenericMethod, Type eventSourceOptionsType, PropertyInfo eventSourceOptionsKeywordsProperty)
        {
            var eventSourceOptions = Activator.CreateInstance(eventSourceOptionsType);
            var keywords           = Keywords.Metrics;

            eventSourceOptionsKeywordsProperty.SetValue(eventSourceOptions, keywords);
            var dummyMetricData = new MetricData();
            var dummyDataPoint  = new DataPoint();
            var writeMethod     = writeGenericMethod.MakeGenericMethod(new
            {
                PartA_iKey       = this.dummyPartAiKeyValue,
                PartA_Tags       = this.dummyPartATagsValue,
                PartB_MetricData = new
                {
                    // The properties and layout should be the same as MetricData_types.cs
                    dummyMetricData.ver,
                    metrics = new[]
                    {
                        new
                        {
                            // The properties and layout should be the same as DataPoint_types.cs
                            dummyDataPoint.name,
                            dummyDataPoint.kind,
                            dummyDataPoint.value,
                            dummyDataPoint.count,
                            dummyDataPoint.min,
                            dummyDataPoint.max,
                            dummyDataPoint.stdDev
                        }
                    }.AsEnumerable(),
                    dummyMetricData.properties
                }
            }.GetType());

            return((item) =>
            {
                if (this.EventSourceInternal.IsEnabled(EventLevel.Verbose, keywords))
                {
                    var telemetryItem = item as MetricTelemetry;
                    var data = telemetryItem.Data;
                    var extendedData = new
                    {
                        // The properties and layout should be the same as the anonymous type in the above MakeGenericMethod
                        PartA_iKey = telemetryItem.Context.InstrumentationKey,
                        PartA_Tags = telemetryItem.Context.Tags,
                        PartB_MetricData = new
                        {
                            data.ver,
                            metrics = data.metrics.Select(i => new
                            {
                                i.name,
                                i.kind,
                                i.value,
                                i.count,
                                i.min,
                                i.max,
                                i.stdDev
                            }),
                            data.properties
                        }
                    };

                    writeMethod.Invoke(eventSource, new object[] { MetricTelemetry.TelemetryName, eventSourceOptions, extendedData });
                }
            });
        }
Exemplo n.º 56
0
 protected override void ProcessSize(DataPoint point, Size size)
 {
     throw new NotSupportedException();
 }
Exemplo n.º 57
0
 internal virtual void OnDataPointSelectionChanged(DataPoint point)
 {
     this.InvalidatePalette();
 }
Exemplo n.º 58
0
 protected override void ProcessPoint(DataPoint dataPoint, Point point)
 {
     throw new NotSupportedException();
 }
Exemplo n.º 59
0
 public DataPoints(int samples)
 {
     dataPoints = new DataPoint[samples];
 }
Exemplo n.º 60
0
 /// <summary>
 /// Annetaan plotin päivittyä
 /// </summary>
 /// <param name="point1"></param>
 public void Notify(DataPoint point1)
 {
     updateneeded = true;
     this.point   = point1;
 }