Im trying to traversal a graph using
from neo4jrestclient.client import GraphDatabase
G = GraphDatabase("http://localhost:7474/db/data/")
# G is generated here in my program but for space purpose I removed these steps
traverser = G.traversal().evaluator(my_evaluator).traverse(root)
I borrowed my_evaluator function from stackoverflow which is
def my_evaluator(path):
# Filter on end node property
if path.end['value'] == 105:
return Evaluation.INCLUDE_AND_CONTINUE
# Filter on last relationship type
if path.last_relationship.type.name() == 'edge':
return Evaluation.INCLUDE_AND_PRUNE
# You can do even more complex things here, like subtraversals.
return Evaluation.EXCLUDE_AND_CONTINUE
When I tried to execute the code I got the following error message:
Traceback (most recent call last):
File "C:\Users\firas\Desktop\ACO_neo4j.py", line 747, in
traverser = G.traversal().evaluator(my_evaluator).traverse(root)
AttributeError: 'TraversalDescription' object has no attribute 'evaluator'
Can you help me in this please. Thanks.
Firas
You can always use a Cypher query to to the same.
The problem here is that the evaluator funcion may be borrowed from the native driver by Neo4j guys, the embedded Python driver. So far, there is some limitations on traversing the graph using the neo4-rest-client traversals. Because underneath it is using the REST interface, the only way to write a evaluator is by writing a Javascript function, AFAIK.
Related
python3.8
My code:
from googleads import adwords
def execute_request():
adwords_client = adwords.AdWordsClient.LoadFromStorage(path="google_general/googleads.yaml")
campaign_service = adwords_client.GetService('CampaignService', version='v201809')
pass
context["dict_list"] = execute_request()
Traceback:
Traceback (most recent call last):
File "/home/michael/pycharm-community-2019.3.2/plugins/python-ce/helpers/pydev/_pydevd_bundle/pydevd_xml.py", line 282, in frame_vars_to_xml
xml += var_to_xml(v, str(k), evaluate_full_value=eval_full_val)
File "/home/michael/pycharm-community-2019.3.2/plugins/python-ce/helpers/pydev/_pydevd_bundle/pydevd_xml.py", line 369, in var_to_xml
elif hasattr(v, "__len__") and not is_string(v):
File "/home/michael/PycharmProjects/ads3/venv/lib/python3.8/site-packages/googleads/common.py", line 694, in __getattr__
raise googleads.errors.GoogleAdsValueError('Service %s not found' % attr)
googleads.errors.GoogleAdsValueError: Service __len__ not found
Unexpected error, recovered safely.
googleads.yaml about logging
logging:
version: 1
disable_existing_loggers: False
formatters:
default_fmt:
format: ext://googleads.util.LOGGER_FORMAT
handlers:
default_handler:
class: logging.StreamHandler
formatter: default_fmt
level: DEBUG
loggers:
# Configure root logger
"":
handlers: [default_handler]
level: DEBUG
I've just started studying the API.
Namely, I'm trying to execute my first request (https://developers.google.com/adwords/api/docs/guides/first-api-call#make_your_first_api_call)
Could you help me with this problem? At least how to localize it more precisely.
This seems to be a problem which results from the way the PyCharm debugger inspects live objects during debugging.
Specifically, it checks if a given object has the __len__ attribute/method in the code of var_to_xml, most likely to determine an appropriate representation of the object for the debugger interface (which seems to require constructing an XML representation).
googleads service objects such as your campaign_service, however, use some magic to be able to call the defined SOAP methods on them without requiring to hard-code all of them. The code looks like this:
def __getattr__(self, attr):
"""Support service.method() syntax."""
if self._WsdlHasMethod(attr):
if attr not in self._method_proxies:
self._method_proxies[attr] = self._CreateMethod(attr)
return self._method_proxies[attr]
else:
raise googleads.errors.GoogleAdsValueError('Service %s not found' % attr)
This means that the debugger's check for a potential __len__ attribute is intercepted, and because the CampaignService does not have a SOAP operation called __len__, an exception is raised.
You can validate this by running your snippet in the regular way (i.e. not debugging it) and checking if that works.
An actual fix would seem to either require that PyCharm's debugger changes the way it inspects objects (not calling hasattr(v, "__len__")) or that googleads modifies the way it implements __getattr__, for example by actually implementing a __len__ method that just raises AttributeError.
i am using JIRA-python 1.0.7. Given a particular issue i am trying to get the attachment id and attachment uri. the JIRA-python document says that i can access the attachment with the following attributes
issue.fields.attachment
issue.fields.attachment.id
But however i am getting these error
In [23]: issue.fields.attachment
--------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/usr/lib/python3.4/site-packages/jira/jirashell.py in <module>()
----> 1 issue.fields.attachment
AttributeError: type object 'PropertyHolder' has no attribute 'attachment'
The document also suggests that i can get an attachment resource using the following method
jira.attachment(id)
In [24]: issue=jira.issue('OPENNLP-830')
In [25]: issue.id
Out[25]: '12931716'
In [26]: jira.attachment(12931716)
---------------------------------------------------------------------------
JIRAError Traceback (most recent call last)
/usr/lib/python3.4/site-packages/jira/jirashell.py in <module>()
----> 1 jira.attachment(12931716)
JIRAError: JiraError HTTP 404 url: https://issues.apache.org/jira/rest/api/2/attachment/12931716 details: /tmp/jiraerror-0n8wkhwj.tmp
where have i gone wrong.kindly do advice
edit
My actual code
#!usr/bin/python
from jira import JIRA
import psycopg2
from creating_db import create_db
def main():
#Establishing connection with JIRA
options = {'server': 'https://issues.apache.org/jira'}
jira = JIRA(options)
#Creating the necessary database
create_db()
#Connecting to the database
try:
conn=psycopg2.connect("dbname='issue_db' host='master' user='hema' password='password'")
except psycopg2.Error as e:
print (e)
cur=conn.cursor ()
#This command returns an object of type ResultList. ResultList has an attribute called 'total' which gives us the total number of issues filled so far in a given project.
issue_count=jira.search_issues('project=OPENNLP')
#Iteratively receiving the issues
for count in range(0, issue_count.total,50):
issue_in_proj = jira.search_issues('project=OPENNLP', startAt = count, maxResults = 50)
issue_attachment=[issue.fields.attachment for issue in issue_in_proj] # the documentation says its issue.fields.attachment and not attachments
for i in range( len(issue_in_proj)):
for j in range(len(issue_attachment[i]):
cur.execute('''INSERT INTO attachments VALUES(%s,%s)''', [(issue_id[i],issue_attachment[i][j].id)])
conn.commit()
cur.close
conn.close
if __name__=="__main__":
main()
I've had the exact same problem with version 1.0.7 today: attribute 'attachment' not found, but when I use <tab> it is actually found.
Are you perhaps using issues = jira.search_issues() to retrieve issues first, like I do? The objects it returns are missing the 'attachment' attribute for some reason.
However, you can retrieve a new object for a particular issue by calling issue = jira.issue(issues[i].key). This object will have an 'attachment' attribute (so issue.fields.attachment).
Hope this helps!
The parser in jira is not parsing out the attachment key returned by the rest response in the JSON document. You'll need to
issues = jira.search_issues("assignee in (currentUser())", fields=["attachment"]
I have a table that I would like to join to an ArcGIS shapefile. My problem is that the table has two Identity fields (i.e. "Plan Number" and "Contract Number") and the shapefile has one Identity field (i.e. "Name"). I want to join the shapefile's "Name" to either the "Plan Number" OR the "Contract Number".
As background, the shapefile is created by manually drawing in polygons in ArcGIS. These polygons represent various projects. The identifier "Name" can either be a project's initial Planning Number, or the Contract Number that exists after the project is budgeted. The Planning Number exists when there is no budget, and the Contract Number comes later. Polygons are created and the "Name" field is filled in with whichever identifying stage (either Planning Number or Contract Number) the project has reached. So, the shapefile field "Name" contains either Planning Numbers or Contract Numbers.
Concurrently, we have a complex Database of all projects with two fields representing both the Planning Number and Contract Number:
PLN------------Contract-----Phase------------Length-----NTP---------SC-------------Notes
1415-003-----WD-2506----Pre-Planning----45----------1/1/1900----1/20/1900-----test
To create my code, I created a simple xml table that links to the Database. This xml table has a PLN (Plan Number) field and a Contract (Contract Number) field. In my code, I converted this xml to a dbf. I am now trying to find a way to join a Shapefile "Name" to EITHER the "PLN" or the "Contract".
Please see code below:
#Convert xlsx to table:
import xlrd
in_excel= r'W:\\Engineering\\ENGINEER\\LAMP (062012)\\Database\\VisualDatabase\\Planning_Out\\JoinTest.xlsx'
out_table= r'W:\\Engineering\\ENGINEER\\LAMP (062012)\\Database\\VisualDatabase\\Planning_Out\\JoinTest.gdb'
# Perform the conversion
join_table= arcpy.ExcelToTable_conversion(in_excel, out_table)
print join_table
# Join
# Set the local parameters
inFeatures = r'W:\\Engineering\\ENGINEER\\LAMP (062012)\\Database\\VisualDatabase\\Planning_Out\\CDDprojects.shp'
joinField =
joinTable = join_table
fieldList = ["PLN", "Contract", "Phase", "Length", "NTP", "SC", "Notes]
I am unsure what to enter in joinField and if there is any other code I should include.
REVISION 1:
I used Ethan's code but received an error message at:
with master_table.open():
with minimal_table.open():
minimal_index = dbf.create_index(minimal_table, lambda record: record.name)
The error reads:
Traceback (most recent call last):
File "W:\Engineering\ENGINEER\LAMP (062012)\Database\VisualDatabase\LAMP.py", line 53, in <module>
with master_table.open():
AttributeError: 'Result' object has no attribute 'open'
REVISION 2:
I am a beginner level so perhaps I am missing something fairly simple. When I try to import dbf, I am receiving the an error after my code:
Traceback (most recent call last):
File "W:\Engineering\ENGINEER\LAMP (062012)\Database\VisualDatabase\LAMP.py", line 50, in <module>
import dbf
ImportError: No module named dbf
I downloaded the dbf module, but when running the setup, I receive this error:
Warning (from warnings module):
File "C:\Python27\ArcGIS10.3\lib\distutils\dist.py", line 267
warnings.warn(msg)
UserWarning: Unknown distribution option: 'install_requires'
I'm not sure what I'm doing wrong to install the dbf.
REVISION 3:
I have installed the dbf module and it is successfully imported into arcpy. However, I am still receiving the same error message:
Traceback (most recent call last):
File "W:\Engineering\ENGINEER\LAMP (062012)\Database\VisualDatabase\LAMP.py", line 56, in <module>
with master_table.open():
AttributeError: 'Result' object has no attribute 'open'
My code is:
#Convert xlsx to table:
import xlrd
in_excel= r'W:\\Engineering\\ENGINEER\\LAMP (062012)\\Database\\VisualDatabase\\Planning_Out\\JoinTest.xlsx'
out_table= r'W:\\Engineering\\ENGINEER\\LAMP (062012)\\Database\\VisualDatabase\\Planning_Out\\JoinTest.gdb'
# Perform the conversion
join_table= arcpy.ExcelToTable_conversion(in_excel, out_table)
import enum
import dbf
# table with all projects at all stages
master_table = join_table
# table with single project and most up-to-date stage
minimal_table = r'W:\\Engineering\\ENGINEER\\LAMP (062012)\\Database\\VisualDatabase\\Planning_Out\\CDDprojects.dbf'
with master_table.open(): (LINE 56 which the AttributeError calls)
with minimal_table.open():
minimal_index = dbf.create_index(minimal_table, lambda record: record.name)
# cycle through master, updating minimal if necessary
for master in master_table:
# look for PLN # first
found = minimal_index.search(master.PLN)
if not found:
# if record doesn't exist with PLN #, try CONTRACT #
found = minimal_index.search(master.Contract)
I am using the dbf module here: https://pypi.python.org/pypi/dbf
Thanks.
I haven't worked with arcpy (and I'm not entirely certain I understand what you are trying to do), but using my dbf module this is what you do to update/add from the master table to the shape table's dbf file:
import dbf
# table with all projects at all stages
master_table = dbf.Table(complex_table)
# table with single project and most up-to-date stage
minimal_table = dbf.Table(single_project_table)
with master_table.open():
with minimal_table.open():
minimal_index = dbf.create_index(minimal_table, lambda record: record.name)
# cycle through master, updating minimal if necessary
for master in master_table:
# look for PLN # first
found = minimal_index.search(master.pln)
if not found:
# if record doesn't exist with PLN #, try CONTRACT #
found = minimal_index.search(master.contract)
if not found:
# not there at all, add it
minimal_table.append(master.contract or master.pln, master.phase, master.length, ...)
break
# have a match, update it
found.name = master.contract or master.pln
# plus any other updates you need
# ...
# and then write the record
dbf.write(found)
I upgraded to py2neo 2.0 and the code I used for streaming and writing results to file doesn't work any more. The error I am getting is TypeError: 'CypherResource' object is not callable.
from py2neo import Graph
from py2neo.packages.httpstream import http
http.socket_timeout = 9999
graph = Graph()
query="""
MY QUERY
"""
result=graph.cypher(graph,query)
with open('myfile','w') as f:
for record in result.stream():
v=record.values
I assume the error is in graph.cypher(graph,query), but I was not successful in fixing the error.
You are using Graph.cypher incorrectly. This is an object with execution and transaction management methods, not a callable itself. Please read the docs at:
http://py2neo.org/2.0/cypher.html
I'm trying to get started with the Python API for Google Compute Engine using their "hello world" tutorial on https://developers.google.com/compute/docs/api/python_guide#setup
Whenever making the call response = request.execute(auth_http) though, I get the following error signaling that I can't authenticate:
WARNING:oauth2client.util:execute() takes at most 1 positional argument (2 given)
I'm clearly only passing one positional argument (auth_http), and I've looked into oauth2client/util.py, apiclient/http.py, and oauth2client/client.py for answers, but nothing seems amiss. I found another stack overflow post that encountered the same issue, but it seems that in the constructor of the OAuth2WebServerFlow class in oauth2client/client.py, 'access_type' is set to 'offline' already (though to be honest I don't completely understand what's going on here in terms of setting up oauth2.0 flows).
Any suggestions would be much appreciated, and thanks in advance!
Looking at the code, the #util.positional(1) annotation is throwing the warning. Avoid it using named parameters.
Instead of:
response = request.execute(auth_http)
Do:
response = request.execute(http=auth_http)
https://code.google.com/p/google-api-python-client/source/browse/apiclient/http.py#637
I think documentation is wrong. Please use the following:
auth_http = credentials.authorize(http)
# Build the service
gce_service = build('compute', API_VERSION, http=auth_http)
project_url = '%s%s' % (GCE_URL, PROJECT_ID)
# List instances
request = gce_service.instances().list(project=PROJECT_ID, filter=None, zone=DEFAULT_ZONE)
response = request.execute()
You can do one of three things here:
1 Ignore the warnings and do nothing.
2 Suppress the warnings and set the flag to ignore:
import oauth2client
import gflags
gflags.FLAGS['positional_parameters_enforcement'].value = 'IGNORE'
3 Figure out where the positional parameter is being provided and fix it:
import oauth2client
import gflags
gflags.FLAGS['positional_parameters_enforcement'].value = 'EXCEPTION'
# Implement a try and catch around your code:
try:
pass
except TypeError, e:
# Print the stack so you can fix the problem, see python exception traceback docs.
print str(e)