I need to run a script in wrk to test my endpoint. My script is as followed:
thread_counter = 0
local thread_id = 1
setup = function (thread)
thread_counter = thread_counter + 1
thread_id = thread_counter
print("thread_id 1 " ..thread_id)
end
request = function()
idx = math.random(200)
print("thread_id 2 " ..thread_id)
...
end
I can see that thread_id is updated in the setup function, but not the request function. Why and how can I fix this?
Related
Instead of defining a Bitbucket Cloud workspace variable that can be used by all the repos in the workspace, someone defined it in each repo, but not in all of them, of the workspace. Now I want to remove the variable in the individual repos, and define it in the workspace.
Is there a Bitbucket API that would do this pseudo-code?
def bb = Bitbucket.getInstance()
String workspace = "MyWorkspace"
String myVariable = "NEXUS_USER"
List<Repository> reposInWorkspace = bb.getWorkspace(workspace).getAllReposInWorkspace()
reposInWorkspace.each { repo ->
if (repo.hasVariable(myVariable)) {
println repo.name
}
}
I put a Bitbucket support ticket, and a sharp Atlassian support person gave me this Python3 script
from requests import Session
from time import sleep
username = 'your_username_not_email'
password = 'app_pw_not_bb_user_pw'
workspace = 'your_workspace'
variable_name = 'your_variable'
URL = f'https://api.bitbucket.org/2.0/repositories/{workspace}'
session = Session()
session.auth = (username, password)
def get_repos(page=None):
while True:
params = {'page': page, 'pagelen': 100}
r = session.get(URL, params=params)
while r.status_code == 429:
print("Hit the API rate limit. Sleeping for 10 sec...")
sleep(10)
print("Resuming...")
r = session.get(URL, params=params)
r_data = r.json()
for repo in r_data.get('values'):
yield repo.get('slug')
if not r_data.get('next'):
return
if page is None:
page = 1
page += 1
def get_variables(repo, page=None):
while True:
params = {'page': page, 'pagelen': 100}
r = session.get(f'{URL}/{repo}/pipelines_config/variables/', params=params)
while r.status_code == 429:
print("Hit the API rate limit. Sleeping for 10 sec...")
sleep(10)
print("Resuming...")
r = session.get(URL, params=params)
r_data = r.json()
for var in r_data.get('values'):
yield var.get('key')
if not r_data.get('next'):
return
if page is None:
page = 1
page += 1
def has_variable(var):
if var == variable_name:
return True
def main():
for repo in get_repos():
for var in get_variables(repo):
if has_variable(var):
print(f'{repo}')
if __name__ == '__main__':
main()
I am trying to assign the output of a function to a variable, but I can’t do it. :(
I use Lua 5.3.4 and luarocks 3.2.1 (+luasql-postgres)
My script:
luasql = require "luasql.postgres"
value=arg[1]
current_time=os.date("%Y-%m-%d %H:%M:%S")
env = luasql.postgres()
con = assert (env:connect('postgres', 'postgres', 'postgres', '192.168.241.93','5432'))
function printvalues(res)
row = res:fetch ({}, "a")
while row do
print(string.format("%-12s", row.client_addr))
row = res:fetch (row, "a")
end
print()
end
res = assert (con:execute('select client_addr from pg_stat_replication order by replay_lag asc limit 1'))
--txn = res
a = {myfunc = printvalues(res)}
if a == '192.168.242.41' then
print("backend1")
elseif a == '192.168.241.76' then
print("backend2")
end
print(string.format("%-12s",a))
print(a)
Script result:
root#haproxy:/etc/haproxy# lua scripts/test.lua
192.168.1.76
table: 0x559fadf97080
table: 0x559fadf97080
Please tell me:
How can I assign the result of a function to a variable?
How to remove the empty line in the output of the function printvalues(res)
you need to make a return statement in the function body to return a value
the empty line in your example is the print() statement in the function printvalues
I see you are making a query using limit 1, since you will only get one value, the while loop statement is useless.
I hope this works for you
local luasql = require "luasql.postgres"
local env = luasql.postgres()
local con = assert (env:connect(
'postgres', 'postgres', 'postgres', '192.168.241.93', '5432'
))
local res = assert(con:execute(
'select client_addr from pg_stat_replication order by replay_lag asc limit 1'
))
local row = res:fetch({}, 'a')
local a = string.format('%-12s', row.client_addr)
res:close()
if a == '192.168.242.41' then
print('backend1')
elseif a == '192.168.241.76' then
print('backend2')
end
print(a)
but if you want an example with function:
local luasql = require "luasql.postgres"
local env = luasql.postgres()
local con = assert (env:connect(
'postgres', 'postgres', 'postgres', '192.168.241.93', '5432'
))
local res = assert(con:execute(
'select client_addr from pg_stat_replication order by replay_lag asc limit 1'
))
local function printvalues(res)
local row = res:fetch({}, 'a')
res:close()
return string.format('%-12s', row.client_addr)
end
local a = printvalues(res)
if a == '192.168.242.41' then
print('backend1')
elseif a == '192.168.241.76' then
print('backend2')
end
print(a)
try to use local keyword before variables, this will make them scope variables
Thank. I ended up using this script:
luasql = require "luasql.postgres"
env = luasql.postgres()
con = assert (env:connect('postgres', 'postgres', 'postgres','333.333.333.333','5432')) --master
backend = function(txn)
res = assert (con:execute('select client_addr from pg_stat_replication order by replay_lag asc limit 1'))
row = res:fetch ({}, "a")
while row do
ip = string.format("%-12s", row.client_addr)
row = res:fetch (row, "a")
end
result = "backend1"
if ip == '111.111.111.111' then
result = "backend1"
elseif ip == '222.222.222.222' then
result = "backend2"
end
return result
end
core.register_fetches("choose_backend", backend)
We have a lengthy lua script. Please find it below after the problem description.
The logic of the script is to return true/false if all the 3 parameters match (UserName, UserCategory, UserCategoryItem)
The first part of the script splits the RedisKeys to fetch the UserName, UserCategory, UserCategoryItem. There is also a random function to test if ‘functions’ works in the Redis lua script. It works.
The second part of the script compares this values against the values in the Database. The values are hard-coded in the script. If all the values match it returns true else it returns false.
The two scripts run perfect when ran individually. But they throw an error when run together.
ISSUE/PROBLEM
All the three scripts run perfectly when run in an IDE. I use the SciTE IDE (an IDE for Lua for Windows envrionment)
The script creates an issue when run from the Stackexchange.Redis client.
The first two parts of the script (Part One and Part Two) run perfectly from the Stackexchange.Redis. It is only when they are combined in the third script (Part Three) does it throw an error.
As the error is generic in nature hence I am not able to further investigate the issue.
I have divided the script in Three parts. The final script combines the first two scripts.
var redis = ConnectionMultiplexer.Connect("localhost");
var db = redis.GetDatabase();
//PART ONE OF THE SCRIPT
var doesExist1 = (string)db.ScriptEvaluate(#"
local function isDateInRange(DateStart, DateEnd, GivenDate)
if (GivenDate > DateStart and GivenDate < DateEnd)
then
return(true)
else
return(false)
end
end
--Fetch User's Category's StartDate and EndDate
local function IsCategoryDateValid()
local givenDate, DateStart, DateEnd
GivenDate = '2017-01-09'
StartDate = '2015-01-01'
EndDate = '2018-01-01'
local isDateValid
isDateValid = isDateInRange(StartDate, EndDate, GivenDate)
return(isDateValid)
end
-- Pass User, UserCategory and UserCategoryItem as parameters
local userNameKey = 'UserDetails:DummyName'
local userCategoryKey = 'UserCategories:Book'
local userCategoryItemKey = 'UserCategoryItems:Harry-Potter'
local userNameKeySplit = {}
local a = 1
for i in string.gmatch(userNameKey, '([^'..':'..']+)') do
userNameKeySplit[a] = i
a = a + 1
end
local userName = userNameKeySplit[2]
local userCategoryKeySplit = {}
local b = 1
for j in string.gmatch(userCategoryKey, '([^'..':'..']+)') do
userCategoryKeySplit[b] = j
b = b + 1
end
local userCategory = userCategoryKeySplit[2]
local userCategoryItemKeySplit = {}
local c = 1
for k in string.gmatch(userCategoryItemKey, '([^'..':'..']+)') do
userCategoryItemKeySplit[c] = k
c = c + 1
end
local userCategoryItem = userCategoryItemKeySplit[2]
return(userName..' '..userCategory..' '..userCategoryItem)
",
new RedisKey[] { "UserCategoryItemNames:" + userModel.UserId });
//PART TWO OF THE SCRIPT
var doesExist2 = (bool)db.ScriptEvaluate(#"
local userName = 'DummyName'
local userCategory = 'Book'
local userCategoryItem = 'Harry-Potter'
-- Fetch Users, UserCategories and UserCategoryItems from the Redis DB
local userData = {'DummyName', 'User1', 'User2', 'User3'}
local userCategoryData = {'Book', 'Movie', 'Journals'}
local userCategoryItemData = {'Hardy-Boys', 'Harry-Potter', 'Shawshank-Redemption', 'The-Terminal'}
local msg
-- Loop through the fetched values and compare them with parameters; if all the parameters are found return true else return false
for i=1,#userData,1
do
if(userData[i] == userName)
then
for i=1,#userCategoryData,1
do
if(userCategoryData[i] == userCategory)
then
for i=1,#userCategoryItemData,1
do
if(userCategoryItemData[i] == userCategoryItem)
then
msg = true
break
else
msg = false
end
end
break
else
msg = false
end
end
break
else
msg = false
break
end
end
return(msg)
//PART ONE & TWO COMBINED OF THE SCRIPT
",
new RedisKey[] { "UserDetails:" + "DummyName", "UserCategories:" + "Book", "UserCategoryItems:" + "Harry-Potter" });
var doesExist3 = (bool)db.ScriptEvaluate(#"
local function isDateInRange(DateStart, DateEnd, GivenDate)
if (GivenDate > DateStart and GivenDate < DateEnd)
then
return(true)
else
return(false)
end
end
--Fetch User's Category's StartDate and EndDate
local function IsCategoryDateValid()
local givenDate, DateStart, DateEnd
GivenDate = '2017-01-09'
StartDate = '2015-01-01'
EndDate = '2018-01-01'
local isDateValid
isDateValid = isDateInRange(StartDate, EndDate, GivenDate)
return(isDateValid)
end
-- Pass User, UserCategory and UserCategoryItem as parameters
local userNameKey = 'UserDetails:DummyName'
local userCategoryKey = 'UserCategories:Book'
local userCategoryItemKey = 'UserCategoryItems:Harry-Potter'
local userNameKeySplit = {}
local a = 1
for i in string.gmatch(userNameKey, '([^'..':'..']+)') do
userNameKeySplit[a] = i
a = a + 1
end
local userName = userNameKeySplit[2]
local userCategoryKeySplit = {}
local b = 1
for j in string.gmatch(userCategoryKey, '([^'..':'..']+)') do
userCategoryKeySplit[b] = j
b = b + 1
end
local userCategory = userCategoryKeySplit[2]
local userCategoryItemKeySplit = {}
local c = 1
for k in string.gmatch(userCategoryItemKey, '([^'..':'..']+)') do
userCategoryItemKeySplit[c] = k
c = c + 1
end
local userCategoryItem = userCategoryItemKeySplit[2]
-- Fetch Users, UserCategories and UserCategoryItems from the Redis DB
local userData = {'DummyName', 'User1', 'User2', 'User3'}
local userCategoryData = {'Book', 'Movie', 'Journals'}
local userCategoryItemData = {'Hardy-Boys', 'Harry-Potter', 'Shawshank-Redemption', 'The-Terminal'}
local msg
-- Loop through the fetched values and compare them with parameters; if all the parameters are found return true else return false
for i=1,#userData,1
do
if(userData[i] == userName)
then
for i=1,#userCategoryData,1
do
if(userCategoryData[i] == userCategory)
then
for i=1,#userCategoryItemData,1
do
if(userCategoryItemData[i] == userCategoryItem)
then
msg = true
break
else
msg = false
end
end
break
else
msg = false
end
end
break
else
msg = false
break
end
end
return(msg)
",
new RedisKey[] { "UserDetails:" + "DummyName", "UserCategories:" + "Book", "UserCategoryItems:" + "Harry-Potter" });
Thank you for your patience and reading this much. I hope I have clarified the problem in detail. Please provide some help in solving the issue. Thank you.
I'm trying to build a script for a MUD I play that will create a table to keep track of average xp for each mob. I'm having trouble with the syntax of checking whether an element in a table exists and if not creating it. I tried something like this but keep getting: attempt to index field '?' (a nil value)
mobz_buried = {
{mob = "troll", quantity = 2}
{mob = "warrior", quantity = 1}
{mob = "wizard", quantity = 1}} -- sample data
number_of_mobz_buried = 4
xp_from_bury = 2000 -- another script generates these values, these are all just examples
xp_per_corpse = xp_from_bury / number_of_mobz_buried
for _, v in ipairs(mobz_buried) do
if type(mobz[v].kc) == "variable" then -- kc for 'kill count', number of times killed
mobz[v].kc = mobz[v].kc + 1 -- if it exists increment kc
else
mobz[v].kc = 1 -- if it doesn't exist create a key value that matches the mobs name and make the kc 1
end
if type(mobz[v].xp) == "variable" then -- xp for average experience points
mobz[v].xp = (((mobz[v].kc - 1) * mobz[v].xp + xp_per_corpse)/mobz[v].kc) -- just my formula to find the average xp over a range of differant buries
else
mobz[v].xp = xp_per_corpse -- if it doesn't exist create the table just like before
end
end
I'm trying to end up with mobz.troll = {kc, xp}, mobz.warrior = {kc, xp}, mobz.wizard = {kc, xp} and the ability to add more key values based off of the names mobz_buried gives me.
Based on extra info from your comments, it sounds like you didn't construct a table for mobz. Try this:
local mobz = {}
for _, v in ipairs(mobz_buried) do
mobz[v.mob] = mobz[v.mob] or {}
mobz[v.mob].kc = (mobz[v.mob].kc or 0) + 1
-- etc...
end
Quick facts, I got this function from http://lua-users.org/wiki/SplitJoin at the very bottom, and am attempting to use it in the Corona SDK, though I doubt that's important.
function string:split(sSeparator, nMax, bRegexp)
assert(sSeparator ~= '')
assert(nMax == nil or nMax >= 1)
local aRecord = {}
if self:len() > 0 then
local bPlain = not bRegexp
nMax = nMax or -1
local nField=1 nStart=1
local nFirst,nLast = self:find(sSeparator, nStart, bPlain)
while nFirst and nMax ~= 0 do
aRecord[nField] = self:sub(nStart, nFirst-1)
nField = nField+1
nStart = nLast+1
nFirst,nLast = self:find(sSeparator, nStart, bPlain)
nMax = nMax-1
end
aRecord[nField] = self:sub(nStart)
end
return aRecord
end
The input: "1316982303 Searching server"
msglist = string.split(msg, ' ')
Gives me the error in the title. Any ideas? I'm fairly certain it's just the function is out of date.
Edit: lots more code
Here's some more from the main.lua file:
multiplayer = pubnub.new({
publish_key = "demo",
subscribe_key = "demo",
secret_key = nil,
ssl = nil, -- ENABLE SSL?
origin = "pubsub.pubnub.com" -- PUBNUB CLOUD ORIGIN
})
multiplayer:subscribe({
channel = "MBPocketChange",
callback = function(msg)
-- MESSAGE RECEIVED!!!
print (msg)
msglist = string.split(msg, ' ')
local recipient = msglist[0] --Get the value
table.remove(msglist, 0) --Remove the value from the table.
local cmdarg = msglist[0]
table.remove(msglist, 0)
arglist = string.split(cmdarg, ',')
local command = arglist[0]
table.remove(arglist, 0)
argCount = 1
while #arglist > 0 do
argname = "arg" .. argCount
_G[argname] = arglist[0]
table.remove(arglist, 0)
argCount = argCount + 1
end
Server.py:
This is the multiplayer server that sends the necessary info to clients.
import sys
import tornado
import os
from Pubnub import Pubnub
## Initiat Class
pubnub = Pubnub( 'demo', 'demo', None, False )
## Subscribe Example
def receive(message) :
test = str(message)
msglist = test.split()
recipient = msglist.pop(0)
msg = msglist.pop(0)
id = msglist.pop(0)
if id != "server":
print id
print msg
commandHandler(msg,id)
return True
def commandHandler(cmd,id):
global needOp
needOp = False
global matchListing
if server is True:
cmdArgList = cmd.split(',')
cmd = cmdArgList.pop(0)
while len(cmdArgList) > 0:
argument = 1
locals()["arg" + str(argument)] = cmdArgList.pop(0)
argument += 1
if cmd == "Seeking":
if needOp != False and needOp != id:
needOp = str(needOp)
id = str(id)
pubnub.publish({
'channel' : 'MBPocketChange',
#Message order is, and should remain:
#----------Recipient, Command,Arguments, Sender
'message' : needOp + " FoundOp," + id + " server"
})
print ("Attempting to match " + id + " with " + needOp + ".")
needOp = False
matchListing[needOp] = id
else:
needOp = id
pubnub.publish({
'channel' : 'MBPocketChange',
#Message order is, and should remain:
#----------Recipient, Command,Arguments, Sender
'message' : id + ' Searching server'
})
print "Finding a match for: " + id
elif cmd == "Confirm":
if matchListing[id] == arg1:
pubnub.publish({
'channel' : 'MBPocketChange',
#Message order is, and should remain:
#----------Recipient, Command,Arguments, Sender
'message' : arg1 + ' FoundCOp,' + id + ' server'
})
matchListing[arg1] = id
else:
pass #Cheater.
elif cmd == "SConfirm":
if matchListing[id] == arg1 and matchListing[arg1] == id:
os.system('python server.py MBPocketChange' + arg1)
#Here, the argument tells both players what room to join.
#The room is created from the first player's ID.
pubnub.publish({
'channel' : 'MBPocketChange',
#Message order is, and should remain:
#----------Recipient, Command,Arguments, Sender
'message' : id + ' GameStart,' + arg1 + ' server'
})
pubnub.publish({
'channel' : 'MBPocketChange',
#Message order is, and should remain:
#----------Recipient, Command,Arguments, Sender
'message' : arg1 + ' GameStart,' + arg1 + ' server'
})
else:
pass #hax
else:
pass
def connected():
pass
try:
channel = sys.argv[1]
server = False
print("Listening for messages on '%s' channel..." % channel)
pubnub.subscribe({
'channel' : channel,
'connect' : connected,
'callback' : receive
})
except:
channel = "MBPocketChange"
server = True
print("Listening for messages on '%s' channel..." % channel)
pubnub.subscribe({
'channel' : channel,
'connect' : connected,
'callback' : receive
})
tornado.ioloop.IOLoop.instance().start()
This error message happens if you run:
string.split(nil, ' ')
Double check your inputs to be sure you are really passing in a string.
Edit: in particular, msglist[0] is not the first position in the array in Lua, Lua arrays start at 1.
As an aside, this function was written when the intention that you'd use the colon syntactic sugar, e.g.
msglist=msg:split(' ')