print method in lua script/redis is not working - docker

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

Related

Cannot resolve method error when trying to reproduce the code

I know it's been a while since this issue was resolved ( Simple calculator in java - using boolean to ask if user wants to continue ), but I wanted to recreate this, and when I tried to run it, I got error for all mathematical operators (add, minus, multiply or divide). Error says: "Cannot resolve method 'add'/'minus'/'multiply'/'divide'"
Maybe it would be easier if I add the actual code:
import javax.swing.JOptionPane;
public class Calculator {
public static void main(String[] args) {
double numberOne;
double numberTwo;
double result;
String number1;
String number2;
String input;
boolean useCalculator = false;
while (!useCalculator) {
number1 = JOptionPane.showInputDialog(null, "This is a calculator\nEnter first number");
numberOne = Double.parseDouble(number1);
input = JOptionPane.showInputDialog(null, "Choose from the following options:\n+\n-\n*\n/");
while (input == null || !(input.equals("+") || input.equals("*") || input.equals("/") || input.equals("-")))
input = JOptionPane.showInputDialog(null, "Thank you! What would you like to do?\nPlease choose from the following options:\n+\n-\n*\n/");
{
input = JOptionPane.showInputDialog(null, "The operator" + input + "is invalid. Please choose a correct one");
}
number2 = JOptionPane.showInputDialog(null, "Enter second number");
numberTwo = Double.parseDouble(number2);
if (input != null && input.equals("+")) {
add(numberOne, numberTwo);
result = add(numberOne, numberTwo);
JOptionPane.showMessageDialog(null, "The result of " + numberOne + " " + input + " " + numberTwo + " is: " + result);
} else if (input != null && input.equals("-")) {
minus(numberOne, numberTwo);
result = minus(numberOne, numberTwo);
JOptionPane.showMessageDialog(null, "The result of " + numberOne + " " + input + " " + numberTwo + " is: " + result);
} else if (input != null && input.equals("*")) {
multiply(numberOne, numberTwo);
result = multiply(numberOne, numberTwo);
JOptionPane.showMessageDialog(null, "The result of " + numberOne + " " + input + " " + numberTwo + " is: " + result);
} else if (input != null && input.equals("/")) {
divide(numberOne, numberTwo);
result = divide(numberOne, numberTwo);
JOptionPane.showMessageDialog(null, "The result of " + numberOne + " " + input + " " + numberTwo + " is: " + result);
}
}
System.out.println("End of program.");
}
}
Any thoughts on how to fix this and run it without those errors?
Thanks in advance :)
It looks like GUI was running in the background, so when I minimized window, I was able to see the calculator and to run it normally.
Message that was displayed in console was reminder about old JDK, so everything is fine now.

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(" #==================================================")

Store environment variables within declared environment variable, Jenkins Pipeline 2.0

This code is giving me error in jenkins
groovy.lang.MissingPropertyException: No such property: Metrics for class: java.lang.String
def init_metrics(){
env.previousStageEnd = 0
env.stageDuration
env.stageTimes = [:]
}
init_metrics()
node{
stage('Metrics'){
println " - " + env.previousStageEnd + " - " + env.stageTimes + " - " + env.stageDuration + " - " + env.STAGE_NAME
env.stageTimes[env.STAGE_NAME] = currentBuild.duration - (env.previousStageEnd as int)
previousStageEnd = currentBuild.duration
}
}
the problem with this guy here env.stageTimes[env.STAGE_NAME] for some reasons I can't add environment stage_name in another environment declared by me. it works only if those variables are not environment but local.
solution to this would be to define environment = []
def init_metrics(){
environment = [
previousStageEnd = 0,
stageDuration = null,
stageTimes = [:]
]
}
init_metrics()
node{
stage('Metrics'){
println " - " + env.previousStageEnd + " - " + env.stageTimes + " - " + env.stageDuration + " - " + env.STAGE_NAME
env.stageTimes[env.STAGE_NAME] = currentBuild.duration - (env.previousStageEnd as int)
previousStageEnd = currentBuild.duration
}
}

ERR value is not an integer or out of range

I have this code in a lua script which I run from .net.
const string script = " if redis.call('EXISTS', '{0}') == 1 then" +
" local user = redis.call('get','{0}')" +
" local value = cjson.decode(user)" +
" value['UserPreferences'] = cjson.decode('{1}')" +
" value['Timestamp'] = cjson.decode('{2}')" +
" local val=cjson.encode(value)" +
" redis.call('set', '{0}', val)" +
" redis.call('EXPIRE', '{0}','{3}')" +
" end";
var redisScript = string.Format(script, "User_" + userId, JsonConvert.SerializeObject(userPreferences), JsonConvert.SerializeObject(DateTime.UtcNow), ConfigurationManager.AppSettings["RedisKeyExpiryTime"]);
await Cache.ScriptEvaluateAsync(redisScript);
This returns the error :
Error: ERR value is not an integer or out of range
please give some feedback to solve the issue.

Twitter API link parser

I am having an issue and tried to do everything regarding this!! even HttpUtility.ParseQueryString won't help!
I am trying to parse twitter links coming from the API in the form of http://t.co/oEVQbihMWu. I need the fully resolved URL.
My code:
richTextBox1.Clear();
richTextBox1.Visible = true;
SearchOptions SO = new SearchOptions();
SO.GeoCode = richTextBox3.Text + "," + richTextBox2.Text + "mi";
TwitterResponse<TwitterSearchResultCollection> TweetSearchResult = TwitterSearch.Search(tokens, "#blogger", SO);
if (TweetSearchResult.Result != RequestResult.Success) richTextBox1.Text = "connection Error";
else
{
string a = null;
foreach (var tweet in TweetSearchResult.ResponseObject)
{
string b = tweet.User.Location.Contains(",") ? tweet.User.Location.Replace(",", "-") : tweet.User.Location;
a += string.Format("{0},{1},{2},{3},{4},{5},{6},{7}", tweet.CreatedDate, b, tweet.User.Id,
tweet.User.ScreenName, tweet.User.Name, tweet.User.NumberOfFollowers, tweet.User.Website, Environment.NewLine);
richTextBox1.AppendText(" " + tweet.CreatedDate + "\n" + tweet.User.Location + "\n" + tweet.User.Id + "\n" + tweet.User.ScreenName + "\n" + tweet.User.Name + "\n" + tweet.User.NumberOfFollowers +
"\n" + tweet.User.Website + "\n" + tweet.Text + "\n\n\n");
}
links being represented by tweet.user.website.
any help? :)
In the API response, there is entities.urls which contains an array of url and expanded_url mappings. Check your library's documentation for equivalent.
Alternatively, if you inspect the response for t.co links, you will find this:
<noscript><META http-equiv="refresh" content="0;URL=http://www.fitnessbydanielle.com"></noscript><title>http://www.fitnessbydanielle.com</title><script>window.opener = null; location.replace("http:\/\/www.fitnessbydanielle.com")</script>
Parse it to get the url.
I managed to crack it.
What I did:
foreach (var tweet in TweetSearchResult.ResponseObject)
{
if(tweet.User.Website != null)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(tweet.User.Website);
req.AllowAutoRedirect = false;
var resp = req.GetResponse();
string realUrl = resp.Headers["Location"];
string b = tweet.User.Location.Contains(",") ? tweet.User.Location.Replace(",", "-") : tweet.User.Location;
a += string.Format("{0},{1},{2},{3},{4},{5},{6},{7}", tweet.CreatedDate, b, tweet.User.Id,
tweet.User.ScreenName, tweet.User.Name, tweet.User.NumberOfFollowers, realUrl, Environment.NewLine);
richTextBox1.AppendText(" " + tweet.CreatedDate + "\n" + tweet.User.Location + "\n" + tweet.User.Id + "\n" + tweet.User.ScreenName + "\n" + tweet.User.Name + "\n" + tweet.User.NumberOfFollowers +
"\n" + realUrl + "\n" + tweet.Text + "\n\n\n");
}
}
File.AppendAllText(#".\BloggerTable.csv", a, Encoding.UTF8);
}
Wrapped it inside a condition so no users without website will show and used a webrequest to get the link. stored the location inside the httprequest header for each and every tweet.

Resources