public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { Dictionary<string, object> wholeDict = serializer.Deserialize<Dictionary<string, object>>(reader); Dictionary<string, object> facetDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(wholeDict.First().Value.ToString()); Dictionary<string, object> histoDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(facetDict.GetString(AggregationTypeEnum.DateHistogram.ToString())); DateHistogramAggregate agg = null; string aggName = wholeDict.First().Key; string field = histoDict.GetStringOrDefault(_FIELD); Script script = histoDict.DeserializeObject<Script>(); DateIntervalEnum intervalType = DateIntervalEnum.Day; string intervalValue = histoDict.GetString(_INTERVAL); intervalType = DateIntervalEnum.Find(intervalValue); if (intervalType != null) { if (!string.IsNullOrWhiteSpace(field) && script != null) agg = new DateHistogramAggregate(aggName, field, script, intervalType); else if (!string.IsNullOrWhiteSpace(field)) agg = new DateHistogramAggregate(aggName, field, intervalType); else if(script != null) agg = new DateHistogramAggregate(aggName, script, intervalType); } else { TimeValue timeValue = new TimeValue(intervalValue); if (!string.IsNullOrWhiteSpace(field) && script != null) agg = new DateHistogramAggregate(aggName, field, script, timeValue); else if (!string.IsNullOrWhiteSpace(field)) agg = new DateHistogramAggregate(aggName, field, timeValue); else if(script != null) agg = new DateHistogramAggregate(aggName, script, timeValue); } if (agg == null) throw new RequiredPropertyMissingException(_FIELD + "/" + Script.SCRIPT); if (histoDict.ContainsKey(_POST_OFFSET)) agg.PostOffset = JsonConvert.DeserializeObject<TimeValue>(histoDict.GetString(_POST_OFFSET)); if (histoDict.ContainsKey(_PRE_OFFSET)) agg.PreOffset = JsonConvert.DeserializeObject<TimeValue>(histoDict.GetString(_PRE_OFFSET)); agg.PostZone = histoDict.GetTimeSpan(_POST_ZONE, _TIMESPAN_DEFAULT); agg.PreZone = histoDict.GetTimeSpan(_PRE_ZONE, _TIMESPAN_DEFAULT); agg.PreZoneAdjustLargeInterval = histoDict.GetBool(_PRE_ZONE_ADJUST_LARGE_INTERVAL, _PRE_ZONE_ADJUST_LARGE_INTERVAL_DEFAULT); agg.TimeZone = histoDict.GetTimeSpan(_TIME_ZONE, _TIMESPAN_DEFAULT); agg.MinimumDocumentCount = histoDict.GetInt32(_MINIMUM_DOCUMENT_COUNT, _MINIMUM_DOCUMENT_COUNT_DEFAULT); if (histoDict.ContainsKey(_ORDER)) { Dictionary<string, object> orderDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(histoDict.GetString(_ORDER)); if (orderDict.Count != 1) throw new Exception("The order parameter must be a dictionary of one key value pair."); agg.SortValue = orderDict.First().Key; agg.SortOrder = SortOrderEnum.Find(orderDict.First().Value.ToString()); } return agg; }
// Position callback public static void myPositionCallback(Object sender, TimeValue timestamp, Int32 sensor, Vec3 report) { Console.WriteLine("Got POSITION report: Position = ({0}, {1}, {2}), Sensor = ({3})", report.x, report.y, report.z, sensor); }
public void ConstructorTest() { var time = new TimeValue(18, 23, 56, 344); time.Hour.Should().Be(18); time.Minute.Should().Be(23); time.Second.Should().Be(56); time.Millisecond.Should().Be(344); }
/// <summary> /// Creates a default time to live for the documents that this mapping applies to. Sets IsEnabled to true. /// </summary> /// <param name="defaultTimeToLive">Sets the DefaultTimeToLive.</param> public DocumentTimeToLive(TimeValue defaultTimeToLive) : base(_INDEX_DEFAULT, _STORE_DEFAULT) { if (defaultTimeToLive == null) throw new ArgumentNullException("defaultTimeToLive", "DocumentTimeToLive requires a TimeValue."); DefaultTimeToLive = defaultTimeToLive; IsEnabled = true; }
// Orientation callback public static void myOrientationCallback(Object sender, TimeValue timestamp, Int32 sensor, Quaternion report) { Console.WriteLine("Got ORIENTATION report: Orientation = ({0}, {1}, {2}, {3}), Sensor = ({4})", report.w, report.x, report.y, report.z, sensor); }
static void imaging_StateChanged(object sender, TimeValue timestamp, int sensor, ImagingState report) { var m = report.metadata; Console.WriteLine("Got Imaging report {0}:", reportNum++); Console.WriteLine("\twidth: {0}", m.width); Console.WriteLine("\theight: {0}", m.height); Console.WriteLine("\tdepth: {0}", m.depth); Console.WriteLine("\tnumber of color channels: {0}", m.channels); Console.WriteLine("\ttype: {0}", m.type.ToString()); }
/// <summary> /// Create a fuzzy query against a date field, specifying a fuzziness value. /// </summary> /// <param name="field">The name of the field to search against.</param> /// <param name="value">The date value to search for.</param> /// <param name="fuzziness">The range of time that will be accepted as a match.</param> public FuzzyDateQuery(string field, DateTime value, TimeSpan? fuzziness) :base(field) { if (value == default(DateTime)) throw new ArgumentNullException("value", "FuzzyDateQuery requires non-default date time."); _Value = value; if(fuzziness.HasValue) _Fuzziness = new TimeValue(fuzziness.Value); }
public void TimeConstructorTest() { var test = DateTime.Now; var time = new TimeValue(test); time.Duration.Should().Be(test.TimeOfDay); test.Hour.Should().Be(time.Hour); time.Minute.Should().Be(test.Minute); time.Second.Should().Be(test.Second); time.Millisecond.Should().Be(test.Millisecond); }
// Pose callback public static void myTrackerCallback(Object sender, TimeValue timestamp, Int32 sensor, Pose3 report) { Console.WriteLine("Got POSE report: Position = ({0}, {1}, {2}), orientation ({3}, {4}, {5}, {6}), sensor ({7})", report.translation.x, report.translation.y, report.translation.z, report.rotation.w, report.rotation.x, report.rotation.y, report.rotation.z, sensor); }
public void EmptyConstructorTest() { var time = new TimeValue(); time.Hour.Should().Be(0); time.Minute.Should().Be(0); time.Second.Should().Be(0); time.Millisecond.Should().Be(0); time.Ticks.Should().Be(0); time.Duration.Should().Be(TimeSpan.Zero); time.TotalHours.Should().Be(0); time.TotalMinutes.Should().Be(0); time.TotalSeconds.Should().Be(0); time.TotalMilliseconds.Should().Be(0); }
public void Convert() { var timevalues = new TimeValue[20000]; for(int i = 0; i < timevalues.Length; i++) { timevalues[i] = new TimeValue {Time = new DateTime(2001, 1, 1).AddMinutes(i), Value = i}; } var serie = new TimeSerie {TimeValues = timevalues}; var cloudEntity = new CloudEntity<TimeSerie> { PartitionKey = "part", RowKey = "key", Value = serie }; var fatEntity = FatEntity.Convert(cloudEntity, _serializer); var cloudEntity2 = FatEntity.Convert<TimeSerie>(fatEntity, _serializer, null); var fatEntity2 = FatEntity.Convert(cloudEntity2, _serializer); Assert.IsNotNull(cloudEntity2); Assert.IsNotNull(fatEntity2); Assert.AreEqual(cloudEntity.PartitionKey, fatEntity.PartitionKey); Assert.AreEqual(cloudEntity.RowKey, fatEntity.RowKey); Assert.AreEqual(cloudEntity.PartitionKey, fatEntity2.PartitionKey); Assert.AreEqual(cloudEntity.RowKey, fatEntity2.RowKey); Assert.IsNotNull(cloudEntity2.Value); Assert.AreEqual(cloudEntity.Value.TimeValues.Length, cloudEntity2.Value.TimeValues.Length); for(int i = 0; i < timevalues.Length; i++) { Assert.AreEqual(cloudEntity.Value.TimeValues[i].Time, cloudEntity2.Value.TimeValues[i].Time); Assert.AreEqual(cloudEntity.Value.TimeValues[i].Value, cloudEntity2.Value.TimeValues[i].Value); } var data1 = fatEntity.GetData(); var data2 = fatEntity2.GetData(); Assert.AreEqual(data1.Length, data2.Length); for(int i = 0; i < data2.Length; i++) { Assert.AreEqual(data1[i], data2[i]); } }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { Dictionary<string, object> wholeDict = serializer.Deserialize<Dictionary<string, object>>(reader); Dictionary<string, object> facetDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(wholeDict.First().Value.ToString()); Dictionary<string, object> histoDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(facetDict.GetString(FacetTypeEnum.DateHistogram.ToString())); DateHistogramFacet facet = null; string facetName = wholeDict.First().Key; string field = histoDict.GetStringOrDefault(_FIELD); DateIntervalEnum intervalType = DateIntervalEnum.Day; string intervalValue = histoDict.GetString(_INTERVAL); intervalType = DateIntervalEnum.Find(intervalValue); if (intervalType != null) { if (string.IsNullOrWhiteSpace(field)) facet = new DateHistogramFacet(facetName, intervalType); else facet = new DateHistogramFacet(facetName, field, intervalType); } else { TimeValue timeValue = new TimeValue(intervalValue); if (string.IsNullOrWhiteSpace(field)) facet = new DateHistogramFacet(facetName, timeValue); else facet = new DateHistogramFacet(facetName, field, timeValue); } FacetSerializer.DeserializeFacetInfo(facet, histoDict); facet.KeyField = histoDict.GetStringOrDefault(_KEY_FIELD); if (histoDict.ContainsKey(_POST_OFFSET)) facet.PostOffset = JsonConvert.DeserializeObject<TimeValue>(histoDict.GetString(_POST_OFFSET)); if(histoDict.ContainsKey(_PRE_OFFSET)) facet.PreOffset = JsonConvert.DeserializeObject<TimeValue>(histoDict.GetString(_PRE_OFFSET)); facet.PostZone = histoDict.GetTimeSpan(_POST_ZONE, _TIMESPAN_DEFAULT); facet.PreZone = histoDict.GetTimeSpan(_PRE_ZONE, _TIMESPAN_DEFAULT); facet.PreZoneAdjustLargeInterval = histoDict.GetBool(_PRE_ZONE_ADJUST_LARGE_INTERVAL, _PRE_ZONE_ADJUST_LARGE_INTERVAL_DEFAULT); if (histoDict.ContainsKey(_PARAMETERS)) facet.ScriptParameters = JsonConvert.DeserializeObject<ScriptParameterCollection>(histoDict.GetString(_PARAMETERS)); facet.TimeZone = histoDict.GetTimeSpan(_TIME_ZONE, _TIMESPAN_DEFAULT); facet.ValueField = histoDict.GetStringOrDefault(_VALUE_FIELD); facet.ValueScript = histoDict.GetStringOrDefault(_VALUE_SCRIPT); facet.ScriptLanguage = histoDict.GetStringOrDefault(_LANGUAGE); return facet; }
public void DurationTest() { var test = new TimeSpan(0, 18, 23, 56, 344); var time = new TimeValue(test.Hours, test.Minutes, test.Seconds, test.Milliseconds); time.Hour.Should().Be(test.Hours); time.Minute.Should().Be(test.Minutes); time.Second.Should().Be(test.Seconds); time.Millisecond.Should().Be(test.Milliseconds); time.Duration.Ticks.Should().Be(test.Ticks); time.TotalHours.Should().Be(test.TotalHours); time.TotalMinutes.Should().Be(test.TotalMinutes); time.TotalSeconds.Should().Be(test.TotalSeconds); time.TotalMilliseconds.Should().Be(test.TotalMilliseconds); }
//////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void HandleChanged(object pSender, TimeValue pTime, int pSensor, ImagingState pReport) { if ( vIsChanged ) { return; } for ( int x = 0 ; x < ImageWidth ; x++ ) { for ( int y = 0 ; y < ImageHeight ; y++ ) { int byteI = x+y*ImageWidth; int colorI = (ImageWidth-x-1) + y*ImageWidth; byte b = Marshal.ReadByte(pReport.data, byteI); vImgColors[colorI] = new Color32(b, b, b, 255); } } vIsChanged = true; }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { Dictionary<string, object> wholeDict = serializer.Deserialize<Dictionary<string, object>>(reader); Dictionary<string, object> facetDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(wholeDict.First().Value.ToString()); Dictionary<string, object> histoDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(facetDict.GetString(FacetTypeEnum.Histogram.ToString())); HistogramFacet facet = null; string facetName = wholeDict.First().Key; string field = histoDict.GetStringOrDefault(_FIELD); if (histoDict.ContainsKey(_INTERVAL)) { Int64 interval = histoDict.GetInt64(_INTERVAL); if (string.IsNullOrWhiteSpace(field)) facet = new HistogramFacet(facetName, interval); else facet = new HistogramFacet(facetName, field, interval); } else if (histoDict.ContainsKey(_TIME_INTERVAL)) { TimeValue timeInterval = new TimeValue(histoDict.GetString(_TIME_INTERVAL)); if (string.IsNullOrWhiteSpace(field)) facet = new HistogramFacet(facetName, timeInterval); else facet = new HistogramFacet(facetName, field, timeInterval); } facet.KeyField = histoDict.GetStringOrDefault(_KEY_FIELD); facet.ValueField = histoDict.GetStringOrDefault(_VALUE_FIELD); facet.KeyScript = histoDict.GetStringOrDefault(_KEY_SCRIPT); facet.ValueScript = histoDict.GetStringOrDefault(_VALUE_SCRIPT); facet.ScriptLanguage = histoDict.GetStringOrDefault(_LANGUAGE); if (histoDict.ContainsKey(_PARAMETERS)) { facet.ScriptParameters = JsonConvert.DeserializeObject<ScriptParameterCollection>(histoDict.GetString(_PARAMETERS)); } FacetSerializer.DeserializeFacetInfo(facet, histoDict); return facet; }
//////////////////////////////////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------------------------*/ private void HandleChanged(object pSender, TimeValue pTime, int pSensor, ImagingState pReport) { if ( vIsChanged ) { return; } Marshal.Copy(pReport.data, vImgFloats, 0, vImgFloats.Length); for ( int x = 0 ; x < ImageWidth ; x++ ) { for ( int y = 0 ; y < ImageHeight ; y++ ) { int floatI = (x + y*ImageWidth)*ImageChannels; int colorI = (ImageWidth-x-1) + y*ImageWidth; vImgColors[colorI] = new Color( vImgFloats[floatI+2], vImgFloats[floatI+1], vImgFloats[floatI] ); } } vIsChanged = true; }
protected void InterfaceCallback(IntPtr userdata, ref TimeValue timestamp, ref NaviVelocityReport report) { OnStateChanged(timestamp, report.sensor, report.state); }
public DayHourRange(DayOfWeek dayOfWeek, TimeValue start, TimeValue end) : base(start, end) { _dayOfWeek = dayOfWeek; }
//yet to complete public DataGrid DivideGranularityTo5Mins(DateTime StartTime, DateTime EndTime, string ProbeGroupName, string ProbeName, string ServerName, string ProbeType, string metrics) { try { DataGrid result = new DataGrid(); List <string> TimeInterval = new List <string>(); DateTime start = DateTime.Parse(StartTime.ToString()); DateTime end = DateTime.Parse(EndTime.ToString()); List <TimeValue> ObjList = new List <TimeValue>(); TimeValue ObjValue = new TimeValue(); string htmlCode = string.Empty; string htmlResponse = string.Empty; // Create Request //HttpWebRequest req = (HttpWebRequest)WebRequest.Create(@"" + ConfigurationManager.AppSettings["DiagnosticsServerURL"] +"/query/?action=trend&granularity=[name='5m',start='9223372036854775807',end='9223372036854775807']&response_format=excel&path=%2Fgroupby%5Bname%3D'Default%20Client%3A'%5D%2Fprobegroup%5Bname%3D'ACAS_profiling'%5D%2Fprobe%5Bname%3D'gblabvl281_ACAS_server1'%2ChostName%3D'gblabvl281.gb.tntpost.com'%2CsystemGroup%3D'Default'%2CprobeType%3D'Java'%5D%2Fmetric[name='Availability',type='average']"); // Create Client WebClient client = new WebClient(); // Assign Credentials client.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["DiagnosticsServerUserName"], ConfigurationManager.AppSettings["DiagnosticsServerPassword"]); while (end > start) { TimeInterval.Add(start.ToString("h.mmtt", CultureInfo.InvariantCulture)); var url = "" + ConfigurationManager.AppSettings["DiagnosticsServerURL"] + "/query/?action=trend&granularity=[name='5m',start='" + ((start.ToOADate() - 25569) * 60 * 60 * 24 * 1000).ToString() + "',end='" + ((start.AddMinutes(5).ToOADate() - 25569) * 60 * 60 * 24 * 1000).ToString() + "']&response_format=excel&path=%2Fgroupby%5Bname%3D'Default%20Client%3A'%5D%2Fprobegroup%5Bname%3D'" + ProbeGroupName + "'%5D%2Fprobe%5Bname%3D'" + ProbeName + "'%2ChostName%3D'" + ServerName + "'%2CsystemGroup%3D'Default'%2CprobeType%3D'" + ProbeType + "'%5D%2Fmetric[name='" + metrics.Replace(',', '_') + "',type='average']"; try { htmlCode = client.DownloadString(url); } catch (Exception) { } int numLines = htmlCode.Split('\n').Length; if (numLines <= 3) { goto exitloop; } for (int i = 4; i < numLines - 1; i++) { //Add column names if (i == 4) { ObjValue = new TimeValue(); ObjValue.Time = "DateTime"; ObjValue.value = "Value"; ObjList.Add(ObjValue); } ObjValue = new TimeValue(); ObjValue.Time = DateTime.FromOADate(Convert.ToDouble(htmlCode.Split('\n')[i].Split('\t')[0])).ToString(); ObjValue.value = Convert.ToString(Convert.ToDecimal((htmlCode.Split('\n')[i].Split('\t')[1])) * 100); ObjList.Add(ObjValue); } start = start.AddMinutes(5); htmlResponse = string.Concat(htmlCode); } result.DataSource = ObjList; exitloop: return(result); } catch (Exception ex) { throw ex; } }
public static extern Byte osvrGetDirectionState(SafeClientInterfaceHandle iface, ref TimeValue timestamp, ref Vec3 state);
private void EyeTrackerBlinkInterface_StateChanged(object sender, TimeValue timestamp, int sensor, bool report) { valueBlink = report; }
/// <summary> /// Adds the specified TimeValue to the DateTimeOffset object. /// </summary> /// <param name="startTime">The date to add the time value to.</param> /// <param name="timeStep">The amount of time to add.</param> /// <returns>A DateTimeOffset object with the specified time added.</returns> public static DateTimeOffset AddTimeValue(this DateTimeOffset startTime, TimeValue timeStep) { var timeValueAsTimeSpan = TimeSpan.FromMilliseconds(0); var timeValueAsMonths = 0d; switch (timeStep.Unit) { case TimeUnit.Milliseconds: timeValueAsTimeSpan = TimeSpan.FromMilliseconds(timeStep.Duration); break; case TimeUnit.Seconds: timeValueAsTimeSpan = TimeSpan.FromSeconds(timeStep.Duration); break; case TimeUnit.Minutes: timeValueAsTimeSpan = TimeSpan.FromMinutes(timeStep.Duration); break; case TimeUnit.Hours: timeValueAsTimeSpan = TimeSpan.FromHours(timeStep.Duration); break; case TimeUnit.Days: timeValueAsTimeSpan = TimeSpan.FromDays(timeStep.Duration); break; case TimeUnit.Weeks: timeValueAsTimeSpan = TimeSpan.FromDays(timeStep.Duration * 7); break; case TimeUnit.Months: timeValueAsMonths = timeStep.Duration; break; case TimeUnit.Years: timeValueAsMonths = timeStep.Duration * 12; break; case TimeUnit.Decades: timeValueAsMonths = timeStep.Duration * 120; break; case TimeUnit.Centuries: timeValueAsMonths = timeStep.Duration * 1200; // Use DateTime.AddMonths for these break; } if (timeValueAsTimeSpan.Ticks > 0) { // Time value maps to a definitive timespan return(startTime + timeValueAsTimeSpan); } else { // Time value is months-based, so can equate to different timespans depending on the particular calendar month(s) return(startTime.AddMonths(timeValueAsMonths)); } }
internal override void SetXML(XmlElement xml, BaseClassIfc host, Dictionary <string, XmlElement> processed) { base.SetXML(xml, host, processed); xml.SetAttribute("TimeValue", TimeValue.ToString()); setAttribute(xml, "Formula", Formula); }
static void locomotionVelocity_StateChanged(object sender, TimeValue timestamp, Int32 sensor, Vec2 report) { Console.WriteLine("Got report: sensor is {0}. Velocity is ( x: {1}, y: {2} )", sensor, report.x, report.y); }
public static extern int select([In] int ignoredParameter, [In, Out] ref FileDescriptorSet readfds, [In, Out] ref FileDescriptorSet writefds, [In, Out] ref FileDescriptorSet exceptfds, [In] ref TimeValue timeout);
public async Task RapidRetention() { var cluster = await CreateRaftCluster(3); using (var store = GetDocumentStore(new Options { Server = cluster.Leader, ReplicationFactor = 3 })) { var retention = TimeValue.FromSeconds(120); var raw = new RawTimeSeriesPolicy(retention); var config = new TimeSeriesConfiguration { Collections = new Dictionary <string, TimeSeriesCollectionConfiguration> { ["Users"] = new TimeSeriesCollectionConfiguration { RawPolicy = raw, } }, PolicyCheckFrequency = TimeSpan.FromSeconds(1) }; var now = DateTime.UtcNow; var baseline = now.Add(-retention * 3); var total = (int)((TimeSpan)retention).TotalMilliseconds * 3; using (var session = store.OpenSession()) { session.Store(new User { Name = "Karmel" }, "users/karmel"); for (int i = 0; i < total; i++) { session.TimeSeriesFor("users/karmel", "Heartrate") .Append(baseline.AddMilliseconds(i), new[] { 29d * i, i, i * 0.01, i * 0.1 }, "watches/fitbit"); } session.SaveChanges(); session.Store(new User(), "marker"); session.SaveChanges(); Assert.True(await WaitForDocumentInClusterAsync <User>(cluster.Nodes, store.Database, "marker", null, TimeSpan.FromSeconds(15))); } await store.Maintenance.SendAsync(new ConfigureTimeSeriesOperation(config)); var sp = Stopwatch.StartNew(); await Task.Delay((TimeSpan)retention / 2); var debug = new Dictionary <string, (long Count, DateTime Start, DateTime End)>(); var check = true; while (check) { Assert.True(sp.Elapsed < ((TimeSpan)retention).Add((TimeSpan)retention), $"too long has passed {sp.Elapsed}, retention is {retention} {Environment.NewLine}" + $"debug: {string.Join(',', debug.Select(kvp => $"{kvp.Key}: ({kvp.Value.Count},{kvp.Value.Start},{kvp.Value.End})"))}"); await Task.Delay(100); check = false; foreach (var server in Servers) { var database = await server.ServerStore.DatabasesLandlord.TryGetOrCreateResourceStore(store.Database); using (database.DocumentsStorage.ContextPool.AllocateOperationContext(out DocumentsOperationContext ctx)) using (ctx.OpenReadTransaction()) { var tss = database.DocumentsStorage.TimeSeriesStorage; var stats = tss.Stats.GetStats(ctx, "users/karmel", "Heartrate"); var reader = tss.GetReader(ctx, "users/karmel", "Heartrate", DateTime.MinValue, DateTime.MaxValue); if (stats.Count == 0) { debug.Remove(server.ServerStore.NodeTag); continue; } check = true; Assert.Equal(stats.Start, reader.First().Timestamp, RavenTestHelper.DateTimeComparer.Instance); Assert.Equal(stats.End, reader.Last().Timestamp, RavenTestHelper.DateTimeComparer.Instance); debug[server.ServerStore.NodeTag] = stats; } } } Assert.Empty(debug); Assert.True(sp.Elapsed < (TimeSpan)retention + (TimeSpan)retention); await Task.Delay(3000); // let the dust to settle await EnsureNoReplicationLoop(Servers[0], store.Database); await EnsureNoReplicationLoop(Servers[1], store.Database); await EnsureNoReplicationLoop(Servers[2], store.Database); foreach (var server in Servers) { var database = await server.ServerStore.DatabasesLandlord.TryGetOrCreateResourceStore(store.Database); await TimeSeriesReplicationTests.AssertNoLeftOvers(database); } } }
public void LoadContent(ContentManager content) { //i = row y, j column x for (int i = 0; i < raw.Count; i++) { for (int j = 0; j < raw[i].Length; j++) { Actor actor = null; using (ContentManager c = new ContentManager(content.ServiceProvider, content.RootDirectory)) { switch (raw[i][j]) { case 'W': { actor = c.Load <Actor>("Actors/Border"); break; } case 'X': { actor = c.Load <Actor>("Actors/Player"); Player = actor; break; } case '.': { actor = c.Load <Actor>("Actors/Dirt"); break; } case 'w': { actor = c.Load <Actor>("Actors/Wall"); break; } case 'r': { actor = c.Load <Actor>("Actors/Boulder"); break; } case 'd': { actor = c.Load <Actor>("Actors/Diamond"); break; } case 'P': { actor = c.Load <Actor>("Actors/Exit"); break; } } } if (actor != null) { actor.Owner = this; actor.LoadContent(content); actor.GetComponent <RenderableComponent>().DrawColor = ForegroundColor; actor.Position = new Vector2(j * TileDimensions.X, i * TileDimensions.Y); Actors.Add(actor); } } } Actors.Where(x => x.HasComponent <ExitComponent>()).ToList().ForEach(x => x.GetComponent <ExitComponent>().ExitEntered += ActorMap_ExitEntered); Actors.Where(x => x.HasComponent <DestroyableComponent>()).ToList().ForEach(x => x.GetComponent <DestroyableComponent>().Destroyed += ActorMap_ActorDestroyed); Actors.Where(x => x.HasComponent <PlayerComponent>()).ToList().ForEach(x => x.GetComponent <PlayerComponent>().PlayerKilled += ActorMap_PlayerKilled); Actors.Where(x => x.HasComponent <CollectableComponent>()).ToList().ForEach(x => x.GetComponent <CollectableComponent>().Collected += ActorMap_Collected); //force 1lvl Time = Int32.Parse(TimeValue.Split(" ").FirstOrDefault()); DiamondsRequired = Int32.Parse(DiamondsRequiredValue.Split(" ").FirstOrDefault()); Size = new Vector2(Actors.Last().Position.X - Actors[0].Position.X + TileDimensions.X, Actors.Last().Position.Y - Actors[0].Position.Y + TileDimensions.Y); InputManager.Instance.OnFlickDown += Instance_OnFlickDown; InputManager.Instance.OnFlickUp += Instance_OnFlickUp; InputManager.Instance.OnFlickLeft += Instance_OnFlickLeft; InputManager.Instance.OnFlickRight += Instance_OnFlickRight; MapStartSound = content.Load <Song>("Sounds/MapStart"); MapEndSound = content.Load <Song>("Sounds/MapComplete"); MapLoaded?.Invoke(this, null); MediaPlayer.Play(MapStartSound); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldEncodeArrays() public virtual void ShouldEncodeArrays() { AssertEncoding("D1.0|2.0|3.0|", new int[] { 1, 2, 3 }); AssertEncoding("Ztrue|false|", new bool[] { true, false }); AssertEncoding("LYWxp|YXJl|eW91|b2s=|", new string[] { "ali", "are", "you", "ok" }); AssertEncoding("", new string[] {}); AssertEncoding("P1:4326:1.234;2.567|1:4326:2.345;5.678|2:9157:3.0;4.0;5.0|", new Point[] { Values.pointValue(CoordinateReferenceSystem.WGS84, 1.234, 2.567), Values.pointValue(CoordinateReferenceSystem.WGS84, 2.345, 5.678), Values.pointValue(CoordinateReferenceSystem.Cartesian_3D, 3, 4, 5) }); AssertEncoding("T1991-03-05|1992-04-06|", new LocalDate[] { DateValue.date(1991, 3, 5).asObjectCopy(), DateValue.date(1992, 4, 6).asObjectCopy() }); AssertEncoding("T12:45:13.000008676|05:04:50.000000076|", new LocalTime[] { LocalTimeValue.localTime(12, 45, 13, 8676).asObjectCopy(), LocalTimeValue.localTime(5, 4, 50, 76).asObjectCopy() }); AssertEncoding("T1991-03-05T12:45:13.000008676|1992-04-06T05:04:50.000000076|", new DateTime[] { LocalDateTimeValue.localDateTime(1991, 3, 5, 12, 45, 13, 8676).asObjectCopy(), LocalDateTimeValue.localDateTime(1992, 4, 6, 5, 4, 50, 76).asObjectCopy() }); AssertEncoding("T02:45:13.000008676Z|01:05:00.0000003+01:00|05:04:50.000000076+05:00|", new OffsetTime[] { TimeValue.time(2, 45, 13, 8676, UTC).asObjectCopy(), TimeValue.time(OffsetTime.ofInstant(Instant.ofEpochSecond(300, 300), ZoneId.of("Europe/Stockholm"))).asObjectCopy(), TimeValue.time(5, 4, 50, 76, "+05:00").asObjectCopy() }); AssertEncoding("T1991-03-05T02:45:13.000008676Z|1991-03-05T02:45:13.000008676+01:00[Europe/Stockholm]|1992-04-06T05:04:50.000000076+05:00|", new ZonedDateTime[] { DateTimeValue.datetime(1991, 3, 5, 2, 45, 13, 8676, UTC).asObjectCopy(), DateTimeValue.datetime(1991, 3, 5, 2, 45, 13, 8676, ZoneId.of("Europe/Stockholm")).asObjectCopy(), DateTimeValue.datetime(1992, 4, 6, 5, 4, 50, 76, "+05:00").asObjectCopy() }); AssertEncoding("AP165Y11M3DT5.000000012S|P166Y4DT6.000000005S|", new TemporalAmount[] { DurationValue.duration(1991, 3, 5, 12).asObjectCopy(), DurationValue.duration(1992, 4, 6, 5).asObjectCopy() }); }
private void Location2DInterface_StateChanged(object sender, TimeValue timestamp, int sensor, Vec2 report) { value = report; }
internal static unsafe partial int select( int ignoredParameter, IntPtr *readfds, IntPtr *writefds, IntPtr *exceptfds, ref TimeValue timeout);
static void myAnalogCallback(IntPtr userdata, ref TimeValue timestamp, ref AnalogReport report) { Console.WriteLine("Got report: channel is {0}", report.state); }
public static extern Byte osvrGetEyeTrackerBlinkState(SafeClientInterfaceHandle iface, ref TimeValue timestamp, [MarshalAs(UnmanagedType.I1)]ref bool state);
internal static extern unsafe int select( [In] int ignoredParameter, [In] IntPtr *readfds, [In] IntPtr *writefds, [In] IntPtr *exceptfds, [In] ref TimeValue timeout);
static void Main() { var serviceUrl = "http://ws.lokad.com/TimeSeries2.asmx"; var login = "******"; // your Sandbox login here var pwd = "yourpassword"; // your Sandbox password here var service = ServiceFactory .GetConnectorForTesting(login, pwd, serviceUrl); var existingSeries = service.GetSeries(); service.DeleteSeries(existingSeries); var serie1 = new SerieInfo { Name = "MySerie1" }; var serie2 = new SerieInfo { Name = "MySerie2" }; var mySeries = new[] {serie1, serie2}; Console.WriteLine("Saving series..."); service.AddSeries(mySeries); // add values var value1 = new TimeValue { Time = new DateTime(2008, 7, 1), Value = 10 }; var value2 = new TimeValue { Time = new DateTime(2008, 7, 2), Value = 12 }; var value3 = new TimeValue { Time = new DateTime(2008, 7, 3), Value = 11 }; // create association between serie1 and values 1,2,3 var segment1 = new SegmentForSerie(serie1, new[] {value1, value2, value3}); // create association between serie2 and values 1,2 var segment2 = new SegmentForSerie(serie2, new[] {value1, value2}); Console.WriteLine("Saving values..."); service.UpdateSerieSegments(new[] {segment1, segment2}); // create new forecasting task // to create 3 days forecast with daily interval var task = new TaskInfo(serie1) { FuturePeriods = 3, Period = Period.Day }; Console.WriteLine("Saving Tasks..."); service.AddTasks(new[] {task}); Console.WriteLine("Retrieving forecasts..."); var forecasts = service.GetForecasts(new[] {task}); foreach (var forecast in forecasts) { Console.WriteLine("Forecast for task {0}", forecast.TaskID); foreach (var value in forecast.Values) { Console.WriteLine(" {0} - {1}", value.Time.ToShortDateString(), value.Value); } } Console.WriteLine("Press any key to continue"); Console.ReadKey(true); }
/// <summary> /// Remove stale values from the collection of PC-Mount time difference measurements /// </summary> /// <param name="timevalue">The time value to test</param> /// <returns>Boolean value indicating whether a particular time value should be removed from the collection</returns> /// <remarks>Originally this was treating AveragePeriod as being in minutes, it now treats it as hours per the specification.</remarks> private static bool TimeRemovePredicate(TimeValue timevalue) { // Next line revised to treat AveragePeriod as being in hours per the interface specification, previously it was treating it as being in minutes. Peter Simpson 29th May 2019 return(DateTime.Now.Subtract(timevalue.ObservationTime).TotalHours > AveragePeriod); }
public TimeSeriesPolicy(string name, TimeValue aggregationTime) : this(name, aggregationTime, TimeValue.MaxValue) { }
public static extern Byte osvrGetLocation2DState(SafeClientInterfaceHandle iface, ref TimeValue timestamp, ref Vec2 state);
private void AnalogInterface_StateChanged(object sender, TimeValue timestamp, Int32 sensor, Double report) { analogValue = report; }
public static extern Byte osvrGetEyeTracker3DState(SafeClientInterfaceHandle iface, ref TimeValue timestamp, ref EyeTracker3DState state);
private void EyeTracker3DInterface_StateChanged(object sender, TimeValue timestamp, int sensor, EyeTracker3DState report) { value3D = report; }
public void GetDateTimeTest() { var dateTime = DateTime.Now; var timeSpan = new TimeSpan(0, 18, 23, 56, 344); var time = new TimeValue(timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds); time.GetDateTime(dateTime).Should().Be(dateTime.Date.Add(timeSpan)); }
public static TimeValue ParseTimePeriodFromString(long duration, string source, ref int offset) { TimeValue result; while (char.IsWhiteSpace(source[offset]) && offset < source.Length) { offset++; } if (offset >= source.Length) { throw new ArgumentException("Unable to find range specification in: " + source); } switch (char.ToLower(source[offset++])) { case 's': if (TryConsumeMatch(source, ref offset, "seconds") == false) { TryConsumeMatch(source, ref offset, "second"); } result = TimeValue.FromSeconds((int)duration); break; case 'm': if (TryConsumeMatch(source, ref offset, "minutes") || TryConsumeMatch(source, ref offset, "minute") || TryConsumeMatch(source, ref offset, "min")) { result = TimeValue.FromMinutes((int)duration); break; } if (TryConsumeMatch(source, ref offset, "ms") || TryConsumeMatch(source, ref offset, "milliseconds") || TryConsumeMatch(source, ref offset, "milli")) { // TODO use TimeValue.FromMilliseconds when RavenDB-14988 is fixed throw new NotSupportedException("Unsupported time period. Using milliseconds in Last/First is not supported : " + source); } if (TryConsumeMatch(source, ref offset, "months") || TryConsumeMatch(source, ref offset, "month") || TryConsumeMatch(source, ref offset, "mon") || TryConsumeMatch(source, ref offset, "mo")) { result = TimeValue.FromMonths((int)duration); break; } goto default; case 'h': if (TryConsumeMatch(source, ref offset, "hours") == false) { TryConsumeMatch(source, ref offset, "hour"); } result = TimeValue.FromHours((int)duration); break; case 'd': if (TryConsumeMatch(source, ref offset, "days") == false) { TryConsumeMatch(source, ref offset, "day"); } result = TimeValue.FromDays((int)duration); break; case 'q': if (TryConsumeMatch(source, ref offset, "quarters") == false) { TryConsumeMatch(source, ref offset, "quarter"); } duration *= 3; AssertValidDurationInMonths(duration); result = TimeValue.FromMonths((int)duration); break; case 'y': if (TryConsumeMatch(source, ref offset, "years") == false) { TryConsumeMatch(source, ref offset, "year"); } duration *= 12; AssertValidDurationInMonths(duration); result = TimeValue.FromMonths((int)duration); break; default: throw new ArgumentException($"Unable to understand time range: '{source}'"); } while (offset < source.Length && char.IsWhiteSpace(source[offset])) { offset++; } if (offset != source.Length) { throw new ArgumentException("After range specification, found additional unknown data: " + source); } return(result); }
static void location2D_StateChanged(object sender, TimeValue timestamp, Int32 sensor, Vec2 report) { Console.WriteLine("Got 2D Location Report, for sensor #{0}", sensor); Console.WriteLine(FormatLocation2DReport(report)); }
public override ListValue MapTime(TimeValue value) { return(null); }
static void eyeTracker3D_StateChanged(object sender, TimeValue timestamp, Int32 sensor, EyeTracker3DState report) { Console.WriteLine("Got 3D eye tracker report, for sensor #{0}", sensor); Console.WriteLine(FormatEyeTracker3DReport(report)); }
public void CanCreateSubscriptionWithIncludeTimeSeries_LastRangeByTime() { var now = DateTime.UtcNow.EnsureMilliseconds(); using (var store = GetDocumentStore()) { var name = store.Subscriptions .Create(new SubscriptionCreationOptions <Company>() { Includes = builder => builder .IncludeTimeSeries("StockPrice", TimeSeriesRangeType.Last, TimeValue.FromMonths(1)) }); var mre = new ManualResetEventSlim(); var worker = store.Subscriptions.GetSubscriptionWorker <Company>(name); worker.Run(batch => { using (var session = batch.OpenSession()) { Assert.Equal(0, session.Advanced.NumberOfRequests); var company = session.Load <Company>("companies/1"); Assert.Equal(0, session.Advanced.NumberOfRequests); var timeSeries = session.TimeSeriesFor(company, "StockPrice"); var timeSeriesEntries = timeSeries.Get(from: now.AddDays(-7)); Assert.Equal(1, timeSeriesEntries.Length); Assert.Equal(now, timeSeriesEntries[0].Timestamp); Assert.Equal(10, timeSeriesEntries[0].Value); Assert.Equal(0, session.Advanced.NumberOfRequests); } mre.Set(); }); using (var session = store.OpenSession()) { var company = new Company { Id = "companies/1", Name = "HR" }; session.Store(company); session.TimeSeriesFor(company, "StockPrice").Append(now, 10); session.SaveChanges(); } Assert.True(mre.Wait(TimeSpan.FromSeconds(30))); } }
protected void InterfaceCallback(IntPtr userdata, ref TimeValue timestamp, ref DirectionReport report) { OnStateChanged(timestamp, report.sensor, report.direction); }
public static extern int select([In] int ignoredParameter, [In] IntPtr ignoredA, [In, Out] ref FileDescriptorSet writefds, [In] IntPtr ignoredB, [In] ref TimeValue timeout);
public void CanCreateSubscriptionWithIncludeTimeSeries_Array_LastRange(bool byTime) { var now = DateTime.UtcNow.EnsureMilliseconds(); using (var store = GetDocumentStore()) { string name; if (byTime) { name = store.Subscriptions .Create(new SubscriptionCreationOptions <Company>() { Includes = builder => builder .IncludeTimeSeries(new[] { "StockPrice", "StockPrice2" }, TimeSeriesRangeType.Last, TimeValue.FromDays(7)) }); } else { name = store.Subscriptions .Create(new SubscriptionCreationOptions <Company>() { Includes = builder => builder .IncludeTimeSeries(new[] { "StockPrice", "StockPrice2" }, TimeSeriesRangeType.Last, count: 32) }); } var mre = new ManualResetEventSlim(); var worker = store.Subscriptions.GetSubscriptionWorker <Company>(name); var t = worker.Run(batch => { using (var session = batch.OpenSession()) { Assert.Equal(0, session.Advanced.NumberOfRequests); var company = session.Load <Company>("companies/1"); Assert.Equal(0, session.Advanced.NumberOfRequests); var timeSeries = session.TimeSeriesFor(company, "StockPrice"); var timeSeriesEntries = timeSeries.Get(from: now.AddDays(-7)); Assert.Equal(1, timeSeriesEntries.Length); Assert.Equal(now.AddDays(-7), timeSeriesEntries[0].Timestamp); Assert.Equal(10, timeSeriesEntries[0].Value); Assert.Equal(0, session.Advanced.NumberOfRequests); timeSeries = session.TimeSeriesFor(company, "StockPrice2"); timeSeriesEntries = timeSeries.Get(from: now.AddDays(-5)); Assert.Equal(1, timeSeriesEntries.Length); Assert.Equal(now.AddDays(-5), timeSeriesEntries[0].Timestamp); Assert.Equal(100, timeSeriesEntries[0].Value); Assert.Equal(0, session.Advanced.NumberOfRequests); } mre.Set(); }); using (var session = store.OpenSession()) { var company = new Company { Id = "companies/1", Name = "HR" }; session.Store(company); session.TimeSeriesFor(company, "StockPrice").Append(now.AddDays(-7), 10); session.TimeSeriesFor(company, "StockPrice2").Append(now.AddDays(-5), 100); session.SaveChanges(); } var result = WaitForValue(() => mre.Wait(TimeSpan.FromSeconds(500)), true); if (result == false && t.IsFaulted) { Assert.True(result, $"t.IsFaulted: {t.Exception}, {t.Exception?.InnerException}"); } Assert.True(result); } }
private void ReadImpl() { List <IntPtr> dead = null, active = new List <IntPtr>(); List <ISocketCallback> activeCallbacks = new List <ISocketCallback>(); IntPtr[] readSockets = EmptyPointers, errorSockets = EmptyPointers; long lastHeartbeat = Environment.TickCount; SocketPair[] allSocketPairs = null; while (true) { managerState = ManagerState.CheckForHeartbeat; active.Clear(); activeCallbacks.Clear(); if (dead != null) { dead.Clear(); } // this check is actually a pace-maker; sometimes the Timer callback stalls for // extended periods of time, which can cause socket disconnect long now = Environment.TickCount; if (unchecked (now - lastHeartbeat) >= 15000) { managerState = ManagerState.ExecuteHeartbeat; lastHeartbeat = now; lock (socketLookup) { if (allSocketPairs == null || allSocketPairs.Length != socketLookup.Count) { allSocketPairs = new SocketPair[socketLookup.Count]; } socketLookup.Values.CopyTo(allSocketPairs, 0); } foreach (var pair in allSocketPairs) { var callback = pair.Callback; if (callback != null) { try { callback.OnHeartbeat(); } catch { } } } } managerState = ManagerState.LocateActiveSockets; lock (socketLookup) { if (isDisposed) { return; } if (socketLookup.Count == 0) { // if empty, give it a few seconds chance before exiting managerState = ManagerState.NoSocketsPause; Monitor.Wait(socketLookup, TimeSpan.FromSeconds(20)); if (socketLookup.Count == 0) { return; // nothing new came in, so exit } } managerState = ManagerState.PrepareActiveSockets; foreach (var pair in socketLookup) { var socket = pair.Value.Socket; if (socket.Handle == pair.Key && socket.Connected) { if (pair.Value.Socket.Connected) { active.Add(pair.Key); activeCallbacks.Add(pair.Value.Callback); } else { (dead ?? (dead = new List <IntPtr>())).Add(pair.Key); } } } if (dead != null && dead.Count != 0) { managerState = ManagerState.CullDeadSockets; foreach (var socket in dead) { socketLookup.Remove(socket); } } } int pollingSockets = active.Count; if (pollingSockets == 0) { // nobody had actual sockets; just sleep managerState = ManagerState.NoActiveSocketsPause; Thread.Sleep(10); continue; } if (readSockets.Length < active.Count + 1) { managerState = ManagerState.GrowingSocketArray; ConnectionMultiplexer.TraceWithoutContext("Resizing socket array for " + active.Count + " sockets"); readSockets = new IntPtr[active.Count + 6]; // leave so space for growth errorSockets = new IntPtr[active.Count + 6]; } managerState = ManagerState.CopyingPointersForSelect; readSockets[0] = errorSockets[0] = (IntPtr)active.Count; active.CopyTo(readSockets, 1); active.CopyTo(errorSockets, 1); int ready; try { var timeout = new TimeValue(1000); managerState = ManagerState.ExecuteSelect; ready = select(0, readSockets, null, errorSockets, ref timeout); if (ready <= 0) { if (ready == 0) { foreach (var s in activeCallbacks) { s.CheckForStaleConnection(); } } continue; // -ve typically means a socket was disposed just before; just retry } ConnectionMultiplexer.TraceWithoutContext((int)readSockets[0] != 0, "Read sockets: " + (int)readSockets[0]); ConnectionMultiplexer.TraceWithoutContext((int)errorSockets[0] != 0, "Error sockets: " + (int)errorSockets[0]); } catch (Exception ex) { // this typically means a socket was disposed just before; just retry Trace.WriteLine(ex.Message); continue; } int queueCount = (int)readSockets[0]; if (queueCount != 0) { managerState = ManagerState.EnqueueRead; lock (readQueue) { for (int i = 1; i <= queueCount; i++) { readQueue.Enqueue(readSockets[i]); } } } queueCount = (int)errorSockets[0]; if (queueCount != 0) { managerState = ManagerState.EnqueueError; lock (errorQueue) { for (int i = 1; i <= queueCount; i++) { errorQueue.Enqueue(errorSockets[i]); } } } if (ready >= 5) // number of sockets we should attempt to process by ourself before asking for help { // seek help, work in parallel, then synchronize var obj = new QueueDrainSyncLock(this); lock (obj) { managerState = ManagerState.RequestAssistance; ThreadPool.QueueUserWorkItem(HelpProcessItems, obj); managerState = ManagerState.ProcessQueues; ProcessItems(true); if (!obj.Consume()) { // then our worker arrived and picked up work; we need // to let it finish; note that if it *didn't* get that far // yet, the Consume() call will mean that it never tries Monitor.Wait(obj); } } } else { // just do it ourself managerState = ManagerState.ProcessQueues; ProcessItems(true); } } }
private static extern int select( [In] int ignoredParameter, [In, Out] IntPtr[] readfds, [In, Out] IntPtr[] writefds, [In, Out] IntPtr[] exceptfds, [In] ref TimeValue timeout);
public void GetEmptyDateTimeTest() { var dateTime = DateTime.Today; var time = new TimeValue(); time.GetDateTime(dateTime).Should().Be(dateTime); }
private void ReceiveLogic(object state) { Socket socket = (Socket)state; EndPoint bufferEndPoint = new IPEndPoint(socket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0); NetEndPoint bufferNetEndPoint = new NetEndPoint((IPEndPoint)bufferEndPoint); #if WIN32 && UNSAFE int saddrSize = 32; byte[] prevAddress = new byte[saddrSize]; byte[] socketAddress = new byte[saddrSize]; byte[] addrBuffer = new byte[16]; //IPAddress.IPv6AddressBytes var sockeHandle = socket.Handle; IntPtr[] fileDescriptorSet = { (IntPtr)1, sockeHandle }; TimeValue time = new TimeValue { Microseconds = SocketReceivePollTime }; #endif byte[] receiveBuffer = new byte[NetConstants.PacketSizeLimit]; while (_running) { int result; //Reading data try { #if WIN32 && UNSAFE fileDescriptorSet[0] = (IntPtr)1; fileDescriptorSet[1] = sockeHandle; int socketCount = select(0, fileDescriptorSet, null, null, ref time); if ((SocketError)socketCount == SocketError.SocketError) { throw new SocketException(Marshal.GetLastWin32Error()); } if ((int)fileDescriptorSet[0] == 0 || fileDescriptorSet[1] != sockeHandle) { continue; } result = recvfrom( sockeHandle, receiveBuffer, receiveBuffer.Length, SocketFlags.None, socketAddress, ref saddrSize); if ((SocketError)result == SocketError.SocketError) { throw new SocketException(Marshal.GetLastWin32Error()); } bool recreate = false; for (int i = 0; i < saddrSize; i++) { if (socketAddress[i] != prevAddress[i]) { prevAddress[i] = socketAddress[i]; recreate = true; } } if (recreate) { if (socket.AddressFamily == AddressFamily.InterNetwork) { int port = (socketAddress[2] << 8 & 0xFF00) | socketAddress[3]; long address = ( (socketAddress[4] & 0x000000FF) | (socketAddress[5] << 8 & 0x0000FF00) | (socketAddress[6] << 16 & 0x00FF0000) | (socketAddress[7] << 24) ) & 0x00000000FFFFFFFF; bufferNetEndPoint = new NetEndPoint(new IPEndPoint(address, port)); } else { for (int i = 0; i < addrBuffer.Length; i++) { addrBuffer[i] = socketAddress[i + 8]; } int port = (socketAddress[2] << 8 & 0xFF00) | (socketAddress[3]); long scope = (socketAddress[27] << 24) + (socketAddress[26] << 16) + (socketAddress[25] << 8) + (socketAddress[24]); bufferNetEndPoint = new NetEndPoint(new IPEndPoint(new IPAddress(addrBuffer, scope), port)); } } #else if (!socket.Poll(SocketReceivePollTime, SelectMode.SelectRead)) { continue; } result = socket.ReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref bufferEndPoint); if (!bufferNetEndPoint.EndPoint.Equals(bufferEndPoint)) { bufferNetEndPoint = new NetEndPoint((IPEndPoint)bufferEndPoint); } #endif } catch (SocketException ex) { if (ex.SocketErrorCode == SocketError.ConnectionReset || ex.SocketErrorCode == SocketError.MessageSize) { //10040 - message too long //10054 - remote close (not error) //Just UDP NetUtils.DebugWrite(ConsoleColor.DarkRed, "[R] Ingored error: {0} - {1}", (int)ex.SocketErrorCode, ex.ToString()); continue; } NetUtils.DebugWriteError("[R]Error code: {0} - {1}", (int)ex.SocketErrorCode, ex.ToString()); _onMessageReceived(null, 0, (int)ex.SocketErrorCode, bufferNetEndPoint); continue; } //All ok! NetUtils.DebugWrite(ConsoleColor.Blue, "[R]Received data from {0}, result: {1}", bufferNetEndPoint.ToString(), result); _onMessageReceived(receiveBuffer, result, 0, bufferNetEndPoint); } }
static void analogTrigger_StateChanged(object sender, TimeValue timestamp, Int32 sensor, Double report) { Console.WriteLine("Got report: channel is {0}, sensor is {1}", report, sensor); }
static void button1_StateChanged(object sender, TimeValue timestamp, Int32 sensor, Byte report) { Console.WriteLine("Got report: button from sensor {0} is {1}", sensor, report == ButtonInterface.Pressed ? "pressed" : "released"); }
static void eyeTrackerBlink_StateChanged(object sender, TimeValue timestamp, Int32 sensor, bool report) { Console.WriteLine("Got eye tracker blink Location Report, for sensor #{0}", sensor); Console.WriteLine("blink value: {0}", report); }
public BuiltInFunctions() { // Text Functions["len"] = new Len(); Functions["lower"] = new Lower(); Functions["upper"] = new Upper(); Functions["left"] = new Left(); Functions["right"] = new Right(); Functions["mid"] = new Mid(); Functions["replace"] = new Replace(); Functions["rept"] = new Rept(); Functions["substitute"] = new Substitute(); Functions["concatenate"] = new Concatenate(); Functions["char"] = new CharFunction(); Functions["exact"] = new Exact(); Functions["find"] = new Find(); Functions["fixed"] = new Fixed(); Functions["proper"] = new Proper(); Functions["search"] = new Search(); Functions["text"] = new Text.Text(); Functions["t"] = new T(); Functions["hyperlink"] = new Hyperlink(); Functions["value"] = new Value(); // Numbers Functions["int"] = new CInt(); // Math Functions["abs"] = new Abs(); Functions["asin"] = new Asin(); Functions["asinh"] = new Asinh(); Functions["cos"] = new Cos(); Functions["cosh"] = new Cosh(); Functions["power"] = new Power(); Functions["sign"] = new Sign(); Functions["sqrt"] = new Sqrt(); Functions["sqrtpi"] = new SqrtPi(); Functions["pi"] = new Pi(); Functions["product"] = new Product(); Functions["ceiling"] = new Ceiling(); Functions["count"] = new Count(); Functions["counta"] = new CountA(); Functions["countblank"] = new CountBlank(); Functions["countif"] = new CountIf(); Functions["countifs"] = new CountIfs(); Functions["fact"] = new Fact(); Functions["floor"] = new Floor(); Functions["sin"] = new Sin(); Functions["sinh"] = new Sinh(); Functions["sum"] = new Sum(); Functions["sumif"] = new SumIf(); Functions["sumifs"] = new SumIfs(); Functions["sumproduct"] = new SumProduct(); Functions["sumsq"] = new Sumsq(); Functions["stdev"] = new Stdev(); Functions["stdevp"] = new StdevP(); Functions["stdev.s"] = new Stdev(); Functions["stdev.p"] = new StdevP(); Functions["subtotal"] = new Subtotal(); Functions["exp"] = new Exp(); Functions["log"] = new Log(); Functions["log10"] = new Log10(); Functions["ln"] = new Ln(); Functions["max"] = new Max(); Functions["maxa"] = new Maxa(); Functions["median"] = new Median(); Functions["min"] = new Min(); Functions["mina"] = new Mina(); Functions["mod"] = new Mod(); Functions["average"] = new Average(); Functions["averagea"] = new AverageA(); Functions["averageif"] = new AverageIf(); Functions["averageifs"] = new AverageIfs(); Functions["round"] = new Round(); Functions["rounddown"] = new Rounddown(); Functions["roundup"] = new Roundup(); Functions["rand"] = new Rand(); Functions["randbetween"] = new RandBetween(); Functions["rank"] = new Rank(); Functions["rank.eq"] = new Rank(); Functions["rank.avg"] = new Rank(true); Functions["quotient"] = new Quotient(); Functions["trunc"] = new Trunc(); Functions["tan"] = new Tan(); Functions["tanh"] = new Tanh(); Functions["atan"] = new Atan(); Functions["atan2"] = new Atan2(); Functions["atanh"] = new Atanh(); Functions["acos"] = new Acos(); Functions["acosh"] = new Acosh(); Functions["var"] = new Var(); Functions["varp"] = new VarP(); Functions["large"] = new Large(); Functions["small"] = new Small(); Functions["degrees"] = new Degrees(); // Information Functions["isblank"] = new IsBlank(); Functions["isnumber"] = new IsNumber(); Functions["istext"] = new IsText(); Functions["isnontext"] = new IsNonText(); Functions["iserror"] = new IsError(); Functions["iserr"] = new IsErr(); Functions["error.type"] = new ErrorType(); Functions["iseven"] = new IsEven(); Functions["isodd"] = new IsOdd(); Functions["islogical"] = new IsLogical(); Functions["isna"] = new IsNa(); Functions["na"] = new Na(); Functions["n"] = new N(); // Logical Functions["if"] = new If(); Functions["iferror"] = new IfError(); Functions["ifna"] = new IfNa(); Functions["not"] = new Not(); Functions["and"] = new And(); Functions["or"] = new Or(); Functions["true"] = new True(); Functions["false"] = new False(); // Reference and lookup Functions["address"] = new Address(); Functions["hlookup"] = new HLookup(); Functions["vlookup"] = new VLookup(); Functions["lookup"] = new Lookup(); Functions["match"] = new Match(); Functions["row"] = new Row(); Functions["rows"] = new Rows(); Functions["column"] = new Column(); Functions["columns"] = new Columns(); Functions["choose"] = new Choose(); Functions["index"] = new RefAndLookup.Index(); Functions["indirect"] = new Indirect(); Functions["offset"] = new Offset(); // Date Functions["date"] = new Date(); Functions["today"] = new Today(); Functions["now"] = new Now(); Functions["day"] = new Day(); Functions["month"] = new Month(); Functions["year"] = new Year(); Functions["time"] = new Time(); Functions["hour"] = new Hour(); Functions["minute"] = new Minute(); Functions["second"] = new Second(); Functions["weeknum"] = new Weeknum(); Functions["weekday"] = new Weekday(); Functions["days360"] = new Days360(); Functions["yearfrac"] = new Yearfrac(); Functions["edate"] = new Edate(); Functions["eomonth"] = new Eomonth(); Functions["isoweeknum"] = new IsoWeekNum(); Functions["workday"] = new Workday(); Functions["networkdays"] = new Networkdays(); Functions["networkdays.intl"] = new NetworkdaysIntl(); Functions["datevalue"] = new DateValue(); Functions["timevalue"] = new TimeValue(); // Database Functions["dget"] = new Dget(); Functions["dcount"] = new Dcount(); Functions["dcounta"] = new DcountA(); Functions["dmax"] = new Dmax(); Functions["dmin"] = new Dmin(); Functions["dsum"] = new Dsum(); Functions["daverage"] = new Daverage(); Functions["dvar"] = new Dvar(); Functions["dvarp"] = new Dvarp(); //Finance Functions["pmt"] = new Pmt(); }
private static TimeValue[] GetTimeValues(int count, int dayOffset, double phaseOffset) { var array = new TimeValue[count]; var baseDay = new DateTime(2001, 1, 1).AddDays(dayOffset); for (int i = 0; i < array.Length; i++) { array[i] = new TimeValue { Time = baseDay.AddDays(7*i), Value = 100 * (1 + Math.Sin(phaseOffset + (0.2 * i))) }; } return array; }
private void UpdatePoint(GameObject datapoint) { MapDataPoint dataPointScript = datapoint.GetComponent <MapDataPoint>(); Vector2d latLng = new Vector2d(dataPointScript.point.point[1], dataPointScript.point.point[0]); Vector3 pos = map.GeoToWorldPosition(latLng, false); datapoint.transform.position = pos; dataPointScript.ResetPosition(); if (boundingBox.Contains(pos)) { datapoint.SetActive(true); } else { datapoint.SetActive(false); } if (zoomMap != null && zoomMap.activeSelf) { Bounds zoombb = zoomMap.GetComponent <DataHandler>().boundingBox; zoombb.min = new Vector3(zoombb.min.x, transform.position.y - 0.1f, zoombb.min.z); if (zoombb.Contains(pos)) { dataPointScript.muted = true; } else { dataPointScript.muted = false; } } else { dataPointScript.muted = false; } MapDataPoint parameters = datapoint.GetComponent <MapDataPoint>(); var secondaryField = DataLoader.secondaryField; var primaryField = DataLoader.primaryField; TimeValue currentValue = dataPointScript.point.values.Find(el => el.timestamp == date); if (primaryVizualizer != null) { if (currentValue != null) { FieldValue val = currentValue.fields.Find(el => el.id == primaryField.id); if (val != null) { parameters.height = primaryVizualizer.getVizualization(float.Parse(val.value, CultureInfo.InvariantCulture)); } else { parameters.height = 0; } } else { parameters.height = 0; } } else { parameters.height = 1; } if (secondaryDiscreteVizualizer != null && currentValue != null) { FieldValue val = currentValue.fields.Find(el => el.id == secondaryField.id); if (val != null) { parameters.color = secondaryDiscreteVizualizer.getVizualization(val.value); } } else if (rangeColorVizualizer != null && currentValue != null) { FieldValue val = currentValue.fields.Find(el => el.id == secondaryField.id); if (val != null) { parameters.color = rangeColorVizualizer.getVizualization(float.Parse(val.value, CultureInfo.InvariantCulture)); } } }