PyQt5 combo retrieve the value rather than the key or text - combobox

In my class definition I have:
colours = {
None: None,
"Red": "255,0,0",
"Green": "0, 255, 0",
"Blue": "0, 0, 255",
}
self.colourComboTop.addItems(colours)
In my code:
def some_function(self):
self.colourComboTop.currentIndex()
Gets the index, 0, 1, 2, 3
self.colourComboTop.itemText(self.colourComboTop.currentIndex())
Gets the displayed text.
How do I access the value associated with the key? So with {"Red": "255,0,0"} I want the rgb value as a string.

Either set the RGB value as the userData argument,
for key, value in colours.items():
self.colourComboTop.addItem(key, value)
key = self.colourComboTop.currentText()
rgb = self.colourComboTop.currentData()
Or keep a reference to the dict and just map it.
self.colours = {
None: None,
"Red": "255,0,0",
"Green": "0, 255, 0",
"Blue": "0, 0, 255",
}
self.colourComboTop.addItems(self.colours)
key = self.colourComboTop.currentText()
rgb = self.colours[key]

Related

My react native tensorflow model gives the same prediction every result

I have trained a keras model with 6 classes for CNN Image Recognition. Then, I converted it to tensorflowjs using this command:
tensorflowjs_converter --quantization_bytes 1 --input_format=keras {saved_model_path} {target_path}
which then gives me 2 files (model.json, group1-shard1of1.bin). After adding it to my react native project and test the prediction function, it always returns the same result. I am converting my image to tensor base on this github thread:
const processImagePrediction = async (base64Image: any) => {
const fileUri = base64Image.uri;
const imgB64 = await FileSystem.readAsStringAsync(fileUri, {
encoding: FileSystem.EncodingType.Base64,
});
const imgBuffer = tf.util.encodeString(imgB64, 'base64').buffer;
const raw = new Uint8Array(imgBuffer);
let imageTensor = decodeJpeg(raw);
const scalar = tf.scalar(255);
imageTensor = tf.image.resizeNearestNeighbor(imageTensor, [224, 224]);
const tensorScaled = imageTensor.div(scalar);
//Reshaping my tensor base on my model size (224, 224)
const img = tf.reshape(tensorScaled, [1, 224, 224, 3]);
console.log("IMG: ", img);
const results = model.predict(img);
let pred = results.dataSync();
console.log("PREDICTION: ", pred);
}
I was expecting to have a different result but no matter what image I capture it always returns this result:
LOG IMG: {"dataId": {"id": 23}, "dtype": "float32", "id": 38, "isDisposedInternal": false, "kept": false, "rankType": "4", "scopeId": 6, "shape": [1, 224, 224, 3], "size": 150528, "strides": [150528, 672, 3]} LOG PREDICTION: [-7.7249579429626465, 4.73449182510376, 2.609705924987793, 20.0458927154541, -7.944214344024658, -18.101320266723633]
The numbers somehow change slightly but it retains the highest prediction (which is class number 4).
P.S. I'm new to image recognition so any tips would be appreciated.

How to get JSON Key and Values using Swift

I am trying to get below JSON result of Key and Value and store it into two separate arrays (keyArray and valuesArray). Keys I can append easily but values not appending. It's showing
error 'AnyObject' is not convertible to 'String'; did you mean to use 'as!' to force downcast?`.
JSON Keys are string but value is Int. How to append Int into string array?
{
"status_code": 200,
"message": “ranking”,
"result": {
"cost": 150,
"discount": 25,
“fixon": 0,
"fee": 0,
"check": 0,
"mailing": 20,
}
}
I tried
for (key, value) in results {
print("key (key) value2 (value)")
self.processtitle.append(key)
self.price.append(value) as! String? //'AnyObject' is not convertible to 'String'; did you mean to use 'as!' to force downcast?
}
Dear you can't parse JSON by this way , so you can parse JSON by Decodable
But for pass this error you can add a condition:
if let key = key {
self.processtitle.append(key)
}
if let value = value {
self.price.append("\(value)")
}

Array as value in a lua table

I couldn't find an answer to my question: Can you have an array as value in a lua table?
local colors = {"blue" = {0,0,1,1}, "green" = {0,1,0,1}, "red" = {1,0,0,1} , "orange" = {0.5, 0, 0.5, 1}, "black" = {0,0,0,1}, "gold" = {1, 215/255, 0, 1}}
I get the error on this line using the corona sdk:
'}' expected near '='
It's tables all the way down :-) Yes, tables (including ones indexed like arrays) can be elements of tables in Lua. This chapter in the Lua manual explains the different ways of defining the elements of a table.
In your example, you should not put quotation marks around the key.
local colors = { blue = { 0, 1, ...}, green = { ... }, ... }
Or you can do:
local colors = {}
colors[ "blue" ] = { 0, ... }
colors[ "green" ] = ...
Or
colors.blue = { 0, .... }
colors.green = ....
The latter is syntactic sugar for the other forms.

What is a StateImage in a TreeView?

I have recently discovered this answer which allows me to identify if a user has clicked on a node or not. The TreeViewHitTestInfo returned by the HitTest() method contains a Location field of type TreeViewHitTestLocations with the following flags:
public enum TreeViewHitTestLocations
{
None = 1,
Image = 2,
Label = 4,
Indent = 8,
PlusMinus = 16,
RightOfLabel = 32,
StateImage = 64,
AboveClientArea = 256,
BelowClientArea = 512,
RightOfClientArea = 1024,
LeftOfClientArea = 2048,
}
This is what I found through testing:
None: White
Image: Green
Label: Yellow
Indent: Dark blue
PlusMinus: Red
RightOfLabel: Light blue
The ClientArea flags are in light gray, but I haven't been able to identify the StateImage one. What is a StateImage?

soapUI - Parse JSON Response containing arrays

Given the following JSON response from a previous test step (request) in soapUI:
{
"AccountClosed": false,
"AccountId": 86270,
"AccountNumber": "2915",
"AccountOwner": 200000000001,
"AccountSequenceNumber": 4,
"AccountTotal": 6,
"ActiveMoneyBeltSession": true,
"CLMAccountId": "",
"CustomerName": "FRANK",
"Lines": [{
"AndWithPreviousLine": false,
"IngredientId": 10000025133,
"OrderDestinationId": 1,
"PortionTypeId": 1,
"Quantity": 1,
"QuantityAsFraction": "1",
"SentToKitchen": true,
"TariffPrice": 6,
"Id": 11258999068470003,
"OriginalRingUpTime": "2014-10-29T07:37:38",
"RingUpEmployeeName": "Andy Bean",
"Seats": []
}, {
"Amount": 6,
"Cashback": 0,
"Change": 0,
"Forfeit": 0,
"InclusiveTax": 1,
"PaymentMethodId": 1,
"ReceiptNumber": "40/1795",
"Tip": 0,
"Id": 11258999068470009,
"Seats": []
}],
"MoaOrderIdentifier": "A2915I86270",
"OutstandingBalance": 0,
"SaveAccount": false,
"ThemeDataRevision": "40",
"TrainingMode": false
}
I have the following groovy script to parse the information from the response:
import groovy.json.JsonSlurper
//Define Variables for each element on JSON Response
String AccountID, AccountClosed, AccountOwner, AccountSeqNumber, AccountTotal, ActMoneyBelt
String CLMAccountID, ThemeDataRevision, Lines, MoaOrderIdentifier, OutstandingBalance, SaveAccount, TrainingMode, CustName, AccountNumber
String AndWithPreviousLine, IngredientId, OrderDestinationId, PortionTypeId, Quantity, SentToKitchen, TariffPrice, Id, OriginalRingUpTime, RingUpEmployeeName, Seats
int AccSeqNumInt
def responseContent = testRunner.testCase.getTestStepByName("ReopenAcc").getPropertyValue("response")
// Create JsonSlurper Object to parse the response
def Response = new JsonSlurper().parseText(responseContent)
//Parse each element from the JSON Response and store in a variable
AccountClosed = Response.AccountClosed
AccountID = Response.AccountId
AccountNumber = Response.AccountNumber
AccountOwner = Response.AccountOwner
AccountSeqNumber = Response.AccountSequenceNumber
AccountTotal = Response.AccountTotal
ActMoneyBelt = Response.ActiveMoneyBeltSession
CLMAccountID = Response.CLMAccountId
CustName = Response.CustomerName
Lines = Response.Lines
/*Lines Variables*/
AndWithPreviousLine = Response.Lines.AndWithPreviousLine
IngredientId = Response.Lines.IngredientId
OrderDestinationId = Response.Lines.OrderDestinationId
PortionTypeId = Response.Lines.PortionTypeId
Quantity = Response.Lines.Quantity
SentToKitchen = Response.Lines.SentToKitchen
TariffPrice = Response.Lines.TariffPrice
Id = Response.Lines.Id
OriginalRingUpTime = Response.Lines.OriginalRingUpTime
RingUpEmployeeName = Response.Lines.RingUpEmployeeName
Seats = Response.Lines.Seats
/*End Lines Variables*/
MoaOrderIdentifier = Response.MoaOrderIdentifier
OutstandingBalance = Response.OutstandingBalance
SaveAccount = Response.SaveAccount
ThemeDataRevision = Response.ThemeDataRevision
TrainingMode = Response.TrainingMode
As you can see above there is an element (Array) called "Lines". I am looking to get the individual element value within this array. My code above when parsing the elements is returning the following:
----------------Lines Variables----------------
INFO: AndWithPreviousLine: [false, null]
INFO: IngredientId: [10000025133, null]
INFO: OrderDestinationId: [1, null]
INFO: PortionTypeId: [1, null]
INFO: Quantity: [1.0, null]
INFO: SentToKitchen: [true, null]
INFO: TariffPrice: [6.0, null]
INFO: Id: [11258999068470003, 11258999068470009]
INFO: OriginalRingUpTime: [2014-10-29T07:37:38, null]
INFO: RingUpEmployeeName: [Andy Bean, null]
INFO: Seats: [[], []]
How can i get the required element from the above, also note the the 2 different data contracts contain the same element "ID". Is there a way to differenciate between the 2.
any help appreciated, thanks.
The "Lines" in the Response can be treated as a simple list of maps.
Response["Lines"].each { println it }
[AndWithPreviousLine:false, Id:11258999068470003, IngredientId:10000025133, OrderDestinationId:1, OriginalRingUpTime:2014-10-29T07:37:38, PortionTypeId:1, Quantity:1, QuantityAsFraction:1, RingUpEmployeeName:Andy Bean, Seats:[], SentToKitchen:true, TariffPrice:6]
[Amount:6, Cashback:0, Change:0, Forfeit:0, Id:11258999068470009, InclusiveTax:1, PaymentMethodId:1, ReceiptNumber:40/1795, Seats:[], Tip:0]
The Response is just one huge map, with the Lines element a list of maps.
Using groovysh really helps here to interactively play with the data, i did the following commands after starting a "groovysh" console:
import groovy.json.JsonSlurper
t = new File("data.json").text
r = new JsonSlurper().parse(t)
r
r["Lines"]
r["Lines"][0]
etc
Edit: In response to your comment, here's a better way to get the entry with a valid AndWithPreviousLine value.
myline = r["Lines"].find{it.AndWithPreviousLine != null}
myline.AndWithPreviousLine
>>> false
myline.IngredientId
>>> 10000025133
If you use findAll instead of find you'll get an array of maps and have to index them, but for this case there's only 1 and find gives you the first whose condition is true.
By using Response["Lines"].AndWithPreviousLine [0] you're assuming AndWithPreviousLine exists on each entry, which is why you're getting nulls in your lists. If the json responses had been reversed, you'd have to use a different index of [1], so using find and findAll will work better for you than assuming the index value.

Resources