changes not occur in dart list when using copyWith - list

Whenever the player pause I want to update the value isPlaying to false but that change not occur in list.
pause: (e) async* {
await audioPlayer?.pause();
yield state.copyWith(
audioItems: AudioItems(
audioItems: List<AudioItem>.from(state.audioItems.audioItems)
..firstWhere((element) => element.para == state.lastPlayingPara)
.copyWith(isPlaying: false),
),
);
}

Related

adding record from one List to another List

In List One, I am getting some items. Each time those items are changing. Sometimes, I can get more than one record in the List.
In a second List, I would like to store all the data of List One. So, I can then display all the items of List Two.
To make it more clear.
List One = "/temp/file1.jpeg"
List Two = "/temp/file1.jpeg"
List One = "/temp/file2.jpeg"
List Two = "/temp/file1.jpeg,/temp/file2.jpeg"
I have tried this
void _openDocumentFileExplorer({fileType: FileType.custom}) async {
setState(() => _loadingPath = true);
try{
_paths = (await FilePicker.platform.pickFiles(
type: fileType,
allowMultiple: true,//_multiPick,
allowedExtensions: ['pdf']))?.files;
} on PlatformException catch (e) {
print("Unsupported operation" + e.toString());
} catch (ex) {
print('$ex');
}
if (!mounted) return;
setState(() {
_loadingPath = false;
_fileName = _paths != null ?
_paths!.map((e) => e.name).toString() : '...';
});
}
ListView.separated(
itemCount:
_paths != null && _paths!.isNotEmpty
? _paths!.length
: 1,
itemBuilder:
(BuildContext context, int index) {
final bool isMultiPath =
_paths != null && _paths!.isNotEmpty;
final String name = _paths!
.map((e) => e.name)
.toList()[index];
//filesGB store the full path + the file name
final filesGB = _paths!
.map((e) => e.path)
.toList()[index]
.toString();
print (filesGB);
_paths?.addAll(allFiles!.map((e) ));
allFiles.addAll(filesGB.toList());
allFiles.addAll(filesGB);
// allFilesV2.addAll(filesGB);
but it does not work. I am getting this error message.
"The argument type 'String' can't be assigned to the parameter type 'Iterable'"
Please, do you have any suggestion?
I think you can use SPREAD OPERATOR (...) using a triple dot for merging one array into another.
For example:
List list1= ["/temp/file1.jpeg"];
List list2 = [];
after some time
list1 = ["/temp/file2.jpeg"];
so whenever your list one change do
list2 = [...list2,...list1];
print(list2);
output: ["/temp/file1.jpeg","/temp/file2.jpeg"]
I think it would help.

How can I unit test a retryWhen operator in rxjs?

I am attempting to unit test a custom RxJS operator. The operator is very simple, it uses RetryWhen to retry a failed HTTP request, but has a delay and will only retry when the HTTP Error is in the 500 range. Using jasmine, and this is in an Angular application.
I've looked at this:
rxjs unit test with retryWhen
Unfortunately, updating the SpyOn call doesn't seem to change the returned observable on successive retries. Each time it retries it is retrying with the original spyon Value.
I have also looked at a bunch of rxjs marble examples, none of which seem to work. I am not sure it is possible to use rxjs marbles here, because (AFAIK) there is no way to simulate a situation where you first submit an errored observable, then submit a successful observable on subsequent tries.
The code is basically a clone of this:
https://blog.angularindepth.com/retry-failed-http-requests-in-angular-f5959d486294
export function delayedRetry(delayMS: number, maxRetry) {
let retries = maxRetry;
return (src: Observable<any>) =>
src.pipe(
retryWhen((errors: Observable<any>) => errors.pipe(
delay(delayMS),
mergeMap(error =>
(retries-- > 0 && error.status >= 500) ? of(error) : throwError(error))
))
);
}
I would like to be able to demonstrate that it can subscribe to an observable that returns an error on the first attempt, but then returns a successful response. The end subscription should show whatever success value the observable emits.
Thank you in advance for any insights.
try use this observable as source observable to test
const source = (called,successAt)=>{
return defer(()=>{
if(called<successAt){
called++
return throwError({status:500})
}
else return of(true)
})
}
test
this.delayedRetry(1000,3)(source(0,3)).subscribe()
To test the retry functionality, you need a observable which emits different events each time you call it. For example:
let alreadyCalled = false;
const spy = spyOn<any>(TestBed.inject(MyService), 'getObservable').and.returnValue(
new Observable((observer) => {
if (alreadyCalled) {
observer.next(message);
}
alreadyCalled = true;
observer.error('error message');
})
);
This observable will emit an error first and after that a next event.
You can check, if your observable got the message like this:
it('should retry on error', async(done) => {
let alreadyCalled = false;
const spy = spyOn<any>(TestBed.inject(MyDependencyService), 'getObservable').and.returnValue(
new Observable((observer) => {
if (alreadyCalled) {
observer.next(message);
}
alreadyCalled = true;
observer.error('error message');
})
);
const observer = {
next: (result) => {
expect(result.value).toBe(expectedResult);
done();
}
}
subscription = service.methodUnderTest(observer);
expect(spy).toHaveBeenCalledTimes(1);
}
Building on a previous answer I have been using this, which gives you more control over what's returned.
const source = (observables) => {
let count = 0;
return defer(() => {
return observables[count++];
});
};
Which can then be used like this
const obsA = source([
throwError({status: 500}),
of(1),
]);
Or it can then be used with rxjs marbles like
const obsA = source([
cold('--#', null, { status: 500 }),
cold('--(a|)', { a: 1 }),
]);

get response from expo sqlite query

According to Expo documentation with SQLite I would make a query like so:
tx.executeSql(sqlStatement, arguments, success, error)
I execute it like this:
db.transaction(tx => {
tx.executeSql('SELECT * FROM dr_report_properties WHERE orderId = (?)', [this.state.orderId]);
},
error => {
alert(error);
},
(tx, results) => {
console.log(results);
}
);
My question is how do I get the response? The above returns as undefined.
I then try (not expecting it to work but just for kicks)
console.log(tx);
This does give a console.log
(tx, results) => {
console.log('I got data');
}
)
According to the documentation:
ResultSet objects are returned through second parameter of the success callback for the tx.executeSql() method on a Transaction (see above). They have the following form:
{
insertId,
rowsAffected,
rows: {
length,
item(),
_array,
},
}
I would expect result would be this object. Any ideas at what I'm doing wrong?
The problem with the above was that I placed the call AFTER the execution it's actually in the same method as that.
The result should have gone in the callback like so:
db.transaction(
tx => {
tx.executeSql('select * from my_table', [], (trans, result) => {
console.log(trans, result)
});
}
);
Thanks to #charliecruzan from expo team!

Postman API testing: Unable to assert a value is true

I am testing an API with a GET request that returns the following data:
{
"Verified": true,
"VerifiedDate": 2018-10-08
}
I am trying to test that the first field comes back true, and the second field has a value. I have the following code:
pm.test("Verified should be true", function () {
var Status = pm.response.json();
pm.expect(Status.Verified).to.be.true;
});
pm.test("Returns a verified date", function () {
var Status = pm.response.json();
pm.expect(Status.VerifiedDate).to.not.eql(null);
});
The assert on true is failing for the following reason:
Verified should be true | AssertionError: expected undefined to be true
Why is the first test failing?
I am running the same test on a post command without any issues.
Any ideas?
thanks
Root cause:
Your result is an array but your test is verifying an object. Thus, the postman will throw the exception since it could not compare.
Solution:
Use exactly value of an item in the list with if else command to compare.
var arr = pm.response.json();
console.log(arr.length)
for (var i = 0; i < arr.length; i++)
{
if(arr[i].Verified === true){
pm.test("Verified should be true", function () {
pm.expect(arr[i].Verified).to.be.true;
});
}
if(arr[i].Verified === false){
pm.test("Verified should be false", function () {
pm.expect(arr[i].Verified).to.be.false;
});
}
}
Hope it help you.
You could also just do this:
pm.test('Check the response body properties', () => {
_.each(pm.response.json(), (item) => {
pm.expect(item.Verified).to.be.true
pm.expect(item.VerifiedDate).to.be.a('string').and.match(/^\d{4}-\d{2}-\d{2}$/)
})
})
The check will do a few things for you, it will iterate over the whole array and check that the Verified property is true and also check that the VerifiedDate is a string and matches the YYYY-MM-DD format, like in the example given in your question.

Alexa aws lambda function prompting an error when creating a new object

I am starting to learn how to create a lambda function. I wanted to implement a lambda function that can control a led on an arduino uno device. I found this code on GitHub.
I copied and pasted it and got the following error:
"errorMessage": "Exception: TypeError: Cannot read property 'new' of
undefined".
I searched on StackOverflow and I found this similar question but the answer did not help a lot.
Please I need help in fixing this code. I do not know if it matters but the variable endpoint that contains links for a cloud (sparkfun) is out of service.
Thank you so much for your time and consideration!
Below is the code:
var https = require('https'); //include https
var http = require('http');
exports.handler = (event, context) => {
try {
if (event.session.new) {
// New Session
console.log("NEW SESSION"); //log this for debugging
}
switch (event.request.type) {
case "LaunchRequest":
// Launch Request
console.log(`LAUNCH REQUEST`)
context.succeed(
generateResponse(
buildSpeechletResponse("Welcome to the ForceTronics Home Automation Skill, say turn light on or turn light off", true), //response for Alexa if you just call the skill without intent
{}
)
)
break;
case "IntentRequest":
// Intent Request
console.log(`INTENT REQUEST`)
switch(event.request.intent.name) { //switch statement to select the right intent
case "TurnLightOn": //if you told alexa to turn the light on this will be true
var endpoint = "https://data.sparkfun.com/input/1nlZrX0NbdfwxgrY0zA0?private_key=0mDlvAkdoRIq976eakpa&lightstate=1" //https string to log data to phant phant
https.get(endpoint, function (result) { //use https get request to send data to phant
console.log('Success, with: ' + result.statusCode);
context.succeed(
generateResponse( //if you succeeded allow Alexa to tell you state of light
buildSpeechletResponse("The light is turned on", true),
{}
)
)
}).on('error', function (err) {
console.log('Error, with: ' + err.message);
context.done("Failed");
});
break;
case "TurnLightOff": //the turn light off intent
var endpoint2 = "https://data.sparkfun.com/input/1nlZrX0NbdfwxgrY0zA0?private_key=0mDlvAkdoRIq976eakpa&lightstate=0"; // phant string to set light state to off
https.get(endpoint2, function (result) {
console.log('Success, with: ' + result.statusCode);
context.succeed(
generateResponse( //Alexa response if successful
buildSpeechletResponse("The light is turned off", true),
{}
)
);
}).on('error', function (err) {
console.log('Error, with: ' + err.message);
context.done("Failed");
});
break;
case "IsWasherRunning": //check the state of the washer
var endpoint3 = "http://data.sparkfun.com/output/pw8EWVl18zUgW9OYzJNv.csv?page=1"; // phant csv file page
http.get(endpoint3, function (response) { //http get request, data is returned to response
response.setEncoding('utf8');
response.on('data', function (body) { //now let's go through response data from phant cloud
//following variables are getting hour and date info to ensure data is new and not old
var lHour = Date().substr(16,2); //hour from amazon server
var dHour = body.substr(35,2); //hour from phant cloud data
var lDate = Date().substr(8,2);
var dDate = body.substr(32,2);
if(checkTime(lHour, dHour, lDate, dDate)===1) { //if this is true data from phant is fresh
var s = body.substr(22,1); //read washer state data from phant string
if (s=='1') { //if it is 1 then washer is on
context.succeed(
generateResponse( //if you succeeded allow Alexa to tell you state of light
buildSpeechletResponse("The washer is running", true),
{}
)
);
}
else if (s=='0') { //if it is 0 then washer is off
context.succeed(
generateResponse( //if you succeeded allow Alexa to tell you state of light
buildSpeechletResponse("The washer is off", true),
{}
)
);
}
else { //if this is true then there is an issue getting data from phant
context.succeed(
generateResponse( //if you succeeded allow Alexa to tell you state of light
buildSpeechletResponse("There was an error checking washer state", true),
{}
)
);
}
}
else { //if this is true the data is old and there maybe something wrong with the hardware
console.log("didn't pass date and time test");
context.succeed(
generateResponse( //if you succeeded allow Alexa to tell you state of light
buildSpeechletResponse("No recent washer state data available", true),
{}
)
);
}
});
response.on('error', console.error);
});
break;
default:
throw "Invalid intent";
}
break;
case "SessionEndedRequest":
// Session Ended Request
console.log(`SESSION ENDED REQUEST`);
break;
default:
context.fail(`INVALID REQUEST TYPE: ${event.request.type}`)
}
} catch(error) { context.fail(`Exception: ${error}`) }
}
// builds an Alexa response
buildSpeechletResponse = (outputText, shouldEndSession) => {
return {
outputSpeech: {
type: "PlainText",
text: outputText
},
shouldEndSession: shouldEndSession
}
};
//plays Alexa reponse
generateResponse = (speechletResponse, sessionAttributes) => {
return {
version: "1.0",
sessionAttributes: sessionAttributes,
response: speechletResponse
}
};
//this function checks to see if data from phant cloud is relitively new
function checkTime(lTime, dTime, lDay, dDay) {
//turn hour and date strings into ints
var lT = parseInt(lTime);
var dT = parseInt(dTime);
var lD = parseInt(lDay);
var dD = parseInt(dDay);
if(lD===dD && lT===dT) { //if it is same day and hour then data is good
return 1;
}
else if(lD===dD && (lT - 1)===dT) { //if day is the same and hour is only off by one then data is good
return 1;
}
else if((lD - 1)===dD && lT===0 && dT===23) { //if date is one off but time is around midnight then data is good
return 1;
}
else return 0; //if none of the above if statements are true then data is old
}
It means the object 'event' (look at your line exports.handler) does not have a key called 'session'. Everything after that is non consequential until you fix that. I cannot know what you wanted to accomplish with that call.
Do this:
console.log(event);
You can also look up 'event' in the AWS documentation.
Then you can look for whatever you thought 'session' was and move forward from there. Good luck. Post details of what you thought 'session' was if you get stuck. I don't think you need that though. I can't know for sure from what you posted.