Code error with variable storage from selected feature - python

I'm using QGIS 3.6 with the built in Python text editor. I have found a snippet of code that I'm trying to make work, and I've modified it to the best of my abilities to fit my specific needs. I have a point layer called "Regulators" and it contains a field called "Town". The idea of the code is that when I select a single feature on the "Regulators" layer, the code will look at the "Town" field, and select all other features that match that field's value. I select a feature, run this code:
layer = iface.activeLayer()
field_name = 'Town'
values = []
for feat in layer.selectedFeatures():
tmp_value = feat[field_name]
if tmp_value not in values:
values.append(str(tmp_value))
strings = []
for val in values:
if val != values[-1]:
string = field_name + ' = ' + val + ' or '
strings.append(string)
else:
last_string = field_name + ' = ' + val
strings.append(last_string)
query = ''.join(strings)
request = QgsFeatureRequest().setFlags(QgsFeatureRequest.NoGeometry)
request.setSubsetOfAttributes([]).setFilterExpression(query)
selection = layer.getFeatures(request)
layer.setSelectedFeatures([k.id() for k in selection])
and I get this error:
Traceback (most recent call last):
File "C:\PROGRA~1\QGIS3~1.6\apps\Python37\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "<string>", line 24, in <module>
AttributeError: 'QgsVectorLayer' object has no attribute 'setSelectedFeatures'
I'm very much new to python, and see nothing wrong with line 1 or 5. I have found some other codes that do what I'm attempting here, but they also return errors, so I'm wondering if there is some method or function that has changed since this code was posted. The integrated compiler with QGIS is also much different than I am used to.
EDIT: I've updated the code and the error message based on feedback I've received on the post so far. I assume that QgsVectorLayer is the generic term for a vector layer being referenced, in this case the "Regulators" layer. but I don't understand why it's trying to use the setSelectedFeatures method as an attribute.

Related

Too many values to unpack? python-radar

I have problem which when i run the code it shows an error:
Traceback (most recent call last):
File "C:\Users\server\PycharmProjects\Publictest2\main.py", line 19, in <module>
Distance = radar.route.distance(Starts, End, modes='transit')
File "C:\Users\server\PycharmProjects\Publictest2\venv\lib\site-packages\radar\endpoints.py", line 612, in distance
(origin_lat, origin_lng) = origin
ValueError: too many values to unpack (expected 2)
My Code:
from radar import RadarClient
import pandas as pd
API_key = 'API'
radar = RadarClient(API_key)
file = pd.read_excel('files')
file['AntGeo'] = Sourced[['Ant_lat', 'Ant_long']].apply(','.join, axis=1)
file['BaseGeo'] = Sourced[['Base_lat', 'Base_long']].apply(','.join, axis=1)
antpoint = file['AntGeo']
basepoint = file['BaseGeo']
for antpoint in antpoint:
dist= radar.route.distance(antpoint , basepoint, modes='transit')
dist= dist['routes'][0]['distance']
dist= dist / 1000
Firstly, your error code does not match your given code sample correctly.
It is apparent you are working with the python library for the Radar API.
Your corresponding line 19 is dist= radar.route.distance(antpoint , basepoint, modes='transit')
From the radar-python 'pypi manual', your route should be referenced as:
## Routing
radar.route.distance(origin=[lat,lng], destination=[lat,lng], modes='car', units='metric')
Without having sight of your dataset, file, one can nonetheless deduce or expect the following:
Your antpoint and basepoint must be a two-item list (or tuple).
For instance, your antpoint ought to have a coordinate like [40.7041029, -73.98706]
See the radar-python manual
line 11 and 13 in your code
file['AntGeo'] = Sourced[['Ant_lat', 'Ant_long']].apply(','.join, axis=1)
file['BaseGeo'] = Sourced[['Base_lat', 'Base_long']].apply(','.join, axis=1)
Your error is occuring at this part:
Distance = radar.route.distance(Starts, End, modes='transit')
(origin_lat, origin_lng) = origin
First of all check the amount of variables that "origin" delivers to you, it's mismatched with the expectation I guess.

graph-tool - 'NestedBlockState' object has no attribute 'get_nonempty_B'

I am trying to replicate a section of code from the graph-tool cookbook to find the marginal probablity of the number of groups in a graph when using hierarchical partitioning. I however get an error telling me that 'NestedBlockState' object has no attribute 'get_nonempty_B' so presumably I have made a mistake somewhere. Does anybody know where I went wrong?
import graph_tool.all as gt
import cPickle as pickle
g = gt.load_graph('graph_no_multi_reac_type.gt')
gt.remove_parallel_edges(g)
state = gt.minimize_nested_blockmodel_dl(g, deg_corr=True)
state = state.copy(sampling=True)
with open('state_mcmc.pkl','wb') as state_pkl:
pickle.dump(state,state_pkl,-1)
print 'equilibrating Markov chain'
gt.mcmc_equilibrate(state, wait=1000, mcmc_args=dict(niter=10))
h = np.zeros(g.num_vertices() + 1)
def collect_num_groups(s):
B = s.get_nonempty_B()
h[B] += 1
print 'colleting marginals'
gt.mcmc_equilibrate(state, force_niter=10000, mcmc_args=dict(niter=10),
callback=collect_num_groups)
with open('state_ncnc.pkl','wb') as state_pkl:
pickle.dump(state,state_pkl,-1)
with open('hist.pkl','wb') as h_pkl:
pickle.dump(h,h_pkl,-1)
The error I get looks as follows:
Traceback (most recent call last):
File "num_groups_marg_prob.py", line 42, in <module>
gt.mcmc_equilibrate(state, force_niter=10000, mcmc_args=dict(niter=10),
File "/usr/lib/python2.7/dist-packages/graph_tool/inference/mcmc.py", line 172, in mcmc_equilibrate
extra = callback(state)
File "num_groups_marg_prob.py", line 35, in collect_num_groups
def collect_num_groups(s):
AttributeError: 'NestedBlockState' object has no attribute 'get_nonempty_B'
Quoting from an answer from the graph-tool mailing list:
"The error message is clear. This attribute belongs to BlockState, not
NestedBlockState. What you wish to do is:
s.levels[0].get_nonempty_B()
"
http://main-discussion-list-for-the-graph-tool-project.982480.n3.nabble.com/self-state-couple-state-state-state-entropy-args-Python-argument-types-did-not-match-C-signature-td4026975.html

Python - Delete from Array while enumerating

Error:
Traceback (most recent call last):
File "<string>", line 10, in <module>
File "/Users/georg/Programmierung/Glyphs/Glyphs/Glyphs/Scripts/GlyphsApp.py", line 59, in __iter__
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC/objc/_convenience.py", line 589, in enumeratorGenerator
yield container_unwrap(anEnumerator.nextObject(), StopIteration)
objc.error: NSGenericException - *** Collection <__NSArrayM: 0x7f9906245480> was mutated while being enumerated.
I know this error occurs because I'm trying to delete objects from the array while also enumerating these objects. But I don't know how to solve it. I'm fairly new to object orientated programming and am limiting myself to scripting.
I searched the web and it seems to solve the error, I have to copy the array before deleting objects from it. When I'm tying to copy the array via deepcopy
import copy
pathcopy = copy.deepcopy(thisLayer.paths)
right before for path in thisLayer.paths:
But in this case I get the following error:
Cannot pickle Objective-C objects
Usually the program crashes after the first Glyph. For clarification: I work in Glyphsapp, a Typedesigning software.
Here is the Code:
# loops through every Glyph and deletes every path with nodes on the left half
for myGlyph in Glyphs.font.glyphs:
glname = myGlyph.name
thisLayer = Glyphs.font.glyphs[glname].layers[1]
middle = thisLayer.bounds.size.width/2+thisLayer.LSB
thisGlyph = thisLayer.parent
for path in thisLayer.paths: # this is where the code crashes
for thisNode in path.nodes:
if thisNode.position.x < middle:
#print thisNode.position.x
try:
thisLayer = path.parent()
except Exception as e:
thisLayer = path.parent
try:
thisLayer.removePath_ ( thisNode.parent() )
except AttributeError:
pass
Thank you in advance
Thank you very much Andreas,
with your help I was able to fix my code :-)
Here is the outcome:
for myGlyph in Glyphs.font.glyphs:
glname = myGlyph.name
thisLayer = Glyphs.font.glyphs[glname].layers[1]
middle = thisLayer.bounds.size.width/2+thisLayer.LSB
thisGlyph = thisLayer.parent
for path in thisLayer.paths:
for thisNode in path.nodes:
if thisNode.position.x < middle:
nodeList = []
nodeList.append(thisNode.parent())
nLCopy = nodeList[:]
for ncontainer in nLCopy:
thisLayer.removePath_ ( ncontainer )

Sage for Graph Theory, KeyError

I'll start with my code, because this may just be an obvious problem to those with better understanding of the language:
g = graphs.CompleteGraph(60).complement()
for i in range(1,180):
a = randint(0,59)
b = randint(0,59)
h = copy(g)
h.add_edge(a,b)
if h.is_circular_planar():
g.add_edge(a,b)
strong = copy(strong_resolve(g))
S = strong.vertex_cover()
d = {'#00FF00': [], '#FF0000': []}
for v in G.vertices():
if v in S:
d['#FF0000'].append(v)
else:
d['#00FF00'].append(v)
g.plot(layout="spring", vertex_colors=d).show()
strong.plot(vertex_colors=d).show()
new_strong = copy(strong)
for w in new_strong.vertices():
if len(new_strong.neighbors(w)) == 0: #trying to remove
new_strong.delete_vertex(w) #disconnected vertices
new_strong.plot(vertex_colors=d).show()
A couple notes: strong_resolve is a function which takes in a graph and outputs another graph. The first two blocks of code work fine.
My problem is that once I add the third block things don't work anymore. In fiddling around I've gotten variants of this code that when added cause errors, and when removed the errors remain somehow. What happens now is that the for loop seems to go until its end and only then it will give the following error:
Traceback (most recent call last): if h.is_circular_planar():
File "", line 1, in <module>
File "/tmp/tmprzreop/___code___.py", line 30, in <module>
exec compile(u'new_strong.plot(vertex_colors=d).show()
File "", line 1, in <module>
File "/usr/lib/sagemath/local/lib/python2.7/site-packages/sage/misc/decorators.py", line 550, in wrapper
return func(*args, **options)
File "/usr/lib/sagemath/local/lib/python2.7/site-packages/sage/graphs/generic_graph.py", line 15706, in plot
return self.graphplot(**options).plot()
File "/usr/lib/sagemath/local/lib/python2.7/site-packages/sage/graphs/generic_graph.py", line 15407, in graphplot
return GraphPlot(graph=self, options=options)
File "/usr/lib/sagemath/local/lib/python2.7/site-packages/sage/graphs/graph_plot.py", line 247, in __init__
self.set_vertices()
File "/usr/lib/sagemath/local/lib/python2.7/site-packages/sage/graphs/graph_plot.py", line 399, in set_vertices
pos += [self._pos[j] for j in vertex_colors[i]]
KeyError: 0
this can vary in that KeyError: 0 is occasionally 1 or 2 depending on some unknown factor.
I apologize in advance for my horrible code and acknowledge that I really have no idea what I'm doing but I'd really appreciate if someone could help me out here.
I figured it out! It turns out the error came from d having entries that made no sense in new_strong, namely those for vertices that were deleted already. This caused the key error when plot() tried to colour the vertices according to d.

Substring in Python, what is wrong here?

I'm trying to simulate a substring in Python but I'm getting an error:
length_message = len(update)
if length_message > 140:
length_url = len(short['url'])
count_message = 140 - length_url
update = update["msg"][0:count_message] # Substring update variable
print update
return 0
The error is the following:
Traceback (most recent call last):
File "C:\Users\anlopes\workspace\redes_sociais\src\twitterC.py", line 54, in <module>
x.updateTwitterStatus({"url": "http://xxx.com/?cat=49s", "msg": "Searching for some ....... tips?fffffffffffffffffffffffffffffdddddddddddddddddddddddddddddssssssssssssssssssssssssssssssssssssssssssssssssssseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddfffffffffffffffffffffffffffffffffffffffffffff "})
File "C:\Users\anlopes\workspace\redes_sociais\src\twitterC.py", line 35, in updateTwitterStatus
update = update["msg"][0:count_message]
TypeError: string indices must be integers
I can't do this?
update = update["msg"][0:count_message]
The variable "count_message" return "120"
Give me a clue.
Best Regards,
UPDATE
I make this call, update["msg"] comes from here
x = TwitterC()
x.updateTwitterStatus({"url": "http://xxxx.com/?cat=49", "msg": "Searching for some ...... ....?fffffffffffffffffffffffffffffdddddddddddddddddddddddddddddssssssssssssssssssssssssssssssssssssssssssssssssssseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddfffffffffffffffffffffffffffffffffffffffffffffddddddddddddddddd"})
Are you looping through this code more than once?
If so, perhaps the first time through update is a dict, and update["msg"] returns a string. Fine.
But you set update equal to the result:
update = update["msg"][0:int(count_message)]
which is (presumably) a string.
If you are looping, the next time through the loop you will have an error because now update is a string, not a dict (and therefore update["msg"] no longer makes sense).
You can debug this by putting in a print statement before the error:
print(type(update))
or, if it is not too large,
print(repr(update))

Categories