How to check if a Gtk Constant (GdkWindowState) contains a flag - python

It makes a while that I've been searching to find how to check if a Gtk Constant of type GdkWindowState contains a flag.
I'm currently doing this:
state=self.window_root.get_window().get_state()
if 'GDK_WINDOW_STATE_FULLSCREEN' in str(state):
...
Where self.window_root is a Gtk.Window
This is a soft hack, but I'd like to do it in the proper way by using Gdk.WindowState.FULLSCREEN
I've tried some things like: if Gdk.WindowState.FULLSCREEN in state: but the constant is not iterable. And I'd like to point that just using if Gdk.WindowState.FULLSCREEN == state: doesn't works because the window is also focused.
When I print state I get:
<flags GDK_WINDOW_STATE_FULLSCREEN | GDK_WINDOW_STATE_FOCUSED of type
GdkWindowState>
So I actually see that there is an | operator and I think that it should be possible to do something with it. Something like state.get_flags()

According to PyGtk documentation, GdkWindowState is a set of bit flags. Try converting it to integer value and use binary AND:
if Gdk.WindowState.FULLSCREEN & int(state):
# ...
Actually it's quite possible the GdkWindowState class supports this operation directly, or has some standard methods to convert to integer.
You can use print dir(state) to see what fields and methods are available, and investigate from there.

Related

How to initialise QTextEdit find options

I am trying to set the options in the following call:
bool QTextEdit::find(const QString &exp, QTextDocument::FindFlags options = QTextDocument::FindFlags())
But the signature of option is complicated for a Python programmer. I tried the following:
option = 0
option = option | QTextDocument.FindBackward
# continue to check other checkboxes and build up the option this way
Unfortunately, the error is that 'int' is unexpected. I understand that since the option=0, then the following OR operation probably didn't yield an int type as well. But how to get a the proper starting null/unset/zero value?
If you would have default value let this parameter unfilled:
doc = QTextDocument()
doc.find("aaa")
If you would like to use flag, do not read value from documentation, but use
QTextDocument.FindBackward
QTextDocument.FindCaseSensitively
QTextDocument.FindWholeWords
If you would like to have or use | operator:
QTextDocument.FindWholeWords | QTextDocument.FindBackward
If you have default value in function signature, you not need to provide this argument.
The error is caused by a minor bug that occasionally appears in PyQt. If you update to the latest version, the error will probably go away. However, if you can't update, or if you want to bullet-proof your code against this problem, a work-around is to initialise the variable like this:
>>> option = QTextDocument.FindFlag(0)
>>> option = option | QTextDocument.FindBackward
This will now guarantee that option has the expected type. The correct flag to use can be found by explicitly checking the type of one of the enum values:
>>> print(type(QTextDocument.FindBackward))
<class 'PyQt5.QtGui.QTextDocument.FindFlag'>
Or you can just look up the relevant enum in the docs: QTextDocument.

Python-pptx: “Show legend overlapping the chart”

I am using Office 2007.
I found if I would like to show the legend overlapping the chart in office2007.
The XML should be as the following.
`-<c:legend>
<c:overlay val="1"/>`
But no matter I use the API from python-pptx 'chart.legend.include_in_layout = True' or I leave it as the default. The generated XML would always be as the following.
`-<c:legend>
<c:overlay/>`
Without the val=1, then office2007 won't show the format properly.
What can I do to force the python-pptx to write the val=1? thanks.
Explanation
In short, the True value is not explicitly set (in contrast to False) because True corresponds to the default value of overlay's val attribute.
To explain it in more detail - you can follow the python-pptx hierarchy as follows: overlay is mapped to CT_Boolean (all overlay oxml elements are instantiated from CT_Boolean). The actual val parameter is then mapped via OptionalAttribute and is defined with the default value of True:
class CT_Boolean(BaseOxmlElement):
"""
Common complex type used for elements having a True/False value.
"""
val = OptionalAttribute('val', XsdBoolean, default=True)
Now, when setting the optional attribute to its default value, it is actually skipped/deleted, as you can see here if value == self._default:
class OptionalAttribute(BaseAttribute):
"""
Defines an optional attribute on a custom element class. An optional
attribute returns a default value when not present for reading. When
assigned |None|, the attribute is removed.
"""
#property
def _setter(self):
def set_attr_value(obj, value):
if value == self._default:
if self._clark_name in obj.attrib:
del obj.attrib[self._clark_name]
return
str_value = self._simple_type.to_xml(value)
obj.set(self._clark_name, str_value)
return set_attr_value
Fix - provide custom CT_Boolean class
Add these lines somewhere before you need to use the overlay. It will overwrite python-pptx overlay mapping with the custom CT_Boolean_NoDefault class:
from pptx.oxml import register_element_cls
from pptx.oxml.xmlchemy import BaseOxmlElement, OptionalAttribute
from pptx.oxml.simpletypes import XsdBoolean
class CT_Boolean_NoDefault(BaseOxmlElement):
"""
Common complex type used for elements having a True/False value with no
default value.
"""
val = OptionalAttribute('val', XsdBoolean)
register_element_cls('c:overlay', CT_Boolean_NoDefault)
This worked for me and finally I got:
<c:legend>
<c:overlay val="1"/>
</c:legend>
Fix - modify python-pptx permanently
This is not recommended but you might want to modify python-pptx instead of adding the solution from above for each script you run.
First, add the following to pptx/oxml/chart/shared.py which defines a new bool class without a default value:
class CT_Boolean_NoDefault(BaseOxmlElement):
"""
Common complex type used for elements having a True/False value.
"""
val = OptionalAttribute('val', XsdBoolean)
Second, modify pptx/oxml/__init__.py to add the new bool class:
from .chart.shared import (
CT_Boolean, CT_Double, CT_Layout, CT_LayoutMode, CT_ManualLayout,
CT_NumFmt, CT_Tx, CT_UnsignedInt, CT_Boolean_NoDefault
)
Third, modify pptx/oxml/__init__.py to change the mapping of the overlay element to the new bool class:
register_element_cls('c:overlay', CT_Boolean_NoDefault)
Better solution
In case you have time, please submit a ticket here so it might become a permanent fix. In case #scanny finds some time, he will read this. Perhaps there is some better solution for this, too, and I've completely missed something.
#pansen 's analysis is spot-on. Here's an alternative way to get this working in your case that might be a little lighter weight:
def include_in_layout(legend):
legend_element = legend._element
overlay = legend_element.get_or_add_overlay()
overlay.set('val', '1')
This appears to be a localized non-conformance of that version of PowerPoint with the ISO/IEC 29500 spec. As pansen rightly points out, a missing val attribute is to be interpreted the same as val=1 (True). I'd be interested to discover how extensive this non-conformance goes, i.e. what other elements exhibit this same behavior. The CT_Boolean type is used quite frequently in PowerPoint, for things like bold, italic, varyColors, smooth, and on and on. So a "compensating" fix would need to be applied carefully to avoid reporting incorrect results for other elements.
I think I'll take pansen's cue and use a specialized element class for this element only. It will still report True for an element without the val attribute, which will be inconsistent with the observed behavior on this version of PowerPoint; but assuming other versions behave correctly (according to the spec), the inconsistency will be localized and at least assigning True to that property will make the legend show up the way you want.

Change struct field in GDB using a gdb.value

I am defining a convenience variable in gdb
>set $param = (T_packet*)malloc(sizeof(T_packet))
I can retrieve it via Python
>p = gdb_helper.parse_and_eval("$param")
<gdb.Value at 0x7f30b42f9170>
show the fields of the struct
>python print(p.dereference())
{ID_PACKET = 0 , L_PACKET = 0}
Try to change a field (C equivalent: p->ID_PACKET=1)
p.dereference()["ID_PACKET"] = 1
>"Setting of struct elements is not currently supported"
Is there way to update the value of the field ID_Packet inside p using GDB's Python API?
There's currently no way to set a value using the Value API. This is just a little hole in gdb (I looked but could not find a bug for this, so perhaps filing one would be a good thing to do).
Meanwhile you can work around it, with a bit of difficulty, using gdb.parse_and_eval. The idea is to get the address of the field in question, then form an expression like *(TYPE *) 0xADDR = VALUE. Alternatively you can write directly to memory using Inferior.write_memory.
Both of these approaches will fail in some situations, for example you cannot write to a register this way, preventing this from working on a structure that's been split apart due to SRA optimization.

How do I use the GeometryConstraint class?

I've been trying to get this to work for so long now, I've read the docs here, but I can't seem to understand how to implement the GeometryConstraint.
Normally, the derivative version of this would be:
geometryConstraintNode = pm.geometryConstraint(target, object)
However, in Pymel, It looks a little nicer when setting attributes, which is why I want to use it, because it's much more readable.
I've tried this:
geometryConstraintNode = nt.GeometryConstraint(target, object).setName('geoConstraint')
But no luck, can someone take a look?
Shannon
this doesn't work for you?
import pymel.core as pm
const = pm.geometryConstraint('pSphere1', 'locator1', n='geoConstraint')
print const
const.rename('fred')
print const
output would be
geoConstraint
fred
and a constraint object named 'fred'.
The pymel node is the return value that comes back from the command defined in pm.animation.geometryConstraint. What it returns is a class wrapper for the actual in-scene constraint, which is defined in pm.nodetypes.GeometryConstraint. It's the class version where you get to do all the attribute setting, etc; the command version is a match for the same thing in maya.cmds with sometimes a little syntactic sugar added.
In this case, the pymel node is like any other pymel node, so things like renamimg use the same '.rename' functionality inherited from DagNode. You could also use functions inherited from Transform, like 'getChildren()' or 'setParent()' The docs make this clear in a round-about way by including the inheritance tree at the top of the nodetype's page. Basically all pynode returns will share at least DagNode (stuff like naming) and usually Transform (things like move, rotate, parent) or Shape (query components, etc)

Make python __doc__ property display correctly in a Windows CMD window?

In Windows, if I open a command prompt, start python, and inspect something using its __doc__ property, it doesn't display correctly. Instead of the lines being separated, I see one continuous string with the newline character every once and a while.
Is there a way to make it appear correctly?
Here's an example of what I see:
>>> hashlib.__doc__
'hashlib module - A common interface to many hash functions.\n\nnew(name, string=\'\') - returns a n
ew hash object implementing the\n given hash function; initializing the hash\n
using the given string data.\n\nNamed constructor functions are also availabl
e, these are much faster\nthan using new():\n\nmd5(), sha1(), sha224(), sha256(), sha384(), and sha5
12()\n\nMore algorithms may be available on your platform but the above are\nguaranteed to exist.\n\
nNOTE: If you want the adler32 or crc32 hash functions they are available in\nthe zlib module.\n\nCh
Rather than pulling __doc__ yourself, try this:
>>> help(hashlib)
It will give you a nicely formatted summary of the module, including (but not limited to) the docstring.
try
>>> print hashlib.__doc__
or (v3)
>>> print(hashlib.__doc__)
def help_(obj):
if type(obj).__name__ == 'ufunc':
print obj.__doc__
else:
help(obj)

Categories

Resources