ArcGIS Python Label Expression Error - python

I've recently started learning Python and started using it to create label expressions in ArcMap. I ran into an error today that I can't figure out though (and seems like it should be simple). When I try to create the following expression:
def FindLabel ( [FacilityName] ):
S = [FacilityName]
S = S.upper()
return S
I get back an error as follows:
Error 0 on line 0.
Error running expression: FindLabel(ESRIExpressionArg0)
Traceback (most recent call last):
File "<expression>", line 1, in <module>
File "<string>", line 3, in FindLabel
AttributeError: 'NoneType' object has no attribute 'upper'.
[FacilityName] is a domained field, and Null values are allowed. I understand, I think, that 'NoneType' means that [FacilityName] is being given a None value before it's trying to be returned, but I don't know how to fix the problem.
Thanks,
Ethan

I'm pretty sure all the values get returned as strings, but in the case of a null value, it might be returned as None, which would explain the error you're getting.
You can use a try..except block or make a conditional statement inside your function to ignore None values.
Here's with try..except:
def FindLabel ( [FacilityName] ):
try:
S = [FacilityName]
S = S.upper()
return S
except AttributeError:
pass

Related

'str' object has no attribute 'from_directory_url' in python

I am trying to make the call
from azure.storage.fileshare import ShareDirectoryClient
shrdDirClient = ShareDirectoryClient.from_directory_url
(detailedFileURI,snapshot=None, credential=None)
but resulted in the error above.
I tried
if hasattr(ShareDirectoryClient, 'from_directory_url'):
print("Present")
But it did not go into the loop.
My full code is too long. This is another approach I tried resulting in 'str' object is not callable error
from azure.storage.fileshare import ShareDirectoryClient
from datetime import timedelta,datetime
now = datetime.now(timezone('UTC'))
sasToken = generate_share_sas(accountName, shareName, accountKey,\
permission=AccountSasPermissions(read=True, \
write=False, \
delete=False, \
list=True, create=True), expiry=now + timedelta(days=3650)\
)
accountURL = "https://nsclusterhdistorage.file.core.windows.net"
shareName = "dev-archived-data"
detailedFileURI = accountURL+'/'+shareName
sh = ShareDirectoryClient()
sh.from_directory_url(detailedFileURI,snapshot=None, credential=sasToken)
I am relatively new to python azure storage file share.
can someone help
Sorry, I can't reproduce this.
I ran the following code:
from azure.storage.fileshare import ShareDirectoryClient
detailedFileURI = "Something"
shrdDirClient = ShareDirectoryClient.from_directory_url(detailedFileURI,snapshot=None, credential=None)
and it generated the following error:
Traceback (most recent call last):
File "D:\StackOverflow\azure_storage_test.py", line 4, in <module>
shrdDirClient = ShareDirectoryClient.from_directory_url(detailedFileURI,snapshot=None, credential=None)
File "C:\Python37\lib\site-packages\azure\storage\fileshare\_directory_client.py", line 164, in from_directory_url
credential=credential, **kwargs)
File "C:\Python37\lib\site-packages\azure\storage\fileshare\_directory_client.py", line 96, in __init__
raise ValueError("Please specify a share name.")
ValueError: Please specify a share name.
Now clearly this isn't successful execution. If I'm honest, I don't know what to set detailedFileURI to. But that's not the point. The point is that the code sample above is enough to prove that I can get in to the from_directory_url method, and this is clear from the traceback.
However, if I run the following code:
from azure.storage.fileshare import ShareDirectoryClient
ShareDirectoryClient = "some string"
detailedFileURI = "Something"
shrdDirClient = ShareDirectoryClient.from_directory_url(detailedFileURI,snapshot=None, credential=None)
then I do encounter the same error:
Traceback (most recent call last):
File "D:\StackOverflow\azure_storage_test.py", line 5, in <module>
shrdDirClient = ShareDirectoryClient.from_directory_url(detailedFileURI,snapshot=None, credential=None)
AttributeError: 'str' object has no attribute 'from_directory_url'
Of course, there's not a lot of point in importing ShareDirectoryClient if you're then going to assign a string to it. You may as well remove the import statement. However, doing this reproduces your error message. In the absence of any further code in your question I can only conclude that your code does the same as this, although perhaps more subtly.
The only other suggestion I have is that your installation of the azure-storage-file-share package has somehow got broken. If you run a Python script containing the following two lines only, you should get either <class 'type'> or <class 'str'> as output. I get <class 'type'>, and I would expect that anyone else using this package would get the same. However, if you get <class 'str'>, then it is likely that the package has got corrupted and you may want to try reinstalling it.
from azure.storage.fileshare import ShareDirectoryClient
print(type(ShareDirectoryClient))
For some reason ‘ ShareDirectoryClient’ is of type {string}. You either import it as a string, i.e. ‘ azure.storage.fileshare’ simply has this defined as a string, or, you assign it to a string later in your code (not visible in the part that has been shared). Please try this:
X = ‘some_string’
X()
… and you will get the string-is-not-callable error which means a string cannot be invoked (i.e. it is not a function one can call)
Then another experiment:
Y = ‘another_string’
Y.bla()
… and you get the other error that a string object has no attribute named ‘bla’.
In Python everything is an object. If you define
class MyClass()
pass
And then try ‘MyClass.bla()’ you will get MyClass does does not have attribute ‘bla’.
Can you try to import ShareDirectoryClient and then type(ShareDirectoryClient) and we’ll see what type of object gets imported.

Python: 'json_store_client' returning 'null' upon request

I'm trying to contact json_store_client to see how many times my program has been executed. However, although I have a proper key, I get thrown the following error:
/home/runner/.local/lib/python3.6/site-packages/json_store_client/__init__.py:99: EmptyResponseWarning: Jsonstore returned null, please make sure something is saved under this key.
warn('Jsonstore returned null, please make sure something issaved under this key.', EmptyResponseWarning)
Traceback (most recent call last):
File "main.py", line 5, in <module>
runnum = client.store("runs", runs + 1)
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
I'm more worried about the first error, as it has to do directly with getting the data. I went to jsonstore.io and copy-pasted the given key. Is this not enough? Or is there another way to do this?
Current code:
from json_store_client import Client
key = "168034i5o4433136733f5e6c9c70bdee1a113474602675459e3ffa9bd584a03314f"
client = Client(key)
runs = client.retrieve("runs")
runnum = client.store("runs", runs + 1)
print(runnum)

Python returning type error on wrong line

I'm not sure if the issue I'm experiencing is my lack of experience with Python or if it's a bug in the interpreter, but I think I'm getting a TypeError message on the wrong line.
Please explain to me why this is happening if it's not a bug. My code is as follows:
#!/usr/bin/env python3
from awacs.aws import Policy, Principal, Statement
from troposphere import Template
from troposphere.iam import Role
t = Template()
t.add_resource(Role(
"SESLambdaRole",
AssumeRolePolicyDocument = Policy(
Version = "2012-10-17",
Statement = [
Statement(
Effect = "Allow",
Resource = "arn:aws:logs:*:*:*",
Principal = Principal(
"Service",
["lambda.amazonaws.com"]
),
)
]
)
))
print(t.to_json())
This is my output
ubuntu#ip-111-11-11-111:~$ ./ses-lambda-forwarder-resources.py
Traceback (most recent call last):
File "./ses-lambda-forwarder-resources.py", line 19, in <module>
["lambda.amazonaws.com"]
File "/home/ubuntu/.local/lib/python3.6/site-packages/awacs/__init__.py", line 113, in __init__
sup.__init__(None, props=self.props, **kwargs)
File "/home/ubuntu/.local/lib/python3.6/site-packages/awacs/__init__.py", line 40, in __init__
self.__setattr__(k, v)
File "/home/ubuntu/.local/lib/python3.6/site-packages/awacs/__init__.py", line 81, in __setattr__
self._raise_type(name, value, expected_type)
File "/home/ubuntu/.local/lib/python3.6/site-packages/awacs/__init__.py", line 90, in _raise_type
(name, type(value), expected_type))
TypeError: Resource is <class 'str'>, expected <class 'list'>
ubuntu#ip-111-11-11-111:~$ python3 --version
Python 3.6.3
If I change the following line
Resource = "arn:aws:logs:*:*:*",
to
Resource = [ "arn:aws:logs:*:*:*" ],
It works. Why is Python complaining about the line 3 lines below?
Python doesn't know which actual argument errored, just that it was passed from an expression that stretches across a few lines. It makes a rough guess at the erroring line (which as Ryan points out in the comments seems to be the last non-punctuation line in the expression), and reports the error as coming from there, but it could have come from any part of the expression that errored. For a simpler example, consider:
>>> i = int(
... '#',
... base=2
... )
...
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-6-1e4a194d0c31> in <module>()
1 i = int(
2 '#',
----> 3 base=2
4 )
5
ValueError: invalid literal for int() with base 2: '#'
The error comes from the int constructor (call begins on line 1), from the '#' argument (line 2), and the expression ends on line 4, but the arrow implicates line 3. All Python really knows is that the error came from the int(...) expression, and it makes a stab at the problem being the final meaningful line of the expression, but it doesn't really know which of the arguments was at fault (the exception raising APIs aren't fine-grained enough to tell Python programmatically which argument is the problem in a way that could help), and the heuristic doesn't work.
The same thing happens with your code; Python knows the Statement constructor raised the exception, and it points to the last non-trivial line of that expression when the error is raised, but it doesn't really know which line contained the problematic argument, and the heuristic gives you misleading information. Luckily, the exception message tells you what is wrong (the Resource argument must be a list), so you can use that context to scan the nearby lines and notice the non-list Resource argument.

Unbound method must be called with X instance as first argument (got str instance instead)

I am playing with pyelliptic, but I can't use the method raw_get_ecdh_key defined in the file ecc.py.
Here's my example code:
>>> import pyelliptic
>>> pubkey1="0453eb8248f42b00d057bc1adc724c4c841ec75851d6cd86f56f9bae5223219c7d3c7aff832d2383dfec167327ef38e9bf066690a8f94c055b336a607cebc2dddf".decode('hex')
>>> pubkey2="04678b95e902b04817ba258ecd3dbb2150d83850848a3b8523c11d51b6a9f89b93ea82db74ba82ba44fadb050b35eae8b96f3738e88c7c117227303a528c8df985".decode('hex')
>>> pyelliptic.ECC.raw_get_ecdh_key(pubkey1, pubkey2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method raw_get_ecdh_key() must be called with ECC instance as first argument (got str instance instead)
I searched and found many questions on the subject here. I learned that I need to call ECC() instead of ECC, but it doesn't work any better:
>>> pyelliptic.ECC().raw_get_ecdh_key(pubkey1, pubkey2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/pyelliptic/ecc.py", line 324, in raw_get_ecdh_key
OpenSSL.EC_KEY_free(own_key)
UnboundLocalError: local variable 'own_key' referenced before assignment
I can't figure what's wrong. I checked and the variable own_key should be referenced.
It's a very obvious bug in pyelliptic - if you look at the code, the part where own_key is defined (ecc.py line 301) is wrapped in huge try/finally block. If an exception is raised (and not managed) before line 301 (which is obviously what happened to you), then the execution flow jumps to the finally block, which to tries to reference own_key which at this point has not yet been defined.
You can fix by cloning the git repo and editing the raw_get_ecdh_key function's code so 1. the relevant local variables are defined at the beginning of the function before the try block (setting them to None) and 2. in the finally block these variables are tested against None before trying to use them to free resources, ie (untested):
def raw_get_ecdh_key(self, pubkey_x, pubkey_y):
other_key = None
other_pub_key_x = None
other_pub_key_y = None
other_pub_key = None
own_key = None
own_priv_key = None
try:
# (snip code)
finally:
if other_key is not None:
OpenSSL.EC_KEY_free(other_key)
if other_pub_key_x is not None:
OpenSSL.BN_free(other_pub_key_x)
if other_pub_key_y is not None:
OpenSSL.BN_free(other_pub_key_y)
if other_pub_key is not None:
OpenSSL.EC_POINT_free(other_pub_key)
if own_key is not None:
OpenSSL.EC_KEY_free(own_key)
if own_priv_key is not None:
OpenSSL.BN_free(own_priv_key)
And then run the the unittests (eventually adding some tests for this case) and submit a pull request to the author.
Note that you'll have applied this (untested) fix you should have another error - the one that sent you in the finally block at first - but at least you should then have more infos about why the call failed.

Entry().get() doesn't work in Python 3.4

Despite all attempts, I cannot seem to get Entry().get() to assign a string in an Entry window. Here's a code snippet:
Itx_bcn_ent = Entry(win).grid(row=1,column=1)
I define a button to call a function:
btn = Button(win,text="Run",command=getnums).grid(row=5,column=3,padx=100)
Here's the function:
def getnums():
Itx_bcn = Itx_bcn_ent.get()
When I run the script, I get the following error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1482, in __call__
return self.func(*args)
File "C:\Python34\voltage_substate_GUI.py", line 7, in getnums
Itx_bcn = Itx_bcn_ent.get()
AttributeError: 'NoneType' object has no attribute 'get'
I've seen the construct to use a Class StringVar() and the option "textvariable=" with the Entry() object, however doing this seems overly complicated as it just creates an additional set of variables between what's in the Entry window and the variable I am trying to assign.
Any thoughts on this?
Entry.grid() returns None, so when you do something = Entry(root).grid(), you're getting something=None.
This isn't a problem until you try to use that thing! That's why you're getting a 'NoneType' object has no attribute 'get' error.
Itx_bcn_ent = Entry(win)
Itx_bcn_ent.grid(row=1,column=1)
Now your button works :), though you have the same problem with your btn = line. I've yet to have to reuse that assignment, so maybe just drop it?
Button(win,text="Run",command=getnums).grid(row=5,column=3,padx=100)

Categories

Resources