Is there any way to find a string from a table? - module

I don't know if there's any way to find a string from a table in Lua that matches the argument for example.
function Library.Instance(object,name)
local Explorer = {}
local Storage = {
"fart",
}
if Storage == ((theobjectname)) then
print(object)
end
end

You have to implement it by yourself.
Here is my version of a tsearch()...
-- tsearch.lua
local magictab = {}
function magictab.tsearch(self, searchfor, replace)
local searchfor, replace, self = searchfor or 'Lua', replace or '<%1>', self or _G
for key, value in pairs(self) do
if type(value) == 'string' then
local found, count = value:gsub(searchfor, replace)
if count > 0 then
print('Key:', key, 'Found:', found)
end
end
end
end
-- Creating Key/Value Pairs
magictab['A Key With Spaces'] = 'Ghostbuster Goes Ghost Busting'
magictab[#magictab + 1] = 'Another Day - Another Table'
magictab[0] = 'Here I am - The Ghost Within Machine'
-- magictab.tsearch() -- Using defaults
return magictab
An impression typed in Lua Standalone...
$ /usr/local/bin/lua
Lua 5.4.3 Copyright (C) 1994-2021 Lua.org, PUC-Rio
> t=require('tsearch')
> t.tsearch()
Key: _VERSION Found: <Lua> 5.4
> t:tsearch('Ghost')
Key: A Key With Spaces Found: <Ghost>buster Goes <Ghost> Busting
Key: 0 Found: Here I am - The <Ghost> Within Machine
> t:tsearch('%u%l+','*%1*')
Key: 1 Found: *Another* *Day* - *Another* *Table*
Key: A Key With Spaces Found: *Ghostbuster* *Goes* *Ghost* *Busting*
Key: 0 Found: *Here* I am - *The* *Ghost* *Within* *Machine*
And...
This is only one way.
...there are many.
By the way...
Above tsearch() gives arguments 1:1 to gsub().
Therefore it could be a usefull training function for pattern matching and replacement checks.
For example: Do you know the pattern %f[] is usefull for?
Or: What is a replacement function?
> t:tsearch('%f[%u+%l+]',function(match_not_used_here) return '>>' end)
Key: 1 Found: >>Another >>Day - >>Another >>Table
Key: 0 Found: >>Here >>I >>am - >>The >>Ghost >>Within >>Machine
Key: A Key With Spaces Found: >>Ghostbuster >>Goes >>Ghost >>Busting
> t:tsearch('%f[^%u+%l+]',function(match_not_used_here) return '>>' end)
Key: 1 Found: Another>> Day>> - Another>> Table>>
Key: 0 Found: Here>> I>> am>> - The>> Ghost>> Within>> Machine>>
Key: A Key With Spaces Found: Ghostbuster>> Goes>> Ghost>> Busting>>

Related

How to use mapFieldType with gdal.VectorTranslate

I'm trying to export a postgresql database into a .gpkg file, but some of my fields are lists, and ogr2ogr send me the message :
Warning 1: The output driver does not natively support StringList type for field my_field_name. Misconversion can happen. -mapFieldType can be used to control field type conversion.
But, as in the documentation, -mapFieldType is not a -lco, i don't find how to use it with the python version of gdal.VectorTranslate
here ma config :
gdal_conn = gdal.OpenEx(f"PG:service={my_pgsql_service}", gdal.OF_VECTOR)
gdal.VectorTranslate("path_to_my_file.gpkg"), gdal_conn,
SQLStatement=my_sql_query,
layerName=my_mayer_name,
format="GPKG",
accessMode='append',
)
so i've tried to add it in the -lco :
layerCreationOptions=["-mapFieldType StringList=String"]
but it didn't work
so i diged into the code of gdal, added a field mapFieldType=None into the VectorTranslateOptions function, and added into its code the following lines :
if mapFieldType is not None:
mapField_str = ''
i = 0
for k, v in mapFieldType.items():
i += 1
mapField_str += f"{k}={v}" if i == len(mapFieldType) else f"{k}={v},"
new_options += ['-mapFieldType', mapField_str]
And it worked, but is there an other way ?
And if not, where can i propose this feature ?
Thank you for your help

Schema validation of empty array for nested structure verification

I am working on a POC with Karate framework (latest version 0.9.6) and I came across with the following:
* match each response.bar contains { id:"#uuid ? _ != ''", name: "#notnull", foo: "#[] #object"}
I noticed that, when foo is an empty array, it does not fail the step.
Is it possible to add a length verification on the above step to fail if the array is empty?
Thanks in advance.
Yes, read the docs: https://github.com/intuit/karate#schema-validation
* match each response.bar contains { id:"#uuid ? _ != ''", name: "#notnull", foo: "#[_ > 0] #object"}

Bro script for reading a list of Ips and domains

I am trying to read a file with a list of IP addresses and another one with domains, as a proof of concept of the Input Framework defined in https://docs.zeek.org/en/stable/frameworks/input.html
I´ve prepared the following bro scripts:
reading.bro:
type Idx: record {
ip: addr;
};
type Idx: record {
domain: string;
};
global ips: table[addr] of Idx = table();
global domains: table[string] of Idx = table();
event bro_init() {
Input::add_table([$source="read_ip_bro", $name="ips",
$idx=Idx, $destination=ips, $mode=Input::REREAD]);
Input::add_table([$source="read_domain_bro", $name="domains",
$idx=Idx, $destination=domains, $mode=Input::REREAD]);
Input::remove("ips");
Input::remove("domains");
}
And the bad_ip.bro script, which check if an IP is in the blacklist, which loads the previous one:
bad_ip.bro
#load reading.bro
module HTTP;
event http_reply(c: connection, version: string, code: count, reason: string)
{
if ( c$id$orig_h in ips )
print fmt("A malicious IP is connecting: %s", c$id$orig_h);
}
However, when I run bro, I get the error:
error: Input stream ips: Table type does not match index type. Need type 'string':string, got 'addr':addr
Segmentation fault (core dumped)
You cannot assign a string type to an addr type. In order to do so, you must use the utility function to_addr(). Of course, it would be wise to verify that that string contains a valid addr first. For example:
if(is_valid_ip(inputString){
inputAddr = to_addr(inputString)
} else { print "addr expected, got a string"; }

What is fieldno in Tarantool space config?

Extract from the config:
space[0].index[0].type = "TREE"
space[0].index[0].unique = 1
space[0].index[0].key_field[0].fieldno = 0
space[0].index[0].key_field[0].type = "STR"
What does fieldno mean? Failed to find clear answer in the docs.

How can I signal parsing errors with LPeg?

I'm writing an LPeg-based parser. How can I make it so a parsing error returns nil, errmsg?
I know I can use error(), but as far as I know that creates a normal error, not nil, errmsg.
The code is pretty long, but the relevant part is this:
local eof = lpeg.P(-1)
local nl = (lpeg.P "\r")^-1 * lpeg.P "\n" + lpeg.P "\\n" + eof -- \r for winblows compat
local nlnoeof = (lpeg.P "\r")^-1 * lpeg.P "\n" + lpeg.P "\\n"
local ws = lpeg.S(" \t")
local inlineComment = lpeg.P("`") * (1 - (lpeg.S("`") + nl * nl)) ^ 0 * lpeg.P("`")
local wsc = ws + inlineComment -- comments count as whitespace
local backslashEscaped
= lpeg.P("\\ ") / " " -- escaped spaces
+ lpeg.P("\\\\") / "\\" -- escaped escape character
+ lpeg.P("\\#") / "#"
+ lpeg.P("\\>") / ">"
+ lpeg.P("\\`") / "`"
+ lpeg.P("\\n") -- \\n newlines count as backslash escaped
+ lpeg.P("\\") * lpeg.P(function(_, i)
error("Unknown backslash escape at position " .. i) -- this error() is what I wanna get rid of.
end)
local Line = lpeg.C((wsc + (backslashEscaped + 1 - nl))^0) / function(x) return x end * nl * lpeg.Cp()
I want Line:match(...) to return nil, errmsg when there's an invalid escape.
LPeg itself doesn't provide specific functions to help you with error reporting. A quick fix to your problem would be to make a protected call (pcall) to match like this:
local function parse(text)
local ok, result = pcall(function () return Line:match(text) end)
if ok then
return result
else
-- `result` will contain the error thrown. If it is a string
-- Lua will add additional information to it (filename and line number).
-- If you do not want this, throw a table instead like `{ msg = "error" }`
-- and access the message using `result.msg`
return nil, result
end
end
However, this will also catch any other error, which you probably don't want. A better solution would be to use LPegLabel instead. LPegLabel is an extension of LPeg that adds support for labeled failures. Just replace require"lpeg" with require"lpeglabel" and then use lpeg.T(L) to throw labels where L is an integer from 1-255 (0 is used for regular PEG failures).
local unknown_escape = 1
local backslashEscaped = ... + lpeg.P("\\") * lpeg.T(unknown_escape)
Now Line:match(...) will return nil, label, suffix if there is a label thrown (suffix is the remaining unprocessed input, which you can use to compute for the error position via its length). With this, you can print out the appropriate error message based on the label. For more complex grammars, you would probably want a more systematic way of mapping the error labels and messages. Please check the documentation found in the readme of the LPegLabel repository to see examples of how one may do so.
LPegLabel also allows you to catch the labels in the grammar by the way (via labeled choice); this is useful for implementing things like error recovery. For more information on labeled failures and examples, please check the documentation.