AWS-IoT-Core / Device Shadow: Use more than one shadow_property in the AWS-IoT-Device-SDK for Python - aws-iot

The AWS-IoT-Device-SDK for Python contains the sample file "shadow.py".
In this file I can only specify one shadow_property like "color".
[...]
cmdUtils.register_command("shadow_property", "<str>", "The name of the shadow property you want to change (optional, default='color'", default="color")
[...]
shadow_property = cmdUtils.get_command("shadow_property")
[...]
Do any of you have an idea to use more than one shadow properties like "color", "status" etc?
I can start and run the script several times, but it isn't handy.
Source:
Sample File shadow.py on GitHub
https://github.com/aws/aws-iot-device-sdk-python-v2
https://docs.aws.amazon.com/iot/latest/developerguide/iot-sdks.html

something like this should work:
request = iotshadow.UpdateShadowRequest(
thing_name=shadow_thing_name,
state=iotshadow.ShadowState(
reported={ 'color': 'blue',
'status': 'connected' }
),
client_token=token,
)

Related

React (native) image storing / fetching good practices

My use case is a mobile app with react native, but I guess it's very common good practices.
I want to be able, in an app, to take an image (from the camera or the gallery), and to be able to store it so it can be fetched from the date it was added, or some metadata added by the user.
The theory seems quite simple, a way of doing it can be :
Use any library (eg this great one) to get the image,
Store image as base64 and metadata in, let's say RealmJS (some internal DB),
Query this DB to get what I want.
This should work, and should be quite simple to implement.
But I'm wondering about a few things :
According to the performance of a smartphone's camera, isn't it quite a shame to store it as base64 (and no checksum, more memory used, ...) ?
This format, base64, isn't a bad idea in general for storing image ?
Is it a good idea to store the image in RealmJS, as it will be a pain for the user to reuse the image (share it on facebook...), but on the other hand, if I wrote it to the smartphone and store a URI, it can lead to a lot of problems (missing file if the user deletes it, need to access to memory, ...)
Is this approach "clean" (ok it works, but ...) ?
If you have any experience, tips, or good practice to share, I'll be happy to talk about it :)
You can store binary data (images) in Realm. But if you are using Realm locally (not sync), I will suggest that you store the image on the file system and store the path in Realm. Your model could be something like:
const ImageSchema = {
name: 'Image',
properties: {
path: 'string',
created: 'Date',
modified: 'Date?',
tags: 'Tag[]'
}
};
const TagSchema = {
name: 'Tag',
properties: {
name: 'string',
images: { type: 'linkingObjects', objectType: 'Image', property: 'tags' }
}
};
That is, for every image the timestamp for its creation is stored. Moreover, it has an optional timestamp if the image has been modified. The property path is where to find the image. If you prefer to store the image, you can use a property of type data instead. To find image less that a week old, you can use realm.objects('Image').filtered('created >= $1', new Date(Date.now()-7*24*60*60)).
Just for fun, I have added a list of tags for each image. The linkingObject in Tag makes it possible to find all image which have a particular tag e.g., realm.objects('Tag').filtered('#links.Tag.name == "Dog"').

Scala Play Framework image upload with Angular ng-file-upload

I am using Angular ng-file-upload (https://github.com/danialfarid/ng-file-upload) on the frontend to manage the file upload process.
Unfortunately, form contains a complex object with multiple files. Using the MultipartFormData (https://www.playframework.com/documentation/2.5.x/ScalaBodyParsers) on the server side I have successfully decomposed the uploaded content and can read it from the request.body.
Now, to my surprise, I do not have a simple Json Objects but rather a strangely formed datatype, described on the ng-file-upload website as:
(...) server implementations expecting nested data object keys in .key or [key] format.
Example: data: {rec: {name: 'N', pic: file}} sent as: rec[name] -> N, rec[pic] -> file
data: {rec: {name: 'N', pic: file}, objectKey: '.k'} sent as: rec.name -> N, rec.pic -> file
So far I have managed to bring all the data to a common MultipartFormData.Part type, using the DataPart and FilePart like this:
val opts = body.dataParts.map {
case (key, values) => DataPart(key, values.head)
}
val parts = opts ++ body.files
So I am now left with a quite unfortunate Iterable[Part]:
0 = {MultipartFormData$DataPart#86271} "DataPart(arabic[active],false)"
1 = {MultipartFormData$DataPart#86273} "DataPart(english[active],true)"
2 = {MultipartFormData$DataPart#86277} "DataPart(english[url],2132132132)"
...
7 = {MultipartFormData$FilePart#76473} "FilePart(english[image],fb_icon_325x325.png,Some(image/png),TemporaryFile(/tmp/playtemp5909927824995768544/multipartBody8348573128070542611asTemporaryFile))"
Each object name contains the key of it's Json structure and its according value. Now instead of key[level1][level2] I would like to parse it to objects, in my case:
case class PcBanner(english: PcBanners, arabic: PcBanners, kurdish: PcBanners)
case class PcBanners(active: Boolean, url: Option[String], image: Option[String])`
I hope you got the idea.
The question
I know I could try to parse the name strings trying to fit it to objects, but I believe I made a mistake someway in the middle.
Is there a way to parse this structure into the objects, using field names as a reference? Any build in Play functions or alike?
Thanks for help!
As I stated in the title my case was to send images. As you would expect, I am also presenting a preview and the files currently saved in the database.
Considering all pros and cons I have decided to send all the data in JSON format, both ways. Meaning that the images are encoded and sent along in JSON structure.
Despite the fact that above solution looks very convenient it actually creates new problems during the implementation.
You will quickly exceed the server's POST request size limit. For Play server the default 100kB is possible to be extended, but...
I have soon run into some data malformations as the image saved as huge String of bytes probably had some sending/parsing errors.
Not going deeper into this faulty solution I have used the #danial advice:
No have the file sent separately like this
{file: file, otherData: JSON.stringify(myData)}
My solution
If anyone would like to use similar approach to mine I present my answer.
On the front-end side I have decided used ng-file-upload library. Binding it to HTML component with ngf-select with ngf-drop which enables the component:
<div ngf-drop ngf-select
ng-model="image"
ngf-accept="'image/*'"
ngf-resize="{width: {{width}}, height: {{height}}, quality: 1.0, restoreExif: false}">
<img ng-show="!!image && !!image.$ngfName" ngf-src="image">
<img ng-show="(!image || !image.$ngfName)" ng-src="{{ imageUrl }}">
</div>
Inside the upload tag I put the image preview. This works flawlessly. If the image is not selected I use the image saved in the db.
The data and images do not share the model anymore. The upload function looks as follow:
return Upload.upload({
url: url,
data: {file: images, data: angular.toJson(data)}
}).then(function (resp) {
console.log(resp);
}, function (error) {
console.log(error);
});
Putting together all the above gave me the output data object:
{
"english":{
"active":true,
"url":"http://google.com"
},
"arabic":{
"active":true,
"url":"http://google.com"
},
"kurdish":{
"active":true,
"url":"http://google.com"
}
}
On the server side the JSON matches the prepared case class and is parsed with build-in Jackson parser, allowing for easy object manipulation. The image has to be manually selected:
val json = r.body.dataParts("data")
val jsValue = Json.parse(json.head)
val result = jsValue.validate(LocalizedBanner.dataModelFormat) // parse JSON
Extracting the files from body can be done with build in function .file:
val key = s"file[${lang.name}][${imageType.name}]"
body.file(key).map(mp => (mp.ref.file, imageType))
Enjoy!

Semantic ui search module

I am using semantic ui search module, the content will be a remote JSON file, can make it work but no matter what i typed whether its found or not, i will show up the list from the JSON file.
script
$('.ui.search')
.search({
apiSettings: {
url: 'http://localhost/api/materialMaster.json'
},
fields: {
results : 'data',
title : 'matcode'
},
minCharacters : 2
})
;
JSON file format is
{"data":[{"matcode":"0A66244S1"},{"matcode":"200GD0S100150CM"}]}
See if this can help. I had this same problem and I solved using this instructions.
https://stackoverflow.com/a/32937262/5381965

What is meaning of gettext('Some Text') in Openstack

What is meaning of gettext('Some text are written')?. I am using openstack, there they have use gettext(), please see the following link openstack on github
I want to know meaning of it, if they are assigning the text to the variable why they didn't use just assignment opearator
$scope.label = {
title: gettext('Instance Details'),
instanceName: gettext('Instance Name'),
availabilityZone: gettext('Availability Zone'),
instance_count: gettext('Count'),
};
It's probably related to localization. Function gettext is looking for translation of provided arguments and display them in selected locale.
As an example of translation service in angular, check https://angular-translate.github.io/

Get meta data from delegated files using QML

I'm creating a music player for Ubuntu Touch in QML and I have some things I would appreciate some help with since I'm new to QML.
I have a list of tracks from a directory, but I want to show the meta data (artist, track name, year, album and so on) instead of the filename.
Using Qt.Multimedia am able to get the meta data from the currently playing track, but I can't find how to do it per file from my FolderListModel delegated files.
How would I do that?
This is the current code:
Column {
anchors.centerIn: parent
anchors.fill: parent
ListView {
id: musicFolder
FolderListModel {
id: folderModel
folder: musicDir
showDirs: false
nameFilters: ["*.ogg","*.mp3","*.oga","*.wav"]
}
width: parent.width
height: parent.height
model: folderModel
delegate: ListItem.Subtitled {
text: fileName
subText: "Artist: "
onClicked: {
console.debug('Debug: User pressed '+musicDir+fileName)
playMusic.source = musicDir+fileName
playMusic.play()
trackInfo.text = playMusic.metaData.albumArtist+" - "+playMusic.metaData.title // show track meta data
}
}
}
}
It seems like the easiest thing to do here would be to go get a C++ library that can parse the meta data out of these files and use it to create a custom ListModel in C++ that populates this information onto itself. Unfortunately, this will have to be done in C++ as javascript does not have the IO capabilities to read and parse files.
Actually I think I might go ahead and use QtMultimedia, but keep data in a local database. On startup, it checks the music dir and adds/removes tracks. That way it will be only be slow at first startup (hopefully)

Resources