In Tsung, I want publish message time in milisec, I tried below but able to get time in Sec only.
<setdynvars sourcetype="eval" code='fun({Pid,DynVars})->
{{Year,Month,Day},{Hour,Minute,Second}} = erlang:localtime(),
io_lib:format('~4..0B-~2..0B-~2..0B::~2..0B:~2..0B:~4..0B\n', [Year,Month,Day,Hour,Minute,Second]) end.'>
<var name="time" />
</setdynvars>
<request subst="true">
<mqtt type="publish" topic="xxx" qos="0" retained="true">%%_time%%</mqtt>
</request>
you can use
1> Time_milli = fun() ->
Um = erlang:system_time(milli_seconds),
{D,T} = calendar:gregorian_seconds_to_datetime(Um div 1000 + 719528*86400)
{D,T,Um rem 1000}
end.
#Fun<erl_eval.20.54118792>
2> Time_milli().
{{2015,12,9},{8,13,53},40}
The value 719528*86400 is the number of seconds between the 1 1 1 at 0 0 0 and the 1970 1 1 at 0 0 0.
Note: the system_time is not monotonic, if you need this feature you can use erlang:monotonic_time/1, but in this case you cannot convert to a date or compare between different nodes.
Related
I have a database in SPSS structured like the following table:
ID
Gender
Age
Var1
Var...
1
0
7
3
...
2
1
8
4
...
3
1
9
5
...
4
1
9
2
...
I want to select only the first n (e.g.: 150) cases, where Gender = 1 and Age = 9, so in the table above the 3. and 4. case. How can I do it? Thanks!
compute filter_ = $sysmis.
compute counter_ = 0.
if $casenum=1 and (Gender = 1 and Age = 9) counter_ =1 .
do if $casenum <> 1.
if ~(Gender = 1 and Age = 9) counter_ = lag(counter).
if (Gender = 1 and Age = 9) counter_ = lag(counter) +1.
end if.
compute filter_ = (Gender = 1 and Age = 9 and counter<= 150).
execute.
I am not sure if this is the most efficient way, but it gets the job done. We use the counter_ variable to assign an order number for each record which satisfies the condition ("counting" records with meet the criteria, from the top of the file downwards). Then create a filter of the first 150 such records.
The below will select the first 150 cases where gender=1 AND age=9 (assuming 150 cases meet that criteria).
N 150.
SELECT IF (Gender=1 AND Age=9).
EXE .
Flipping the order of N and SELECT IF () would yield the same result. You can read more about N in the IBM documentation
I'm having this problem for a while and I can't find a good way to resolve it. So I have a timestamp like this for example : local t = "00:00:0.031" and I'm trying to convert it into an array like this :
local ft = {
hours = 0,
minutes = 0,
seconds = 0,
milliseconds = 31
}
This is pretty much the same no matter the language so if you have an idea on how to solve this but don't know Lua you can submit your answer anyway in any language. I tried solving it myself using regex and I'm quite sure it's possible this way...
Thank you for the interest to my question, have a good day (:
You could use string.match to extract the substrings in a first place. In a second time, you could use the function tonumber to convert it into numbers.
function ParseTimestampString (TimestampString)
local Hours, Minutes, Seconds, Milliseconds = string.match(TimestampString, "(%d+)%:(%d+)%:(%d+)%.(%d+)")
local Result
if Hours and Minutes and Seconds and Milliseconds then
Result = {
hours = tonumber(Hours),
minutes = tonumber(Minutes),
seconds = tonumber(Seconds),
milliseconds = tonumber(Milliseconds)
}
end
return Result
end
With the following code, you could get the results you want:
Result = ParseTimestampString("00:00:0.031")
print(Result.hours)
print(Result.minutes)
print(Result.seconds)
print(Result.milliseconds)
This should returns:
> Result = ParseTimestampString("00:00:0.031")
>
> print(Result.hours)
0
> print(Result.minutes)
0
> print(Result.seconds)
0
> print(Result.milliseconds)
31
Here is a not bad way using string.gmatch which is splitting by regex in Lua. Here the value is being split by either ":" or ".". Then there is a counter in place to match the index for the resulting table.
local t = "00:00:0.031"
local ft = {
hours = 0,
minutes = 0,
seconds = 0,
milliseconds = 0
}
local count = 1
for str in string.gmatch(t, "([^:|.]+)") do
ft[count] = tonumber(str)
count = count + 1
end
You can do a printing loop afterwards to check the results
for i = 1, 4 do
print(ft[i])
end
Output:
0
0
0
31
The main problem I have found with my solution is that it does not save the values under the keys listed but instead the numbers 1 2 3 4.
My Simplest Answer Will Be Just Split the given string by your regex, in This Case For HOUR:MIN:SEC.MS
first Split By (:) To Get HOUR MIN & SEC+MS, Then Split SEC+MS by (.) To separate Both seconds And milliseconds
Below is my answer in java
import java.util.*;
class timeX {
long hours = 0,
minutes = 0,
seconds = 0,
milliseconds = 31;
//Convert Given Time String To Vars
timeX(String input) {
//Split Input By (:) For Hour, Minutes & Seconds+Miliseconds
String[] splitted=input.split(":");
this.hours=Long.parseLong(splitted[0]);
this.minutes=Long.parseLong(splitted[1]);
//Split Again For Seconds And Miliseconds By (.)
String[] splittedMandS=splitted[2].split("\\.");
this.seconds=Long.parseLong(splittedMandS[0]);
this.milliseconds=Long.parseLong(splittedMandS[1]);
}
}
public class Main
{
public static void main(String[] args)
{
timeX tmp = new timeX("30:20:2.031");
System.out.println("H: "+tmp.hours+" M: "+tmp.minutes+" S: "+tmp.seconds+" MS: "+tmp.milliseconds);
}
}
With Lua you can do...
The os.date() can be a format tool for seconds.
...but depends on Operating System.
This works on Linux but not (as i know so far) on MS-Windows.
print(os.date('%H:%M:%S',0-3600)) -- puts out: 00:00:00
print(os.date('%H:%M:%S',300-3600)) -- puts out: 00:05:00
Also it can output the date/time as a table.
> tshow=function(tab) for k,v in pairs(tab) do print(k,'=',v) end end
> tshow(os.date('*t'))
day = 4
year = 2021
month = 11
hour = 11
yday = 308
isdst = false
min = 23
wday = 5
sec = 51
...and unfortunally it has no milliseconds.
If the table output of os.date() is saved as a table...
> ttable=os.date('*t')
> os.time(ttable)
1636021672
> os.date(_,os.time(ttable))
Thu Nov 4 11:27:52 2021
> os.date('%H:%M:%S',os.time(ttable))
11:27:52
...then its key/value pairs can be used for: os.time()
Further code do nearly what you expect when in ttable key 1 is your time with milliseconds as a string...
local tshow=function(tab) for k,v in pairs(tab) do print(k,'=',v) end end
local ttable=os.date('*t') -- Create a time table
ttable[1]='0:0:0.31' -- Numbered keys in sequence are ignored by os.tim()
ttable[2]=ttable[1]:gsub('(%d+):(%d+):(%d+)[.](%d+)','return {year=ttable.year,month=ttable.month,day=ttable.day,hour=%1,min=%2,sec=%3,milliseconds=%4}')
-- That creates ttable[2] with the value:
--- return {year=ttable.year,month=ttable.month,day=ttable.day,hour=0,min=0,sec=0,milliseconds=31}
-- Lets convert it now to a table with...
ttable[2]=load(ttable[2])()
-- Using tshow() to look inside
tshow(ttable[2])
That will output...
milliseconds = 31
day = 4
year = 2021
hour = 0
month = 11
min = 0
sec = 0
And this will put it out formated with os.date()
print(os.date('%H:%M:%S.'..ttable[2].milliseconds,os.time(ttable[2])))
-- Output: 00:00:00.31
I am new to the Ruby scripting language.
I was learning how to generate the byte code in Ruby.
I found the answer for generating the byte code.
But I don't know how to run that generated byte code. I searched the internet, but I didn't get the answer for this.
Generating a byte code:-
puts RubyVM::InstructionSequence.compile("x = 50; x > 100 ? 'foo' : 'bar'").disassemble
The output is,
== disasm: <RubyVM::InstructionSequence:<compiled>#<compiled>>==========
local table (size: 2, argc: 0 [opts: 0, rest: -1, post: 0, block: -1] s1)
[ 2] x
0000 trace 1 ( 1)
0002 putobject 50
0004 setlocal x
0006 trace 1
0008 getlocal x
0010 putobject 100
0012 opt_gt <ic:1>
0014 branchunless 20
0016 putstring "foo"
0018 leave
0019 pop
0020 putstring "bar"
0022 leave
I don't know how to execute the same script, by using the generated byte code.
Anyone please explain me how to execute this.
Thanks in advance!
TL;DR; You are looking for .eval method.
The .compile method would return an instance of RubyVM::InstructionSequence class, which has .eval method that evaluates/runs your "compiled" instructions.
iseq = RubyVM::InstructionSequence.compile("x = 50; x > 100 ? 'foo' : 'bar'")
iseq.eval # => "bar"
Or, a oneliner:
RubyVM::InstructionSequence.compile("x = 50; x > 100 ? 'foo' : 'bar'").eval
I am writing code in gfortran to separate a variable time stamp into its separate parts of year, month, and day. I have written this code so the user can input what the time stamp format will be (ie. YEAR/MON/DAY, DAY/MON/YEAR, etc). This creates a total of 6 possible combinations. I have written code that attempts to deal with this, but I believe it to be ugly and poorly done.
My current code uses a slew of 'if' and 'goto' statements. The user provides 'tsfo', the time stamp format. 'ts' is a character array containing the time stamp data (as many as 100,000 time stamps). 'tsdelim' is the delimiter between the year, month, and day. I must loop from 'frd' (the first time stamp) to 'nlines' (the last time stamp).
Here is the relevant code.
* Choose which case to go to.
first = INDEX(tsfo,tsdelim)
second = INDEX(tsfo(first+1:),tsdelim) + first
if (INDEX(tsfo(1:first-1),'YYYY') .ne. 0) THEN
if (INDEX(tsfo(first+1:second-1),'MM') .ne. 0) THEN
goto 1001
else
goto 1002
end if
else if (INDEX(tsfo(1:first-1),'MM') .ne. 0) THEN
if (INDEX(tsfo(first+1:second-1),'DD') .ne. 0) THEN
goto 1003
else
goto 1004
end if
else if (INDEX(tsfo(1:first-1),'DD') .ne. 0) THEN
if (INDEX(tsfo(first+1:second-1),'MM') .ne. 0) THEN
goto 1005
else
goto 1006
end if
end if
first = 0
second = 0
* Obtain the Julian Day number of each data entry.
* Acquire the year, month, and day of the time stamp.
* Find 'first' and 'second' and act accordingly.
* Case 1: YYYY/MM/DD
1001 do i = frd,nlines
first = INDEX(ts(i),tsdelim)
second = INDEX(ts(i)(first+1:),tsdelim) + first
read (ts(i)(1:first-1), '(i4)') Y
read (ts(i)(first+1:second-1), '(i2)') M
read (ts(i)(second+1:second+2), '(i2)') D
* Calculate the Julian Day number using a function.
temp1(i) = JLDYNUM(Y,M,D)
end do
goto 1200
* Case 2: YYYY/DD/MM
1002 do i = frd,nlines
first = INDEX(ts(i),tsdelim)
second = INDEX(ts(i)(first+1:),tsdelim) + first
read (ts(i)(1:first-1), '(i4)') Y
read (ts(i)(second+1:second+2), '(i2)') M
read (ts(i)(first+1:second-1), '(i2)') D
* Calculate the Julian Day number using a function.
temp1(i) = JLDYNUM(Y,M,D)
end do
goto 1200
* Onto the next part of the code
1200 blah blah blah
I believe this code will work, but I do not think it is a very good method. Is there a better way to go about this?
It is important to note that the indices 'first' and 'second' must be calculated for each time stamp as the month and day can both be represented by 1 or 2 integers. The year is always represented by 4.
With only six permutations to handle I would just build a look-up table with the whole tsfo string as the key and the positions of year, month and day (1st, 2nd or 3rd) as the values. Any unsupported formats should produce an error, which I haven't coded below. When subsequently you loop though your ts list and split an item you know which positions to cast to the year, month and day integer variables:
PROGRAM timestamp
IMPLICIT NONE
CHARACTER(len=10) :: ts1(3) = ["2000/3/4 ","2000/25/12","2000/31/07"]
CHARACTER(len=10) :: ts2(3) = ["3/4/2000 ","25/12/2000","31/07/2000"]
CALL parse("YYYY/DD/MM",ts1)
print*
CALL parse("DD/MM/YYYY",ts2)
CONTAINS
SUBROUTINE parse(tsfo,ts)
IMPLICIT NONE
CHARACTER(len=*),INTENT(in) :: tsfo, ts(:)
TYPE sti
CHARACTER(len=10) :: stamp = "1234567890"
INTEGER :: iy = -1, im = -1, id = -1
END TYPE sti
TYPE(sti),PARAMETER :: stamps(6) = [sti("YYYY/MM/DD",1,2,3), sti("YYYY/DD/MM",1,3,2),&
sti("MM/DD/YYYY",2,3,1), sti("DD/MM/YYYY",3,2,1),&
sti("MM/YYYY/DD",2,1,3), sti("DD/YYYY/MM",3,1,2)]
TYPE(sti) :: thisTsfo
INTEGER :: k, k1, k2
INTEGER :: y, m, d
CHARACTER(len=10) :: cc(3)
DO k=1,SIZE(stamps)
IF(TRIM(tsfo) == stamps(k)%stamp) THEN
thisTsfo = stamps(k)
EXIT
ENDIF
ENDDO
print*,thisTsfo
DO k=1,SIZE(ts)
k1 = INDEX(ts(k),"/")
k2 = INDEX(ts(k),"/",BACK=.TRUE.)
cc(1) = ts(k)(:k1-1)
cc(2) = ts(k)(k1+1:k2-1)
cc(3) = ts(k)(k2+1:)
READ(cc(thisTsfo%iy),'(i4)') y
READ(cc(thisTsfo%im),'(i2)') m
READ(cc(thisTsfo%id),'(i2)') d
PRINT*,ts(k),y,m,d
ENDDO
END SUBROUTINE parse
END PROGRAM timestamp
I would encode the different cases in another way, like this:
module foo
implicit none
private
public encode_datecode
contains
integer function encode_datecode(datestr, sep)
character(len=*), intent(in) :: datestr, sep
integer :: first, second
character(len=1) :: c1, c2, c3
first = index(datestr, sep)
second = index(datestr(first+1:), sep) + first
c1 = datestr(1:1)
c2 = datestr(first+1:first+1)
c3 = datestr(second+1:second+1)
foo = num(c1) + 3*num(c2) + 9*num(c3)
end function encode_datecode
integer function num(c)
character(len=1) :: c
if (c == 'Y') then
num = 0
else if (c == 'M') then
num = 1
else if (c == 'D') then
num = 2
else
stop "Illegal character"
end if
end function num
end module foo
and then handle the legal cases (21, 15, 19, 7, 11, 5) in a SELECT statement.
This takes advantage of the fact that there won't be a 'YDDY/MY/YM' format.
If you prefer better binary or decimal readability, you can also multiply by four or by 10 instead of 3.
What does coroutine.yield(-1) mean? I don't understand -1 here.
code piece and out put is:
> function odd(x)
>> print('A: odd', x)
>> coroutine.yield(x)
>> print('B: odd', x)
>> end
>
> function even(x)
>> print('C: even', x)
>> if x==2 then return x end
>> print('D: even ', x)
>> end
>
> co = coroutine.create(
>> function (x)
>> for i=1,x do
>> if i==3 then coroutine.yield(-1) end
>> if i % 2 == 0 then even(i) else odd(i) end
>> end
>> end)
>
> count = 1
> while coroutine.status(co) ~= 'dead' do
>> print('----', count) ; count = count+1
>> errorfree, value = coroutine.resume(co, 5)
>> print('E: errorfree, value, status', errorfree, value, coroutine.status(co))
>> end
---- 1
A: odd 1
E: errorfree, value, status true 1 suspended
---- 2
B: odd 1
C: even 2
E: errorfree, value, status true -1 suspended
---- 3
A: odd 3
E: errorfree, value, status true 3 suspended
---- 4
B: odd 3
C: even 4
D: even 4
A: odd 5
E: errorfree, value, status true 5 suspended
---- 5
B: odd 5
E: errorfree, value, status true nil dead
>
Any arguments passed to the corresponding coroutine.yield are returned by coroutine.resume. So -1 in coroutine.yield(-1) here is nothing special, it's similar to coroutine.yield(x) in the function odd(x).
It is executed when counter is 2 and i is 3. The corresponding output is:
---- 2
B: odd 1
C: even 2
E: errorfree, value, status true -1 suspended
After ture which indicates no error, see the -1 here? That's the value from the call to coroutine.yield(-1), it ended up as a return value of coroutine.resume.
For the similar reason, the other return values of coroutine.resume are 1, 3 and 5, all coming from coroutine.yield(x) in the function odd(x).
coroutine.yield (ยทยทยท)
Suspends the execution of the calling coroutine. The coroutine cannot be running a C function, a metamethod, or an iterator. Any arguments to yield are passed as extra results to resume.
http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.yield
So in other words the -1 could have been anything or even multiple values and how those values are used is up to the programmer.