how to parse data from json file in flutter? - flutter-dependencies

Error on line 60, column 2 of pubspec.yaml: Expected a key while parsing a block mapping.
â•·
60 │ assets:
│ ^
╵
Process finished with exit code 65
i need to show data from json file

you can user dart:convert API. you can use JsonCodec class to parse data from json file.
here is an example .
{
"name": "John Doe",
"age": 30,
"email": "johndoe#example.com"
}
String jsonData = await rootBundle.loadString('assets/data.json');
dynamic data = json.decode(jsonData);
String name = data['name'];
int age = data['age'];
String email = data['email'];

Related

Kraken API authentication sample converted from python to Google apps script is not returning the same output

I am trying to convert python kraken API auth to Google Script to use it in a Google Spreadsheet, but with no luck.
# python sample
def get_kraken_signature(urlpath, data, secret):
postdata = urllib.parse.urlencode(data)
encoded = (str(data['nonce']) + postdata).encode()
message = urlpath.encode() + hashlib.sha256(encoded).digest()
mac = hmac.new(base64.b64decode(secret), message, hashlib.sha512)
sigdigest = base64.b64encode(mac.digest())
return sigdigest.decode()
api_sec = "kQH5HW/8p1uGOVjbgWA7FunAmGO8lsSUXNsu3eow76sz84Q18fWxnyRzBHCd3pd5nE9qa99HAZtuZuj6F1huXg=="
data = {
"nonce": "1616492376594",
"ordertype": "limit",
"pair": "XBTUSD",
"price": 37500,
"type": "buy",
"volume": 1.25
}
signature = get_kraken_signature("/0/private/AddOrder", data, api_sec)
print("API-Sign: {}".format(signature))
# prints API-Sign: 4/dpxb3iT4tp/ZCVEwSnEsLxx0bqyhLpdfOpc6fn7OR8+UClSV5n9E6aSS8MPtnRfp32bAb0nmbRn6H8ndwLUQ==
I ended up with this, but it's not returning the same output.
# google script sample from my sheet
function get_kraken_sinature(url, data, nonce, secret) {
var message = url + Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, Utilities.base64Encode(nonce + data));
var base64Secret = Utilities.base64Decode(secret);
var mac = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, message, secret);
return Utilities.base64Encode(mac);
}
signature = get_kraken_signature("/0/private/AddOrder", data, api_sec)
print("API-Sign: {}".format(signature))
# prints API-Sign: Jn6Zk8v41uvMWOY/RTBTrb7zhGxyAOTclFFe7lySodBnEnXErfJgIcQb90opFwccuKDd0Nt1l71HT3V9+P8pUQ==
Both code samples should do the same, and are supposed to output an identical API-Sign key. They are not at this stage, and I am wondering why is that.
I believe your goal is as follows.
You want to convert your python script to Google Apps Script.
In your Google Apps Script, you have already confirmed that the script for requesting works fine. You want to convert get_kraken_signature of your python script to Google Apps Script.
In this case, how about the following modified script?
Modified script:
function get_kraken_sinature(url, data, nonce, secret) {
var str = Object.entries(data).map(([k, v]) => `${k}=${v}`).join("&");
var message = Utilities.newBlob(url).getBytes().concat(Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, nonce + str));
var mac = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, message, Utilities.base64Decode(secret));
return Utilities.base64Encode(mac);
}
// Please run this function.
function main() {
const data = {
"nonce": "1616492376594",
"ordertype": "limit",
"pair": "XBTUSD",
"price": 37500,
"type": "buy",
"volume": 1.25
};
var url = "/0/private/AddOrder";
var nonce = "1616492376594";
var secret = "kQH5HW/8p1uGOVjbgWA7FunAmGO8lsSUXNsu3eow76sz84Q18fWxnyRzBHCd3pd5nE9qa99HAZtuZuj6F1huXg==";
var res = get_kraken_sinature(url, data, nonce, secret);
console.log(res)
}
References:
computeDigest(algorithm, value)
computeHmacSignature(algorithm, value, key)

set pagesize limit for Getrequest using Java in Rally rest API

THe question i have is i am trying to get all the userstories related to a release, i created a query request for type release and got the ref to workproduct.
so i got something like this from the query response "https://rally1.rallydev.com/slm/webservice/v2.0/Release/12345678/WorkProducts"
Now I am use this in my GET REQUEST to get all the user stories related to the Release.
The response is giving only 20 user stories since the default page size is 20.
Is there a way to increase the page size for get request.
the code is something like this :
QueryRequest iterationRequest = new QueryRequest("release");
iterationRequest.setFetch(new Fetch("Name", "Workspace", "WorkProducts","Feature"));
iterationRequest.setWorkspace("/workspace/12345678");
iterationRequest.setProject("/project/4567890");
iterationRequest.setPageSize(200);
iterationRequest.setQueryFilter(new QueryFilter("Name", "=", Release));
QueryResponse iterationQueryResponse = restApi.query(iterationRequest);
JsonArray iterationQueryResults = iterationQueryResponse.getResults();
JsonElement iterationQueryElement = iterationQueryResults.get(0);
JsonObject iterationQueryObject = iterationQueryElement.getAsJsonObject();
JsonObject workprodobj = iterationQueryObject.get("WorkProducts").getAsJsonObject();
String workprodref = workprodobj.get("_ref").getAsString();
System.out.println("workprodref :" + workprodref);
GetRequest getRequest = new GetRequest(workprodref);
getRequest.setFetch(new Fetch("FormattedID"));
GetResponse getResponse = restApi.get(getRequest);
The response output is like this
{"QueryResult": {"_rallyAPIMajor": "2", "_rallyAPIMinor": "0", "Errors": [], "TotalResultCount": 120, "StartIndex": 1, "PageSize": 20,
"Results": [{"_rallyAPIMajor": "2","_rallyAPIMinor": "0","_ref": "https://rally1.rallydev.com/slm/webservice/v2.0/hierarchicalrequirement/123456789",
"_refObjectUUID": "xxxxxx",
"_objectVersion": "1",
"_refObjectName": "obj name removed masked",
"FormattedID": "US123456",
"DirectChildrenCount": 0,
} .....
Can we change the page size from 20 to 200 for a getrequest??
GetRequest extends Request which has method addParam(String, String) which can be used to pass get parameters into the encoded URL, such as setting page size.
getRequest.addParam("pagesize", "200")
ref: https://github.com/RallyTools/RallyRestToolkitForJava/blob/542afa16ea44c9c64cebb0299500dcbbb50b6d7d/src/main/java/com/rallydev/rest/request/Request.java#L54

g1ant: jsonpath with method length() not implemented

I have problem to get size items of array. Function of jsonPath "length()" not implemented in g1ant, because throwing exception "Array index expected".
Below is sample in g1ant script for test.
addon core version 4.103.0.0
addon language version 4.104.0.0
♥jsonImage = ⟦json⟧‴{ "book" : [ { "name" : "Bambi"} , { "name" : "Cinderella" } ] }‴
♥aaa = ♥jsonImage⟦$.book.length()⟧
dialog ♥aaa
Are there other solutions related to the length of the array?
It's not possible to get the number of json array elements in the way that you are trying. G1ANT is using Newtonsoft.Json library for selecting json tokens where they don't allow expressions like .length() as you can read here.
Here's how you can workaround this issue.
♥jsonImage = ⟦json⟧‴{ "book" : [ { "name" : "Bambi"} , { "name" : "Cinderella" } ] }‴
♥jsonArrLength = 0
♥hasExceptionOccurred = false
while ⊂!♥hasExceptionOccurred⊃
try errorcall NoMoreElements
♥test = ♥jsonImage⟦book[♥jsonArrLength]⟧
♥jsonArrLength = ♥jsonArrLength + 1
end try
end while
dialog ♥jsonArrLength
procedure NoMoreElements
♥hasExceptionOccurred = true
end procedure

Chaining REST calls in a pipeline while managing errors

Coming from nodejs where I could chain asynchronous events using Promises and then operator I'm trying to explore how things are done in idiomatic F#.
The calls I'm trying to chain are HTTP rest calls on some entity from creation to update to uploading images to publishing.
Function composition says the output of one function should match the input of the second one to be composed and that common input and output in my case will be string, i.e. JSON serialized string as input and output of all of these functions.
I've learned that you can compose functions using >> operator. Ideally functions should not throw errors but things happen with IO, for instance in this case what if the id of the entity I'm trying to create exists etc.
The unknown and the question is what happens if an error occurs during the chained sequence, how the caller will know what went wrong along with description message? The operation could fail in the middle or towards the end or right in the beginning of the chain sequence.
What I'm expecting from these functions upon error to stop executing the chain and return the error message to the caller. Error message is also a JSON string so there's no incompatibility between inputs and outputs of a function so you know.
I looked at Choice too but not sure if that's the direction I should be going for.
The code is not necessarily complete and all I'm looking for a is a direction to research further to get answers and possibly improve this question. Here's some code to start with.
let create schema =
// POST request
"""{"id": 1, "title": "title 1"}""" // result output
let update schema =
// PUT request, update title
"""{"id": 1, "title": "title 2"}""" // output
let upload schema =
// PUT request, upload image and add thumbnail to json
"""{"id": 1, "title": "title 2", "thumbnail": "image.jpg"}"""
let publish schema =
// PUT request, publish the entity, add url for the entity
if response.StatusCode <> HttpStatusCode.OK then
"""{"code": "100", "message": "file size above limit"}"""
else
"""{"id": 1, "title": "title 2", "thumbnail": "image.jpg", "url": "http://example.com/1"}"""
let chain = create >> update >> upload >> publish
Edit - Attempt
Trying to parameterize the image thumbnail in the upload part
let create (schema: string) : Result<string,string> =
Ok """{"id": 1, "title": "title 1"}""" // result output
let update (schema: string) : Result<string,string> =
Ok """{"id": 1, "title": "title 2"}""" // output
let upload2 (img: string) (schema: string) : Result<string,string> =
printf "upload image %s\n" img
let statusCode = HttpStatusCode.OK
match statusCode with
| HttpStatusCode.OK -> Ok """{"id": 1, "title": "title 2", "thumbnail": "image.jpg"}"""
| x -> Error (sprintf "%A happened" x)
let publish (schema: string) =
let statusCode = HttpStatusCode.InternalServerError
match statusCode with
| HttpStatusCode.OK -> Ok """{"id": 1, "title": "title 2", "thumbnail": "image.jpg", "url": "http://example.com/1"}"""
| _ -> Error """{"code": "100", "message": "couldn't publish, file size above limit"}"""
let chain = create >> Result.bind update >> Result.bind (upload2 "image.jpg") >> Result.bind publish
A good general approach to this problem is wrapping your functions' return values in a Choice/Either-like type and using a higher-order function to bind them together such that a failure propagates/short-circuits with some meaningful data. F# has a Result type with a bind function that can be used like this:
type MyResult = Result<string,string>
let f1 x : MyResult = printfn "%s" x; Ok "yep"
let f2 x : MyResult = printfn "%s" x; Ok "yep!"
let f3 x : MyResult = printfn "%s" x; Error "nope :("
let fAll = f1 >> Result.bind f2 >> Result.bind f3
> fAll "howdy";;
howdy
yep
yep!
[<Struct>]
val it : Result<string,string> = Error "nope :("
The first two functions succeed, but the third fails and so you get an Error value back.
Also check out this article on Railway-oriented programming.
Update to be more specific to your example:
let create (schema: string) : Result<string,string> =
Ok """{"id": 1, "title": "title 1"}""" // result output
let update (schema: string) : Result<string,string> =
Ok """{"id": 1, "title": "title 2"}""" // output
let upload (schema: string) =
let statusCode = HttpStatusCode.OK
match statusCode with
| HttpStatusCode.OK -> Ok """{"id": 1, "title": "title 2", "thumbnail": "image.jpg"}"""
| x -> Error (sprintf "%A happened" x)
let publish (schema: string) =
let statusCode = HttpStatusCode.InternalServerError
match statusCode with
| HttpStatusCode.OK -> Ok """{"id": 1, "title": "title 2", "thumbnail": "image.jpg", "url": "http://example.com/1"}"""
| _ -> Error """{"code": "100", "message": "file size above limit"}"""
let chain =
create >> Result.bind update >> Result.bind upload >> Result.bind publish

Lua in Redis from JSON

I have a list of JSON strings stored in Redis that looks something like this:
[
{ "ID": 25, "DomainID": 23455, "Name": "Stuff", "Value": 23 },
{ "ID": 35, "DomainID": 23455, "Name": "Stuff", "Value": 10 }
]
The key would be something like "Event:23455".
Using a Lua script and ServiceStack.Redis how would I pull out an anonymous object containing only values where the value is less than 20?
So what I want to return would look like this:
[{ "ID": 35, "Value": 10}]
Thanks.
UPDATE 03/31/2013:
After trying what has been suggested I now have a new problem. A Lua script syntax error.
I'm getting a Lua syntax error about "expecting '=' near cjson". Here is the Lua script string (in C#) I am feeding to Redis:
string luaScript = "local tDecoded = cjson.decode(redis.call('GET', KEYS[1]));"
+ "local tFinal = {};"
+ "for iIndex, tValue in ipairs(tDecoded) do"
+ " if tonumber( tValue.Value ) < 20 then"
+ " table.insert(tFinal, { ID = tValue.ID, Value = tValue.Value});"
+ " end"
+ "end"
+ "return cjson.encode(tFinal);";
Are there any Lua or Redis Lua experts out there that can see what might be the problem? i.e. Does the Lua syntax look correct?
UPDATE 04/02/2013
The parsing error was resolved by adding \n newline characters to end of each line like so.
string luaScript = "local tDecoded = redis.call('GET', KEYS[1]);\n"
+ "local tFinal = {};\n"
+ "for iIndex, tValue in ipairs(tDecoded) do\n"
+ " if tonumber( tValue.Value ) < 20 then\n"
+ " table.insert(tFinal, { ID = tValue.ID, Value = tValue.Value});\n"
+ " else\n"
+ " table.insert(tFinal, { ID = 999, Value = 0});\n"
+ " end\n"
+ "end\n"
+ "return cjson.encode(tFinal);";
Unfortunately this works without errors but for some reason only returns "{}" or an empty list in the ServiceStack RedisClient. So I'm not there yet but I am one step closer.
You can use LuaJSON available on GitHub or you can also try this JSON to Lua table parser for the task. The usage will be something like this(for the GitHub link):
local json = require( "json" ) -- or JSON.lua
local tDecoded = json.decode(sJSON) -- sJSON is the original JSON string
local tFinal = {}
for iIndex, tValue in ipairs( tDecoded ) do
if tonumber( tValue.Value ) < 20 then
table.insert( tFinal, { ID = tValue.ID, Value = tValue.Value} )
end
end
print( json.encode(tFinal) )