I'm trying to create multiple graph and using Dijkstra's. However I'm getting an error: NoneType object has no attribute 'set_distance'. The very strange thing is that the first item in the list ['2001A1'] runs fine but then when the list is longer than 1 it just crashes with that error. If I run the code with just one item in the list, it works as well. Printing out my vertices, the graph shows that there are vertex instances for all of my keys... Is there something that I'm missing? Why can't I do this more than one times? Why is it that when I try to get my vertex object I get returned null when my map of vertices has key {1:(Vertex object)}?
def create_graph(q,y,pop,psub,a,b,c):
a = Graph(q,y,pop,psub,a,b,c)
for i in range(0,9):
a.add_vertex(i)
return a
def run_dijkstras(graph,data):
for i in data:
try:
year = int(i[0:4])
print year
except:
print i
rest = i[4:]
graph.add_edge(year,rest)
quarter = graph.get_quarter()
print graph.vert_dict
print quarter
print graph.get_vertex(quarter)
print str(graph.get_vertex(quarter))
dijkstra(graph,graph.get_vertex(quarter))
target = graph.get_vertex(quarter+4)
path = [target.get_id()]
shortest(target, path)
if len(path) == 1:
path = "NULL"
return [path,(str(target.get_distance())),data]
i = 2001
for j in range(1,5):
for datacombo in ([['2001A1'], ['2001R4']]):
a = run_dijkstras(create_graph(j,i,10,1,.05,-.1,-.5),datacombo)
result,score = a[0],a[1]
if score == 9999999999999:
score = "NULL"
score = score.ljust(15)
datacombo = generate_matrix(datacombo)
i = str(i).ljust(5)
j = str(j).ljust(2)
datacombo=re.sub("\[|\]|'","",str(datacombo)).ljust(100)
result=re.sub("\[|\]|'","",str(result)).ljust(25)
print(i,j,result,score,datacombo)
ERROR LOG:
{0: <__main__.Vertex instance at 0x0000000002439DC8>, 1: <__main__.Vertex instan
ce at 0x0000000002439CC8>, 2: <__main__.Vertex instance at 0x0000000002439C88>,
3: <__main__.Vertex instance at 0x0000000002439C08>, 4: <__main__.Vertex instanc
e at 0x0000000002439E48>, 5: <__main__.Vertex instance at 0x0000000002439E88>, 6
: <__main__.Vertex instance at 0x0000000002439EC8>, 7: <__main__.Vertex instance
at 0x0000000002439F08>, 8: <__main__.Vertex instance at 0x0000000002439F48>}
1
None
None
Traceback (most recent call last):
File "dijkstras3.py", line 282, in <module>
a = run_dijkstras(create_graph(j,i,10,1,.05,-.1,-.5),datacombo)
File "dijkstras3.py", line 190, in run_dijkstras
dijkstra(graph,graph.get_vertex(quarter))
File "dijkstras3.py", line 132, in dijkstra
start.set_distance(0)
AttributeError: 'NoneType' object has no attribute 'set_distance'
Related
If anyone can help me to get a value from a json response. I intend to get only the first incidence of id where the type is CLIENTREF.
I am reading a list to get some values to do a GET and check if the response is other than null "".
This is the JSON structure:
This is my code so far
def checkParent(list):
for item in list:
cdwParenturl = f"http://cdwu/cdw/counterparties/{item}/?yyyy-mm-dd={dateinplay}"
r = requests.get(cdwParenturl).json()
jsonpath_expression = parse("$..identifier[*]")
# $..identifier[?(#.type == 'CLIENTREF')].id
parentId = []
for match in jsonpath_expression.find(r):
# print(f"match id: {match.value}")
thisdict = match.value
if thisdict["type"] == "CLIENTREF":
# print(thisdict["id"])
parentId.append(thisdict["id"])
elif thisdict["id"] == "":
print(colored(f"The parent {item} does not have ultimateParent", "red"))
print(colored(f"All counterparties have parent", "green"))
checkParent(r_mheu_trade)
print(f "match id: {match.value}") I get this, What I need is the first id related to the type: CLIENTREF
The error that appears on my console is this:
Traceback (most recent call last):
File "h:\DESKTOP\test_check\checkCounterpartie.py", line 114, in <module>
checkParent(r_mheu_trade)
File "h:\DESKTOP\test_check\checkCounterpartie.py", line 106, in checkParent
if thisdict["type"] == "CLIENTREF":
KeyError: 'type'
With the help of pyzer I found a solution to my problem. This is how the code looks like:
# Request to get all UltimateParent
def checkParent(murex):
for item in murex:
cdwParenturl = f"http://cdwu/cdw/counterparties/{item}/?yyyy-mm-dd={dateinplay}"
r = requests.get(cdwParenturl).json()
clientref = r[0]["riskUltimateParent"]["identifier"][1]
if clientref == "":
print(colored(f"The parent {item} does not have ultimateParent", "red"))
else:
print(colored(f"All counterparties have parent", "green"))
checkParent(r_mheu_trade)
Im trying to load the data from a list in python where, I save the data in a list:
class Region(object):
def __init__(self, cities: list[CitiySalah], label: str):
self.cities = cities
self.label = label
def toMap(self) -> dict:
map = self.__dict__
r = [{}]
for x in self.cities:
r.append(x.toMap())
map["cities"] = r
return map
and the one that loads the data is:
def startLoading() -> list[Region]:
.......
for select in selects:
if select.has_attr("name") and select['name'] == "ville":
groups = select.find_all('optgroup')
for group in groups:
lable = group['label']
allR = {"lable": lable}
cities = [CitiySalah]
for option in group:
try:
# the city
if(option.has_attr('value')):
value = option['value']
city = str(option).split('<')[1].split('>')[1]
id = str(option).split('<')[1].split(
'?ville=')[1].split('"')[0]
dataUrl = url+"?ville="+id
data = MySalah(getSalahHour(dataUrl))
R = CitiySalah(argu={"value": value,
"city": city,
"dataUrl": dataUrl,
"id": id, }, data=data)
# print(R.toMap())
cities.append(R)
except:
pass
# allR['cities'] = cities
res.append(Region(label=lable, cities=cities))
return res
and when I'm trying to call the function by:
def getDataForDatabase():
listR = [{}]
data = startLoading()
for x in data:
listR.append(x.toMap())
return listR
I get this error
Traceback (most recent call last):
File "/home/nimr/ServerApps/ScrappingProject/Salah/Functions.py", line 108, in <module>
print(getDataForDatabase())
File "/home/nimr/ServerApps/ScrappingProject/Salah/Functions.py", line 104, in getDataForDatabase
listR.append(x.toMap())
TypeError: toMap() missing 1 required positional argument: 'self'
I have tried, I'm still new in python as I'm from c++ family, and I got stuck here,
I need to save the data in a list and convert them into Map, so I can save them in the database (NoSQL).
and as for the rest of models they are working correct, I don't know why I'm getting this error.
I'm completing a task I was given by my Teacher and it asks for a modular program so I tried to create some def modules but I can't figure out how to pass parameters between them.
Here's the code so far. (I don't know how to make it much neater on the site sorry.)
import string
def Datawrite ():
forename = []
surname = []
distance = []
data = open("members.txt","r")
for line in data:
value = line.split(',')
forename.append(value[0])
surname.append(value[1])
distance.append(value[2])
data.close()
def FarthestWalker(distance):
farthest_walk = distance[0]
for counter in range(len(distance)):
if float(distance[counter]) >= float(farthest_walk):
farthest_walk = distance[counter]
farthest_walk = float(farthest_walk)
Calcandstore()
def Calcandstore(forename,surname,distance,farthest_walk):
Results = open("Results.txt","w+")
Results.write("The prize winnning memberes are:\n")
seventy = 0.7*farthest_walk
Winning = []
for count in range(len(distance)):
if float(distance[count]) >= float(seventy):
Winning.append([count])
for count in range(len(Winning)):
Results.write(forename[count]+":")
Results.write(surname[count]+":")
Results.write(distance[count])
Results.close()
Datawrite()
FarthestWalker(distance)
Calcandstore(forename,surname,distance,farthest_walk)
When I run the code it returns this.
Traceback (most recent call last):
File "E:\Assignment\Test.py", line 58, in <module>
FarthestWalker(distance)
File "E:\Assignment\Test.py", line 29, in FarthestWalker
farthest_walk = distance[0]
IndexError: list index out of range
I have been tinkering with this for a few days now and I can't get the thing to work.
Here are some issues:
1) Datawrite doesn't return anything so the lists you're building are lost in the ether.
2) You call FarthestWalker with distance which is never initialized.
3) You call Calcandstore with values that are not initialized.
To pass values from functions you need to return values and declare them. For example:
def make_cat():
return 'Cat'
def print_animal(animal):
print(animal)
c = make_cat()
print_animal(c)
i have a nested dictionary in the form of:
self.emoji_per_word = {0: {'worte': 0, 'emojis': 0, '#': 0}}
Now i need to add more sub dictionaries to this as my program runs. I do this:
worte = 0
emoji = 0
# some code that assigns values to the 2 variables and creates the time_stamp variable
if time_stamp in self.emoji_per_word:
self.emoji_per_word[time_stamp]['worte'] = self.emoji_per_word[time_stamp]['worte'] + worte
self.emoji_per_word[time_stamp]['emojis'] = self.emoji_per_word[time_stamp]['emojis'] + emojis
else:
self.emoji_per_word[time_stamp]['worte'] = worte
self.emoji_per_word[time_stamp]['emojis'] = emojis
As you can see, i try to the test if the key time_stamp already exists and if yes, update the value with the new data. If not i want to create the key time_stamp and assign it a inital value. However im getting a Key Error once the programm goes past the inital value (see top).
Exception in thread Video 1:
Traceback (most recent call last):
File "C:\Anaconda\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\MA\Code\jsonparser_v2\jsonparser_v2.py", line 418, in run
self.process_json()
File "C:\MA\Code\jsonparser_v2\jsonparser_v2.py", line 201, in process_json
self.emoji_per_word[time_stamp]['worte'] = worte
KeyError: 1
What I want in the end is something like this:
self.emoji_per_word = {0: {'worte': 20, 'emojis': 5, '#':0.25}, 1: {'worte': 20, 'emojis': 5, '#':0.25}}
What am I doing wrong here?
You're getting the error because self.emoji_per_word[time_stamp] doesn't exist when time_stamp != 0 so you need to create the dictionary first before assigning values to it, like so:
else:
self.emoji_per_word[time_stamp] = {}
self.emoji_per_word[time_stamp]['worte'] = worte
self.emoji_per_word[time_stamp]['emojis'] = emojis
I'm trying to follow this guide: https://medium.com/#sarahnadia/how-to-code-a-simple-twitter-bot-for-complete-beginners-36e37231e67d#.k2cljjf0m
This is the error message:
MacBook-Pro-2:heroku_ebooks-master Rupert$ heroku run worker
Running worker on ⬢ desolate-brushlands-56729... up, run.6788
Traceback (most recent call last):
File "ebooks.py", line 79, in <module>
source_tweets_iter, max_id = grab_tweets(api,max_id)
File "ebooks.py", line 51, in grab_tweets
max_id = user_tweets[len(user_tweets)-1].id-1
IndexError: list index out of range
This is the code:
def grab_tweets(api, max_id=None):
source_tweets=[]
user_tweets = api.GetUserTimeline(screen_name=user, count=200, max_id=max_id, include_rts=True, trim_user=True, exclude_replies=True)
max_id = user_tweets[len(user_tweets)-1].id-1
for tweet in user_tweets:
tweet.text = filter_tweet(tweet)
if len(tweet.text) != 0:
source_tweets.append(tweet.text)
return source_tweets, max_id
if __name__=="__main__":
order = ORDER
if DEBUG==False:
guess = random.choice(range(ODDS))
else:
guess = 0
if guess == 0:
if STATIC_TEST==True:
file = TEST_SOURCE
print ">>> Generating from {0}".format(file)
string_list = open(file).readlines()
for item in string_list:
source_tweets = item.split(",")
else:
source_tweets = []
for handle in SOURCE_ACCOUNTS:
user=handle
api=connect()
max_id=None
for x in range(17)[1:]:
source_tweets_iter, max_id = grab_tweets(api,max_id)
source_tweets += source_tweets_iter
The traceback tells us the error is here:
max_id = user_tweets[len(user_tweets)-1].id-1
which will be out of range if user_tweets is an empty list. You can check to make sure it isn't before trying to access its value.
if len(user_tweets) > 0:
max_id = user_tweets[-1].id-1
Note the use of user_tweets[-1]. Using a negative index counts backward from the end, so the last element of a list is always at [-1].