Paraview: NameError: name 'inputs' is not defined - python

I'm trying to create a ProgrammableFilter in Paraview using Python. The filter should take the current selected points and count them (the filter will be more elaborated, but this is enough for explaining my problem).
In my code I'm not using any variable called 'inputs', but when I execute it I get this output (note there is an error at the end, and the code seems to be executed twice):
Generated random int: 13 using time 1419991906.3
13 Execution start
13 Selection is active
Generated random int: 59 using time 1419991906.34
59 Execution start
59 No selection is active
59 Execution end
13 Extr_Sel_raw was not None
13 Number of cells: 44
13 Execution end
Traceback (most recent call last):
File "<string>", line 22, in <module>
NameError: name 'inputs' is not defined
The code is the following, my pipeline has 2 steps, the first is a "Sphere source" and the second is the ProgrammableFilter with this code:
import paraview
import paraview.simple
import paraview.servermanager
import random
import time
a = time.time()
random.seed(a)
#time.sleep(1)
tmp_id = random.randint(1,100)
print "\nGenerated random int: %s using time %s" % (tmp_id, a)
print "%s Execution start" % (tmp_id)
proxy = paraview.simple.GetActiveSource()
active_selection = proxy.GetSelectionInput(proxy.Port)
if active_selection is None:
print "%s No selection is active" % (tmp_id)
else:
print "%s Selection is active" % (tmp_id)
Extr_Sel = paraview.simple.ExtractSelection(Selection=active_selection)
Extr_Sel_raw = paraview.servermanager.Fetch(Extr_Sel)
if Extr_Sel_raw is None:
print "%s Extr_Sel_raw was None" % (tmp_id)
else:
print "%s Extr_Sel_raw was not None" % (tmp_id)
print "%s Number of cells: %s" % (tmp_id, Extr_Sel_raw.GetNumberOfCells())
pdi = self.GetPolyDataInput()
pdo = self.GetPolyDataOutput()
pdo.SetPoints(pdi.GetPoints())
print "%s Execution end\n" % (tmp_id)
Do you know what can be causing my problem?

After some work I found how to achieve to access the selected points in Paraview without generating that weird error mentioned above.
Here is the code:
import paraview
import paraview.simple
proxy = paraview.simple.GetActiveSource()
if proxy is None:
print "Proxy is None"
return
active_selection = proxy.GetSelectionInput(proxy.Port)
if active_selection is None:
print "No selection is active"
return
print "Selected points: %s" % (active_selection.IDs)
print "Amount of points: %s" % (len(active_selection.IDs) / 2)
And this is the output if I select 6 points in a Sphere Source:
Selected points: [0, 14, 0, 15, 0, 16, 0, 20, 0, 21, 0, 22]
Amount of points: 6
You can see that each selected point generates 2 IDs, the first one is the "Process ID" and the second one is the actual ID of your point.
Anyway, the reason of the original error remains unclear to me.

Related

How to do a python web API request return a value only if it exists

Im trying to do an api connection, its all ok but when python has to print some values that doesnt exists, it gives me error. When the value exists it goes all ok
code: (using python 3.7)
r = requests.get('https://api.csgofloat.com/?url=%s' %floaat, headers={})
data = r.json()
print("Sticker 1: %s" %data['iteminfo']['stickers'][0]['name'])
print("Sticker 2: %s" %data['iteminfo']['stickers'][1]['name'])
print("Sticker 3: %s" %data['iteminfo']['stickers'][2]['name'])
print("Sticker 4: %s" %data['iteminfo']['stickers'][3]['name'])
i get all the values when i have all the 4 values, but with only 1 value, it prints the value that exists but then gives error and exit the script, and with no returned value, i only get the error (as said before)
printed error:
Traceback (most recent call last): File
"C:\Users\Joao\Desktop\Folderzz\Scripts\script.py", line 47, in
print("Sticker 1: %s" %data['iteminfo']['stickers'][0]['name']) IndexError: list index out of range
The problem is that you don't know how many 'stickers' are coming in, so you should make a loop:
i = 0
for sticker in data['iteminfo']['stickers']
i += 1
print "Sticker {}: {}".format(i, sticker)

DHT Sensor Python script error

I have a sensor type DHT22 connected to a raspberry.
I have written a script in python but when I run it I get errors
#!/usr/bin/python
import MySQLdb
import subprocess
import re
import sys
import time
import datetime
import Adafruit_DHT
conn = MySQLdb.connect("localhost","zeus","gee3g673r","logi")
while(True):
date = time.strftime("%d/%m/%Y")
clock = time.strftime("%H:%M")
#output = subprocess.check_output(["/usr/bin/AdafruitDHT.py 2302", "4"]);
output = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302, 4)
matches = re.search("Temp =\s+([0-9.]+)", output)
if (not matches):
time.sleep(0)
continue
temp = float(matches.group(1))
matches = re.search("Hum =\s+([0-9.]+)", output)
if (not matches):
time.sleep(0)
continue
humidity = float(matches.group(1))
# MYSQL DATA Processing
c = conn.cursor()
c.execute("INSERT INTO data_th (date, clock, temp, hum) VALUES (%s, %s,%s, %s)",(date, clock, temp, humidity))
#print "DB Loaded"
time.sleep(360)
This is the error encountered on running the script:
root#raspberrypi:/home# ./hdt.py
Traceback (most recent call last):
File "./dht.py", line 22, in <module>
matches = re.search("Temp =\s+([0-9.]+)", output)
File "/usr/lib/python2.7/re.py", line 142, in search
return _compile(pattern, flags).search(string)
TypeError: expected string or buffer
Adafruit_DHT.read_retry() does not return string. re.search expects string as second parameter.
Please have a look at code below (taken from Adafruit_Python_DHT/examples):
# Try to grab a sensor reading. Use the read_retry method which will retry up
# to 15 times to get a sensor reading (waiting 2 seconds between each retry).
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
# Un-comment the line below to convert the temperature to Fahrenheit.
# temperature = temperature * 9/5.0 + 32
# Note that sometimes you won't get a reading and
# the results will be null (because Linux can't
# guarantee the timing of calls to read the sensor).
# If this happens try again!
if humidity is not None and temperature is not None:
print 'Temp={0:0.1f}* Humidity={1:0.1f}%'.format(temperature, humidity)
else:
print 'Failed to get reading. Try again!'
sys.exit(1)

Adding and accessing values to key in python dictionary

I'm writing a python script that reads a players name and stats from a sentence in a .txt file, then updates their stats within a dictionary and then prints out their average stats. I'm having trouble with assigning multiple values to the same 'player' key, as well as getting the logic below it to correctly update the player stats. The .group part is giving me trouble too. How can I do this?
import re, sys, os, math
if len(sys.argv) < 2:
sys.exit("Usage: %s filename" % sys.argv[0])
filename = sys.argv[1]
if not os.path.exists(filename):
sys.exit("Error: File '%s' not found" % sys.argv[1])
line_regex = re.compile(r"^(\w+ \w+) batted (\d+) times with (\d+) hits and (\d+) runs")
line = [line.strip() for line in open(filename)]
f = open (filename)
playerStats = {'players': [0, 0, 0]}
for players in playerStats:
player = line.group(1)
atBat = line.group(2)
hit = line.group(3)
if player in playerStats:
playerStats[player][0] += atBat
playerStats[player][1] += hit
if player not in players:
player = line.group(1)
playerStats[player][0] = atBat
playerStats[player][1] = hit
avgs = 0
else:
playerStats[player][0] = player
playerStats[player][0] = atBat
playerStats[player][1] = hit
playerStats[player][2] = 0
for player in players:
avgs[player] = round(float(hits[player])/float(atBats[player]), 3)
print "%s: %.3f" % (player, avgs[player])
Traceback (most recent call last):
File "ba.py", line 19, in
player = line.group(1)
AttributeError: 'list' object has no attribute 'group'
You should change this
playerStats = {'players': hits, atBats, avgs}
To
playerStats = {'players': [0, 0, 0]}
The latter stores the value as a list , the former is not valid Python syntax.
To modify one of these values you would do, for example
playerStats[player][1] = 5 # atBat value
You could also change to a nested structure like
playerStats = {'players': {'hits' : 0,
'atBats' : 0,
'avgs' : 0)}
Then you could modify the values as
playerStats[player]['hits'] = 3

Type Error - Python Simpy

I have searched online for many answers related to TypeError and scanned through my code multiple times but I can't seem to see what is the 3rd argument I'm missing. I am using Python 2.7 with Simpy 3
My code is as follows:
import simpy
import random
RANDOM_SEED = 42
NUM_SERVERS = 1
MTBF = 10
MTTR = 5
TOTAL_ENGINES = 6
TOTAL_SPARES = 3
TOTAL_IN_USE = TOTAL_ENGINES - TOTAL_SPARES
SIM_TIME = 100
class Working(object):
def __init__ (self, env, num, repair_facility, spares_inventory, downtime):
self.env = env
self.repair_facility = repair_facility
self.spares_inventory = spares_inventory
self.downtime = downtime
self.name = 'Engine %d' % (num + 1)
print('%s at %.2f' % (self.name, self.env.now))
self.env.process(self.run())
def run(self):
yield self.env.timeout(random.expovariate(1.0 / MTBF))
print('%s at %.2f' % (self.name, self.env.now))
downtime_start = self.env.now
spare = yield self.spares_inventory.get()
self.downtime.append(self.env.now - downtime_start)
print('%s at %.2f' % (spare.name, self.env.now))
print('%d' % len(spares_inventory.items))
with self.repair_facility.request() as req:
yield req
print('%s begins repair at %.2f' % (self.name, self.env.now))
yield self.env.timeout(random.expovariate(1.0 / MTTR))
yield self.spares_inventory.put(self)
print('%s at %.2f' % (self.name, self.env.now))
print('%d' % len(spares_inventory.items))
def main():
env = simpy.Environment()
repair_facility = simpy.Resource(env, capacity = NUM_SERVERS)
spares_inventory = simpy.Container(env, capacity = TOTAL_ENGINES, init = TOTAL_SPARES)
downtime = []
working = [Working(env, i, repair_facility, spares_inventory, downtime) for i in range(TOTAL_IN_USE)]
env.run(SIM_TIME)
if __name__ == '__main__':
main()
This is the error I keep getting:
Traceback (most recent call last):
File "", line 61, in <module>
main()
File "", line 55, in main
env.run(SIM_TIME)
File "", line 120, in run
self.step()
File "", line 213, in step
raise event._value
TypeError: __init__() takes exactly 3 arguments (2 given)
Any help at all is much appreciated, Thanks a lot in advance
You forgot some extra info in your traceback; above your quoted traceback, there's a a few lines that say:
Traceback (most recent call last):
File "/data/evertr/sw/lib/python2.7/site-packages/simpy/events.py", line 312, in _resume
event = self._generator.send(event._value)
File "simptest.py", line 31, in run
spare = yield self.spares_inventory.get()
TypeError: __init__() takes exactly 3 arguments (2 given)
The above exception was the direct cause of the following exception:
followed by your traceback.
With that, you can see that the self.spares_inventory.get() call is the real culprit. Annoyingly enough, this method is actually a hidden class instantiation (lots of tricky stuff happening behind the scenes in simpy, I've noticed), and that's why you see the __init__() warning.
Basically, you need to supply an amount to self.spares_inventory.get() (there's, for better or worse, no convenient default of 1).
So changing that to
spare = yield self.spares_inventory.get(1)
may solve your problem.
(You'll run into other errors after that though; you'll find out. Those new errors follow the same structure: a traceback, followed by the line The above exception was the direct cause of the following exception, followed by another (less relevant) traceback).

NodeBox error for a verb in python

I downloaded the package http://nodebox.net/code/index.php/Linguistics#verb_conjugation
I'm getting an error even when I tried to get a tense of a verb .
import en
print en.is_verb('use')
#prints TRUE
print en.verb.tense('use')
KeyError Traceback (most recent call last)
/home/cse/version2_tense.py in <module>()
----> 1
2
3
4
5
/home/cse/en/__init__.pyc in tense(self, word)
124
125 def tense(self, word):
--> 126 return verb_lib.verb_tense(word)
127
128 def is_tense(self, word, tense, negated=False):
/home/cse/en/verb/__init__.pyc in verb_tense(v)
175
176 infinitive = verb_infinitive(v)
--> 177 a = verb_tenses[infinitive]
178 for tense in verb_tenses_keys:
179 if a[verb_tenses_keys[tense]] == v:
KeyError: ''
The reason you are getting this error is because there is a mistake in the ~/Library/Application Support/NodeBox/en/verb/verb.txt file they are using to create the dictionary.
use is the infinitive form, however, "used" is entered as the infinitive.
at line 5857:
used,,,uses,,using,,,,,used,used,,,,,,,,,,,,
should be:
use,,,uses,,using,,,,,used,used,,,,,,,,,,,,
after editing and saving the file:
import en
print en.is_verb("use")
print en.verb.infinitive('use')
print en.verb.tense('use')
gives:
True
use
infinitive
extra:
import en
print 'use %s' % en.verb.tense("use")
print 'uses %s' % en.verb.tense("uses")
print 'using %s' % en.verb.tense('using')
print 'used %s' % en.verb.tense('used')
use infinitive
uses 3rd singular present
using present participle
used past

Categories

Resources