How do I resolve the method [] cannot be unconditionally invoked because the receiver can be ‘null’ - dart-null-safety

This is my code:
String returnQuizAnswer(
QuizzesRecord recQuiz,
int answerNumber,
int questionNumber,
) {
// Add your function code here!
late String answerString;
if (questionNumber == 1 ) {
answerString = recQuiz.q1Answers[answerNumber] ;
}
if (questionNumber == 2) {
answerString = recQuiz.q2Answers[answerNumber];
}
return answerString;
}
I tried to add conditionals such as recQuiz.q1Answers[answerNumber] != null in the if statement but they haven't resolved it

Related

Messenger Extensions Javascript SDK Error [duplicate]

I have some JavaScript code that gives this error:
Uncaught TypeError: Cannot read property 'value' of undefined
Here is my code:
var i1 = document.getElementById('i1');
var i2 = document.getElementById('i2');
var __i = {'user' : document.getElementsByName("username")[0], 'pass' : document.getElementsByName("password")[0] };
if( __i.user.value.length >= 1 ) { i1.value = ''; } else { i1.value = 'Acc'; }
if( __i.pass.value.length >= 1 ) { i2.value = ''; } else { i2.value = 'Pwd'; }
What does this error mean?
Seems like one of your values, with a property key of 'value' is undefined. Test that i1, i2and __i are defined before executing the if statements:
var i1 = document.getElementById('i1');
var i2 = document.getElementById('i2');
var __i = {'user' : document.getElementsByName("username")[0], 'pass' : document.getElementsByName("password")[0] };
if(i1 && i2 && __i.user && __i.pass)
{
if( __i.user.value.length >= 1 ) { i1.value = ''; } else { i1.value = 'Acc'; }
if( __i.pass.value.length >= 1 ) { i2.value = ''; } else { i2.value = 'Pwd'; }
}
Either document.getElementById('i1'), document.getElementById('i2'), or document.getElementsByName("username")[0] is returning no element. Check, that all elements exist.
Try this, It always works, and you will get NO TypeError:
try{
var i1 = document.getElementById('i1');
var i2 = document.getElementById('i2');
var __i = {'user' : document.getElementsByName("username")[0], 'pass' : document.getElementsByName("password")[0] };
if( __i.user.value.length >= 1 ) { i1.value = ''; } else { i1.value = 'Acc'; }
if( __i.pass.value.length >= 1 ) { i2.value = ''; } else { i2.value = 'Pwd'; }
}catch(e){
if(e){
// If fails, Do something else
}
}
First, you should make sure that document.getElementsByName("username")[0] actually returns an object and not "undefined". You can simply check like
if (typeof document.getElementsByName("username")[0] != 'undefined')
Similarly for the other element password.
The posts here help me a lot on my way to find a solution for the Uncaught TypeError: Cannot read property 'value' of undefined issue.
There are already here many answers which are correct, but what we don't have here is the combination for 2 answers that i think resolve this issue completely.
function myFunction(field, data){
if (typeof document.getElementsByName("+field+")[0] != 'undefined'){
document.getElementsByName("+field+")[0].value=data;
}
}
The difference is that you make a check(if a property is defined or not) and if the check is true then you can try to assign it a value.
You can just create a function to check if the variable exists, else will return a default value :
function isSet(element, defaultVal){
if(typeof element != 'undefined'){
return element;
}
console.log('one missing element');
return defaultVal;
}
And use it in a variable check:
var variable = isSet(variable, 'Default value');
You code looks like automatically generated from other code - you should check that html elements with id=i1 and i2 and name=username and password exists before processing them.

Swift Optionals Obnoxiousness

Why does the following code fail with a value of optional type 'Section?' not unwrapped; did you mean to use '!' or '?'? compile error?
struct Section
{
let parentID:Int?
let name:String
}
// sometime later ...
var retrievedSections:[Section]?
// Code to retrieve sections here.
/* Filter out any sections that are not under automation root section. */
if let retSections = retrievedSections
{
/* Find the root section in the retrieved sections. */
let rootSections = retSections.filter()
{
return ($0).parentID == nil && ($0).name == config.rootSectionName
}
if rootSections.count != 1
{
print("Invalid root section count!")
}
else
{
model.rootSection = rootSections[0]
model.sections = retSections.filter()
{
return ($0).isRoot() || ($0).parentID == model.rootSection.id
}
}
}
The compiler complains about the ($0).parentID. parentID is already marked as optional. Why does it give an error if I compare it with nil?
Use Below code:-
let retrievedSections = [Section]()
let rootSections = retrievedSections.filter() {
return $0.parentID == nil && $0.name == config.rootSectionName
}

How to check if Value of an array is true in a cell(Google Script)

I am having issues checking if the string value in my array is true in a cell.
function myFunction() {
var People = ['Amanda', 'John'];
for (var n in People )
{
if( People[0] == true);
Logger.log("BOOKED");
}
else{
Logger.log("FREE");
}
}
Plenty of issues with the code!
Does this do it ?
function myFunction() {
var People = ['Amanda', 'John'];
for (var n=0;n<People.length;n++) {
if( People[n] ) {
Logger.log("BOOKED");
}
else {
Logger.log("FREE");
}
}
}
I'm not sure if you just want to test for members of the array being present, or if you want to test actual names in the array

How to pass an Array of Expr (expressions) to Haxe Macro?

I'm basically trying to create a macro that automatically generates an if/else if chain by supplying one common outcome statement for all conditions.
This is what I've tried so far (modified the code just to show as an example):
import haxe.macro.Expr;
class LazyUtils {
public macro static function tryUntilFalse( xBool:Expr, xConds:Array<Expr> ) {
var con1, con2, con3, con4, con5;
/*
* Here's a switch to handle specific # of conditions, because for-loops
* don't seem to be allowed here (at least in the ways I've tried so far).
*
* If you know how to use for-loop for this, PLEASE do tell!
*/
switch(xConds.length) {
case 1: {
con1 = conds[0];
return macro {
if (!$con1) $xBool;
}
}
case 2: {
con1 = conds[0];
con2 = conds[1];
return macro {
if (!$con1) $xBool;
else if (!$con2) $xBool;
}
}
case 3: {
con1 = conds[0];
con2 = conds[1];
con3 = conds[2];
return macro {
if (!$con1) $xBool;
else if (!$con2) $xBool;
else if (!$con3) $xBool;
}
}
// ... so on and so forth
}
return macro { trace("Unhandled length of conditions :("); };
}
}
Then, in theory it could be used like this:
class Main {
static function main() {
var isOK = true;
LazyUtils.tryUntilFalse( isOK = false, [
doSomething(),
doSomethingElse(), //Returns false, so should stop here.
doFinalThing()
]);
}
static function doSomething():Bool {
// ???
return true;
}
static function doSomethingElse():Bool {
// ???
return false;
}
static function doFinalThing():Bool {
return true;
}
}
Which should generate this condition tree:
if (!doSomething()) isOK = false;
else if (!doSomethingElse()) isOK = false;
else if (!doFinalThing()) isOK = false;
Alternatively, I suppose it could output this instead:
if(!doSomething() || !doSomethingElse() || !doFinalThing()) isOK = false;
Looking back at this now, true - it may not make much sense to write a whole macro to generate code that would be easier to type out in it's raw format.
But for the sake of learning about macros, does anyone know if multiple expressions can be passed in an Array<Expr> like I tried in the above code sample?
You probably couldn't get the xConds argument to behave like you expected because the final argument of an expression macro with the type Array<Expr> is implicitly a rest argument. That means you ended up with an array that contained a single EArrayDecl expression. This can be fixed by simply omitting the [].
Regarding generating the if-else-chain - let's take a look at EIf:
/**
An `if(econd) eif` or `if(econd) eif else eelse` expression.
**/
EIf( econd : Expr, eif : Expr, eelse : Null<Expr> );
The chain can be thought of as a singly linked list - the eelse if the first EIf should reference the next EIf and so forth, until we stop with eelse = null for the last EIf. So we want to generate this for your example (pseudo-code):
EIf(doSomething(), isOk = false, /* else */
EIf(doSomethingElse, isOk = false, /* else */
EIf(doFinalThing(), isOk = false, null)
)
)
Recursion works well for this.
Typically it's more convenient to work with reification than raw expressions like I do here, but I'm not sure the former is really possible when dynamically generating expressions like this.
import haxe.macro.Context;
import haxe.macro.Expr;
class LazyUtils {
public macro static function tryUntilFalse(setBool:Expr, conditions:Array<Expr>):Expr {
return generateIfChain(setBool, conditions);
}
private static function generateIfChain(eif:Expr, conditions:Array<Expr>):Expr {
// get the next condition
var condition = conditions.shift();
if (condition == null) {
return null; // no more conditions
}
// recurse deeper to generate the next if
var nextIf = generateIfChain(eif, conditions);
return {
expr: EIf(condition, eif, nextIf),
pos: Context.currentPos()
};
}
}
And Main.hx (mostly unchanged):
class Main {
static function main() {
var isOK = true;
LazyUtils.tryUntilFalse(isOK = false,
!doSomething(),
!doSomethingElse(), //Returns false, so should stop here.
!doFinalThing()
);
}
static function doSomething():Bool {
trace("doSomething");
return true;
}
static function doSomethingElse():Bool {
trace("doSomethingElse");
return false;
}
static function doFinalThing():Bool {
trace("doFinalThing");
return true;
}
}
To keep things simple I inverted the function call arguments with ! at the call site instead of handling that in the macro.
You can use -D dump=pretty to generate AST dumps and check what code is being generated. Here's the result:
if ((! Main.doSomething()))isOK = false else if ((! Main.doSomethingElse()))isOK = false else if ((! Main.doFinalThing()))isOK = false;

AS3/Flash: check if a variable value exists in an array II

Some days ago, Cherniv gave to me this tip:
var name = "Nora";
var names:Array = ["Mary", "Porter", "Nora", "Flint", "Elsa", "Clair",...];
if( names.indexOf( name ) > -1 )
{
// Success
}
Now, I can't check the existence of "Nora" in this array:
var names:Array = [{label:"Mary"}, {label:"Porter"},{label:"Nora"}, ...];
I'll appreciate any help.
Cheers.
UPDATE:
Now it's working. I did use:
for each (var obj:Object in list)
{
if (obj.label == compList.text)
{
updateList = 1;
break;//stops the loop;
}
}
if (updateList == 1)
{
removeCompany();
}
else
{
var nativeAlert:NativeAlert = new NativeAlert();
nativeAlert.alert("You can't update the name!");
}
Is this OK or is an ugly solution?
Thanks
for each( var obj : Object in names )
{
if( obj.label == "Nora" )
{
// Success;
break;//stops the loop;
}
}
I can make it more complex/flexible if you wish.

Resources