Cannot convert value of type string to expected argument type Int - json

I was playing around with code. I found on GitHub (https://github.com/avijeets/ConnectFour) and was thoroughly stumped on an error I couldn't clear out.
The error is:
"Cannot convert value of type '[[CFCellState]]' to expected argument
type 'Int'"
Code from the top of the VC where CFCellState is defined:
enum CFCellState: CustomStringConvertible {
case empty
case occupied(CFPlayer)
var description: String {
switch self {
case .empty:
return "empty"
case .occupied(let player):
return player.description
}
}
}
Code from where the error occurs:
self.init(player: current!, opponent: opponent!, columns:ConnectFour.boardFrom(json: queryItems[1].value!)!)

Try this instead:
self.init(player: current!, opponent: opponent!, board: ConnectFour.boardFrom(json: queryItems[1].value!)!)
In order for this to work, you may need to remove the private keyword from this line in ConnectFour.swift file (look around line #98):
private init(player: CFPlayer, opponent: CFPlayer, board: [[CFCellState]]) { ....

Related

Error returned when trying to run a basic function in dart

I'm new to dart (coming from a python background), and I'm struggling to make a function work. I've created the following function:
void main() {
int number = 22;
Function evenChecker(int number) {
if ((number%2) == 0) {
print('$number is even');
} else {
print('$number is odd');
}
}
}
but is get the following error:
Error: A non-null value must be returned since the return type 'Function' doesn't allow null.
bin/hello_dart_project.dart:4
- 'Function' is from 'dart:core'.
Additionally, if anyone has any suggestions about a good dart learning resource, I'd highly appreciate the advice.
^
Unlike Python or JavaScript, there is no keyword to define functions in dart. Instead, we declare functions by starting with their return type:
void evenChecker(...) {...}
^^^^
// This is the return type. "void" means "returns the value null" or "doesn't return anything"

Kotlinx.Serialization using OkHTTPClient return always Failure

Hello I have a problem with my JSON. I am using OkHTTPClient to get JSON from web - to get objects from JSON using kotlinx.serialization via method which contains this and return value from method should be Result :
private suspend inline fun <reified T> OkHttpClient.get(webUrl: HttpUrl): Result<T> =
try {
//Builder defined here ... but skipping this line of code
val data = Json { ignoreUnknownKeys = true }.decodeFromString<T (result.body!!.string())
Result.Success(data)
} catch (e: Exception) {
Result.Failure(e)
}
suspend fun getFact(): Result<Fact> =
client.httpGet("myURL".toHttpUrl())
Json from myURL:
{"status":"success","data":[{"fact":"This is random information i need to get"}],"message":"Retrieved Fact"}
My serializer and Serializable data classes:
#Serializable
data class Fact(
#Serializable(with = FactListSerializer::class)
val data: String) java.io.Serializable
object FactListSerializer : JsonTransformingSerializer<List<String>>(ListSerializer(String.serializer())) {
override fun transformDeserialize(element: JsonElement): JsonElement {
return if (element is JsonArray) {
JsonArray(listOf(element)).first()
} else {
element
}
}
}
To be honest I am not sure what I am doing, but I am getting this error all the time when I print val fact = api.getFact():
Fact: Failure(error=kotlinx.serialization.json.internal.JsonDecodingException: Expected JsonPrimitive at 0, found {"fact":"This is random information i need to get"}
What I need to return is only first element of array fact, because JSON obtain always only 1 fact inside array. So I don't want to return from Serializer/Json List but only Fact object.
But as you see I am obtaining always Result Fauilure, don't know why. My goal is to obtain Result Success and obtaining from that JSON object Fact (only one), but I am not sure if I am doing it correct (obviously not) and even if it is even possible to return from JSONArray only one object (element of type Fact).
So what I expect is something like this:
Fact: Success(value=Fact(fact=This is random information i need to get))
I think the deserializer definition should be changed on 3 levels. The example of how to use JsonTransformingDeserializer in the docs actually describes most of what you need.
JsonArray(listOf(element)).first() should just be element.first(). Here you're building a JsonArray containing your initial JsonArray as only element, and then taking the first, so you basically get back the exact same element.
The type parameter T of JsonTransformingSerializer is supposed to be the type of the property it's applied to, so you should at least get a warning in the code because yours is defined to work on List<String> but is applied to a String property. It should be JsonTransformingSerializer<String>(String.serializer()).
You not only need to unwrap the data array, you also need to extract the value of the fact key within the element of that array.
So with all these changes, it should give something like this:
object FactListSerializer : JsonTransformingSerializer<String>(String.serializer()) {
override fun transformDeserialize(element: JsonElement): JsonElement {
val unwrappedData = if (element is JsonArray) element.first() else element
return unwrappedData.jsonObject["fact"] ?: error("missing 'fact' key in 'data' array")
}
}

Why does dumping this JObject throw an AmbiguousMatchException in LINQPad?

When I run this code in LINQPad using JSON.NET:
var x = JObject.Parse(
#"{
""data"" : [ {
""id"" : ""bbab529ecefe58569c2b301a"",
""name"" : ""Sample Name"",
""group"" : ""8b618be8dc064e653daf62f9"",
""description"" : ""Sample Name"",
""payloadType"" : ""Geolocation"",
""contract"" : ""a9da09a7f4a7e7becf961865"",
""keepAlive"" : 0
} ]
}");
x.Dump();
An AmbiguousMatchException is thrown when trying to dump the parsed JSON to LINQPad's output window. Why? As far as I can tell this is perfectly legitimate JSON. http://jsonlint.com/ says it's valid, too.
This is a problem with how .Dump() is implemented most likely.
If you check the stack trace:
at System.RuntimeType.GetInterface(String fullname, Boolean ignoreCase)
at System.Type.GetInterface(String name)
at UserQuery.Main()
...
We can see that the method throwing the exception is System.RuntimeType.GetInterface.
System.RuntimeType is one of the concrete classes used to represent Type objects when reflection is used at runtime, so let's check Type.GetInterface(String, Boolean) which has this to say:
AmbiguousMatchException
The current Type represents a type that implements the same generic interface with different type arguments.
So it looks like the GetInterface method is called with a type of an interface that is implemented more than once, with different T's or similar.
To provoke the same error, simply replace x.Dump(); with this:
var type = x.GetType().GetInterface("System.Collections.Generic.IEnumerable`1", true);
This will throw the same exception.
Here's a simpler LINQPad example that shows the underlying problem:
void Main()
{
var type = typeof(Problem).GetInterface("System.Collections.Generic.IEnumerable`1", true);
}
public class Problem : IEnumerable<string>, IEnumerable<int>
{
IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable<string>)this).GetEnumerator();
IEnumerator<string> IEnumerable<string>.GetEnumerator() => Enumerable.Empty<string>().GetEnumerator();
IEnumerator<int> IEnumerable<int>.GetEnumerator() => Enumerable.Empty<int>().GetEnumerator();
}
This example will throw the exact same exception.
Conclusion: There is nothing wrong with the Json, nor with Json.Net, this is a problem with how LINQPad tries to figure out the best way to dump the object to the output window.

AS3 Check if variable is String outputs MouseEvent info

UPDATE: I found a workaround using different code. I am leaving this question in cause someone wants to answer why this was happening and maybe it can help someone else as well. Thanks
I am trying to check if a variable is a string, in this case if it has a url in the string. But the code is executing and in the trace statement I get this:
if (theWebsite is String)
trace(theWebsite);
output:
[MouseEvent type="click" bubbles=true cancelable=false eventPhase=3 localX=2259.8671875 localY=2485.85205078125 stageX=1003.25 stageY=71 relatedObject=null ctrlKey=false altKey=false shiftKey=false buttonDown=false delta=0 commandKey=false controlKey=false clickCount=0]
MainStage? [object Main_Activate] and website? [MouseEvent type="click" bubbles=true cancelable=false eventPhase=3 localX=2259.8671875 localY=2485.85205078125 stageX=1003.25 stageY=71 relatedObject=null ctrlKey=false altKey=false shiftKey=false buttonDown=false delta=0 commandKey=false controlKey=false clickCount=0]
Here is the code that creates this variable.
1.
MenuScreen.One_btn.addEventListener(MouseEvent.CLICK, webViewButton("http://www.MyWebsite.com"));
2.
public function webViewButton(theWebsite:String):Function {
trace("made it here: " + theWebsite); /// output: www.MyWebsite.com
return function(e:MouseEvent):void {
trace("made it here too: " + theWebsite); //output: www.MyWebsite.com
removeMenuScreen(theWebsite);
}
}
3.
public function removeMenuScreen(theWebsite:String = null, e: Event = null) {
if (theWebsite is String) {
trace("But did I make it here? " + theWebsite);
// OUTPUTS all the above code mentioned earlier.
}
I am using that function for other things as well so that is why its set up that way. HOW can I fix this to have that code execute only if it is a defined string? Thanks for any tips.
The code you posted does not produce the output you posted.
What would produce the "[MouseEvent ...]" output is if you had something like addEventListener(MouseEvent.CLICK, removeMenuScreen). Why? Because a MouseEvent will get coerced to its string value since the removeMenuScreen handler's first parameter theWebsite is of type String.
So, to answer your question: it already is only being executed when theWebsite is a string. And it will only ever be a string, or null, otherwhise if coercion to a string is not possible it will throw a runtime error.
If you want to avoid runtime coercion, make the parameter untyped:
public function removeMenuScreen(theWebsite:* = null) {
if (theWebsite is String) {
trace("But did I make it here? " + theWebsite);
} else if (theWebsite is MouseEvent) {
trace("Or did I make it here?", theWebsite)
}
}
I don't recommend you go down this path, though, because it adds a lot of unclarity, which leads to bugs and hard debugging.

Why Java (Eclipse) shows an error indicating 160.934 is a boolean?

for the line of assert below, Eclipse gives an error: Type mismatch: cannot convert from double to boolean. Anyone knows why?
public class ConversionImplTest {
#Test
public void test() {
ConversionImpl conversionImpl = new ConversionImpl();
double result = conversionImpl.milesToKilometers(100);
assert(result = 160.934);
//fail("Not yet implemented");
}
}
Please try this:
double result = 99.99;
assert(result == 66.66);
The test is successful. Why?
I think it should be result == 160.934 instead of result = 160.934
Don't forget that assert is a Java keyword, not a JUnit method, and as such it is normally ignored unless you specify -ea on the command line. JUnit runs do not normally specifiy this argument to the JVM.