public static bool isParseCorrect() { NistTime time = new NistTime(); DateTime result = time.ParseNistAnswer("57368 15-12-12 09:11:54 00 0 0 778.9 UTC(NIST) *"); DateTime control = new DateTime(2015, 12, 12, 9, 11, 54, DateTimeKind.Utc); control = control.AddMilliseconds(778.9); return control.Equals(result); }
public List <PostViewModel> LoadPostsGroup(string date, long UserId, long UserLogin) { DateTime createDate = DateTime.UtcNow; if (!string.IsNullOrEmpty(date)) { createDate = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc); createDate = createDate.AddMilliseconds(double.Parse(date)).ToLocalTime(); } var result = (from c in context.Posts join p4 in context.Users on c.UserId equals p4.ID into ps4 from p4 in ps4.DefaultIfEmpty() join p5 in context.Emotions on new { t1 = UserLogin, t2 = c.ID } equals new { t1 = p5.UserId.Value, t2 = p5.TargetId.Value } into ps5 from p5 in ps5.DefaultIfEmpty() let countEmotions = (from E in context.Emotions where E.TargetId == c.ID select E).Count() let countComments = (from C in context.Comments where C.TargetId == c.ID select C).Count() where c.CreatedTime < createDate && (c.TargetId != null && c.TargetId == UserId) && c.TargetType == TypePost.GROUP orderby c.CreatedTime descending select new{ c, p4, countEmotions, p5, countComments }).Take(10).ToList(); var PostView = new List <PostViewModel>(); foreach (var item in result) { if (createDate == item.c.CreatedTime) { continue; } var Post = new PostViewModel(); Post.Id = item.c.ID; Post.Audios = item.c.Audios; Post.Content = item.c.Content; Post.Images = item.c.Images; if (!string.IsNullOrEmpty(item.c.Images)) { var data = item.c.Images.Split(','); Post.ListImages = new List <string>(); foreach (string image in data) { var respone = AmazonS3Uploader.GetUrl(image); if (!string.IsNullOrEmpty(respone)) { Post.ListImages.Add(respone); } } } if (!string.IsNullOrEmpty(item.c.Videos)) { var data = item.c.Videos.Split(','); Post.ListVideos = new List <string>(); foreach (string video in data) { var respone = AmazonS3Uploader.GetUrl(video); if (!string.IsNullOrEmpty(respone)) { Post.ListVideos.Add(respone); } } } if (!string.IsNullOrEmpty(item.c.Audios)) { var data = item.c.Audios.Split(','); Post.ListAudios = new List <string>(); foreach (string audio in data) { var respone = AmazonS3Uploader.GetUrl(audio); if (!string.IsNullOrEmpty(respone)) { Post.ListAudios.Add(respone); } } } Post.Tags = item.c.Tags; Post.TagsUser = item.c.TagsUser; Post.TargetId = item.c.TargetId; Post.TargetType = item.c.TargetType; Post.Type = item.c.Type; Post.CreatedTime = item.c.CreatedTime; Post.UpdateTime = item.c.UpdateTime; Post.UserId = item.c.UserId; Post.NickName = item.p4?.NickName; var responeImage = AmazonS3Uploader.GetUrl(item.p4?.Avatar, 0); if (!string.IsNullOrEmpty(responeImage)) { Post.Avatar = responeImage; } Post.CountEmotions = item.countEmotions; Post.CountComments = item.countComments; Post.StatusEmotion = item.p5 == null ? (byte)0: item.p5.Status; Post.ShowTarget = "hidden"; PostView.Add(Post); } return(PostView); }
public DateTime FromGoogleTime(long unixTime) { var epoch = new DateTime(1601, 1, 1, 0, 0, 0, DateTimeKind.Utc); return(epoch.AddMilliseconds(unixTime).ToLocalTime()); }
// This is called in the script thread to step script until it calls // CheckRun(). It returns what the instance's next state should be, // ONSLEEPQ, ONYIELDQ, SUSPENDED or FINISHED. public XMRInstState RunOne() { DateTime now = DateTime.UtcNow; m_SliceStart = Util.GetTimeStampMS(); // If script has called llSleep(), don't do any more until time is up. m_RunOnePhase = "check m_SleepUntil"; if (m_SleepUntil > now) { m_RunOnePhase = "return is sleeping"; return(XMRInstState.ONSLEEPQ); } // Also, someone may have called Suspend(). m_RunOnePhase = "check m_SuspendCount"; if (m_SuspendCount > 0) { m_RunOnePhase = "return is suspended"; return(XMRInstState.SUSPENDED); } // Make sure we aren't being migrated in or out and prevent that // whilst we are in here. If migration has it locked, don't call // back right away, delay a bit so we don't get in infinite loop. m_RunOnePhase = "lock m_RunLock"; if (!Monitor.TryEnter(m_RunLock)) { m_SleepUntil = now.AddMilliseconds(15); m_RunOnePhase = "return was locked"; return(XMRInstState.ONSLEEPQ); } try { m_RunOnePhase = "check entry invariants"; CheckRunLockInvariants(true); Exception e = null; // Maybe it has been Disposed() if (m_Part == null || m_Part.Inventory == null) { m_RunOnePhase = "runone saw it disposed"; return(XMRInstState.DISPOSED); } if (!m_Running) { m_RunOnePhase = "return is not running"; return(XMRInstState.SUSPENDED); } // Do some more of the last event if it didn't finish. if (this.eventCode != ScriptEventCode.None) { lock (m_QueueLock) { if (m_DetachQuantum > 0 && --m_DetachQuantum == 0) { m_Suspended = true; m_DetachReady.Set(); m_RunOnePhase = "detach quantum went zero"; CheckRunLockInvariants(true); return(XMRInstState.FINISHED); } } m_RunOnePhase = "resume old event handler"; m_LastRanAt = now; m_InstEHSlice++; callMode = CallMode_NORMAL; e = ResumeEx(); } // Otherwise, maybe we can dequeue a new event and start // processing it. else { m_RunOnePhase = "lock event queue"; EventParams evt = null; ScriptEventCode evc = ScriptEventCode.None; lock (m_QueueLock) { // We can't get here unless the script has been resumed // after creation, then suspended again, and then had // an event posted to it. We just pretend there is no // event int he queue and let the normal mechanics // carry out the suspension. A Resume will handle the // restarting gracefully. This is taking the easy way // out and may be improved in the future. if (m_Suspended) { m_RunOnePhase = "m_Suspended is set"; CheckRunLockInvariants(true); return(XMRInstState.FINISHED); } m_RunOnePhase = "dequeue event"; if (m_EventQueue.First != null) { evt = m_EventQueue.First.Value; m_eventCodeMap.TryGetValue(evt.EventName, out evc); if (m_DetachQuantum > 0) { if (evc != ScriptEventCode.attach) { // This is the case where the attach event // has completed and another event is queued // Stop it from running and suspend m_Suspended = true; m_DetachReady.Set(); m_DetachQuantum = 0; m_RunOnePhase = "nothing to do #3"; CheckRunLockInvariants(true); return(XMRInstState.FINISHED); } } m_EventQueue.RemoveFirst(); if (evc >= 0) { m_EventCounts[(int)evc]--; } } // If there is no event to dequeue, don't run this script // until another event gets queued. if (evt == null) { if (m_DetachQuantum > 0) { // This will happen if the attach event has run // and exited with time slice left. m_Suspended = true; m_DetachReady.Set(); m_DetachQuantum = 0; } m_RunOnePhase = "nothing to do #4"; CheckRunLockInvariants(true); return(XMRInstState.FINISHED); } } // Dequeued an event, so start it going until it either // finishes or it calls CheckRun(). m_RunOnePhase = "start event handler"; m_DetectParams = evt.DetectParams; m_LastRanAt = now; m_InstEHEvent++; e = StartEventHandler(evc, evt.Params); } m_RunOnePhase = "done running"; m_CPUTime += DateTime.UtcNow.Subtract(now).TotalMilliseconds; // Maybe it puqued. if (e != null) { m_RunOnePhase = "handling exception " + e.Message; HandleScriptException(e); m_RunOnePhase = "return had exception " + e.Message; CheckRunLockInvariants(true); return(XMRInstState.FINISHED); } // If event handler completed, get rid of detect params. if (this.eventCode == ScriptEventCode.None) { m_DetectParams = null; } } finally { m_RunOnePhase += "; checking exit invariants and unlocking"; CheckRunLockInvariants(false); Monitor.Exit(m_RunLock); } // Cycle script through the yield queue and call it back asap. m_RunOnePhase = "last return"; return(XMRInstState.ONYIELDQ); }
private static DateTime FromUnixTime(long unixTimeMillis) { return(unixTimeMillis == Long.MinValue ? _epoch : _epoch.AddMilliseconds(unixTimeMillis)); }
public static DateTime DateTimeFromMilliseconds(long millis) { return(LocalFirstDay1970.AddMilliseconds(millis)); }
public void dowork(string logFile, string dirWithImages, float offsetseconds, bool dooffset) { DateTime localmin = DateTime.MaxValue; DateTime localmax = DateTime.MinValue; DateTime startTime = DateTime.MinValue; photocoords = new Hashtable(); timecoordcache = new Hashtable(); imagetotime = new Hashtable(); //logFile = @"C:\Users\hog\Pictures\farm 1-10-2011\100SSCAM\2011-10-01 11-48 1.log"; List <string[]> list = readLog(logFile); //dirWithImages = @"C:\Users\hog\Pictures\farm 1-10-2011\100SSCAM"; string[] files = Directory.GetFiles(dirWithImages); Document kml = new Document(); StreamWriter sw4 = new StreamWriter(dirWithImages + Path.DirectorySeparatorChar + "loglocation.csv"); StreamWriter sw3 = new StreamWriter(dirWithImages + Path.DirectorySeparatorChar + "location.kml"); StreamWriter sw2 = new StreamWriter(dirWithImages + Path.DirectorySeparatorChar + "location.txt"); StreamWriter sw = new StreamWriter(dirWithImages + Path.DirectorySeparatorChar + "location.tel"); sw.WriteLine("version=1"); sw.WriteLine("#seconds offset - " + TXT_offsetseconds.Text); sw.WriteLine("#longitude and latitude - in degrees"); sw.WriteLine("#name utc longitude latitude height"); int first = 0; int matchs = 0; int lastmatchindex = 0; foreach (string filename in files) { if (filename.ToLower().EndsWith(".jpg") && !filename.ToLower().Contains("_geotag")) { DateTime photodt = getPhotoTime(filename); if (startTime == DateTime.MinValue) { startTime = new DateTime(photodt.Year, photodt.Month, photodt.Day, 0, 0, 0, 0, DateTimeKind.Utc).ToLocalTime(); foreach (string[] arr in list) { DateTime crap = startTime.AddMilliseconds(int.Parse(arr[1])).AddSeconds(offsetseconds); if (localmin > crap) { localmin = crap; } if (localmax < crap) { localmax = crap; } } log.InfoFormat("min " + localmin + " max " + localmax); TXT_outputlog.AppendText("Log min " + localmin + " max " + localmax + "\r\n"); } TXT_outputlog.AppendText("Photo " + Path.GetFileNameWithoutExtension(filename) + " time " + photodt + "\r\n"); //Application.DoEvents(); int a = 0; foreach (string[] arr in list) { a++; if (lastmatchindex > (a)) { continue; } //Application.DoEvents(); DateTime logdt = startTime.AddMilliseconds(int.Parse(arr[1])).AddSeconds(offsetseconds); if (first == 0) { TXT_outputlog.AppendText("Photo " + Path.GetFileNameWithoutExtension(filename) + " " + photodt + " vs Log " + logdt + "\r\n"); TXT_outputlog.AppendText("offset should be about " + (photodt - logdt).TotalSeconds + "\r\n"); if (dooffset) { return; } first++; } //Console.Write("ph " + dt + " log " + crap + " \r"); timecoordcache[(long)(logdt.AddSeconds(-offsetseconds) - DateTime.MinValue).TotalSeconds] = new double[] { double.Parse(arr[latpos]), double.Parse(arr[lngpos]), double.Parse(arr[altpos]) }; sw4.WriteLine("ph " + filename + " " + photodt + " log " + logdt); if (photodt.ToString("yyyy-MM-ddTHH:mm:ss") == logdt.ToString("yyyy-MM-ddTHH:mm:ss")) { lastmatchindex = a; TXT_outputlog.AppendText("MATCH Photo " + Path.GetFileNameWithoutExtension(filename) + " " + photodt + "\r\n"); matchs++; SharpKml.Dom.Timestamp tstamp = new SharpKml.Dom.Timestamp(); tstamp.When = photodt; kml.AddFeature( new Placemark() { Time = tstamp, Name = Path.GetFileNameWithoutExtension(filename), Geometry = new SharpKml.Dom.Point() { Coordinate = new Vector(double.Parse(arr[latpos]), double.Parse(arr[lngpos]), double.Parse(arr[altpos])) }, Description = new Description() { Text = "<table><tr><td><img src=\"" + Path.GetFileName(filename).ToLower() + "\" width=500 /></td></tr></table>" }, StyleSelector = new Style() { Balloon = new BalloonStyle() { Text = "$[name]<br>$[description]" } } } ); photocoords[filename] = new double[] { double.Parse(arr[latpos]), double.Parse(arr[lngpos]), double.Parse(arr[altpos]), double.Parse(arr[cogpos]) }; imagetotime[filename] = (long)(logdt.AddSeconds(-offsetseconds) - DateTime.MinValue).TotalSeconds; sw2.WriteLine(Path.GetFileNameWithoutExtension(filename) + " " + arr[lngpos] + " " + arr[latpos] + " " + arr[altpos]); sw.WriteLine(Path.GetFileNameWithoutExtension(filename) + "\t" + logdt.ToString("yyyy:MM:dd HH:mm:ss") + "\t" + arr[lngpos] + "\t" + arr[latpos] + "\t" + arr[altpos]); sw.Flush(); sw2.Flush(); log.InfoFormat(Path.GetFileNameWithoutExtension(filename) + " " + arr[lngpos] + " " + arr[latpos] + " " + arr[altpos] + " "); break; } //Console.WriteLine(crap); } } } Serializer serializer = new Serializer(); serializer.Serialize(kml); sw3.Write(serializer.Xml); sw3.Close(); MainV2.instance.georefkml = serializer.Xml; writeGPX(dirWithImages + Path.DirectorySeparatorChar + "location.gpx"); sw4.Close(); sw2.Close(); sw.Close(); TXT_outputlog.AppendText("Done " + matchs + " matchs"); }
public DateTime GetTime(ulong timeMs) { return(startTime.AddMilliseconds(timeMs)); }
public void timer() { Control.CheckForIllegalCrossThreadCalls = false; videopos = startlogtime.AddMilliseconds(-startlogtime.Millisecond); hud1.SixteenXNine = true; while (true) { try { // GC.Collect(); // long mem = GC.GetTotalMemory(true) / 1024 / 1024; // Console.WriteLine("mem "+mem); System.Threading.Thread.Sleep(20); // 25 fps if (flightdata.Count == 0) { break; } // videopos = videopos.AddMilliseconds(1000 / 25); // m_mediaseek = m_FilterGraph as IMediaSeeking; // m_mediapos.put_CurrentPosition((vidpos - startlogtime).TotalSeconds); //m_mediaseek.SetTimeFormat(TimeFormat.MediaTime); //long poscurrent = 0; //long posend = 0; // m_mediaseek.GetPositions(out poscurrent,out posend); DateTime cstimestamp = videopos.AddSeconds(trackBar1.Value).AddMilliseconds(-(videopos.Millisecond % 20)); int tb = trackBar1.Value; if (flightdata.ContainsKey(cstimestamp)) { cs = flightdata[cstimestamp]; } else if (flightdata.ContainsKey(cstimestamp.AddMilliseconds(-20))) { cs = flightdata[cstimestamp.AddMilliseconds(-20)]; } else if (flightdata.ContainsKey(cstimestamp.AddMilliseconds(-40))) { cs = flightdata[cstimestamp.AddMilliseconds(-40)]; } // Console.WriteLine("Update CS"); Console.WriteLine("log " + cs.datetime); hud1.datetime = cs.datetime; cs.UpdateCurrentSettings(bindingSource1); } catch (ThreadAbortException) { break; } catch { } } }
public void HasInsideDateTimeTest() { TimeInterval timeInterval = new TimeInterval(start, end); Assert.AreEqual(timeInterval.End, end); // start Assert.IsFalse(timeInterval.HasInside(start.AddMilliseconds(-1))); Assert.IsTrue(timeInterval.HasInside(start)); Assert.IsTrue(timeInterval.HasInside(start.AddMilliseconds(1))); // end Assert.IsTrue(timeInterval.HasInside(end.AddMilliseconds(-1))); Assert.IsTrue(timeInterval.HasInside(end)); Assert.IsFalse(timeInterval.HasInside(end.AddMilliseconds(1))); }
void Run() { for (int i = 0; i < PumpThreads.Length; i++) { PumpStart[i] = new AutoResetEvent(false); PumpEnd[i] = new AutoResetEvent(false); int index = i; PumpThreads[i] = new Thread(() => PumpThread(index)); // re-assign i so it is preserved PumpThreads[i].Name = "Pump Thread: " + i.ToString(); PumpThreads[i].Start(); } while (true) { if (Shutdown) { PumpStart.ForEach(e => e.Set()); return; } if (Paused && !Step) { Thread.Sleep(250); continue; } // load users if (Flux) { DoFlux(); } // pump packets, 4 times (250ms latency while (CurrentPump < PumpsPerSec) { for (int i = 0; i < OutPackets.Length; i++) { lock (OutPackets[i]) { InPackets[i] = OutPackets[i]; OutPackets[i] = new List <SimPacket>(); } } // tell all pump threads to go and wait for them to complete PumpStart.ForEach(e => e.Set()); AutoResetEvent.WaitAll(PumpEnd); TimeNow = TimeNow.AddMilliseconds(1000 / PumpsPerSec); if (UpdateView != null) { UpdateView(); } CurrentPump++; if (Step) { Step = false; break; } } CurrentPump = 0; // if run sim slow if (SleepTime > 0) { Thread.Sleep(SleepTime); } } }
private void mainTimer_Tick(object sender, EventArgs e) { bool done = false; bool isjumpNext = jumpNext; while (!done) { currentTime = currentTime.AddMilliseconds(speedFactorIncr);// = new DateTime(DateTime.Now.Subtract(refTime).Add(new TimeSpan(startTime.Ticks)).Ticks); currentTextBox.Text = currentTime.ToLongTimeString(); int nowsec = (int)(new TimeSpan(currentTime.Hour, currentTime.Minute, currentTime.Second).TotalSeconds); int tickTime = nowsec - _worker.ZeroTime; List <object[]> lo = _worker.tick(tickTime); if (lo.Count > 0) { foreach (object[] oo in lo) { runner r = oo[0] as runner; //oo[0] runner //oo[1] punchesok (si plusieurs) // ou //oo[0] runner a fini if (oo.Length == 2) { List <int[]> pok = oo[1] as List <int[]>; foreach (int[] p in pok) { // cherchons si ce poste est checké ! string info = currentTime.ToLongTimeString() + "\t" + p[0].ToString() + "\t" + r.Name; logFullTextBox.AppendText(info); int index = _checkedRadio.IndexOf(p[0]); if (index >= 0) { done = true; int timeCode = (p[1] + _worker.ZeroTime) * 10; _actionToDo.Enqueue(new object[] { actionType.ePunch, p[0], r.CardNo, timeCode, info + "\t* RADIO *" + Environment.NewLine }); logFullTextBox.AppendText("\t* RADIO *"); //_sender.sendPunch(p[0], r.CardNo, timeCode); //logTextBox.AppendText(currentTime.ToLongTimeString() + "\t" + p[0].ToString() + "\t" + r.Name + "\t* RADIO *" + Environment.NewLine); } logFullTextBox.AppendText(Environment.NewLine); } } else if (oo.Length == 1) { done = true; //_sender.sendCard(r.CardNo, r.Card.Punches, _worker.ZeroTime); string info = currentTime.ToLongTimeString() + "\t" + r.Name + "\t* FINISH **********" + Environment.NewLine; logFullTextBox.AppendText(info); _actionToDo.Enqueue(new object[] { actionType.eCard, r.CardNo, r.Card.Punches, _worker.ZeroTime, info }); //logTextBox.AppendText(currentTime.ToLongTimeString() + "\t" + r.Name + "\t* FINISH *" + Environment.NewLine); } } } if (currentTime.CompareTo(stopTime) > 0) { done = true; stopButton_Click(null, null); } if (!isjumpNext) { done = true;// on attendra la suite } if (!isjumpNext) { Application.DoEvents(); } } if (isjumpNext) { jumpNext = false; } }
public static DateTime ReadEpochMilliseconds( this BitReader bitReader) { return(_epoch.AddMilliseconds(bitReader.ReadVariableUInt64())); }
// Simple Handler for receiving the reader events from the reader static void reader_OnReaderEventNotification(MSG_READER_EVENT_NOTIFICATION msg) { // Events could be empty if (msg.ReaderEventNotificationData == null) { return; } // Just write out the LTK-XML for now eventCount++; // speedway readers always report UTC timestamp UNION_Timestamp t = msg.ReaderEventNotificationData.Timestamp; PARAM_UTCTimestamp ut = (PARAM_UTCTimestamp)t[0]; double millis = (ut.Microseconds + 500) / 1000; // LLRP reports time in microseconds relative to the Unix Epoch DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); DateTime now = epoch.AddMilliseconds(millis); Console.WriteLine("======Reader Event " + eventCount.ToString() + "======" + now.ToString("O")); // this is how you would look for individual events of interest // Here I just dump the event if (msg.ReaderEventNotificationData.AISpecEvent != null) { Console.WriteLine(msg.ReaderEventNotificationData.AISpecEvent.ToString()); } if (msg.ReaderEventNotificationData.AntennaEvent != null) { Console.WriteLine(msg.ReaderEventNotificationData.AntennaEvent.ToString()); } if (msg.ReaderEventNotificationData.ConnectionAttemptEvent != null) { Console.WriteLine(msg.ReaderEventNotificationData.ConnectionAttemptEvent.ToString()); } if (msg.ReaderEventNotificationData.ConnectionCloseEvent != null) { Console.WriteLine(msg.ReaderEventNotificationData.ConnectionCloseEvent.ToString()); } if (msg.ReaderEventNotificationData.GPIEvent != null) { Console.WriteLine(msg.ReaderEventNotificationData.GPIEvent.ToString()); } if (msg.ReaderEventNotificationData.HoppingEvent != null) { Console.WriteLine(msg.ReaderEventNotificationData.HoppingEvent.ToString()); } if (msg.ReaderEventNotificationData.ReaderExceptionEvent != null) { Console.WriteLine(msg.ReaderEventNotificationData.ReaderExceptionEvent.ToString()); } if (msg.ReaderEventNotificationData.ReportBufferLevelWarningEvent != null) { Console.WriteLine(msg.ReaderEventNotificationData.ReportBufferLevelWarningEvent.ToString()); } if (msg.ReaderEventNotificationData.ReportBufferOverflowErrorEvent != null) { Console.WriteLine(msg.ReaderEventNotificationData.ReportBufferOverflowErrorEvent.ToString()); } if (msg.ReaderEventNotificationData.ROSpecEvent != null) { Console.WriteLine(msg.ReaderEventNotificationData.ROSpecEvent.ToString()); } }
public static DateTime FromMillisecondsSinceUnixEpoch(long milliseconds) { return(UnixEpoch.AddMilliseconds(milliseconds)); }
internal void MarkIdle(DateTime idleSince) { m_ExpiresAt = idleSince.AddMilliseconds(m_MaxIdleTime); }
private void AddRow(string key, string family, string column, string value, long?timestamp) { var row = new DataListRowModel(); if ((_lastKeyRow == null) || (key != _lastKeyRow.Key)) { row.Key = key; row.KeyRowSpan = 1; _lastKeyRow = row; _lastFamilyRow = null; _lastColumnRow = null; _lastTimeStampRow = null; } else { _lastKeyRow.KeyRowSpan += 1; } if ((_lastFamilyRow == null) || (family != _lastFamilyRow.Family)) { row.Family = family ?? "n/a"; row.FamilyRowSpan = 1; _lastFamilyRow = row; _lastColumnRow = null; } else { _lastFamilyRow.FamilyRowSpan += 1; } if ((_lastColumnRow == null) || (column != _lastColumnRow.Column)) { row.Column = column ?? "n/a"; row.ColumnRowSpan = 1; _lastColumnRow = row; } else { _lastColumnRow.ColumnRowSpan += 1; } if (timestamp.HasValue) { var millis = timestamp.Value; // TODO - look at the table info to know if timestamp is micro- or nano- (or milli-?) seconds millis /= 1000; // for now, assume microseconds var tstring = UnixEpoch.AddMilliseconds(millis).ToString("dd-MMM-yyyy HH:mm:ss.fff K"); if ((_lastTimeStampRow == null) || (tstring != _lastTimeStampRow.TimeStamp)) { row.TimeStamp = tstring; row.TimeStampRowSpan = 1; _lastTimeStampRow = row; } else { _lastTimeStampRow.TimeStampRowSpan += 1; } } else { _lastTimeStampRow = null; } row.Value = value; _rows.Add(row); }
public DateTime LocalToServerTime(DateTime localTime) { return(localTime.AddMilliseconds(ServerTimeOffsetMS)); }
public IEnumerable <Flight> GetFlights() { if (flights == null) { flights = new List <Model.Flight>(); int min = int.MaxValue; int max = int.MinValue; // mavlink_servo_output_raw_t is an actual PWM signal, so it toggles between RC0_TRIM (usually 1500) and the // values it is sending to the motor, so we have to weed out the trim values in order to see the actual // values. int trim = 1500; // should get this from the parameter values. // compute the min/max servo settings. foreach (var msg in this.data) { if (msg.TypedValue is MAVLink.mavlink_servo_output_raw_t) { MAVLink.mavlink_servo_output_raw_t servo = (MAVLink.mavlink_servo_output_raw_t)msg.TypedValue; if (servo.servo1_raw != 0 && servo.servo1_raw != trim) { min = Math.Min(min, servo.servo1_raw); max = Math.Max(max, servo.servo1_raw); } } } // find flights DateTime start = this.startTime; DateTime endTime = start; Flight current = null; int offCount = 0; // compute the min/max servo settings. foreach (var msg in this.data) { if (msg.TypedValue is MAVLink.mavlink_servo_output_raw_t) { MAVLink.mavlink_servo_output_raw_t servo = (MAVLink.mavlink_servo_output_raw_t)msg.TypedValue; endTime = start.AddMilliseconds(servo.time_usec / 1000); if (servo.servo1_raw != trim) { if (servo.servo1_raw > min) { if (current == null) { current = new Flight() { Log = this, StartTime = start.AddMilliseconds(servo.time_usec / 1000) }; flights.Add(current); offCount = 0; } } else if (servo.servo1_raw == min && offCount++ > 10) { if (current != null) { current.Duration = endTime - current.StartTime; current = null; } } } } } if (current != null) { current.Duration = endTime - current.StartTime; } } return(flights); }
public DateTime ServerToLocalTime(DateTime serverTime) { return(serverTime.AddMilliseconds(-ServerTimeOffsetMS)); }
public DFItem GetDFItemFromLine(string line, int lineno) { //line = line.Replace(",", ","); //line = line.Replace(":", ":"); string[] items = line.Trim().Split(new char[] { ',', ':' }, StringSplitOptions.RemoveEmptyEntries); if (line.StartsWith("FMT")) { FMTLine(line); } else if (line.StartsWith("GPS")) { if (line.StartsWith("GPS") && gpsstarttime == DateTime.MinValue) { var time = GetTimeGPS(line); if (time != DateTime.MinValue) { gpsstarttime = time; lasttime = gpsstarttime; int indextimems = FindMessageOffset(items[0], "T"); if (indextimems != -1) { try { msoffset = int.Parse(items[indextimems]); } catch { gpsstarttime = DateTime.MinValue; } } int indextimeus = FindMessageOffset(items[0], "TimeUS"); if (indextimeus != -1) { try { msoffset = long.Parse(items[indextimeus]) / 1000; } catch { gpsstarttime = DateTime.MinValue; } } } } } else if (line.StartsWith("ERR")) { Array.Resize(ref items, items.Length + 2); try { int index = FindMessageOffset("ERR", "Subsys"); if (index == -1) { throw new ArgumentNullException(); } int index2 = FindMessageOffset("ERR", "ECode"); if (index2 == -1) { throw new ArgumentNullException(); } items[items.Length - 2] = "" + (DFLog.error_subsystem) int.Parse(items[index]); } catch { } } else if (line.StartsWith("EV")) { Array.Resize(ref items, items.Length + 1); try { int index = FindMessageOffset("EV", "Id"); if (index == -1) { throw new ArgumentNullException(); } items[items.Length - 1] = "" + (DFLog.events) int.Parse(items[index]); } catch { } } else if (line.StartsWith("MAG")) { } DFItem item = new DFItem() { parent = this }; try { item.lineno = lineno; if (items.Length > 0) { item.msgtype = items[0]; item.items = items; bool timeus = false; if (logformat.ContainsKey(item.msgtype)) { int indextimems = FindMessageOffset(item.msgtype, "TimeMS"); if (item.msgtype.StartsWith("GPS")) { indextimems = FindMessageOffset(item.msgtype, "T"); } if (indextimems == -1) { indextimems = FindMessageOffset(item.msgtype, "TimeUS"); timeus = true; } if (indextimems != -1) { long ntime = 0; if (long.TryParse(items[indextimems], out ntime)) { if (timeus) { ntime /= 1000; } item.timems = (int)ntime; if (gpsstarttime != DateTime.MinValue) { item.time = gpsstarttime.AddMilliseconds(item.timems - msoffset); lasttime = item.time; } } else { item.time = lasttime; } } else { item.time = lasttime; } } } } catch { } return(item); }
public FileInfo() { this.lastModifiedDate = new Lazy <DateTime?>(() => LastModified == null ? null : (DateTime?)Epoch.AddMilliseconds(this.LastModified.Value)); }
public new void Update() { treeView1.BeginUpdate(); bool added = false; foreach (var mavLinkMessage in mavi.GetPacketMessages()) { TreeNode sysidnode; TreeNode compidnode; TreeNode msgidnode; var sysidnodes = treeView1.Nodes.Find(mavLinkMessage.sysid.ToString(), false); if (sysidnodes.Length == 0) { sysidnode = new TreeNode("Vehicle " + mavLinkMessage.sysid) { Name = mavLinkMessage.sysid.ToString() }; treeView1.Nodes.Add(sysidnode); added = true; } else { sysidnode = sysidnodes.First(); } var compidnodes = sysidnode.Nodes.Find(mavLinkMessage.compid.ToString(), false); if (compidnodes.Length == 0) { compidnode = new TreeNode("Comp " + mavLinkMessage.compid) { Name = mavLinkMessage.compid.ToString() }; sysidnode.Nodes.Add(compidnode); added = true; } else { compidnode = compidnodes.First(); } var msgidnodes = compidnode.Nodes.Find(mavLinkMessage.msgid.ToString(), false); if (msgidnodes.Length == 0) { msgidnode = new TreeNode(mavLinkMessage.msgtypename) { Name = mavLinkMessage.msgid.ToString() }; compidnode.Nodes.Add(msgidnode); added = true; } else { msgidnode = msgidnodes.First(); } var msgidheader = mavLinkMessage.msgtypename + " (" + (mavi.SeenRate(mavLinkMessage.sysid, mavLinkMessage.compid, mavLinkMessage.msgid)) .ToString("0.0 Hz") + ", #" + mavLinkMessage.msgid + ") " + mavi.SeenBps(mavLinkMessage.sysid, mavLinkMessage.compid, mavLinkMessage.msgid).ToString("0bps"); if (msgidnode.Text != msgidheader) { msgidnode.Text = msgidheader; } var minfo = MAVLink.MAVLINK_MESSAGE_INFOS.GetMessageInfo(mavLinkMessage.msgid); if (minfo.@type == null) { continue; } foreach (var field in minfo.type.GetFields()) { if (!msgidnode.Nodes.ContainsKey(field.Name)) { msgidnode.Nodes.Add(new TreeNode() { Name = field.Name }); added = true; } object value = field.GetValue(mavLinkMessage.data); if (field.Name == "time_unix_usec") { DateTime date1 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); try { value = date1.AddMilliseconds((ulong)value / 1000); } catch { } } if (field.FieldType.IsArray) { var subtype = value.GetType(); var value2 = (Array)value; if (field.Name == "param_id") // param_value { value = ASCIIEncoding.ASCII.GetString((byte[])value2); } else if (field.Name == "text") // statustext { value = ASCIIEncoding.ASCII.GetString((byte[])value2); } else { value = value2.Cast <object>().Aggregate((a, b) => a + "," + b); } } msgidnode.Nodes[field.Name].Text = (String.Format("{0,-32} {1,20} {2,-20}", field.Name, value, field.FieldType.ToString())); } } if (added) { treeView1.Sort(); } treeView1.EndUpdate(); }
public static DateTime FromJSDate(long dateMillisecondsAfter1970) { DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); return(dateTime.AddMilliseconds(dateMillisecondsAfter1970)); }
/// <summary> /// Converts an Android long value of milliseconds since 1970 to a System.DateTime /// </summary> /// <returns>The System.DateTime.</returns> /// <param name="ms">Source date as milliseconds since 1970.</param> public static DateTime GetDateFromAndroidMS(long ms) { return(_reference.AddMilliseconds(ms).ToLocalTime()); }
public static void Collect() { try { get_CounterCurrentFrame(); get_GameTick(); get_isInGame(); get_BTag(); if (A_Collection.Me.HeroStates.isInGame && A_Collection.Environment.Scene.GameTick > 1 && A_Collection.Environment.Scene.Counter_CurrentFrame != 0) { get_LocalACD(); if (A_Collection.Me.HeroGlobals.LocalACD != null) { get_LocalPlayerData(); get_SelectedAttackableACD(); get_Hero(); if (_lastLVL.AddMilliseconds(1000) <= DateTime.Now) { get_Lvl(); _lastLVL = DateTime.Now; } get_Hitpoints(); if (_lastAPS.AddMilliseconds(500) <= DateTime.Now) { get_AttackPerSecondTotal(); _lastAPS = DateTime.Now; } get_ResourcePrimary(); get_ResourceSecondary(); get_ActivePowers(); if (_lastTotalXP.AddMilliseconds(1000) <= DateTime.Now) { get_TotalXP(); _lastTotalXP = DateTime.Now; } get_LocalDataIndex(); if (_lastPlayersInGame.AddMilliseconds(1000) <= DateTime.Now) { get_PlayersInGame(); _lastPlayersInGame = DateTime.Now; } if (Properties.Settings.Default.overlayconventiondraws) { get_ConventionElement(); } get_isUsingPower(); get_isInTown(); get_isMoving(); get_isTeleporting(); get_isResuracting(); get_isInParty(); get_isAlive(); observe_HealthPotion(); } } } catch (Exception e) { A_Handler.Log.Exception.addExceptionLogEntry(e, A_Enums.ExceptionThread.ICollector); } }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var t = (long)reader.Value; return(BaseDate.AddMilliseconds(t / 1000)); }
public bool IsDirty(DateTime timeStamp) { return(LastChangeDate > timeStamp.AddMilliseconds(0.5)); }
public List <PostViewModel> LoadPostsHome(string date, long UserId) { DateTime createDate = DateTime.UtcNow; if (!string.IsNullOrEmpty(date)) { createDate = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc); createDate = createDate.AddMilliseconds(double.Parse(date)).ToLocalTime(); } var result = (from c in context.Posts join p1 in context.Relationships on new { t1 = UserId, t2 = c.TargetId.Value } equals new { t1 = p1.UserSentID, t2 = p1.UserReceiveID } into ps1 from p1 in ps1.DefaultIfEmpty() join p2 in context.Relationships on new { t1 = UserId, t2 = c.TargetId.Value } equals new { t1 = p2.UserReceiveID, t2 = p2.UserSentID } into ps2 from p2 in ps2.DefaultIfEmpty() join p3 in context.GroupMembers on new { t1 = UserId, t2 = c.TargetId.Value } equals new { t1 = p3.UserId, t2 = p3.GroupID } into ps3 from p3 in ps3.DefaultIfEmpty() join p4 in context.Users on c.UserId equals p4.ID into ps4 from p4 in ps4.DefaultIfEmpty() join p5 in context.Emotions on new { t1 = UserId, t2 = c.ID } equals new { t1 = p5.UserId.Value, t2 = p5.TargetId.Value } into ps5 from p5 in ps5.DefaultIfEmpty() join p6 in context.Groups on new { t1 = c.TargetType.Value, t2 = c.TargetId.Value } equals new { t1 = TypePost.GROUP, t2 = p6.ID } into ps6 from p6 in ps6.DefaultIfEmpty() join p7 in context.Users on new { t1 = c.TargetType.Value, t2 = c.TargetId.Value } equals new { t1 = TypePost.USER, t2 = p7.ID } into ps7 from p7 in ps7.DefaultIfEmpty() let countEmotions = (from E in context.Emotions where E.TargetId == c.ID select E).Count() let countComments = (from C in context.Comments where C.TargetId == c.ID select C).Count() where c.CreatedTime < createDate && (((c.TargetId == p1.UserReceiveID || c.TargetId == UserId || c.TargetId == p2.UserSentID) && c.TargetType == TypePost.USER) || (c.TargetId == p3.GroupID && c.TargetType == TypePost.GROUP) || (c.UserId == c.TargetId && c.UserId == 21 && c.TargetType == TypePost.USER)) orderby c.CreatedTime descending select new{ c, p1, p2, p3, p4, countEmotions, p5, countComments, p6, p7 }).Take(10).ToList(); var PostView = new List <PostViewModel>(); foreach (var item in result) { if (createDate == item.c.CreatedTime) { continue; } var Post = new PostViewModel(); Post.Id = item.c.ID; Post.Audios = item.c.Audios; Post.Content = item.c.Content; Post.Images = item.c.Images; if (!string.IsNullOrEmpty(item.c.Images)) { var data = item.c.Images.Split(','); Post.ListImages = new List <string>(); foreach (string image in data) { var respone = AmazonS3Uploader.GetUrl(image); if (!string.IsNullOrEmpty(respone)) { Post.ListImages.Add(respone); } } } if (!string.IsNullOrEmpty(item.c.Videos)) { var data = item.c.Videos.Split(','); Post.ListVideos = new List <string>(); foreach (string video in data) { var respone = AmazonS3Uploader.GetUrl(video); if (!string.IsNullOrEmpty(respone)) { Post.ListVideos.Add(respone); } } } if (!string.IsNullOrEmpty(item.c.Audios)) { var data = item.c.Audios.Split(','); Post.ListAudios = new List <string>(); foreach (string audio in data) { var respone = AmazonS3Uploader.GetUrl(audio); if (!string.IsNullOrEmpty(respone)) { Post.ListAudios.Add(respone); } } } Post.Tags = item.c.Tags; Post.TagsUser = item.c.TagsUser; Post.TargetId = item.c.TargetId; Post.TargetType = item.c.TargetType; Post.Type = item.c.Type; Post.CreatedTime = item.c.CreatedTime; Post.UpdateTime = item.c.UpdateTime; Post.UserId = item.c.UserId; var responeImage = AmazonS3Uploader.GetUrl(item.p4?.Avatar, 0); if (!string.IsNullOrEmpty(responeImage)) { Post.Avatar = responeImage; } responeImage = AmazonS3Uploader.GetUrl(item.p6 == null ? item.p7.Avatar : item.p6.Avatar, 0); if (!string.IsNullOrEmpty(responeImage)) { Post.TargetAvatar = responeImage; } Post.NickName = item.p4?.NickName; Post.TargetNickName = item.p6 == null ? item.p7.NickName : item.p6.GroupName; Post.TargetUrl = item.p6 == null ? "profile" : "group"; Post.CountEmotions = item.countEmotions; Post.CountComments = item.countComments; Post.StatusEmotion = item.p5 == null ? (byte)0: item.p5.Status; Post.ShowTarget = Post.UserId != Post.TargetId || item.c.TargetType != TypePost.USER ? "" : "hidden"; PostView.Add(Post); } return(PostView); }
public static DateTime ToDateTime(this Java.Util.Date date) { var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); return(epoch.AddMilliseconds(date.Time)); }
public static List <string[]> getUserStoryList(ICollection <YouTrackSharp.Issues.Issue> Issues) { DateTime StartDate = new DateTime(1970, 1, 1, 0, 0, 0, 0); List <string[]> UserStoryList = new List <string[]>(); UserStoryList.Add(new string[] { "UserStory", "Summary", "projectShortName", "Assignee", "State", "SpentTime", "Estimation", "Type", "StoryPoint", "Version", "PBRItem", "Created", "Resolved" }); string SpentTime; string FullName; string projectShortName; string State; string Estimation; string Type; string StoryPoint; string Version; string PBRItem; string Created; string Resolved; foreach (YouTrackSharp.Issues.Issue issue in Issues) { projectShortName = issue.Fields.Where(x => x.Name == "projectShortName").Select(x => x.Value).First().ToString(); State = ((List <string>)issue.Fields.Where(x => x.Name == "State").Select(x => x.Value).First()).First(); Type = ((List <string>)issue.Fields.Where(x => x.Name == "Type").Select(x => x.Value).First()).First(); Created = StartDate.AddMilliseconds(Convert.ToDouble(issue.Fields.Where(x => x.Name == "created").Select(x => x.Value).First().ToString())).ToString(); if (issue.Fields.Where(x => x.Name == "resolved").Select(x => x.Value).Any()) { Resolved = StartDate.AddMilliseconds(Convert.ToDouble(issue.Fields.Where(x => x.Name == "resolved").Select(x => x.Value).First().ToString())).ToString(); } else { Resolved = ""; } if (issue.Fields.Where(x => x.Name == "Story points").Select(x => x.Value).Any()) { StoryPoint = ((List <string>)issue.Fields.Where(x => x.Name == "Story points").Select(x => x.Value).FirstOrDefault()).FirstOrDefault(); } else { StoryPoint = "0"; } if (issue.Fields.Where(x => x.Name == "Version").Select(x => x.Value).Any()) { Version = ((List <string>)issue.Fields.Where(x => x.Name == "Version").Select(x => x.Value).FirstOrDefault()).FirstOrDefault(); } else { Version = ""; } if (issue.Fields.Where(x => x.Name == "Spent time").Select(x => x.Value).Any()) { SpentTime = ((List <string>)issue.Fields.Where(x => x.Name == "Spent time").Select(x => x.Value).FirstOrDefault()).FirstOrDefault(); } else { SpentTime = "0"; } if (issue.Fields.Where(x => x.Name == "Estimation").Select(x => x.Value).Any()) { Estimation = ((List <string>)issue.Fields.Where(x => x.Name == "Estimation").Select(x => x.Value).FirstOrDefault()).FirstOrDefault() ?? ""; } else { Estimation = "0"; } if (issue.Fields.Where(x => x.Name == "Assignee").Select(x => x.Value).Any()) { FullName = ((List <YouTrackSharp.Issues.Assignee>)issue.Fields.Where(x => x.Name == "Assignee").Select(x => x.Value).First()).First().FullName; } else { FullName = ""; } if (issue.Fields.Where(x => x.Name == "PBR item").Select(x => x.Value).Any()) { PBRItem = ((List <string>)issue.Fields.Where(x => x.Name == "PBR item").Select(x => x.Value).FirstOrDefault()).FirstOrDefault(); } else { PBRItem = ""; } UserStoryList.Add(new string[] { issue.Id, issue.Summary, projectShortName, FullName, State, SpentTime, Estimation, Type, StoryPoint, Version, PBRItem, Created, Resolved }); } return(UserStoryList); }
public static DateTime?ParseManual(string dateTimeStr, DateTimeKind dateKind) { if (dateTimeStr == null || dateTimeStr.Length < ShortDateTimeFormat.Length) { return(null); } if (dateTimeStr.EndsWith(XsdUtcSuffix)) { dateTimeStr = dateTimeStr.Substring(0, dateTimeStr.Length - 1); } var parts = dateTimeStr.Split('T'); if (parts.Length == 1) { parts = dateTimeStr.SplitOnFirst(' '); } var dateParts = parts[0].Split('-', '/'); int hh = 0, min = 0, ss = 0, ms = 0; double subMs = 0; int offsetMultiplier = 0; if (parts.Length == 1) { return(dateParts.Length == 3 && dateParts[2].Length == "YYYY".Length ? new DateTime(int.Parse(dateParts[2]), int.Parse(dateParts[1]), int.Parse(dateParts[0]), 0, 0, 0, 0, dateKind) : new DateTime(int.Parse(dateParts[0]), int.Parse(dateParts[1]), int.Parse(dateParts[2]), 0, 0, 0, 0, dateKind)); } else if (parts.Length == 2) { var timeStringParts = parts[1].Split('+'); if (timeStringParts.Length == 2) { offsetMultiplier = -1; } else { timeStringParts = parts[1].Split('-'); if (timeStringParts.Length == 2) { offsetMultiplier = 1; } } var timeOffset = timeStringParts.Length == 2 ? timeStringParts[1] : null; var timeParts = timeStringParts[0].Split(':'); if (timeParts.Length == 3) { int.TryParse(timeParts[0], out hh); int.TryParse(timeParts[1], out min); var secParts = timeParts[2].Split('.'); int.TryParse(secParts[0], out ss); if (secParts.Length == 2) { var msStr = secParts[1].PadRight(3, '0'); ms = int.Parse(msStr.Substring(0, 3)); if (msStr.Length > 3) { var subMsStr = msStr.Substring(3); subMs = double.Parse(subMsStr) / Math.Pow(10, subMsStr.Length); } } } var dateTime = new DateTime(int.Parse(dateParts[0]), int.Parse(dateParts[1]), int.Parse(dateParts[2]), hh, min, ss, ms, dateKind); if (subMs != 0) { dateTime = dateTime.AddMilliseconds(subMs); } if (offsetMultiplier != 0 && timeOffset != null) { timeParts = timeOffset.Split(':'); if (timeParts.Length == 2) { hh = int.Parse(timeParts[0]); min = int.Parse(timeParts[1]); } else { hh = int.Parse(timeOffset.Substring(0, 2)); min = int.Parse(timeOffset.Substring(2)); } dateTime = dateTime.AddHours(offsetMultiplier * hh); dateTime = dateTime.AddMinutes(offsetMultiplier * min); } return(dateTime); } return(null); }
public void CanAddMillisecondsAcrossDstTransition() { var tz = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); var dt = new DateTime(2015, 3, 8, 1, 59, 59, 999); var result = dt.AddMilliseconds(1, tz); var expected = new DateTimeOffset(2015, 3, 8, 3, 0, 0, TimeSpan.FromHours(-7)); Assert.Equal(expected, result); Assert.Equal(expected.Offset, result.Offset); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType != JsonToken.Integer) { throw new Exception(String.Format("日期格式错误,got {0}.", reader.TokenType)); } var ticks = (long)reader.Value; var date = new DateTime(1970, 1, 1).ToLocalTime(); date = date.AddMilliseconds(ticks); return date; }