how to parse this sample of json - objective-c

I assumed this as an array and I typed
_price1=[venues valueForKey:#"price_total”];
I got this an an output ,I expected to get 6 as the count when i typed
this
NSLog(#"%lu", (unsigned long)_price1.count);
The fact is that I got 1 as the output for the count.
(
(
772,
912,
912,
912,
912,
935
)
)
My doubt is how can I parse it so that the ouput is an array.Do tell me the meaning about ( ) [this brackets] when json is considered.
my code is
Ok my code is :
-(void)initialize{
id venues = [[_json valueForKey:#"hotels_prices"]valueForKey:#"agent_prices”];
_price1=[venues valueForKey:#"price_total"];//global array...
NSLog(#"%#", _price1);
NSLog(#"%lu", (unsigned long)_price1.count);}
json is: this is (id venues ) according to the code
(
(
{
id = 146;
"price_per_room_night" = 158;
"price_total" = 944;
"room_offers" = ( //problem
{
available = 0;
"meal_plan" = "Room only";
"policy_dto" = {
};
rooms = (
{
adults = 0;
children = 0;
type = "Double room";
"type_id" = "ROOMTYPE_DOUBLE";
}
);//problem
},
//see that brackets (); is the problem

Yep! I got the answer as Matt told the brackets (); should be treated as an array
the
id venues = [[_json valueForKey:#"hotels_prices"]valueForKey:#"agent_prices”];
gives the above json but if I want to get the meal plan
NSArray*meal=[[_json valueForKey:#"room_offers"]valueForKey:#"meal_plan”];
Then I can type:
NSArray*meal_plan=[meal objectAtIndex:0];//or any other index not beyond the array limit..
We can get the desired output and
the array meal can be parsed normally.

Related

Lua implementation of BestSum function using memoization

I am trying to translate the below javascript "bestSum" memoization function into lua:
const bestSum = (targetSum,numbers,memo ={}) => {
if(targetSum in memo) return memo[targetSum];
if(targetSum === 0 ) return [];
if(targetSum <0)return null;
let shortestCombination = null;
for (let num of numbers) {
const remainder = targetSum - num;
const remainderCombination = bestSum(remainder,numbers,memo);
if (remainderCombination !==null) {
const combination = [...remainderCombination, num];
if (shortestCombination === null || combination.length < shortestCombination.length)
{
shortestCombination = combination;
}
}
}
memo [targetSum] = shortestCombination;
return shortestCombination;
}
sample test cases with correct results:
console.log(bestSum(7,[5,3,4,7])); //[7]
console.log(bestSum(8,[2,3,5])); //[3,5]
console.log(bestSum(8,[1,4,5])); //[4,4]
console.log(bestSum(100,[1,2,5,25])); //[25,25,25,25]
I translated the above javascript into lua as the following:
local function BestSum(target_sum,numbers,memo)
if memo[target_sum] ~= nil then return memo[target_sum] end
if target_sum == 0 then return {} end
if target_sum < 0 then return nil end
local shortest_combination = nil
for i, num in ipairs (numbers) do
local remainder = target_sum - num
local remainder_combination = BestSum(remainder,numbers, memo)
if remainder_combination ~= nil then
local combination = remainder_combination
table.insert(combination,num )
if (shortest_combination == nil) or (#combination < #shortest_combination )then
shortest_combination = combination
end
end
end
memo[target_sum] = shortest_combination;
return shortest_combination;
end
but don't get the desired results for the two last cases...... instead get incorrect results:
BestSum(8,{1,4,5},{})==>{"4","1","4"}
BestSum(150,{5,25},{})==>
{"25","5","5","5","5","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25"}
The results are not even correct let alone being "best" case??
Can anyone spot where I'm going wrong?
Much appreciated
The problem is with this part of the translation:
local combination = remainder_combination
table.insert(combination, num)
Tables are pass by reference, so this isn't creating a new table, it's just assigning the variable combination to the same table. Modifying combination is just adding more data to remainder_combination.
The JavaScript version is taking care to create a new array, and fills it with the contents of the remainderCombination array (using '...', the spread operator):
const combination = [...remainderCombination, num];
This is the most accurate Lua translation:
local combination = {unpack(remainder_combination)}
table.insert(combination, num)
(Edit: For Lua 5.2+ it's table.unpack)

Passing an array as a parameter in a WHERE IN clause

I am trying pass in an array of strings (internal_id) to a query. The portion below counts how many elements are in the internal_id array and parameterizes them into a string so it can be compatible with SQL(Ex. if there are two IDs in internal_id, then paramString would be "$1,$2")
const { internal_id } = args; // This is an array of strings
let paramString: Array<string> = [];
for (let count = 1; count <= internal_id!.length; count++) {
paramString.push(`$${count}`)
}
let queryString = `
SELECT *
FROM customer
WHERE internal_id IN (${paramString.join(',')})`
Then I tried to pass the internal_id array as a parameter below:
const res = await db.get(queryString, [internal_id]);
But I get this error
error: bind message supplies 1 parameters, but prepared statement "" requires 2
I am not sure how to correctly pass internal_id array through db.get().
You provide and array containing another array internal_id instead of just internal_id itself.

How to pass a param for a binding in PostgreSQL - COPY (... ) TO STDOUT (FORMAT binary)?

I have some simple test table in postgres like below:
--DROP TABLE test_point
CREATE TABLE test_point
(
serie_id INT NOT NULL,
version_ts INT NOT NULL,
PRIMARY KEY (serie_id, version_ts)
);
I try to load a data from it by using COPY TO STDOUT and binary buffers. This is sql definition I use in a test case:
COPY (
SELECT version_ts
FROM test_point
WHERE
serie_id = $1::int
) TO STDOUT (FORMAT binary);
It works ok, if I don't provide any param to bind to in SQL. If I use simple select it recognizes params also as well.
I was trying to provide explicit info about param type during stmt preparation also, but results were similar (it doesn't recognize param).
This is a message I receive during the test case:
0x000001740a288ab0 "ERROR: bind message supplies 1 parameters, but prepared statement \"test1\" requires 0\n"
How to properly provide a param for COPY() statement?
I don't want to cut/concatenate strings for timestamp params and similar types.
Below is a test case showing the issue.
TEST(TSStorage, CopyParamTest)
{
auto sql = R"(
COPY (
SELECT version_ts
FROM test_point
WHERE
serie_id = $1::int
) TO STDOUT (FORMAT binary);
)";
auto connPtr = PQconnectdb("postgresql://postgres:pswd#localhost/some_db");
auto result = PQprepare(connPtr, "test1", sql, 0, nullptr);
// Lambda to test result status
auto testRes = [&](ExecStatusType status)
{
if (PQresultStatus(result) != status)
{
PQclear(result);
auto errorMsg = PQerrorMessage(connPtr);
PQfinish(connPtr);
throw std::runtime_error(errorMsg);
}
};
testRes(PGRES_COMMAND_OK);
PQclear(result);
int seriesIdParam = htonl(5);
const char *paramValues[] = {(const char *)&seriesIdParam};
const int paramLengths[] = {sizeof(seriesIdParam)};
const int paramFormats[] = {1}; // 1 means binary
// Execute prepared statement
result = PQexecPrepared(connPtr,
"test1",
1, //nParams,
paramValues,
paramLengths,
paramFormats,
1); // Output format - binary
// Ensure it's in COPY_OUT state
//testRes(PGRES_COPY_OUT);
if (PQresultStatus(result) != PGRES_COPY_OUT)
{
auto errorMsg = PQerrorMessage(connPtr);
int set_breakpoint_here = 0; // !!! !!! !!!
}
PQclear(result);
PQfinish(connPtr);
}

Getting size of a nested dictionary and then populate uitableview objective c

I have this dictionary in objective c:
{
awayScore = 2;
awayTeam = "Kode IF";
events = (
{
eventType = "01:00";
name = "01:00";
},
{
eventType = "01:00";
name = "01:00";
}
);
homeScore = 1;
homeTeam = "Partille IF FK ";
time = "01:00";
}
Now for populating a tableview i would need to know the size of "events" items so i can return the number of rows. Also how could i iterate then through them? (now I'm thinking when I'm going to use the values to populate the cells)
so 1) How can i get the size of it
and 2) How can i iterate through them and get the different values in uitableview
I know how to iterate through ALL THE KEYS, but since i don't know how to just loop through a specific key that has many items i can't show you what i have done so far
Thanks!!
Your JSon events object should be a JSon Array, so you can fast enumerate through it.
`
NSArray *events = jsonDictonary[#"events"];
for (NSDictonary *event in events) {
//parse each event
}
Where JsonDictionary is your entire Json object.

MapKit: How to retrieve apartment number from the return value of MKLocalSearchResponse

I searched thoroughly online but couldn't find any discussion about this:
The MKLocalSearchResponse object returned from a MapKit search is a collection of MKMapItem, which has the information of search results, e.g. City, state, country.
A single MKMapItem looks like this(from Xcode quick look of the object):
"Name: ADVANCED SOLUTIONS ADDICTION MANAGEMENT CurrentLocation: 0 Place: <GEOPlace: 0x9b2db90> {
address = {
formattedAddressLine = (
\"205 W Crestway Ave\",
\"Unit 200\",
\"Derby, KS 67037-1850\",
\"United States\"
);
structuredAddress = {
administrativeArea = Kansas;
administrativeAreaCode = KS;
country = \"United States\";
countryCode = US;
dependentLocality = (
Derby,
Rockford
);
fullThoroughfare = \"205 W Crestway Ave\";
geoId = (
);
locality = Derby;
postCode = 67037;
postCodeExtension = 1850;
postCodeFull = \"67037-1850\";
subAdministrativeArea = Sedgwick;
subLocality = Rockford;
subPremise = (
{
name = 200;
type = 0;
}
);
subThoroughfare = 205;
thoroughfare = \"W Crestway Ave\";
};
};
}"
I was able to retrieve all the information I needed, except the Apartment number. It's contained in the "subPremise" part, which I don't know how to retrieve.
You may suggest me to retrieve it from the "formattedAddressLines", which I have access to, but for some results, that property is empty, so I cannot rely on it.
I've also tried the "addressDictionary" property, it has all the necessary information except apartment number, which is very unthoughtful to me.
mapItem.placemark.subThoroughfare. Note that it may be empty