Reading an array of strings from a file in Rust - rust

I have the following JSON:
[
"String1",
"String2",
"String3"
]
I'm trying to read it in Rust with serde_json like this:
serde_json::from_str::<Vec<String>>("file_path").unwrap();
However, I get the following error:
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error("expected value", line: 1, column: 1)'
The full stack trace isn't giving me much info. I tried converting it into a HashMap of the form <String, Vec<String>>, as well as using custom serializer types, and still get the same error repeatedly. Any ideas what might be going on here?

serde_json::from_str::<Vec<String>>("file_path").unwrap();
// ^^^^^^^^^^^
If that is your code as-is. then it won't work. from_str expects a &str with JSON in it, not a file path, e.g.
serde_json::from_str::<Vec<String>>(r#"["String1", "String2"]"#).unwrap();
Instead, open the file to get a Read and then use serde_json::from_reader.
See the example in the documentation for more information.

Related

Defining a field which holds a procedure fails [Nim]

I am creating a type which holds a procedure as one of its fields. When I attempt to compile the file, it provides me with the error 'CommandC' is not a concrete type.
The problematic snippet is seen below.
type
CommandC = object
tocall: proc (info: CommandC, vrs: SharedTable)
arguments: seq[seq[string]]
subcommands: seq[CommandC]
CommandP = object
cat: string
tocall: proc (info: CommandC, vrs: SharedTable) # This line raises an error during compilation
arguments: seq[string]
textdata: string
I am new to Nim [transitioning from Python for larger projects] and for the life of me cannot figure out what this actually means, or how to fix it. This is likely plain old incompetence on my part.
[I am also new to using Stack Overflow and so if my question is not up to standards then that's my bad and I apologize]
I guess you have found it yourself already. But in case that it was not that obvious, you may understand that Nim is not Python, but a statically typed, compiled language. An unspecified data type like SharedTable can not exist. A table (map) is a mapping from one type to another type, so something like SharedTable[string, int] makes more sense, and the code below compiles for me:
import std/sharedtables
type
CommandC = object
tocall: proc (info: CommandC, vrs: SharedTable[string, int])
arguments: seq[seq[string]]
subcommands: seq[CommandC]
CommandP = object
cat: string
tocall: proc (info: CommandC, vrs: SharedTable[string, int]) # This line raises an error during compilation
arguments: seq[string]
textdata: string

finding the caller object given its name only

I want to find the caller callable from within the called object, without explcitely forwarding the caller to the called as an object.
My current code looks something like this:
class Boo:
#classmethod
def foo(cls, aa, b2=2):
_ret = aa + b2
autolog(fn=Boo.foo, values={"input": locals(), "output": _ret}, message="This is what it should look like")
autolog_nameless(values={"input": locals(), "output": _ret}, message="This would be convenient")
return _ret
and yields
DEBUG | Boo.foo with aa=3.14159, b2=2 yields 5.14159. Message: This is what it should look like
DEBUG | cls=<class '__main__.Boo'>, aa=3.14159, b2=2, _ret=5.14159 yields 5.14159. Message: This would be convenient
The method autolog gets the locals() and the caller method fn, and parses them using the signature of the caller. This works nice and provides the desired output, but requires passing the caller as an object - something I'd like to avoid as I'm refractoring to include this feature and have about 1000 places to modify.
What I'd like to achieve is: pass locals() only; get the name of the caller within autolog_nameless, using inspect.stack()[1][3] or rather inspect.currentframe().f_back.f_code.co_name (latter has much less overhead), and using this - an possibly the information in locals() - find the caller object to inspect it for its signature.
The method autolog_nameless gets cls, actually the class as part of locals() (or would get self if the caller was a simple method), but I can't really do anything with it.
I'd think all the information required is given, but I just can't find a solution. Any help is greatly appreciated.
As it turns out it's quite simple: listing the methods of the class object found in locals() and searching by name should do the trick.
Code, without error checking:
# getting all methods of the class
methods = inspect.getmembers(locals()['cls'], predicate=inspect.ismethod)
# finding the callers name; won't work within the list comprehension for scope issues
_name = inspect.currentframe().f_back.f_code.co_name
# methods is a list of tuples, each tuple holds the name and the method object
fn = [x for x in methods if x[0] == _name][0][1]
and fn is the caller object to check the signature.
Note, locals()['cls'] works here as in the example we have a classmethod, but this is just the object that the called method belongs to.

Not able to pass object in graphql mutation

Can anyone tell me how to pass array of object in graphql mutation from react js side.I tried passing the object in react but getting error of not same type.
[input type][1]
[from api side][2]
[declaring the object][3]
[passing object in mutation][4]
[error i'm facing][5]
[1]: https://i.stack.imgur.com/ufVtA.png
[2]: https://i.stack.imgur.com/kQt5m.png
[3]: https://i.stack.imgur.com/hnxLM.png
[4]: https://i.stack.imgur.com/5JCHf.png
[5]: https://i.stack.imgur.com/BonPE.png
What i understood from your problem is that, You want to pass array of objects as argument to the mutation. It can be done easily.
First define a input in the schema,as below. It has the value name as string. You can add whatever you want. This structure will be used for passing value as argument.
input Product {
name: String
}
The above created input will be passed as a array as given below.
type RootMutation{
createProduct(product: [Product]): String
}
You will get the data in the resolver
createProduct: (args)=>{
// You will get the value in this 'args'
// Do Whatever you want
}
The input is given as follow
createProduct(product:[{name:"has"}])

How to use Instance Method with Lamda, Threads and Named Arugments

The current code below produces an error. I keep tweaking the syntax but keep getting errors. I know I am close. I am tring to use a lambda inside an instance method, to start a thread and the target is an instance method with named arguments. I am seeing various forms of wrong positional arguments Can anyone help?
arguments = {'resource_group_name': resource_group_name,
'vm_name': vm_name,
'script': script,
'parameters': parameters,
'command_id': command_id}
thread = Thread(name=vm_name,
target=lambda self, q, **kwargs: q.put(self.run_command(kwargs)),
args=(que, arguments))
thread.start()
Was able to get it working with this:
thread = Thread(name=vm_name,
target=lambda self, q, kwargs: q.put(self.run_command(**kwargs)),
args=(self, que, arguments))

Why do I get "Multiple markers at this line: Groovy expecting EOF found 'for'"?

The Error in the Question was generated by the following code
package ian.eg.learn
class ReadXMLfile {
def customers = new XmlSlurper().parse(new File("C:\\Users\\IBM_ADMIN
\\Documents\\customers.xml"))
for (customer in customers.corporate.customer){
println "${customer.#name} works for ${customer.#company}"
}
}
I am using a regular "for" and I don't see why the compiler is having a problem
I don't know what version of Groovy you're using so the exact error message could vary, but you cannot just write statements like that anywhere in your class, so the compiler expects something else in place of your for statement.
Example:
class Xxx {
println("yoo")
}
Gives:
unexpected token: println # line 2, column 3.
println("yoo")
^
You need to move that code in a method, or an init block... anywhere but not directly in class body.

Resources