Why Lua creates table inside table in recursive function? - recursion

I want to replace each value in the table to another value. My code:
function substitute_in_table(requests)
local function helper(r, result)
for k, v in pairs(r) do
if type(v) == "table" then
result[k] = helper(v, result)
else
result[k] = 'someValue'
end
end
return result
end
return helper(requests, {})
end
r = {
request = {
headers = "a",
body = "b"
}
}
result = substitute_in_table(r)
print(inspect(result))
In the result I have got a table like this:
{
headers = "someValue"
body = "someValue",
request = {
headers = "someValue"
body = "someValue"
}
}
But the expected result is
request = {
headers = "someValue"
body = "someValue"
}

it looks like you should change line
result[k] = helper(v, result)
into
result[k] = helper(v, {})
so you would copy subtable into new table, and then insert result into original table, instead of copying subtable directly into original table

Related

Lua Recursion issue unexpected result

I'm trying to figure out why this function is ignoring the middle most table? I'm overlooking something simple I assume.
Here's the code
tbl = {
name = "first table";
tbl = {
name = "middle table";
tbl = {
name = "last table";
};
};
}
sayName = function(tbl)
print(tbl.name)
if tbl.tbl ~= nil then
for _,v in pairs(tbl.tbl) do
sayName(v)
end;
end;
end;
sayName(tbl)
Output>
first table
last table
nil
In your example, you have a recursive structure, each table have 1 name and possibly a sub-table named tbl. So, I am not clear why would one use the for loop in these conditions.
tbl = {
name = "first table",
tbl = {
name = "middle table",
tbl = {
name = "last table"
}
}
}
function PrintTable (Table)
print("# Name", Table.name)
local SubTable = Table.tbl
if SubTable then
return PrintTable(SubTable)
end
end
PrintTable(tbl)
Will return:
# Name first table
# Name middle table
# Name last table

Amazon DynamoDBv2 QueryOperationConfig SelectValues.Count not working

I have this piece of code like this:
var options = new DynamoDBOperationConfig
{
ConditionalOperator = ConditionalOperatorValues.Or,
OverrideTableName = nameTable,
ConsistentRead = true
};
new QueryOperationConfig()
{
IndexName = indexName,
Filter = queryFilter,
Select = SelectValues.Count
};
result = context.FromQueryAsync<TEntity>(queryConfig, options).GetRemainingAsync().Result;
as per the documentation, it should return just the count of values that match the filter, at least, the piece of code in the SelectValues class says that
//
// Summary:
// An enumeration of all supported Select values for Query and Scan. Value of Count
// will force service to return the number of items, not the items themselves.
but result is always an empty list; how can i make the count work ?
If you are still looking for the answer, this is the solution:
new QueryOperationConfig()
{
IndexName = indexName,
Filter = queryFilter,
Select = SelectValues.Count,
ConsistentRead = true
};
var table = context.GetTargetTable<TEntity>();
var search = table.Query(queryConfig);
result = search.Count;
Having ConsistentRead set to true will cause it to give you real time updates when the table is updated.
It's not working on Document level...
You can try to do this in low level model.
int count = 0;
Dictionary<string, AttributeValue> lastKey = null;
do
{
var request = new QueryRequest
{
TableName = "tableNmae",
IndexName = "indexName",
KeyConditionExpression = "ID= :v_ID",
ExpressionAttributeValues = new Dictionary<string, AttributeValue>
{
{
":v_ID",
new AttributeValue
{
N = "1"
}
}
},
ConsistentRead = false,
Select = Select.COUNT,
ExclusiveStartKey = lastKey
};
var respone = await tableClient.QueryAsync(request);
count += respone.Count;
lastKey = respone.LastEvaluatedKey;
} while (lastKey != null && lastKey.Count != 0);

List sparql result into asp.net component

I want to list sparql query result into textbox(multi line) or Grid view or list
But the code shown below returns only one result!
Please any help?
IGraph g = new Graph();
g.LoadFromFile("example.owl");
try
{
SparqlQueryParser par = new SparqlQueryParser();
SparqlQuery q = par.ParseFromString(#"PREFIX uni:<http://www.semanticweb.org/salim/ontologies/2018/10/university-ontology-2#>SELECT ?P_Name (COUNT(?P_Name) AS ?Material_Num)
WHERE
{
?P uni:Have ?Material;
uni:P_Name ?P_Name.
}
GROUP BY ?P_Name");
object results = g.ExecuteQuery(q);
if (results is SparqlResultSet)
{
SparqlResultSet rset = (SparqlResultSet)results;
foreach (SparqlResult r in rset)
{
TextBox1.Text = r.ToString();
//or
GridView1.DataSource = r.ToString();
GridView1.DataBind();
}
}
}

dealing with a null date field

I have a date field on an XPage, this control may contain a date or be blank. In a repeat control I have this code:
var doc:NotesDocument = detailData.getDocument();
var sDate = doc.getItemValue("ACAutoStart");
doc.recycle()
return "Start Date = " + sDate
If ACAutoStart contains a date then it is displayed as [10/10/2013 12:34:15 AM MDT] if it is blank it displays as []. As I understand it the [] indicates that the result is an array but if I try using sDate[0] there is an error. I can't use getItemValueDateTime as it does not like the null return. How do I get this into a simple string value?
Replace your last line with return "Start Date = " + sDate.firstElement().
doc.getItemValue() returns an object of class java.util.Vector. As it is not an Array you get the first element with firstElement() instead of [0] .
UPDATE:
As you mentioned in your comment it has to work also for empty values and you added try:
var sDate = "";
try {sDate = doc.getItemValue("ACAutoStart").firstElement()} catch (e) {};
return "Start Date = " + sDate
...just as another way (returns converted NotesDateTime to Date):
function getJavaDateData(doc:NotesDocument, field:string)
{
var item:NotesItem = doc.getFirstItem(field);
if (item != null){
var dt:NotesDateTime = item.getDateTimeValue();
if (dt != null){
return dt.toJavaDate();
}
}
return null;
}
Off-course need to be adapted for your logic...

queries in entity framework

i have written the following query and it is giving error Unable to cast object of type
System.Data.Objects.ObjectQuery'[ITClassifieds.Models.Viewsearch]' to type 'ITClassifieds.Models.Viewsearch'.
my code is as follows
if (zipcode.Contains(","))//opening of zipcode conatins comma
{
do
{
zipcode = zipcode.Replace(" ", " ");
zipcode = zipcode.Replace(", ", ",");
} while (zipcodecity.Contains(" "));
char[] separator = new char[] { ',' };
string[] temparray = zipcode.Split(separator);
var zipcd = (from u in db.ZipCodes1
where u.CityName == temparray[0] && u.StateAbbr == temparray[1] && u.CityType == "D"
select new Viewsearch
{
Zipcode = u.ZIPCode
}).Distinct();
Viewsearch vs = (Viewsearch)zipcd;
if (zipcd.Count() > 0)
{
zipcode = vs.Zipcode;
locations = "";
}
else
{
tempStr = "";
zipcode = "";
}
}
You need to do
If it will always exist:
Viewsearch vs = zipcd.First()
If not use, and then check for null before using
Viewsearch vs = zipcd.FirstOrDefault()
You could also use Single if there will always be 1 or None.
The Distinct method returns an enumerable collection (in your case, and ObjectQuery<T>, which may contain more than one element. You can't typecast that directly to an item in the collection, you need to use one of the IEnumerable methods to get it:
Viewsearch vs = zipcd.SingleOrDefault();
if ( vs != null )
{
zipcode = vs.Zipcode;
locations = String.Empty;
}
else
{
zipcode = String.Empty;
tempStr = String.Empty;
}
SingleOrDefault will throw an exception if there is more than one item in the collection; if that's a problem, you can also use FirstOrDefault to grab the first item, as one example.
Also, unrelated to your question, but you don't need the temporary array variable for your string separators. The parameter to the Split method is a params array so you can just call it like this:
string[] temparray = zipcode.Split(',');
Replace the zipcd query with:
var cityName = temparray[0];
var stateAbbr = temparray[1];
Viewsearch vs = new Viewsearch {
Zipcode = db.ZipCodes1.Where(u.CityName == cityName && u.StateAbbr == stateAbbr && u.CityType == "D").First().ZIPCode
};

Resources