Post request - communicate between r shiny UI and python flask app - post

library(shiny)
library(shiny.router)
library(shinydashboard)
library(shinyWidgets)
library(png)
library(flexdashboard)
library(jsonlite)
library(reticulate)
library(httr)
Location <- c('East','West','South','North','NorthEast','SouthEast','SouthWest','NorthWest')
industry <- c('Finance','Media','Healthcare','Retail','Telecommunications','Automotive','Digital Marketing', 'Professional Services','Cyber Security', 'Mining','Government','Manufacturing','Transport')
skills <- c('Python','R programming', 'Java', 'SQL', 'C++', 'C', 'Interpersonal skills', 'Machine Learning', 'Deep Learning', 'Data Visualisation', 'Data wrangling')
jobtype <- c('Full time', 'Full time', 'Internship')
home_page <- div(
ui <- dashboardPage(
dashboardHeader(title = "Job Portal"),
dashboardSidebar(
sidebarMenu(
menuItem("Search", tabName = "Search", icon = icon("search"))
)
),
dashboardBody(
tabItems(
tabItem("Search",
fluidRow(
column(4,
hr(),
sliderInput(inputId = "Salary", label = "Expected Salary:",
min = 0, max = 10000,
value = 0, step = 500)),
column(4,
hr(),
selectInput(inputId = 'Industry', label='Industry', c(Choose='', industry), selectize=FALSE)
),
column(4,
hr(),
selectInput(inputId = 'Location', label = 'Location', c(Choose='', Location),selectize=FALSE)
)
),
fluidRow(
column(4,
hr(),
selectInput(inputId = 'Type', label = 'Job type', c(Choose='', jobtype),selectize=FALSE)
),
column(4,
hr(),
selectInput(inputId = 'Skills', label = 'Skills', c(Choose='', skills), selectize=FALSE)
),
column(4,
hr(),
actionButton("search", label = "Search", width = '250px'))
)
)
)
)
)
)
server <- function(input, output, session) {
user_input <- reactive({
#url = "http://localhost:5000"
toJSON(
list(
expected_salary = input$Salary,
industry = input$Industry,
location = input$Location,
expected_hours = input$Type,
skills = input$Skills
),
pretty = TRUE
)})
observeEvent(input$search, {
x <- POST("http://127.0.0.1:5000/recommendation", body = user_input, encode = 'json')
content(x)
})
}
shinyApp(ui, server)
# Run the application
shinyApp(ui = ui, server = server)
We want our r shiny app to pass a json object to our python flask through a post request. The code we have so far is given. We want to send the json file to the url in POST. Currently, when we press search on our shiny app, our app crashes. we think the issue is in how we are using observeEvent function linked to our search button. Any help on how to resolve this is appreciated

Related

How do I remove certain special characters from a string in Lua?

Within Lua, how would I remove specific special characters from a string?
For example, a name input would be:
L#)iAm PAGE changed to Liam Page
José Luis changed to Jose Luis
JACK O'NIEL changed to Jack O'Niel
I currently have
firstName = ipFirstName:gsub('[%p%c%s]', '')
lastName = ipLastName:gsub('[%p%c%s]', '')
but it is too broad.
Below is a simple function for sanitizing names, to a certain degree:
local function sanitizeName (name)
local accented = {
['ß'] = 'ss'
, ['à'] = 'a', ['á'] = 'a', ['â'] = 'a', ['ã'] = 'a', ['å'] = 'a'
, ['ä'] = 'ae', ['æ'] = 'ae'
, ['ç'] = 'c'
, ['è'] = 'e', ['é'] = 'e', ['ê'] = 'e', ['ë'] = 'e'
, ['ì'] = 'i', ['í'] = 'i', ['î'] = 'i', ['ï'] = 'i'
, ['ð'] = 'dh'
, ['ñ'] = 'n'
, ['ò'] = 'o', ['ó'] = 'o', ['ô'] = 'o', ['õ'] = 'o', ['ø'] = 'o'
, ['ö'] = 'oe'
, ['ù'] = 'u', ['ú'] = 'u', ['û'] = 'u'
, ['ü'] = 'ue'
, ['ý'] = 'y', ['ÿ'] = 'y'
, ['þ'] = 'th'
}
local sanitized = name
:lower() -- Bring everything to lower case.
:gsub ('%s+', ' ') -- Normalise whitespaces.
-- Replace some non-ASCII characters:
for fancy, plain in pairs (accented) do
sanitized = sanitized:gsub (fancy, plain)
end
return sanitized
:gsub ("[^%a ']", '') -- Remove everyting but ASCII, spaces and apostrophes.
:gsub ('^%a', string.upper) -- Capitalise the first letter of the first name.
:gsub ("[ ']%a", string.upper) -- Capitalise the first letter of other names.
end
for _, name in ipairs {'L#)iAm PAGE', 'José Luis', "JACK O'NIEL"} do
print (name, sanitizeName (name))
end
However, to deal with Unicode character properly, study this page. Also note that most of assumptions about personal names are false.

Array element from lua

I'm making a fivem server. But when i tru to pick the job.grade.name he says No grades.
QBShared.Jobs = {
["unemployed"] = {
label = "Werkloos",
grades = {
[0] = {
name = 'Werkloos',
payment = 10,
},
},
defaultDuty = true,
},
["police"] = {
label = "Politie",
grades = {
[0] = {
name = "Politie - Student", **Want to pick this**
payment = 200,
},
[1] = {
name = 'Aspirant',
payment = 300,
},
[2] = {
name = 'Agent',
payment = 400,
},
[3] = {
name = 'Hoofd Agent',
payment = 400,
},
[4] = {
name = 'Brigadier',
payment = 400,
},
[5] = {
name = 'Inspecteur',
payment = 400,
},
[6] = {
name = 'Hoofd Inspecteur',
payment = 400,
},
[7] = {
name = 'Commissaris',
payment = 400,
},
[8] = {
name = 'Hoofd Commissaris',
payment = 400,
},
[9] = {
name = 'Eerste Hoofd Commissaris',
isboss = true,
payment = 400,
},
},
defaultDuty = true,
So people can type /baan and then the see Baan: Politie
What i want is The must see Baan: Politie - Politie Student
QBCore.Commands.Add("baan", "Kijk wat je baan is", {}, false, function(source, args)
local Player = QBCore.Functions.GetPlayer(source)
TriggerClientEvent('chatMessage', source, "SYSTEM", "warning", "Baan: "..Player.PlayerData.job.label .. ' - ' ..Player.PlayerData.job.grade.name)
end)
Someone can help me? Because i want to learn more about lua but dont get this to work..
'Jobs' needs a string key to access it
and 'grades' needs a numerical index
Player .PlayerData .Jobs [job] .grades [grade] .name
TriggerClientEvent('chatMessage', source, "SYSTEM", "warning", "Baan: "..Player.PlayerData.job.label .. ' - ' ..Player.PlayerData.Jobs[job].grades[grade].name)
I'm assuming that somehow within your game engine, these values get parsed into PlayerData. That'll depend on the functions contained within fivem, and that you've used them properly. Otherwise, to access the raw table data, it's more like this:
print( QBShared.Jobs['police'].label )
Politie
print( QBShared.Jobs['police'].grades[0].name )
Politie - Student
print( QBShared.Jobs['police'].grades[0].payment )
200
if the game rearranges those during import into PlayerData, it might be
Player.PlayerData[job][grade].name
but it's very likely it remains in the original syntax illustrated above.

What is the most efficient way to extract/collect files from a list of targets/providers in Bazel?

I'm writing some rules and learning Starlark as I progress.
Assume I have my own provider:
ModularResources = provider(
doc = "Modular resources",
fields = {
"artifactId": "Former Maven artifact id (don't ask me why)",
"srcs": "List of labels (a glob(..) thing)",
},
)
def _modular_resources_impl(ctx):
return ModularResources(
artifactId = ctx.attr.artifactId,
srcs = ctx.attr.srcs,
)
modular_resources = rule(
implementation = _modular_resources_impl,
attrs = {
"artifactId": attr.string(
mandatory = True,
),
"srcs": attr.label_list(
allow_files = True,
mandatory = True,
),
},
)
Then I have a generator rule which requires these:
some_generator = rule(
attrs = {
"deps": attr.label_list(
providers = [ ModularResources ]
),
...
},
...
)
In my implementation I discovered that I need to do a couple of unwraps to get the files:
def _get_files(deps):
result = []
for dep in deps:
for target in dep[ModularResources].srcs:
result += target.files.to_list()
return result
Is there a more efficient way to perform the collection?
As to why I'm doing this, the generator actually needs a special list of files like this:
def _format_files(deps):
formatted = ""
for dep in deps:
for target in dep[ModularResources].srcs:
formatted += ",".join([dep[ModularResources].artifactId + ":" + f.path for f in target.files.to_list()])
return formatted
FWIW, here is an example how this is used:
a/BUILD:
modular_resources(
name = "generator_resources",
srcs = glob(
["some/path/**/*.whatever"],
),
artifactId = "a",
visibility = ["//visibility:public"],
)
b/BUILD:
some_generator(
name = "...",
deps = [
"//a:generator_resources"
]
)
If you want to trade memory for better performance, maybe the operation can more easily be parallelised by blaze if it's done in the provider instead:
def _modular_resources_impl(ctx):
return ModularResources(
artifactId = ctx.attr.artifactId,
formatted_srcs = ",".join([artifactId + ":" + f.path for f in ctx.files.src])
)

how to save data from a nativeTextField to sqlite database in corona

Having a hard time saving data from a native text field to sqlite database in corona.
here are some relevant code:
function printrecord()
for row in db:nrows("SELECT * FROM test") do
t = display.newText(row.pname .. " " .. row.age .. " " .. row.desc, 20, 30 * row.id, null, 16)
t:setTextColor(255,255,255)
end
end
newData = native.newTextField ( 20, _H - 90, 280, 30 )
newData.inputType = "text"
saveData = function ( event )
textString = newData.text
db:exec( [[ INSERT INTO test VALUES (NULL, textString, 30, "unknown")]] )
t:removeSelf()
t = nil
printrecord()
end
savebutton = widget.newButton {
default = "buttonGreen.png",
over = "buttonGreenOver.png",
label = "Save",
embose = true,
onRelease = saveData
}
when I try to change the textString from db:exec( [[ INSERT INTO test VALUES (NULL, textString, 30, "unknown")]] ) to a string like "this is a string" it seems to work fine, can anyone help?
Lua will not evaluate textString inside the double brackets... Run this in Corona to see the difference:
textString="hello world"
print([[ INSERT INTO test VALUES (NULL, textString, 30, "unknown")]])
print([[ INSERT INTO test VALUES (NULL,"]]..textString..[[",30,"unknown")]])
Hope this helps.

Lua iterator to array

In Lua parlance, is there any syntactic sugar for turning an iterator function into an array (repeated invocations with results stored in ascending indices), perhaps something in the standard library ?
I'm tokenizing a string belonging to a protocol and need to to have positional access to elements at the start of the string, and the end of the string is a variant collection.
The code (specific to my use-case) is as follows, I find it hard to believe that it isn't in the standard library :d
local array_tokenise = function (line)
local i = 1;
local array = {};
for item in string.gmatch(line,"%w+") do
array[i] = item;
i = i +1
end
return array
end
There's no standard library function for it. But really, it's pretty trivial to write:
function BuildArray(...)
local arr = {}
for v in ... do
arr[#arr + 1] = v
end
return arr
end
local myArr = BuildArray(<iterator function call>)
This will only work if your iterator function returns single elements. If it returns multiple elements, you'd have to do something different.
As Nicol Bolas said, there is no standard library function that performs the action you desire.
Here is a utility function that extends the table library:
function table.build(build_fn, iterator_fn, state, ...)
build_fn = (
build_fn
or function(arg)
return arg
end
)
local res, res_i = {}, 1
local vars = {...}
while true do
vars = {iterator_fn(state, vars[1])}
if vars[1] == nil then break end
--build_fn(unpack(vars)) -- see https://web.archive.org/web/20120708033619/http://trac.caspring.org/wiki/LuaPerformance : TEST 3
res[res_i] = build_fn(vars)
res_i = res_i+1
end
return res
end
Here is some example code demonstrating usage:
require"stringify"
local t1 = {4, 5, 6, {"crazy cake!"}}
local t2 = {a = "x", b = "y", c = "z"}
print(stringify(table.build(nil, pairs(t1))))
print(stringify(table.build(nil, pairs(t2))))
print(stringify(table.build(
function(arg) -- arg[1] = k, arg[2] = v
return tostring(arg[1]).." = "..tostring(arg[2])
end
, pairs(t1)
)))
local poetry = [[
Roses are red, violets are blue.
I like trains, and so do you!
By the way, oranges are orange.
Also! Geez, I almost forgot...
Lemons are yellow.
]]
print(stringify(table.build(
function(arg) -- arg[1] == plant, arg[2] == colour
return (
string.upper(string.sub(arg[1], 1, 1))..string.lower(string.sub(arg[1], 2))
.. " is "
.. string.upper(arg[2]).."!"
)
end
, string.gmatch(poetry, "(%a+)s are (%a+)")
)))
Output:
{
[1] = {
[1] = 1,
[2] = 4,
},
[2] = {
[1] = 2,
[2] = 5,
},
[3] = {
[1] = 3,
[2] = 6,
},
[4] = {
[1] = 4,
[2] = {
[1] = "crazy cake!",
},
},
}
{
[1] = {
[1] = "a",
[2] = "x",
},
[2] = {
[1] = "c",
[2] = "z",
},
[3] = {
[1] = "b",
[2] = "y",
},
}
{
[1] = "1 = 4",
[2] = "2 = 5",
[3] = "3 = 6",
[4] = "4 = table: 00450BE8",
}
{
[1] = "Rose is RED!",
[2] = "Violet is BLUE!",
[3] = "Orange is ORANGE!",
[4] = "Lemon is YELLOW!",
}
stringify.lua can be found here
if you are just looking to auto-increment the table key for each data element, you can use table.insert(collection, item) - this will append the item to the collection and sets the key to the collection count + 1

Resources