I cannot make safe_to_exit method in npyscreen work - python

I think I missing something very basic but I cannot make this function work.
I am running python 3.6.12 on Redhat with npyscreen 4.10.5. My expectation is that the safe_to_exit function could be used to validate any input immediately when the user exits the field (using the tab key) but I cannot make it fire at all. Possibly I have misunderstood this completely. Here is my test code, cut down to make it as simple as possible:
import npyscreen
def test1(*args):
F = npyscreen.Form(name='My Test Application')
Field1 = F.add(npyscreen.TitleText, name="My Test Field")
Field1.safe_to_exit = Field1_Validations
F.edit()
return Field1.value
def Field1_Validations():
npyscreen.notify_confirm("Safe to exit")
return True
if __name__ == '__main__':
onefield = npyscreen.wrapper_basic(test1)
print("Results are : {} ".format(onefield))
Any pointers would be greatly appreciated.

I'm still digging, but I have discovered that it appears safe_to_exit is not implemented on all widgets. Changing the widget from "TitleText" to "Textfield" resulted in the validations code firing.

After much hair pulling I worked it out. They syntax is (applying to the code sample above):
self.Field1.entry_widget.safe_to_exit = Field1_Validations

Related

Why my code won't run when I'm using def?

So, I started python 2 weeks ago.
Something important bugs me, what I just don't understand.
When I have functions why my code stop running? Without defs it's working.
In my example I can't call just kezdo(), because i get an empty console.
Process finished with exit code 0
Anyone can explain it with my example code?
def kerdes(self):
self.open1 = self.open("kerdesek.txt")
self.open2 = self.open1.read()
print(self.open2)
return kezdo(self)
def kezdo(self):
print(self.open2)
user = int(input("valasz egy kerdest: "))
kerdesek = self.open2
valaszok = ("egyvalasz", "ketvalasz")
kv = {kerdesek[user]: valaszok[user]}
print(kv)
if I add kezdo()
then I get an error:
Error: kezdo() missing 1 required positional argument: 'self'
Thanks!
you should call the functions. like this:
kerdes()
kezdo()
I can only take a guess based on the limited information but it appears as if you are defining these methods (kezdo() and kerdes()) in some class.
In that case, you need to use self when calling these methods, or Python won't know what you mean.
It needs to be something along the lines of:
def kerdes(self):
self.open1 = self.open("kerdesek.txt")
self.open2 = self.open1.read()
print(self.open2)
return self.kezdo(self)
# ^^^^
# You need to use self here.

Segfault when installing custom IMessageFilter in Python.net app

I'm trying to add a custom IMessageFilter in a Winforms app using Python.net, but I'm getting a segfault.
Here's a minimal sample application:
import clr
clr.AddReference("System.Windows.Forms")
import System.Windows.Forms as WinForms
class MessageFilter(WinForms.IMessageFilter):
__namespace__ = 'System.Windows.Forms'
def PreFilterMessage(self, message):
print('filter', message)
return False
class HelloApp(WinForms.Form):
def __init__(self):
self.textbox = WinForms.TextBox()
self.textbox.Text = "Hello World"
self.Controls.Add(self.textbox)
def main():
form = HelloApp()
app = WinForms.Application
f = MessageFilter()
app.AddMessageFilter(f)
app.Run(form)
if __name__ == '__main__':
main()
If you run this code as presented, the application window displays, but you get a segfault immediately (I presume this is when the first message is passed to the filter). The segfault is entirely opaque. There's no stack trace or other helpful details - it's just the OS-level segfault handler.
If you comment out line 25 (app.AddMessageFilter(f), installing the actual filter), the code works fine.
If you modify MessageFilter so that it doesn't subclass Winforms.IMessageFilter, you get an error saying there's no AddMessageFilter method matching the given arguments.
If you rename or remove the PreFilterMessage() method, you get an error that the Python object doesn't have a PreFilterMessage method.
Any suggestions on what I'm doing wrong, and/or how to fix it? Or how to get more debugging information that could point at the source of the segfault?
It appears that this is a bug in Python.net itself, relating to a problem with marshaling byref arguments. Details can be found here.

Python AppEngine MapReduce

i have created a pretty simple MapReduce pipeline, but i am having a cryptic:
PipelineSetupError: Error starting production.cron.pipelines.ItemsInfoPipeline(*(), **{})#a741186284ed4fb8a4cd06e38921beff:
when i try to start it. This is the pipeline code:
class ItemsInfoPipeline(base_handler.PipelineBase):
"""
"""
def run(self):
output = yield mapreduce_pipeline.MapreducePipeline(
job_name="items_job",
mapper_spec="production.cron.mappers.items_info_mapper",
input_reader_spec="mapreduce.input_readers.DatastoreInputReader",
mapper_params={
"input_reader": {
"entity_kind": "production.models.Transaction"
}
}
)
yield ItemsInfoStorePipeline(output)
class ItemsInfoStorePipeline(base_handler.PipelineBase):
"""
"""
def run(self, statistics):
print statistics
return "OK"
Of course i have double checked that the mapper path is right, and take into account that ItemsInfoStorePipeline is not doing anything because i am focusing the have the pipeline started, which is not happening.
It is all triggered by a Flask view, the following:
class ItemsInfoMRJob(views.MethodView):
"""
It's based on transacions.
"""
def get(self):
"""
:return:
"""
pipeline = ItemsInfoPipeline()
pipeline.start()
redirect_url = "%s/status?root=%s" % (pipeline.base_path, pipeline.pipeline_id)
return flask.redirect(redirect_url)
I am using GoogleAppEngineMapReduce==1.9.22.0
Thanks for any help.
UPDATE
The above code works once deployed.
UPDATE 2
Apparently there's more people dealing with this:
https://github.com/GoogleCloudPlatform/appengine-mapreduce/issues/103
I'm updating this. I have a code base that's using pipelines and works fine in OSX. I had another developer using OSX that simply nothing I do seems to get it working, he gets this:
Encountered unexpected error from ProtoRPC method implementation: PipelineSetupError
I've tried swapping versions around and making our PC's match perfectly and it continue to happen. I finally broke down and built an Ubuntu image in docker. I'm also doing my best to match our versions of AppEngine and libraries perfectly.
It also refuses to start with the same message. I started working through the libraries uncommenting the part that's swallowing the error but that was a long rabbit hole I started down because lots of stuff above it also seems to be swallowing up whatever is going on.

Maya - check if an attributes is enabled / disabled

Since hours I try to solve a problem I have with Maya / MEL / Python.
I have a script to set values of a fluid container.
E.g. setAttr "fluidShape1.densityDissipation" 0.2
Works great...
My problem: Actually it is not possible to change the value using the interface (see image). Is there a way to find out if the "text box" is enabled?
Thanks!!
P.S. I cant upload the image :(. But I hope you guys know what i mean
To find out if the attribute is settable, use
getAttr -settable your_object.your_attribute
it will return 1 if you can set the attribute using setAttr and 0 if you can't.
If the value is grayed out in the UI the attribute is locked, you can unlock it with
setAttr -lock 0 your_object.your_attribute
If the value is purple in the UI it's driven by a connection of some kind, you'll need to use the hypergraph or the listConnections command to find out what's driving it and decide if you want to override the connection.
I already tried the -settable flag, but for some reason this is not working in my case.
Ok, lets say I create a FluidContainer. The density is set to zero, by using this command:
setAttr "fluidShape1.densityMethod" 0;
By using the -settable flag
getAttr -settable "fluidShapeq.densityScale"
the result is 1. But I can not change the corresponding slider.
But still it is possible to change the values by using setAttr... That is confusing for me!
ok I think I found a "solution" for my problem, but I think I can do better.
I use the following command to get the "grougID" of the slider and the field:
import maya.cmds as cmds
txt = "attrFieldSliderGrp214"
cmds.attrFieldSliderGrp( txt, q=True, l=True ) # Density Scale
And now I can usethe enable field by:
gray = cmds.attrFieldSliderGrp(txt, q=True, en=True ) # True/False
This works fine for me.
def gui():
cmds.window()
cmds.columnLayout( adjustableColumn=True )
#since density support only upto 3 setting max to 3
getCurrentInd = int(cmds.getAttr("fluidShape1.densityMethod"))
cmds.intSlider( min=0, max=3, value=getCurrentInd, step=1, cc=updateDens)
cmds.showWindow()
def updateDens(value):
cmds.setAttr("fluidShape1.densityMethod", value)
gui()
By Interface if I understand that you mean the AttributeEditor, you could try this.
import pymel.core as pc
def findAEFieldByLabel(label='Dissipation', field_type=pc.ui.AttrFieldSliderGrp):
for i in pc.ui.PyUI('MainAttributeEditorLayout').walkChildren():
if isinstance(i, pc.ui.RowLayout):
name = i.name()
try:
grp = field_type(name)
if grp.getLabel() == label:
return grp
except:
pass
print findAEFieldByLabel().getEnable()
I used pymel here because it helps you find the type of a python ui. Well ... not quite however! because it recognized attrFieldSliderGrps as RowLayouts

How to debug PyQt5 appcrash on exit

I have been developing a PyQt5 software for a while now. I have managed to package my Python 3 PyQt5 software with py2exe fine in past with everything working perfectly.
However, now I have encountered an issue where the packaged exe-program will crash when user exits. More specifically I get APPCRASH with following details
Problem signature:
Problem Event Name: APPCRASH
Application Name: Sotilasmatrikkelit.exe
Application Version: 0.0.0.0
Application Timestamp: 54467a51
Fault Module Name: PyQt5.QtCore.pyd
Fault Module Version: 0.0.0.0
Fault Module Timestamp: 549be77e
Exception Code: c0000005
Exception Offset: 0010c185
OS Version: 6.1.7601.2.1.0.256.4
Locale ID: 1035
Additional Information 1: 0a9e
Additional Information 2: 0a9e372d3b4ad19135b953a78882e789
Additional Information 3: 0a9e
Additional Information 4: 0a9e372d3b4ad19135b953a78882e789
I never get this crash when running the software from Pycharm during the development. Any idea of how to debug this or what could be the cause in general?
I suspect this might have something to do with memory management (that PyQt doesn't delete all the resources properly on exit and therefore segfaults) but does anyone have any good suggestions to figure out the exact problem without better debug information? Should I try to do some kind of cleanup on exit? Atm I start the software like this:
def start():
import sys
app = QApplication(sys.argv)
fixingtool = Mainwindow(app)
fixingtool.show()
sys.exit(app.exec_())
Additional investigation seems to suggest that I get Access Violation which is caused by C++ null-pointer. Sounds scary since I don't know too much of PyQt debugging. Anyway, I found an area on my businesslogic code which if removed will remove the problem. However, this code has nothing to do with PyQt and is just regular Python code and shouldn't differ in any way. Strangest part is that if I remove certain functions from the code, problem disappears even though functions are not called during runtime meaning that just importing the file with those functions cause the problem. Below is a code sample:
import re
from books.karelians.extraction.extractors.baseExtractor import BaseExtractor
from books.karelians.extraction.extractionExceptions import *
from books.karelians.extraction.extractors.dateExtractor import DateExtractor
from shared import textUtils
from books.karelians.extractionkeys import KEYS
from interface.valuewrapper import ValueWrapper
from shared import regexUtils
from books.karelians.extraction.extractors.professionextractor import ProfessionExtractor
class SpouseExtractor(BaseExtractor):
def extract(self, text, entry):
super(SpouseExtractor, self).extract(text)
self.entry = entry
self.PATTERN = r"Puol\.?(?P<spousedata>[A-ZÄ-Öa-zä-ö\s\.,\d-]*)(?=(Lapset|poika|tytär|asuinp))"
self.NAMEPATTERN = r"(?P<name>^[\w\s\.-]*)"
self.OPTIONS = (re.UNICODE | re.IGNORECASE) #TODO: TRY IGNORE CASE?
self.REQUIRES_MATCH_POSITION = False
self.SUBSTRING_WIDTH = 100
self.hasSpouse = False
self.spouseName = ""
self.profession = {KEYS["profession"] : ValueWrapper("")}
self.initVars(text)
self._findSpouse(text)
return self._constructReturnDict()
def initVars(self,text):
pass
def _findSpouse(self, text):
try:
self.foundSpouse = regexUtils.safeSearch(self.PATTERN, text, self.OPTIONS)
self.hasSpouse = True
self._findSpouseName(self.foundSpouse.group("spousedata"))
self._setFinalMatchPosition()
except regexUtils.RegexNoneMatchException:
pass
def _findSpouseName(self, text):
try:
name = regexUtils.safeSearch(self.NAMEPATTERN, text, self.OPTIONS)
self.spouseName = name.group("name").strip()
self._findProfession(text[name.end():])
except regexUtils.RegexNoneMatchException:
self.errorLogger.logError(SpouseNameException.eType, self.currentChild)
def _findProfession(self, text):
professionExt = ProfessionExtractor(self.entry, self.errorLogger, self.xmlDocument)
professionExt.setDependencyMatchPositionToZero()
self.profession = professionExt.extract(text, self.entry)
def _setFinalMatchPosition(self):
#Dirty fix for inaccuracy in positions which would screw the Location extraction
self.matchFinalPosition = self.foundSpouse.end() + self.matchStartPosition - 4
def _constructReturnDict(self):
print(self.profession)
return {KEYS["spouse"]: ValueWrapper({ KEYS["hasSpouse"]: ValueWrapper(self.hasSpouse),KEYS["spouseName"]: ValueWrapper(self.spouseName), KEYS["spouseProfession"]: ValueWrapper(self.profession[KEYS["profession"]].value) })}
Here if I remove or comment away all functions "initVars()" program exits properly. What gives?
This isn't really a solution to a problem itself but I'm leaving this here in case someone encounters a similar issue.
Today I decided to try cx_freeze instead of py2exe figuring that maybe the problem is with py2exe since the whole issue is not happening when running the application with normal python interpreter.
Turns out I was right and problem seemed to magically disappear after I packaged the app using cx_freeze instead of py2exe. I didn't do any changes to code. Someone more knowledgeable than me about how py2exe and cx_freeze work might be able to explain the difference. My wild guess is that for some reason the exiting from the Python interpreter is not handled perfectly in py2exe case somehow messing the end garbage cleanup. I have no idea if this is py2exe's or my fault by not configuring py2exe properly.
In any case I'm happy it works now since yesterday was a really frustrating day.

Categories