How to iterate javax.management.openmbean.CompositeDataSupport in wlst - python

How do you iterate a array of javax.management.openmbean.CompositeDataSupport?
myBean = ObjectName('com.oracle.sdp.messaging:Location=my_soa_server,name=EmailDriverConfig,type=SDPMessagingDriverConfig,Application=usermessagingdriver-email')
driverParams = mbs.getAttribute(myBean,'DriverParameterProperties')
for param in driverParams:
####How to do iterate and do an if on a name#####
print param.getName()
If I do something like this I am getting..
Traceback (innermost last):
File "<console>", line 1, in ?
AttributeError: getName
I have verified that when you execute driverParams[0] that I am getting something like this
javax.management.openmbean.CompositeDataSupport(compositeType=javax.management.openmbean.CompositeType(name=Property,items=((itemName=allowedValues,itemType=javax.management.openmbean.ArrayType(name=[Ljavax.management.openmbean.CompositeData;,dimension=1,elementType=javax.management.openmbean.CompositeType(name=AllowedValue,items=((itemName=label,itemType=javax.management.openmbean.SimpleType(name=java.lang.String)),(itemName=value,itemType=javax.management.openmbean.SimpleType(name=java.lang.String)))),primitiveArray=false)),(itemName=description,itemType=javax.management.openmbean.SimpleType(name=java.lang.String)),(itemName=encodedCredential,itemType=javax.management.openmbean.SimpleType(name=java.lang.String)),(itemName=mandatory,itemType=javax.management.openmbean.SimpleType(name=java.lang.String)),(itemName=name,itemType=javax.management.openmbean.SimpleType(name=java.lang.String)),(itemName=type,itemType=javax.management.openmbean.SimpleType(name=java.lang.String)),(itemName=value,itemType=javax.management.openmbean.SimpleType(name=java.lang.String)))),contents={allowedValues=[], description=Supported Delivery Types, encodedCredential=false, mandatory=yes, name=SupportedDeliveryTypes, type=java.lang.String, value=EMAIL})
Looking at the attribute, I would like to validate the SupportedDeliveryTypes value
name=SupportedDeliveryTypes
value=EMAIL
description=Supported Delivery Types

CompositeDataSupport is not an array.
To view its content you can try using toString() (in your sample driverParams[0].toString()) or access values with values() or get(String key) / getAll(String[] keys).
For example, try with:
myBean = ObjectName('com.oracle.sdp.messaging:Location=my_soa_server,name=EmailDriverConfig,type=SDPMessagingDriverConfig,Application=usermessagingdriver-email')
driverParams = mbs.getAttribute(myBean,'DriverParameterProperties')
for param in driverParams:
print param.toString()

Related

How to get index position of values in python

I have a scenario , where I am trying to get index position of value
My code :
a_set = {22,56,26}
print(a_set[56])
Getting below error
Traceback (most recent call last):
File "<string>", line 5, in <module>
TypeError: 'set' object is not subscriptable
Expected output :
1 -> This the position of 56 from set
The error is explaining a lot here: sets in Python are not subscriptable.
They dont have order relation.
According to your code example, you are trying to ask weather a value exists in the set, right?
In Python you can do it with in operator:
>> print(36 in a_set)
True
or
if (36 in a_set):
my_function()
Sets are by definition completely unordered and unindexed, you cannot get the information with an index directly as that is not what they were made for. As a workaround, you can simply convert the set to a list that is both indexed and ordered.
a_set = {22,56,26}
print(list(a_set)[3]) # converts the set into and displays it's third entry.
To solve your problem, you can use .index() on the new list such as this:
a_set = {1,2,3}
print(list(a_set).index(1))

Chinese characters as dictionary KEY

I am trying to create a dictionary lookup variable like this:
lookup = {
u'安徽省':'Anhui',
u'福建省':'Fujian',
u'甘肃省':'Gansu',
u'广东省':'Guangdong',
u'贵州省':'Guizhou',
u'浙江省':'Zhejiang'
}
I am calling an API and it returns the result in Chinese. I want to simply have a look up table to convert it to the English name.
So my code is:
api_response = api.geocode(address, isChina)
if len(api_response['Response']['View']) > 0:
state = lookup[api_response['Response']['View'][0]['Result'][0]['Location']['Address']['State']]
But the error I get is:
2019-07-29 15:35:13.193 | ERROR | __main__:<module>:148 - Traceback (most recent call last): File "format.py", line 93, in <module>
new_dict = doStepByStepCleanse(row, isChina, line_count) File "format.py", line 43, in doStepByStepCleanse
state = lookup[api_response['Response']['View'][0]['Result'][0]['Location']['Address']['State']] KeyError: '山东省'
Is this possible to achieve?
If you read the error, I'm not sure you've defined all possible keys that the API returns. There's nothing special about the Chinese characters being in the dictionary, just that KeyError: '山东省' means that it really isn't there in your dictionary
If you're not guaranteed to have all known keys ahead of time, you should fallback to getting a default value
lookup.get(api_response['Response']['View'][0]['Result'][0]['Location']['Address']['State']], "Unknown")

Python 3 Read a json file with missing objects within lines

I'm reading a json file with the structure below:
[{"id":1,"gender":"Male","first_name":"Andrew","last_name":"Scott","email":"ascott0#shutterfly.com","ville":"Connecticut"},
{"id":3,"first_name":"Mary","last_name":"Richards","email":"mrichards2#japanpost.jp","ville":"Minnesota"}]
So, as you can see in the second "line" the field "gender" it'is not present.I realize that because my code to read the file got wrong in this line.
my code:
import json
def jsonreader():
##Reader for json files
##Open files using json library
with open('cust_data.json') as file:
data = json.load(file)
resultlist = list()
for line in data:
print(line["id"],line["gender"])
I got the error:-
C:/xxxxx/x.py
1 Male
Traceback (most recent call last):
2 Female
File "C:/xxxxx/x", line 67, in <module>
jsonreader()
File "C:/xxxxx/x", line 56, in jsonreader
print(line["id"],line["gender"])
KeyError: 'gender'
Before answer guys, you should know that I have a method to define the default value in "gender", voila my method:
def definegender(x):
if x is None:
x = 'unknown'
return x
elif (x =='Male') or (x=='Female'):#not None:
return {
'Male':'M',
'Female': 'F'
}.get(x)
else:
return x
So, in this case, I could not use something like a default value reading the values because I need to send some value to my method.
Some one of you guys would know how should be the best way to read this kind of files when we have missing objects. Thanks
why not using a default value for your dictionary in dict.get?
print(line["id"],line.get("gender","unknown"))
And since you want to transform input further, you could nest two dict.get together, the first one with None as default value, and a new table, like this:
gender_dict = {"Male":"M", "Female":"F", None : "unknown"}
print(line["id"],gender_dict.get(line.get("gender")))
(note that you don't need your overcomplex gender conversion method anymore)
Although this already has a perfect answer, my point of view is that there can be alternatives too. So here it is:
for line in data:
try:
print(line["id"],line["gender"])
except KeyError:
print(line["id"],"Error!!! no gender!")
This is called ErrorHandling. Read the docs here:
https://docs.python.org/3.6/tutorial/errors.html
update: Do you mean this?
update2 corrected misstake
try:
gender = definegender(line["gender"])
except KeyError:
gender = definegender(None)
print(line["id"],gender)
update3: (for future purposes)
as .get() returns None by default the most simple solution would be
gender = definegender(line.get("gender"))
print(line["id"],gender)
Why not simplify this with an if-statement?
for line in data:
if "gender" in line:
print(line)

strip ' from all members in a list

Ok, so I converted each line in a text file into a member of a list by doing the following: chkseq=[line.strip() for line in open("sequence.txt")] So when I print chkseq I get this: ['3','3'] What I would like is for it to instead look like this: [3,3] I know this is possible, I'm just unsure of how! I need them to be intergers, not strings. So if all else fails, that is my main goal in this: create a list from a .txt file whose members are intergers (which would be all the .txt file contained). Thanks!! -OSFTW
It looks like you want to interpret the strings as integers. Use int to do this:
chkseq = [int(line) for line in open("sequence.txt")]
It can also be written using map instead of a list comprehension:
chkseq = map(int, open("sequence.txt"))
iterate over the elements of your list and print them out with your preferred formatting rather than relying on the default formatting when printing the whole list at once.
Say your array is called input, and you want to store the value in an array called chkseq, your code would be:
chkseq = [int(i) for i in input]
Or, if you wanted to do everything all in one line:
chkseq = [int(i.strip()) for i in open("sequence.txt")]
Passing a string to the int constructor will attempt to turn it into a int.
>>> int('3')
3
>>> int('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'foo'

Python JSON Google Translator extraction problem

I am trying to extract the JSON object in python using Simplejson. But I am getting the following error.
Traceback (most recent call last):
File "Translator.py", line 42, in <module>
main()
File "Translator.py", line 38, in main
parse_json(trans_text)
File "Translator.py", line 27, in parse_json
result = json['translations']['translatedText']
TypeError: list indices must be integers, not str
This is my JSON object looks like,
{'translations': [{'translatedText': 'fleur'}, {'translatedText': 'voiture'}]}
and this is my python piece of code for it.
def parse_json(trans_text):
json = simplejson.loads(str(trans_text).replace("'", '"'))
result = json['translations']['translatedText']
print result
any idea on it?
json['translations'] is a list by your definition, so its indices must be integers
to get a list of translations:
translations = [x['translatedText'] for x in json['translations']]
another way:
translations = map(lambda x: x['translatedText'], json['translations'])
json['translations'] is a list of objects. To extract the 'translatedText' property, you could use itemgetter:
from operator import itemgetter
print map(itemgetter('translatedText'), json['translations'])
See the implementation of detect_language_v2() for another usage example.

Categories