Unit root test on lagged variables - time-series

guys!
I'm using this sintaxe but when I use the last part ("modelo = ...") it shows the following: "Error in merge.zoo(difetanol, detanol, mes2, mes3, mes4, mes5, mes6, mes7, :
all(sapply(args, function(x) is.zoo(x) || !is.plain(x) || (is.plain(x) && .... is not TRUE"
ethidra = (tsrelatorio[,"etanol"])
ethidra
length(ethidra)
acuavhp = (tsrelatorio[,"avhp"])
acuavhp
length(acuavhp)```
matr <- matrix(0, nr = 12, nc = 12)
matr[row(matr) == col(matr)] <- 1
matr
Djt <- rbind(matr,matr,matr,matr); Djt
dim(Djt)
names(Djt)
dimnames(Djt) = list(c(),c("M1", "M2", "M3", "M4","M5","M6","M7","M8","M9","M10","M11","M12"))
Djt
dim(Djt)```
teste=data.frame(Djt)
attach(teste)
mes2= teste[1:47,2]
mes2
length(mes2)
mes3= teste[1:47,3]
mes3
length(mes3)
mes4= teste[1:47,4]
mes4
length(mes4)
mes5= teste[1:47,5]
mes5
length(mes5)
mes6= teste[1:47,6]
mes6
length(mes6)
mes7= teste[1:47,7]
mes7
length(mes7)
mes8= teste[1:47,8]
mes8
length(mes8)
mes9= teste[1:47,9]
mes9
length(mes9)
mes10= teste[1:47,10]
mes10
length(mes10)
mes11= teste[1:47,11]
mes11
length(mes11)
mes12= teste[1:47,12]
mes12
length(mes12)
detanol = (ethidra[1:47])
detanol
length(detanol)
difetanol=diff(detanol)
difetanol
length(difetanol)
tempo = tempo <- seq(1:47)
modelo = dynlm(difetanol ~ detanol + mes2 +mes3 +mes4 + mes5 + mes6 + mes7 + mes8 + mes9 + mes10 + mes11 + mes12 + tempo + L(difetanol,1) + L(difetanol,2))
summary(modelo)

Related

how to rename variables in datasummary (rmarkdown, latex pdf)

I am unable to rename the variables in datasummary. I don't think it has an option to do that. Any tips?
summary_vars <- as.formula(glue("any_prio + any_prio_on + any_prio_off + war_prio + war_prio_on +
war_prio_off + war_col + war_inc + war + GPCP + GPCP_g + GPCP_g_l + gdp_g +
gdp_g_l + y_0 + polity2l + polity2l_6 + deml + ethfrac + relfrac + Oil +
mtnest + lpopl1 + tot_100_g ~ mean*Arguments(na.rm = TRUE) + sd*Arguments(na.rm = TRUE) + N"))
TableA1 <- datasummary(data = mss_rep, summary_vars, booktabs = T,
fmt = 2,
col.names = c("", "Mean", "Standard Deviation", "Observations"),
caption = "DESCRIPTIVE STATISTICS") |>
kable_styling() |>
pack_rows("A. Civil Conflict Measures (1981–99)", 1, 9) |>
pack_rows("B. Rainfall Measures (1981–99)", 10, 12) |>
pack_rows("C. Economic Growth", 13, 14) |>
pack_rows("D. Country Characteristics", 15, 24)
TableA1
You could save the datasummary as a dataframe, do the renaming and apply a new kbl afterwards, e.g.
library(modelsummary)
library(kableExtra)
summary_df <- datasummary(mpg + cyl ~ mean, data = mtcars, output = "data.frame", fmt = 2)
# renaming
summary_df[,1] <- c("MPG", "CYL")
summary_df |>
kbl(booktabs = TRUE) |>
kable_styling() |>
pack_rows("A. Civil Conflict Measures (1981–99)", 1, 2)

print method in lua script/redis is not working

I am trying to execute the following script and getting the below error. Redis is running in docker
Exception in thread "main" org.redisson.client.RedisException: ERR
user_script:1: Script attempted to access nonexistent global variable
'print' script: 6f736423f082e141036b833d1f86b5a36a494611, on
#user_script:1..
I get the same error when I execute using redis CLI
127.0.0.1:6379> eval "print("Comparison is_made b/w minimum_value out of two is: ")" 0 (error) ERR user_script:1: Script attempted to
access nonexistent global variable 'print' script:
8598b7f0db450c711d3a9e73a296e331bd1ef945, on #user_script:1.
127.0.0.1:6379>
Java code. I am using Redison lib to connect to Redis and execute script.
String script = "local rate = redis.call('hget', KEYS[1], 'rate');"
+ "local interval = redis.call('hget', KEYS[1], 'interval');"
+ "local type = redis.call('hget', KEYS[1], 'type');"
+ "assert(rate ~= false and interval ~= false and type ~= false, 'RateLimiter is not initialized')"
+ "local valueName = KEYS[2];"
+ "local permitsName = KEYS[4];"
+ "if type == '1' then "
+ "valueName = KEYS[3];"
+ "permitsName = KEYS[5];"
+ "end;"
+"print(\"rate\"..rate) ;"
+"print(\"interval\"..interval) ;"
+"print(\"type\"..type); "
+ "assert(tonumber(rate) >= tonumber(ARGV[1]), 'Requested permits amount could not exceed defined rate'); "
+ "local currentValue = redis.call('get', valueName); "
+ "local res;"
+ "if currentValue ~= false then "
+ "local expiredValues = redis.call('zrangebyscore', permitsName, 0, tonumber(ARGV[2]) - interval); "
+ "local released = 0; "
+ "for i, v in ipairs(expiredValues) do "
+ "local random, permits = struct.unpack('Bc0I', v);"
+ "released = released + permits;"
+ "end; "
+ "if released > 0 then "
+ "redis.call('zremrangebyscore', permitsName, 0, tonumber(ARGV[2]) - interval); "
+ "if tonumber(currentValue) + released > tonumber(rate) then "
+ "currentValue = tonumber(rate) - redis.call('zcard', permitsName); "
+ "else "
+ "currentValue = tonumber(currentValue) + released; "
+ "end; "
+ "redis.call('set', valueName, currentValue);"
+ "end;"
+ "if tonumber(currentValue) < tonumber(ARGV[1]) then "
+ "local firstValue = redis.call('zrange', permitsName, 0, 0, 'withscores'); "
+ "res = 3 + interval - (tonumber(ARGV[2]) - tonumber(firstValue[2]));"
+ "else "
+ "redis.call('zadd', permitsName, ARGV[2], struct.pack('Bc0I', string.len(ARGV[3]), ARGV[3], ARGV[1])); "
+ "redis.call('decrby', valueName, ARGV[1]); "
+ "res = nil; "
+ "end; "
+ "else "
+ "redis.call('set', valueName, rate); "
+ "redis.call('zadd', permitsName, ARGV[2], struct.pack('Bc0I', string.len(ARGV[3]), ARGV[3], ARGV[1])); "
+ "redis.call('decrby', valueName, ARGV[1]); "
+ "res = nil; "
+ "end;"
+ "local ttl = redis.call('pttl', KEYS[1]); "
+ "if ttl > 0 then "
+ "redis.call('pexpire', valueName, ttl); "
+ "redis.call('pexpire', permitsName, ttl); "
+ "end; "
+ "return res;";
RedissonClient client = null;
try {
client = Redisson.create();
client.getRateLimiter("user1:endpoint1").setRate(
RateType.PER_CLIENT, 5, 1, RateIntervalUnit.SECONDS);
String sha1 = client.getScript().scriptLoad(script);
List<Object> keys =
Arrays.asList("user1:endpoint1", "{user1:endpoint1}:value",
"{user1:endpoint1}:value:febbb04d-6365-4cb8-b32b-8d90800cd4e6",
"{user1:endpoint1}:permits", "{user1:endpoint1}:permits:febbb04d-6365-4cb8-b32b-8d90800cd4e6");
byte[] random = new byte[8];
ThreadLocalRandom.current().nextBytes(random);
Object args[] = {1, System.currentTimeMillis(), random};
boolean res = client.getScript().evalSha(READ_WRITE, sha1, RScript.ReturnType.BOOLEAN, keys, 1,
System.currentTimeMillis(), random);
System.out.println(res);
}finally {
if(client != null && !client.isShutdown()){
client.shutdown();
}
}
checked the Lua print on the same line thread but io.write also is giving same error.
As in the comments wrote return() seems* the only way.
Example for redis-cli (set redis DB and use it in Lua)
(Collect Data and return as one string)
set LuaV 'local txt = "" for k, v in pairs(redis) do txt = txt .. tostring(k) .. " => " .. tostring(v) .. " | " end return(txt)'
Now the eval
eval "local f = redis.call('GET', KEYS[1]) return(loadstring(f))()" 1 LuaV
...shows whats in table: redis
(One long String no \n possible)
Exception: eval 'redis.log(2, _VERSION)' 0 gives out without ending the script but only on the server.
Than \n will work when you do...
set LuaV 'local txt = "" for k, v in pairs(redis) do txt = txt .. tostring(k) .. " => " .. tostring(v) .. "\n" end return(txt)'
...and the eval
eval 'local f = redis.call("GET", KEYS[1]) f = loadstring(f)() redis.log(2, f)' 1 LuaV

Regular expression from this dfa

what will be regular express of this transition graph anyone?can make and explain this please i will be very thankful to him.
We can write some equations for this:
(q0) = e + (q1)a + (q3)b
(q1) = (q0)a + (q2)b
(q2) = (q1)b + (q3)a
(q3) = (q0)b + (q2)a
You can read these equations like this: "the set of strings that leads me to state X is the set of strings that lead me to state Y followed by symbol c, or the set of strings that lead me to state Z followed by symbol d, or..."
We can now solve these equations using substitution and a rule to eliminate self-references, namely:
if (q) = (q)x + y, then (q) = y(x*)
We can start solving the system by eliminating (q3):
(q0) = e + (q1)a + [(q0)b + (q2)a]b
(q1) = (q0)a + (q2)b
(q2) = (q1)b + [(q0)b + (q2)a]a
Distributing:
(q0) = e + (q1)a + (q0)bb + (q2)ab
(q1) = (q0)a + (q2)b
(q2) = (q1)b + (q0)ba + (q2)aa
We can get rid of (q1) now:
(q0) = e + [(q0)a + (q2)b]a + (q0)bb + (q2)ab
(q2) = [(q0)a + (q2)b]b + (q0)ba + (q2)aa
Distributing:
(q0) = e + (q0)aa + (q2)ba + (q0)bb + (q2)ab
(q2) = (q0)ab + (q2)bb + (q0)ba + (q2)aa
Grouping like terms:
(q0) = e + (q0)(aa + bb) + (q2)(ab + ba)
(q2) = (q0)(ab + ba) + (q2)(aa + bb)
Using the rule to remove self-reference:
(q0) = (aa + bb)* + (q2)(ab + ba)(aa + bb)*
(q2) = (q0)(ab + ba)(aa + bb)*
Substituting to get rid of (q2):
(q0) = (aa + bb)* + [(q0)(ab + ba)(aa + bb)*](ab + ba)(aa + bb)*
Distributing:
(q0) = (aa + bb)* + (q0)(ab + ba)(aa + bb)*(ab + ba)(aa + bb)*
Using the rule for self-reference:
(q0) = (aa + bb)*[(ab + ba)(aa + bb)*(ab + ba)(aa + bb)*]*
from the given transition diagram or DFA, equations for each state can be written as:
q0 = ε+q1.a+q3.b
q1 = q0.a+q2.b
q2 = q1.b+q3.a
q3 = q0.b+q2.a
substitute q3 in q2,
q2=q1.b+(q0.b+q2.a)a
q2=q2.aa+q0.ba+q1.b
substitute q1 in q2
q2=q2.aa+q0.ba+(q0.a+q2.b)b
q2=q2.aa+q0.ba+q0.ab+q2.bb
finally,
q2=q2(aa+bb)+q0(ba+ab)
It is in the form of t=tr+s
According to Arden's theorem,
the solution is t=sr*
So,q2=q0(ba+ab)(aa+bb)
Now substitute q3 in the equation q0,
q0=ε+q1.a+(q0.b+q2.a)b
q0=ε+q1.a+q0.bb+q2.ab
q0=q0.bb+(q1.a+q2.ab+ε)
substitute q1 in q0,
q0=q0.bb+(q0.a+q2.b)a+q2.ab+ε
q0=q0.bb+q0.aa+q2.ba+q2.ab+ε
q0=q0(bb+aa)+q2(ba+ab)+ε
Now substitute the q2 in the above equation,
q0=q0(bb+aa)+q0(ba+ab)(aa+bb)*(ba+ab)+ε
q0=q0((bb+aa)+(ba+ab)(aa+bb)*(ba+ab))+ε
Now q0 is in the form of t=tr+s so the solution is t=sr*
q0=((bb+aa)+(ba+ab)(aa+bb)(ab+ba))
The Regular Expression for the given DFA is:
q0=((bb+aa)+(ba+ab)(aa+bb)*(ab+ba))

May you assist me with the output of this Fibonacci sequence

enter image description here
Thank you
n = 1 : 1
n = 2 : 1
n = 3 : Fib(n-1) + Fib(n-2) + Fib(n-3) = Fib(2) + Fib(1) + Fib(0) = 1 + 1 + 0 = 2
n = 4 : Fib(n-1) + Fib(n-2) + Fib(n-3) = Fib(3) + Fib(2) + Fib(1) = 2 + 1 + 1 = 4
Basically, you add the 3 previous number before n.

I am trying to make videos of 59 mins and 59 secs, but the video created is always of smaller duration

I want to create videos for multiple cameras stored in MySQL database. At intervals of every 1 hour the duration of video should be 59 mins and 59 secs. The videos should be then uploaded to azure blob storage.
However, every time a video is created, it is of a smaller duration (for example, 44 or 45 mins). I am not getting any errors. What am I doing wrong? any suggestion will be of great help. Thank You.
from threading import Thread
import threading
import cv2
import pymysql
import time
import datetime
import os
from azure.storage.blob import BlockBlobService, PublicAccess
def accessCamera(user_id, location_id, user_name, cursor):
fix_path = '/home/****/****/'
container_name = user_name
block_blob_service = BlockBlobService(account_name='******', account_key='*****+*****+****+/******')
try:
block_blob_service.create_container(container_name)
except:
pass
block_blob_service.set_container_acl(container_name, public_access=PublicAccess.Container)
cursor.execute('SELECT * FROM xxxxx where user_id = ' + str(user_id) + ' and location_id = ' + str(location_id) + '')
cameras = cursor.fetchall()
camera = {}
counter = 0
out = {}
hour = str(datetime.datetime.fromtimestamp(time.time()).strftime('%d-%m-%Y_%H'))
for x in cameras:
try:
os.makedirs(fix_path + x['ip_address'] + '_' + str(x['rtsp_port']) + '/videos/')
except:
pass
rtsp_stream_link = 'rtsp://' + x['username'] + ':' + x['password'] + '#' + x['ip_address'] + ':'
+ str(x['rtsp_port']) + '/stream=1'
out[counter] = cv2.VideoWriter(fix_path + x['ip_address'] + '_' + str(x['rtsp_port']) +
'/videos/' + str(hour) + '.avi',cv2.VideoWriter_fourcc(*'DIVX'), 1, (1920,1080))
camera[counter] = cv2.VideoCapture(rtsp_stream_link)
counter = counter + 1
print(" #==================================================")
print(" #-- Loaded Cameras Now Saving Video for Location " + str(location_id) + " - " +
str(datetime.datetime.fromtimestamp(time.time()).strftime('%d-%m-%Y_%H-%M-%S')))
print(" #==================================================")
framecount = 0
while True:
counter = 0
for x in cameras:
check,frame=camera[counter].read()
if check == True:
out[counter].write(frame)
else:
continue
minutes = str(datetime.datetime.fromtimestamp(time.time()).strftime('%M'))
if int(minutes) == 59 and framecount >= 3599:
out[counter].release()
block_blob_service.create_blob_from_path(container_name, fixpath + x['ip_address'] + '_'
+ str(x['rtsp_port']) + '/videos/' + hour + '.avi', x['ip_address'] + '_' + x['rtsp_port'] +
'/videos/' + hour + '.avi')
print("#==================================================")
print("#-- Video Saved - " +
str(datetime.datetime.fromtimestamp(time.time()).strftime('%d-%m-%Y_%H-%M-%S')))
print("#==================================================")
threading.Thread._stop(self)
exit(1)
counter = counter + 1
framecount = framecount + 1
#===========================================================================
# -- Main function
#===========================================================================
if __name__ == '__main__':
print("Time - " + str(datetime.datetime.fromtimestamp(time.time()).strftime('%d-%m-%Y_%H-%M-%S')))
flag = 1
while True:
if (str(datetime.datetime.fromtimestamp(time.time()).strftime('%S')) == '54' and
str(datetime.datetime.fromtimestamp(time.time()).strftime('%M')) == '59') or flag == 1:
print("#======================================================")
print("#-- Get All Users and Locations to create Threads - " +
str(datetime.datetime.fromtimestamp(time.time()).strftime('%d-%m-%Y_%H-%M-%S')))
print("#======================================================")
db = pymysql.connect('xxxxxxx', 'xxxxxx', 'password', 'xxxxxx')
cursor = db.cursor(pymysql.cursors.DictCursor)
cursor1 = db.cursor(pymysql.cursors.DictCursor)
cursor.execute('select locations.id,locations.user_id,users.username from locations inner
join users on users.id = locations.user_id')
user = cursor.fetchall()
for x in user:
thread = threading.Thread(target=accessCamera,args=
(int(x['user_id']),int(x['id']),x['username'],cursor1,))
print(" #==================================================")
print(' #-- Thread created for location ' + str(x['id']) + ' - ' +
str(datetime.datetime.fromtimestamp(time.time()).strftime('%d-%m-%Y_%H-%M-%S')))
print(" #==================================================")
thread.daemon = True
thread.start()
time.sleep(1)
flag = 0
# print(" #==================================================")
# print(" #-- Sleeping Current Thread for 1 minutes - " +
str(datetime.datetime.fromtimestamp(time.time()).strftime('%d-%m-%Y_%H-%M-%S')))
# print(" #==================================================")

Resources