public bool CreateSamplePoint(SamplePoint item) { bool result = false; try { using (RCID_DWHEntities context = new RCID_DWHEntities()) { int newid = context.Lims_SamplePoint.OrderByDescending(u => u.SamplePointID).FirstOrDefault().SamplePointID; newid++; Lims_SamplePoint efItem = new Lims_SamplePoint() { SamplePointID = newid, SamplePointActive = true, SamplePointName = item.SamplePointName, SourceID = item.SourceID }; context.Lims_SamplePoint.Add(efItem); if (context.SaveChanges() > 0) { result = true; } } } catch (Exception e) { throw e; } return(result); }
public override void OnReceive(Context context, Intent intent) { Bundle bundle = intent.Extras; SamplePoint samplePoint = (SamplePoint)bundle.Get("SamplePoint"); AutoRecorderActivity.ShowSamplePoint(samplePoint); }
public Centroid(SamplePoint samplePoint) : base(samplePoint.Coordinates) { Id = _nextId++; Rgb = new List <byte>(); GenerateAreaColor(); }
public bool InactivateSamplePoint(SamplePoint item) { bool result = false; try { using (RCID_DWHEntities context = new RCID_DWHEntities()) { Lims_SamplePoint efItem = context.Lims_SamplePoint.Where(b => b.SamplePointID == item.SamplePointID).FirstOrDefault(); if (efItem == null) { return(result); } efItem.SamplePointActive = false; if (context.SaveChanges() > 0) { result = true; } } } catch (Exception) { } return(result); }
public Centroid(int expected, SamplePoint samplePoint) : base(samplePoint.Coordinates) { Expected = expected; Id = _nextId++; Rgb = new List <byte>(); GenerateAreaColor(); }
public async void InsertData() { // 1. Build a DataCollector object. DataCollector MyDataCollector = new DataCollector.Builder().SetPackageName(MyContext) .SetDataType(DataType.DtContinuousStepsDelta) .SetDataStreamName("STEPS_DELTA") .SetDataGenerateType(DataCollector.DataTypeRaw) .Build(); // 2. Create a sampling dataset set based on the data collector. SampleSet sampleSet = SampleSet.Create(MyDataCollector); // 3. Build the start time, end time, and incremental step count for a DT_CONTINUOUS_STEPS_DELTA sampling point. DateTime startDate = DateTime.Parse("2020-12-15 09:00:00"); DateTime endDate = DateTime.Parse("2020-12-15 09:05:00"); int stepsDelta = 1000; // 4. Build a DtContinuousStepsDelta sampling point. SamplePoint samplePoint = sampleSet.CreateSamplePoint() .SetTimeInterval(GetTime(startDate), GetTime(endDate), TimeUnit.Milliseconds); samplePoint.GetFieldValue(Field.FieldStepsDelta).SetIntValue(stepsDelta); // 5. Save a DtContinuousStepsDelta sampling point to the sampling dataset. // You can repeat steps 3 through 5 to add more sampling points to the sampling dataset. sampleSet.AddSample(samplePoint); // 6. Call the data controller to insert the sampling dataset into the Health platform. // 7. Calling the data controller to insert the sampling dataset is an asynchronous Task. var InsertTask = MyDataController.InsertAsync(sampleSet); try { await InsertTask; if (InsertTask.IsCompleted) { if (InsertTask.Exception == null) { Logger("Success insert an SampleSet into HMS core"); ShowSampleSet(sampleSet); Logger(Split); } else { PrintFailureMessage(InsertTask.Exception, "Insert"); } } } catch (Exception ex) { PrintFailureMessage(ex, "Insert"); } }
public void Test_1() { var sample = new SamplePoint { Id = 1, Point = new[] { 2.0, 3.0 } }; var model = DeviationModel.Create(sample.MakeEnumerable(), d => d.Point); Assert.AreEqual(true, model.HasRecords); Assert.AreEqual(sample.Point, model.Mean); Assert.AreEqual(0.0, model.StandardDeviation); Assert.AreEqual(0.0, model.Records[0].Deviation); Assert.AreEqual(0.0, model.Records[0].StandardScore); }
public void OnSamplePoint(SamplePoint samplePoint) { // The step count, time, and type data reported by the pedometer is called back to the app through // samplePoint. Intent intent = new Intent(); intent.PutExtra("SamplePoint", samplePoint); intent.SetAction("HealthKitService"); // Transmits service data to activities through broadcast. PersistService.context.SendBroadcast(intent); }
public Result Calculate(SamplePoint point1, SamplePoint point2, bool useDensity) { // Средние значения по каждой точке отбора var avgSample1 = GetAvgSample(point1.Samples.ToHashSet()); var avgSample2 = GetAvgSample(point2.Samples.ToHashSet()); // Пересчитываем в массовые проценты var massSample1 = GetMassSample(avgSample1); var massSample2 = GetMassSample(avgSample2); // Молярная масса смеси ПНГ, г/моль var molarMass1 = GetMolarMass(avgSample1); var molarMass2 = GetMolarMass(avgSample2); // Расчет плотности при ст.у. var density1 = useDensity ? avgSample1.Density : CalcDensity(molarMass1); var density2 = useDensity ? avgSample2.Density : CalcDensity(molarMass2); // Вычисление отобранной массы газа в точках отбора var mass1 = point1.Volume * 1000 * density1; var mass2 = point2.Volume * 1000 * density2; // Соотношение массы ПНГ var alpha = mass1 / (mass1 + mass2); // Сумма компонентов C3+ var compSumm1 = GetComponentsSumm(massSample1); var compSumm2 = GetComponentsSumm(massSample2); // Средневзвешенная массовая концентрация фракций углеводородов var wghtAvgConc = 10 * (alpha * density1 * compSumm1 + (1 - alpha) * density2 * compSumm2); // Оформление результата var result = new Result { SamplesCollection = new List <Sample> { massSample1, massSample2 }, MassCollection = new List <double> { molarMass1, molarMass2 }, DensityCollection = new List <double> { density1, density2 }, ComponentsSummCollection = new List <double> { compSumm1, compSumm2 }, WeightedAvgConc = wghtAvgConc }; return(result); }
static double Kernel(SamplePoint v1, SamplePoint v2, double sigma) { // RBF kernel. v1 & v2 have class label in last cell double num = 0.0; num += Math.Pow((v1.dX - v2.dX), 2); num += Math.Pow((v1.dY - v2.dY), 2); double denom = 2.0 * sigma * sigma; double z = num / denom; //RBF: (高斯)徑向基函數核(英語:Radial basis function kernel),或稱為RBF核,是一種常用的核函數 return(Math.Exp(-z)); }
protected override SamplePoint _interpolate(Sample sample, double frac, int[] indexes, int index) { Debug.Assert(!sample.looped || sample.loop_end > sample.loop_start); Debug.Assert(indexes.Length == 2); var sample_points = new SamplePoint[indexes.Length]; for (int i = 0; i < indexes.Length; i++) { sample_points[i] = sample.sample_data[max(indexes[i], 0)]; } return((frac < 0.5) ? sample_points[0] : sample_points[1]); }
public void TestMethod1() { Centroid centr1 = new Centroid(1.0); Centroid centr2 = new Centroid(1.0, 2.0); Centroid centr3 = new Centroid(1.0, 2.0, 3.0); Centroid centr4 = new Centroid(1.0); var sp = new SamplePoint(); Assert.AreEqual(centr1.Coordinates.Count, 1); Assert.AreEqual(centr2.Coordinates.Count, 2); Assert.AreEqual(centr3.Coordinates.Count, 3); Assert.AreEqual(centr4.Coordinates.Count, 4); }
private void CalculateHiddenLayerOutputs() { _hiddenLayerOutputs.Clear(); for (var j = 0; j < SamplePoints.Count; j++) { SamplePoint samplePoint = SamplePoints[j]; _hiddenLayerOutputs.Add(new List <double>()); for (int i = 0; i < HiddenNeuronsNumber; i++) { _hiddenLayerOutputs[j] .Add(BasisFunction(Euclides.CalculateDistance(samplePoint, Centroids[i]), _betas[i])); } } }
public double CalculateNetworkOutput(SamplePoint samplePoint) { List <double> hiddenLayerOutput = new List <double>(); for (int i = 0; i < HiddenNeuronsNumber; i++) { hiddenLayerOutput.Add(BasisFunction(Euclides.CalculateDistance(samplePoint, Centroids[i]), _betas[i])); } _neuron.Inputs = hiddenLayerOutput; _neuron.CalculateOutput(); return(_neuron.Output); }
IEnumerator WaitForSamplePoints(WWW www) { yield return(www); if (www.error == null) { Debug.Log("WWW SamplePoints data: " + www.text); m_Samples = new ArrayList(); JSONObject j = new JSONObject(www.text); m_ReadingWhich = -1; accessSamplePoints(j); int nrsamples = m_Samples.Count; Debug.Log("nrsamples: " + nrsamples); PlayerPrefs.SetInt("Session_" + m_ValidationId + "_NrSamples", nrsamples); for (int i = 0; i < nrsamples; i++) { SamplePoint point = (SamplePoint)m_Samples[i]; PlayerPrefs.SetInt("Session_" + m_ValidationId + "_Sample_" + i + "_Id", point.m_SampleId); PlayerPrefs.SetInt("Session_" + m_ValidationId + "_Sample_" + i + "_LegendId", point.m_SampleLegendId); PlayerPrefs.SetInt("Session_" + m_ValidationId + "_Sample_" + i + "_Validated", point.m_SampleValidated); PlayerPrefs.SetString("Session_" + m_ValidationId + "_Sample_" + i + "_Lat", point.m_SampleLat); PlayerPrefs.SetString("Session_" + m_ValidationId + "_Sample_" + i + "_Lng", point.m_SampleLng); } PlayerPrefs.Save(); m_LoadingText.SetActive(false); m_LoadingBack.SetActive(false); } else { Debug.Log("Could not load sample points"); Debug.Log("WWW Error: " + www.error); Debug.Log("WWW Error 2: " + www.text); if (www.error == "401 Unauthorized") { Debug.Log("Unauthorized access"); Application.LoadLevel("LoginLacoWiki"); } } }
/// <summary> /// /// </summary> /// <param name="segments"></param> public void Calculate(TimeSegemnts segments) { GetCalculateDetails.Clear(); //_txtRes = new System.Resources.ResourceManager("Konvolucio.Project.Localization.TextResource", typeof(BaudrateCalculator).Assembly); if (_txtRes != null) { /*text_BaudrateSystemClock*/ /*"System Clock[PCLK]: {0:N4} MHz"*/ /*Rendszer órajel[PCLK]: {0:N4} MHz*/ GetCalculateDetails.Add(string.Format(_txtRes.GetString("text_BaudrateSystemClock"), (segments.SystemClock / 1000000))); /*text_BaudRatePrescaler*/ /*Baud Rate Prescaler[BRP]: {0}*/ /*Átviteli sebesség osztó[BRP]: {0}*/ GetCalculateDetails.Add(string.Format(_txtRes.GetString("text_BaudRatePrescaler"), segments.Brp)); } else { GetCalculateDetails.Add("System Clock[PCLK]: " + (segments.SystemClock / 1000000).ToString("N4") + " MHz"); GetCalculateDetails.Add("Baud Rate Prescaler[BRP]: " + segments.Brp.ToString() + ""); GetCalculateDetails.Add("Time Segments Before Sample[TSEG1]: " + segments.Tseg1.ToString() + " Tq"); GetCalculateDetails.Add("Time Segments After Sample[TSEG2]: " + segments.Tseg2.ToString() + " Tq"); GetCalculateDetails.Add("Max Sync Jump Width[SJW]: " + segments.Sjw.ToString() + " Tq"); } TotalNumberOfTimeQuanta = segments.Tseg1 + segments.Tseg2; GetCalculateDetails.Add("Total Number Of Time Quanta[tbit]: " + TotalNumberOfTimeQuanta.ToString()); TimeQuanta = (1 / segments.SystemClock) * segments.Brp * 1000000; /*sec -> usec*/ GetCalculateDetails.Add("Time Quanta[Tq]: " + TimeQuanta.ToString("N5") + " us"); TimeBeforeSample = segments.Tseg1 * TimeQuanta; GetCalculateDetails.Add("Time Before Sample[tseg1]: " + TimeBeforeSample.ToString("N5") + " us"); TimeAfterSample = segments.Tseg2 * TimeQuanta; GetCalculateDetails.Add("Time After Sample[tseg2]: " + TimeAfterSample.ToString("N5") + " us"); NominalBitTime = 1 * TimeQuanta + TimeBeforeSample + TimeAfterSample; /* Mindig bele kell számolni a SYNC-et! ami 1 Tq */ GetCalculateDetails.Add("Nominal Bit Time: " + NominalBitTime.ToString("N5") + " us"); Baudrate = 1 / (NominalBitTime / 1000000); /* osztva ezerrel a usec -> sec miatt*/ GetCalculateDetails.Add("Baud Rate: " + Baudrate.ToString("N") + " Buad"); SamplePoint = ((1.0 + segments.Tseg1) / (double)(segments.Tseg1 + segments.Tseg2 + 1.0)) * 100.0; GetCalculateDetails.Add("Sample Point: " + SamplePoint.ToString("N") + " %"); }
private int GetTheNearestCentroidsId(SamplePoint samplePoint) { int nearestCentroidId = Centroids.First().Id; double nearestDistance = Euclides.CalculateDistance(samplePoint, Centroids.First()); foreach (var centroid in Centroids) { double distance = Euclides.CalculateDistance(samplePoint, centroid); if (distance < nearestDistance) { nearestCentroidId = centroid.Id; nearestDistance = distance; } } return(nearestCentroidId); }
// Returns the callback data in SamplePoint mode. // @param samplePoint Reported data public static void ShowSamplePoint(SamplePoint samplePoint) { if (samplePoint != null) { Logger("Sample point type: " + samplePoint.DataType.Name); foreach (Field field in samplePoint.DataType.Fields) { Logger("Field: " + field.Name + " Value: " + samplePoint.GetFieldValue(field)); Logger(StampToData(DateTime.Now.ToString())); } } else { Logger("samplePoint is null!! "); Logger(Split); } }
private void Canvas_MouseDown(object sender, MouseEventArgs e) { SamplePoint sample; if (e.Button == MouseButtons.Left) { sample = new SamplePoint(e.X, e.Y, 1); } else { sample = new SamplePoint(e.X, e.Y, 0); } pts.Add(sample); DrawPoint(e.X, e.Y, e.Button == MouseButtons.Left); }
protected override SamplePoint _interpolate(Sample sample, double frac, int[] indexes, int index) { Debug.Assert(!sample.looped || sample.loop_end > sample.loop_start); Debug.Assert(indexes.Length == 2); var sample_points = new SamplePoint[indexes.Length]; for (int i = 0; i < indexes.Length; i++) { sample_points[i] = sample.sample_data[max(indexes[i], 0)]; } return(new SamplePoint { left = (int)Math.Floor((1 - frac) * sample_points[0].left + frac * sample_points[1].left + 0.5), right = (int)Math.Floor((1 - frac) * sample_points[0].right + frac * sample_points[1].right + 0.5) }); }
private void SampleMesh(int[] sampleCount_distribution, Transform[] linkedTransforms /*, int stratifiedDivisions*/) { int counter = 0; for (int i = 0; i < sampleCount_distribution.Length; i++) { MeshCollider collider = linkedTransforms[i].GetComponent <MeshCollider>(); if (collider) { collider.convex = false; } int stratifiedDivisions = Mathf.Max((int)Mathf.Pow(sampleCount_distribution[i], 1.0f / 3) - 1, 0); BoundingBox bounds = new BoundingBox(meshRenderers[i].bounds.center, meshRenderers[i].bounds.size); BoundingBox[] bounds_stratified = GenerateStratifiedBounds(bounds, stratifiedDivisions); bounds_stratified = bounds_stratified.OrderBy(x => Random.value).ToArray(); this.bounds_stratified.Add(bounds_stratified);//for debugging int loopCap = 1000 * sampleCount_distribution[i]; int j = 0; while (j < sampleCount_distribution[i] && --loopCap > 0) { Vector3 sample_pos = bounds_stratified[j % bounds_stratified.Length].RandomPoint(); if (ValidateSample(sample_pos)) { SamplePoint sample = new SamplePoint(sample_pos - linkedTransforms[i].position, linkedTransforms[i].rotation, linkedTransforms[i]); MeshApproximation.Samples[counter++] = sample; ++j; } } if (j < sampleCount_distribution[i]) { throw new System.Exception("Failed to place all sample points"); } if (collider) { collider.convex = true; } } }
bool Accuracy(SamplePoint inputData, List <SamplePoint> trainData, double sigma, bool isTesting, double[] weights) { int numTrain = trainData.Count; // compare currrent against all trainData double i_sum = 0.0; for (int j = 0; j < weights.Length - 1; ++j) { double k = Kernel(inputData, trainData[j], sigma); //依序跟每個train sample計算RBF值 較小的 RBF 值指出兩個點比較不類似(距離遠) i_sum += weights[j] * k; // (cannot pre-compute) } i_sum += weights[weights.Length - 1] * 1; // add the bias double y = 1.0 / (1.0 + Math.Exp(-i_sum)); double color = inputData.Color; if (isTesting) { if (y <= 0.5 && color == 0.0 || y > 0.5 && color == 1.0) { return(true);//test result ok } else { return(false);//test result fail } } else // not verbose { if (y <= 0.5) { return(true);//color = 0 } else { return(false);//color = 1 } } }
public void Update() { for (int i = 0; i < ms.MeshApproximation.SampleCount; i++) { SamplePoint sp = ms.MeshApproximation.Samples[i]; if (ms.MeshApproximation.IsUnderWater[i] == 1) { if (sp.LastPosition != null) { Vector3 deltaVelocity = sp.GlobalPosition - (Vector3)sp.LastPosition; rb.AddForceAtPosition(-deltaVelocity * viscosity / ms.MeshApproximation.SampleCount, sp.GlobalPosition, ForceMode.VelocityChange); } sp.LastPosition = sp.GlobalPosition; } else { sp.LastPosition = null; } } }
public void AddSamplePoints(string SqlWhereClause) { int idFld = m_SamplePointsFC.FindField("SamplePoints_ID"); int fieldFld = m_SamplePointsFC.FindField("FieldID"); int staFld = m_SamplePointsFC.FindField("StationID"); int lblFld = m_SamplePointsFC.FindField("Label"); int plotFld = m_SamplePointsFC.FindField("PlotAtScale"); int locConfFld = m_SamplePointsFC.FindField("LocationConfidenceMeters"); int notesFld = m_SamplePointsFC.FindField("Notes"); int symbFld = m_SamplePointsFC.FindField("Symbol"); int dsFld = m_SamplePointsFC.FindField("DataSourceID"); IQueryFilter QF = new QueryFilterClass(); QF.WhereClause = SqlWhereClause; IFeatureCursor theCursor = m_SamplePointsFC.Search(QF, false); IFeature theFeature = theCursor.NextFeature(); while (theFeature != null) { SamplePoint anSamplePoint = new SamplePoint(); anSamplePoint.SamplePoints_ID = theFeature.get_Value(idFld).ToString(); anSamplePoint.FieldID = theFeature.get_Value(fieldFld).ToString(); anSamplePoint.StationID = theFeature.get_Value(staFld).ToString(); anSamplePoint.Label = theFeature.get_Value(lblFld).ToString(); bool result = int.TryParse(theFeature.get_Value(plotFld).ToString(), out anSamplePoint.PlotAtScale); result = double.TryParse(theFeature.get_Value(locConfFld).ToString(), out anSamplePoint.LocationConfidenceMeters); anSamplePoint.Notes = theFeature.get_Value(notesFld).ToString(); anSamplePoint.Symbol = theFeature.get_Value(symbFld).ToString(); anSamplePoint.DataSourceID = theFeature.get_Value(dsFld).ToString(); anSamplePoint.Shape = (IPoint)theFeature.Shape; anSamplePoint.RequiresUpdate = true; m_SamplePointsDictionary.Add(anSamplePoint.SamplePoints_ID, anSamplePoint); theFeature = theCursor.NextFeature(); } }
protected override SamplePoint _interpolate(Sample sample, double frac, int[] indexes, int index) { Debug.Assert(!sample.looped || sample.loop_end > sample.loop_start); Debug.Assert(indexes.Length == 4); var sample_points = new SamplePoint[indexes.Length]; for (int i = 0; i < indexes.Length; i++) { sample_points[i] = sample.sample_data[max(indexes[i], 0)]; } var u = frac; var p = sample_points; return(new SamplePoint { left = (int)Math.Floor(((u * u * (2 - u) - u) * p[0].left + (u * u * (3 * u - 5) + 2) * p[1].left + (u * u * (4 - 3 * u) + u) * p[2].left + u * u * (u - 1) * p[3].left) / 2 + 0.5), right = (int)Math.Floor(((u * u * (2 - u) - u) * p[0].right + (u * u * (3 * u - 5) + 2) * p[1].right + (u * u * (4 - 3 * u) + u) * p[2].right + u * u * (u - 1) * p[3].right) / 2 + 0.5) }); }
public void AddNeighbor(SamplePoint newNeighbor) { neighbors.Add(newNeighbor); newNeighbor.neighbors.Add(this); }
public void UpdateSamplePoint(SamplePoint theSamplePoint) { try { m_SamplePointsDictionary.Remove(theSamplePoint.SamplePoints_ID); } catch { } theSamplePoint.RequiresUpdate = true; m_SamplePointsDictionary.Add(theSamplePoint.SamplePoints_ID, theSamplePoint); }
/// <summary> /// Check if a specific sample point is occluded /// </summary> /// <param name="c">C.</param> public bool Occluded(SamplePoint c) { return samplePointsVisibility [(int)c]; }
void recorder_MaximumCalculated(object sender, MaxSampleEventArgs e) { SamplePoint newSample = new SamplePoint(); newSample.sampleNum = sampleData.Count; newSample.sampleVal = Math.Max(e.MaxSample, Math.Abs(e.MinSample)); sampleData.Add(newSample); RaisePropertyChanged("SampleData"); RaisePropertyChanged("XRange"); }
public string NewSamplePoint(string StationID, string Label, int PlotAtScale, double LocationConfidenceMeters, string Notes, string DataSourceID, string Symbol, IPoint Shape) { SamplePoint newSamplePoint = new SamplePoint(); sysInfo SysInfoTable = new sysInfo(m_theWorkspace); newSamplePoint.SamplePoints_ID = SysInfoTable.ProjAbbr + ".SamplePoints." + SysInfoTable.GetNextIdValue("SamplePoints"); newSamplePoint.FieldID = StationID; newSamplePoint.Label = Label; newSamplePoint.PlotAtScale = PlotAtScale; newSamplePoint.LocationConfidenceMeters = LocationConfidenceMeters; newSamplePoint.Notes = Notes; newSamplePoint.Symbol = Symbol; newSamplePoint.DataSourceID = DataSourceID; newSamplePoint.Shape = Shape; newSamplePoint.RequiresUpdate = false; m_SamplePointsDictionary.Add(newSamplePoint.SamplePoints_ID, newSamplePoint); return newSamplePoint.SamplePoints_ID; }
// Add an activity record to the Health platform public async void AddActivityRecord() { Logger(Split + "Add ActivityRecord"); // Build the time range of the request object: start time and end time Calendar Cal = Calendar.Instance; Date Now = new Date(); Cal.Time = Now; long EndTime = Cal.TimeInMillis; Cal.Add(CalendarField.HourOfDay, -1); long StartTime = Cal.TimeInMillis; // Build the data collector object. DataCollector dataCollector = new DataCollector.Builder().SetDataType(DataType.DtContinuousStepsDelta) .SetDataGenerateType(DataCollector.DataTypeRaw) .SetPackageName(this) .SetDataCollectorName("DataCollector1") .Build(); // Build the activity statistics and activity record request objects. ActivitySummary activitySummary = GetActivitySummary(); // Create a data collector for total step count statistics. // ActivitySummary is used to bear the statistical data. DataCollector dataCollector2 = new DataCollector.Builder().SetDataType(DataType.DtContinuousStepsTotal) .SetDataGenerateType(DataCollector.DataTypeRaw) .SetPackageName(this) .SetDataCollectorName("DataCollector2") .Build(); SamplePoint samplePoint = new SamplePoint.Builder(dataCollector2).Build(); samplePoint.GetFieldValue(Field.FieldSteps).SetIntValue(1024); activitySummary.DataSummary = new[] { samplePoint }; // Build the activity record request object ActivityRecord activityRecord = new ActivityRecord.Builder().SetName("AddActivityRecordTest") .SetDesc("Add ActivityRecord") .SetId("MyAddActivityRecordId") .SetActivityTypeId(HiHealthActivities.Running) .SetStartTime(StartTime, TimeUnit.Milliseconds) .SetEndTime(EndTime, TimeUnit.Milliseconds) .SetActivitySummary(activitySummary) .SetTimeZone("+0800") .Build(); // Build the sampling sampleSet based on the dataCollector SampleSet sampleSet = SampleSet.Create(dataCollector); // Build the (DtContinuousStepsDelta) sampling data object and add it to the sampling dataSet SamplePoint samplePointDetail = sampleSet.CreateSamplePoint().SetTimeInterval(StartTime, EndTime, TimeUnit.Milliseconds); samplePointDetail.GetFieldValue(Field.FieldStepsDelta).SetIntValue(1024); sampleSet.AddSample(samplePointDetail); // Build the activity record addition request object ActivityRecordInsertOptions insertRequest = new ActivityRecordInsertOptions.Builder().SetActivityRecord(activityRecord).AddSampleSet(sampleSet).Build(); CheckConnect(); // Call the related method in the ActivityRecordsController to add activity records var AddTask = MyActivityRecordsController.AddActivityRecordAsync(insertRequest); try { await AddTask; if (AddTask.IsCompleted) { if (AddTask.Exception == null) { Logger("Add ActivityRecord was successful!"); } else { PrintFailureMessage(AddTask.Exception, "AddActivityRecord"); } } } catch (System.Exception ex) { PrintFailureMessage(ex, "AddActivityRecord"); } }
public async void UpdateData() { // 1. Build a DataCollector object. DataCollector MyDataCollector = new DataCollector.Builder().SetPackageName(MyContext) .SetDataType(DataType.DtContinuousStepsDelta) .SetDataStreamName("STEPS_DELTA") .SetDataGenerateType(DataCollector.DataTypeRaw) .Build(); // 2. Build the sampling dataset for the update: create a sampling dataset // for the update based on the data collector. SampleSet sampleSet = SampleSet.Create(MyDataCollector); // 3. Build the start time, end time, and incremental step count for // a DtContinuousStepsDelta sampling point for the update. DateTime startDate = DateTime.Parse("2020-12-15 09:00:00"); DateTime endDate = DateTime.Parse("2020-12-15 09:05:00"); int stepsDelta = 2000; // 4. Build a DtContinuousStepsDelta sampling point for the update. SamplePoint samplePoint = sampleSet.CreateSamplePoint() .SetTimeInterval(GetTime(startDate), GetTime(endDate), TimeUnit.Milliseconds); samplePoint.GetFieldValue(Field.FieldStepsDelta).SetIntValue(stepsDelta); // 5. Add an updated DtContinuousStepsDelta sampling point to the sampling dataset for the update. // You can repeat steps 3 through 5 to add more updated sampling points to the sampling dataset for the update. sampleSet.AddSample(samplePoint); // 6. Build a parameter object for the update. // Note: (1) The start time of the modified object updateOptions cannot be greater than the minimum // value of the start time of all sample data points in the modified data sample set // (2) The end time of the modified object updateOptions cannot be less than the maximum value of the // end time of all sample data points in the modified data sample set UpdateOptions updateOptions = new UpdateOptions.Builder().SetTimeInterval(GetTime(startDate), GetTime(endDate), TimeUnit.Milliseconds) .SetSampleSet(sampleSet) .Build(); // 7. Use the specified parameter object for the update to call the // data controller to modify the sampling dataset. // 8.Calling the data controller to modify the sampling dataset is an asynchronous Task. var UpdateTask = MyDataController.UpdateAsync(updateOptions); try { await UpdateTask; if (UpdateTask.IsCompleted) { if (UpdateTask.Exception == null) { Logger("Success update sample data from HMS core"); Logger(Split); } else { PrintFailureMessage(UpdateTask.Exception, "Update"); } } } catch (Exception ex) { PrintFailureMessage(ex, "Update"); } }
private Vector3 GetPosition(SamplePoint sample) { return(transform.position + new Vector3((sample.position.x - .5f) * placementArea.x, 0f, (sample.position.y - .5f) * placementArea.y)); }
public void CreateGrid() { width = Mathf.CeilToInt(placementArea.x / averageDistance); height = Mathf.CeilToInt(placementArea.y / averageDistance); samplePoints = new List <SamplePoint>(width * height); Vector2 offsetX = 1f / (width - 1f) * Vector2.right; Vector2 offsetY = 1f / (height - 1f) * Vector2.up; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { Vector2 position = offsetX * x + offsetY * y; float weight = weightRange.RandomValue(); SamplePoint newPoint = new SamplePoint(position, weight); if (x > 0) { newPoint.AddNeighbor(GetSample(x - 1, y)); if (x == width - 1) { newPoint.AddNeighbor(new SamplePoint(position + offsetX, weightRange.RandomValue(), true)); } } else { newPoint.AddNeighbor(new SamplePoint(position - offsetX, weightRange.RandomValue(), true)); } if (y > 0) { newPoint.AddNeighbor(GetSample(x, y - 1)); if (x > 0) { if (Random.value > .5f) { newPoint.AddNeighbor(GetSample(x - 1, y - 1)); } else { GetSample(x - 1, y).AddNeighbor(GetSample(x, y - 1)); } } if (y == height - 1) { newPoint.AddNeighbor(new SamplePoint(position + offsetY, weightRange.RandomValue(), true)); } } else { newPoint.AddNeighbor(new SamplePoint(position - offsetY, weightRange.RandomValue(), true)); } samplePoints.Add(newPoint); } } //account for the corners samplePoints[0].AddNeighbor(new SamplePoint(samplePoints[0].position - offsetX - offsetY, weightRange.RandomValue(), true)); samplePoints[width - 1].AddNeighbor(new SamplePoint(samplePoints[width - 1].position + offsetX - offsetY, weightRange.RandomValue(), true)); samplePoints[samplePoints.Count - 1].AddNeighbor(new SamplePoint(samplePoints[samplePoints.Count - 1].position + offsetX + offsetY, weightRange.RandomValue(), true)); samplePoints[samplePoints.Count - width].AddNeighbor(new SamplePoint(samplePoints[samplePoints.Count - width].position - offsetX + offsetY, weightRange.RandomValue(), true)); }
/// <summary> /// Ctor: initialize from sample data in tab-separated format. /// </summary> /// <param name="dataFileName">File to parse for sample points.</param> public Sampler(ILoggerFactory lf, string dataFileName) { logger = lf.CreateLogger(GetType().FullName); logger.LogInformation("Quiz sampler initializing..."); sampleName = Path.GetFileNameWithoutExtension(dataFileName); // Read sample List <SamplePoint> pointList = new List <SamplePoint>(); using (FileStream fs = new FileStream(dataFileName, FileMode.Open, FileAccess.Read)) using (StreamReader sr = new StreamReader(fs)) { string line; int i = -1; int lastRank = -1; RangeSample range = range1; string wordA = null; string wordB = null; string wordC = null; while ((line = sr.ReadLine()) != null) { if (line == "") { continue; } string[] parts = line.Split('\t'); int rank = int.Parse(parts[0]); if (lastRank != rank) { ++i; lastRank = rank; } if (i == 40) { if (range == range1) { range = range2; } else { range = range3; } i = 0; } if (parts[2] == "a") { wordA = parts[1]; } if (parts[2] == "b") { wordB = parts[1]; } if (parts[2] == "c") { wordC = parts[1]; } if (wordA != null && wordB != null && wordC != null) { SamplePoint point = new SamplePoint(rank, wordA, wordB, wordC); range.Points[i] = point; range.WordToIndex[wordA] = i; range.WordToIndex[wordB] = i; range.WordToIndex[wordC] = i; wordA = wordB = wordC = null; } } } logger.LogInformation("Quiz sampler initialized."); }
/// <summary> /// Evaluates a single returned quiz. /// </summary> /// <param name="qres">Words+yes/no pairs.</param> /// <param name="score">Calculated score (not rounded).</param> /// <param name="resCoded">Encoded result to store for analysis.</param> public void Eval(IList <string[]> qres, out int score, out char[] resCoded) { resCoded = new char[120 + sampleName.Length + 1]; for (int i = 0; i != sampleName.Length; ++i) { resCoded[i] = sampleName[i]; } int resOfs = sampleName.Length + 1; resCoded[resOfs - 1] = '-'; int count1 = 0; int count2 = 0; int count3 = 0; foreach (var x in qres) { string word = x[0]; // Which range, which point? RangeSample range; int rangeOfs; if (range1.WordToIndex.ContainsKey(word)) { range = range1; rangeOfs = 0; } else if (range2.WordToIndex.ContainsKey(word)) { range = range2; rangeOfs = 40; } else if (range3.WordToIndex.ContainsKey(word)) { range = range3; rangeOfs = 80; } else { throw new Exception("Word not in sample: " + word); } // Which word int ixInRange = range.WordToIndex[word]; SamplePoint sp = range.Points[ixInRange]; char mark; if (word == sp.WordA) { mark = 'a'; } else if (word == sp.WordB) { mark = 'b'; } else { mark = 'c'; } // Positive or negative? if (x[1] == "yes") { mark = char.ToUpper(mark); if (range == range1) { ++count1; } else if (range == range2) { ++count2; } else { ++count3; } } else if (x[1] != "no") { throw new Exception("Invalid quiz value for word: " + x[1]); } // Encode resCoded[resOfs + rangeOfs + ixInRange] = mark; } // Estimate three ranges separately int est1 = range1.Size * count1 / range1.Points.Length; int est2 = range2.Size * count2 / range2.Points.Length; int est3 = range3.Size * count3 / range3.Points.Length; // Result is sum of three estimates score = est1 + est2 + est3; }
public SamplePointEventArgs(SamplePoint samplePoint) { Point = samplePoint; }