INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Convenience function for accessing tag parameters | def GetParam(tag, param, default=__SENTINEL):
""" Convenience function for accessing tag parameters"""
if tag.HasParam(param):
return tag.GetParam(param)
else:
if default == __SENTINEL:
raise KeyError
else:
return default |
Process an outgoing communication | def send(evt):
"Process an outgoing communication"
# get the text written by the user (input textbox control)
msg = ctrl_input.value
# send the message (replace with socket/queue/etc.)
gui.alert(msg, "Message")
# record the message (update the UI)
log(msg)
ctrl_input.value = ""
ctrl_... |
Basic save functionality: just replaces the gui code | def save(evt, designer):
"Basic save functionality: just replaces the gui code"
# ask the user if we should save the changes:
ok = gui.confirm("Save the changes?", "GUI2PY Designer",
cancel=True, default=True)
if ok:
wx_obj = evt.GetEventObject()
w = wx_obj.obj
... |
Show a tip message | def wellcome_tip(wx_obj):
"Show a tip message"
msg = ("Close the main window to exit & save.\n"
"Drag & Drop / Click the controls from the ToolBox to create new ones.\n"
"Left click on the created controls to select them.\n"
"Double click to edit the default property.\n"
... |
Get the selected object and store start position | def mouse_down(self, evt):
"Get the selected object and store start position"
if DEBUG: print "down!"
if (not evt.ControlDown() and not evt.ShiftDown()) or evt.AltDown():
for obj in self.selection:
# clear marker
if obj.sel_marker:
... |
Move the selected object | def mouse_move(self, evt):
"Move the selected object"
if DEBUG: print "move!"
if self.current and not self.overlay:
wx_obj = self.current
sx, sy = self.start
x, y = wx.GetMousePosition()
# calculate the new position (this will overwrite relative di... |
Called by SelectionTag | def do_resize(self, evt, wx_obj, (n, w, s, e)):
"Called by SelectionTag"
# calculate the pos (minus the offset, not in a panel like rw!)
pos = wx_obj.ScreenToClient(wx.GetMousePosition())
x, y = pos
if evt.ShiftDown(): # snap to grid:
x = x / GRID_SIZE[0] * GRID_S... |
Release the selected object ( pass a wx_obj if the event was captured ) | def mouse_up(self, evt, wx_obj=None):
"Release the selected object (pass a wx_obj if the event was captured)"
self.resizing = False
if self.current:
wx_obj = self.current
if self.parent.wx_obj.HasCapture():
self.parent.wx_obj.ReleaseMouse()
se... |
support cursor keys to move components one pixel at a time | def key_press(self, event):
"support cursor keys to move components one pixel at a time"
key = event.GetKeyCode()
if key in (wx.WXK_LEFT, wx.WXK_UP, wx.WXK_RIGHT, wx.WXK_DOWN):
for obj in self.selection:
x, y = obj.pos
if event.ShiftDown(): # snap ... |
delete all of the selected objects | def delete(self, event):
"delete all of the selected objects"
# get the selected objects (if any)
for obj in self.selection:
if obj:
if DEBUG: print "deleting", obj.name
obj.destroy()
self.selection = [] # clean selectio... |
create a copy of each selected object | def duplicate(self, event):
"create a copy of each selected object"
# duplicate the selected objects (if any)
new_selection = []
for obj in self.selection:
if obj:
if DEBUG: print "duplicating", obj.name
obj.sel_marker.destroy()
... |
Adjust facade with the dimensions of the original object ( and repaint ) | def update(self):
"Adjust facade with the dimensions of the original object (and repaint)"
x, y = self.obj.wx_obj.GetPosition()
w, h = self.obj.wx_obj.GetSize()
self.Hide()
self.Move((x, y))
self.SetSize((w, h))
# allow original control to repaint before taking th... |
Capture the new control superficial image after an update | def refresh(self):
"Capture the new control superficial image after an update"
self.bmp = self.obj.snapshot()
# change z-order to overlap controls (windows) and show the image:
self.Raise()
self.Show()
self.Refresh() |
When dealing with a Top - Level window position it absolute lower - right | def CalculateBestPosition(self,widget):
"When dealing with a Top-Level window position it absolute lower-right"
if isinstance(widget, wx.Frame):
screen = wx.ClientDisplayRect()[2:]
left,top = widget.ClientToScreenXY(0,0)
right,bottom = widget.ClientToScreenXY(*widget.... |
Returns the pyth item data associated with the item | def GetPyData(self, item):
"Returns the pyth item data associated with the item"
wx_data = self.GetItemData(item)
py_data = self._py_data_map.get(wx_data)
return py_data |
Set the python item data associated wit the wx item | def SetPyData(self, item, py_data):
"Set the python item data associated wit the wx item"
wx_data = wx.NewId() # create a suitable key
self.SetItemData(item, wx_data) # store it in wx
self._py_data_map[wx_data] = py_data # map it internally
... |
Do a reverse look up for an item containing the requested data | def FindPyData(self, start, py_data):
"Do a reverse look up for an item containing the requested data"
# first, look at our internal dict:
wx_data = self._wx_data_map[py_data]
# do the real search at the wx control:
if wx.VERSION < (3, 0, 0) or 'classic' in wx.version():
... |
Remove the item from the list and unset the related data | def DeleteItem(self, item):
"Remove the item from the list and unset the related data"
wx_data = self.GetItemData(item)
py_data = self._py_data_map[wx_data]
del self._py_data_map[wx_data]
del self._wx_data_map[py_data]
wx.ListCtrl.DeleteItem(self, item) |
Remove all the item from the list and unset the related data | def DeleteAllItems(self):
"Remove all the item from the list and unset the related data"
self._py_data_map.clear()
self._wx_data_map.clear()
wx.ListCtrl.DeleteAllItems(self) |
Set item ( row ) count - useful only in virtual mode - | def set_count(self, value):
"Set item (row) count -useful only in virtual mode-"
if self.view == "report" and self.virtual and value is not None:
self.wx_obj.SetItemCount(value) |
Deletes the item at the zero - based index n from the control. | def delete(self, a_position):
"Deletes the item at the zero-based index 'n' from the control."
key = self.wx_obj.GetPyData(a_position)
del self._items[key] |
Remove all items and column headings | def clear_all(self):
"Remove all items and column headings"
self.clear()
for ch in reversed(self.columns):
del self[ch.name] |
Associate the header to the control ( it could be recreated ) | def set_parent(self, new_parent, init=False):
"Associate the header to the control (it could be recreated)"
self._created = False
SubComponent.set_parent(self, new_parent, init)
# if index not given, append the column at the last position:
if self.index == -1 or self.index >... |
Remove all items and reset internal structures | def clear(self):
"Remove all items and reset internal structures"
dict.clear(self)
self._key = 0
if hasattr(self._list_view, "wx_obj"):
self._list_view.wx_obj.DeleteAllItems() |
Returns the index of the selected item ( list for multiselect ) or None | def _get_selection(self):
"Returns the index of the selected item (list for multiselect) or None"
if self.multiselect:
return self.wx_obj.GetSelections()
else:
sel = self.wx_obj.GetSelection()
if sel == wx.NOT_FOUND:
return None
... |
Sets the item at index n to be the selected item. | def _set_selection(self, index, dummy=False):
"Sets the item at index 'n' to be the selected item."
# only change selection if index is None and not dummy:
if index is None:
self.wx_obj.SetSelection(-1)
# clean up text if control supports it:
if hasattr(... |
Returns the label of the selected item or an empty string if none | def _get_string_selection(self):
"Returns the label of the selected item or an empty string if none"
if self.multiselect:
return [self.wx_obj.GetString(i) for i in
self.wx_obj.GetSelections()]
else:
return self.wx_obj.GetStringSelection() |
Clear and set the strings ( and data if any ) in the control from a list | def _set_items(self, a_iter):
"Clear and set the strings (and data if any) in the control from a list"
self._items_dict = {}
if not a_iter:
string_list = []
data_list = []
elif not isinstance(a_iter, (tuple, list, dict)):
raise ValueError("ite... |
Associate the given client data with the item at position n. | def set_data(self, n, data):
"Associate the given client data with the item at position n."
self.wx_obj.SetClientData(n, data)
# reverse association:
self._items_dict[data] = self.get_string(n) |
Adds the item to the control associating the given data if not None. | def append(self, a_string, data=None):
"Adds the item to the control, associating the given data if not None."
self.wx_obj.Append(a_string, data)
# reverse association:
self._items_dict[data] = a_string |
Deletes the item at the zero - based index n from the control. | def delete(self, a_position):
"Deletes the item at the zero-based index 'n' from the control."
self.wx_obj.Delete(a_position)
data = self.get_data()
if data in self._items_dict:
del self._items_dict[data] |
Construct a string representing the object | def represent(obj, prefix, parent="", indent=0, context=False, max_cols=80):
"Construct a string representing the object"
try:
name = getattr(obj, "name", "")
class_name = "%s.%s" % (prefix, obj.__class__.__name__)
padding = len(class_name) + 1 + indent * 4 + (5 if context else 0)
... |
Find an object already created | def get(obj_name, init=False):
"Find an object already created"
wx_parent = None
# check if new_parent is given as string (useful for designer!)
if isinstance(obj_name, basestring):
# find the object reference in the already created gui2py objects
# TODO: only useful for designer, ... |
Recreate ( if needed ) the wx_obj and apply new properties | def rebuild(self, recreate=True, force=False, **kwargs):
"Recreate (if needed) the wx_obj and apply new properties"
# detect if this involves a spec that needs to recreate the wx_obj:
needs_rebuild = any([isinstance(spec, (StyleSpec, InitSpec))
for spec_name, sp... |
Remove event references and destroy wx object ( and children ) | def destroy(self):
"Remove event references and destroy wx object (and children)"
# unreference the obj from the components map and parent
if self._name:
del COMPONENTS[self._get_fully_qualified_name()]
if DEBUG: print "deleted from components!"
if isins... |
Create a new object exactly similar to self | def duplicate(self, new_parent=None):
"Create a new object exactly similar to self"
kwargs = {}
for spec_name, spec in self._meta.specs.items():
value = getattr(self, spec_name)
if isinstance(value, Color):
print "COLOR", value, value.default
... |
Raises/ lower the component in the window hierarchy ( Z - order/ tab order ) | def reindex(self, z=None):
"Raises/lower the component in the window hierarchy (Z-order/tab order)"
# z=0: lowers(first index), z=-1: raises (last)
# actually, only useful in design mode
if isinstance(self._parent, Component):
# get the current index (z-order)
... |
Store the gui/ wx object parent for this component | def set_parent(self, new_parent, init=False):
"Store the gui/wx object parent for this component"
# set init=True if this is called from the constructor
self._parent = get(new_parent, init) |
Return parent window name ( used in __repr__ parent spec ) | def _get_parent_name(self):
"Return parent window name (used in __repr__ parent spec)"
parent = self.get_parent()
parent_names = []
while parent:
if isinstance(parent, Component):
parent_name = parent.name
# Top Level Windows has no pare... |
return full parents name + self name ( useful as key ) | def _get_fully_qualified_name(self):
"return full parents name + self name (useful as key)"
parent_name = self._get_parent_name()
if not parent_name:
return self._name
else:
return "%s.%s" % (parent_name, self._name) |
Capture the screen appearance of the control ( to be used as facade ) | def snapshot(self):
"Capture the screen appearance of the control (to be used as facade)"
width, height = self.wx_obj.GetSize()
bmp = wx.EmptyBitmap(width, height)
wdc = wx.ClientDC(self.wx_obj)
mdc = wx.MemoryDC(bmp)
mdc.Blit(0, 0, width, height, wdc, 0, 0)
... |
called when adding a control to the window | def _sizer_add(self, child):
"called when adding a control to the window"
if self.sizer:
if DEBUG: print "adding to sizer:", child.name
border = None
if not border:
border = child.sizer_border
flags = child._sizer_flags
... |
Re - parent a child control with the new wx_obj parent | def set_parent(self, new_parent, init=False):
"Re-parent a child control with the new wx_obj parent"
Component.set_parent(self, new_parent, init)
# if not called from constructor, we must also reparent in wx:
if not init:
if DEBUG: print "reparenting", ctrl.name
... |
Calculate final pos and size ( auto absolute in pixels & relativa ) | def _calc_dimension(self, dim_val, dim_max, font_dim):
"Calculate final pos and size (auto, absolute in pixels & relativa)"
if dim_val is None:
return -1 # let wx automatic pos/size
elif isinstance(dim_val, int):
return dim_val # use fixed pixel value (absolute)
... |
automatically adjust relative pos and size of children controls | def resize(self, evt=None):
"automatically adjust relative pos and size of children controls"
if DEBUG: print "RESIZE!", self.name, self.width, self.height
if not isinstance(self.wx_obj, wx.TopLevelWindow):
# check that size and pos is relative, then resize/move
if s... |
make several copies of the background bitmap | def __tile_background(self, dc):
"make several copies of the background bitmap"
sz = self.wx_obj.GetClientSize()
bmp = self._bitmap.get_bits()
w = bmp.GetWidth()
h = bmp.GetHeight()
if isinstance(self, wx.ScrolledWindow):
# adjust for scrolled positio... |
Draw the image as background | def __on_erase_background(self, evt):
"Draw the image as background"
if self._bitmap:
dc = evt.GetDC()
if not dc:
dc = wx.ClientDC(self)
r = self.wx_obj.GetUpdateRegion().GetBox()
dc.SetClippingRegion(r.x, r.y, ... |
Associate the component to the control ( it could be recreated ) | def set_parent(self, new_parent, init=False):
"Associate the component to the control (it could be recreated)"
# store gui reference inside of wx object (this will enable rebuild...)
self._parent = get(new_parent, init=False) # store new parent
if init:
self._parent[s... |
Update a property value with ( used by the designer ) | def rebuild(self, **kwargs):
"Update a property value with (used by the designer)"
for name, value in kwargs.items():
setattr(self, name, value) |
Custom draws the label when transparent background is needed | def __on_paint(self, event):
"Custom draws the label when transparent background is needed"
# use a Device Context that supports anti-aliased drawing
# and semi-transparent colours on all platforms
dc = wx.GCDC(wx.PaintDC(self.wx_obj))
dc.SetFont(self.wx_obj.GetFont())
... |
Look for every file in the directory tree and return a dict Hacked from sphinx. autodoc | def find_modules(rootpath, skip):
"""
Look for every file in the directory tree and return a dict
Hacked from sphinx.autodoc
"""
INITPY = '__init__.py'
rootpath = os.path.normpath(os.path.abspath(rootpath))
if INITPY in os.listdir(rootpath):
root_package = rootpath.split(... |
Return a list of children sub - components that are column headings | def _get_column_headings(self):
"Return a list of children sub-components that are column headings"
# return it in the same order as inserted in the Grid
headers = [ctrl for ctrl in self if isinstance(ctrl, GridColumn)]
return sorted(headers, key=lambda ch: ch.index) |
Set the row label format string ( empty to hide ) | def _set_row_label(self, value):
"Set the row label format string (empty to hide)"
if not value:
self.wx_obj.SetRowLabelSize(0)
else:
self.wx_obj._table._row_label = value |
Update the grid if rows and columns have been added or deleted | def ResetView(self, grid):
"Update the grid if rows and columns have been added or deleted"
grid.BeginBatch()
for current, new, delmsg, addmsg in [
(self._rows, self.GetNumberRows(),
gridlib.GRIDTABLE_NOTIFY_ROWS_DELETED,
gridlib.GRIDTABLE_NOTIFY_R... |
Update all displayed values | def UpdateValues(self, grid):
"Update all displayed values"
# This sends an event to the grid table to update all of the values
msg = gridlib.GridTableMessage(self,
gridlib.GRIDTABLE_REQUEST_VIEW_GET_VALUES)
grid.ProcessTableMessage(msg) |
update the column attributes to add the appropriate renderer | def _updateColAttrs(self, grid):
"update the column attributes to add the appropriate renderer"
col = 0
for column in self.columns:
attr = gridlib.GridCellAttr()
if False: # column.readonly
attr.SetReadOnly()
if False: # column.rende... |
col - > sort the data based on the column indexed by col | def SortColumn(self, col):
"col -> sort the data based on the column indexed by col"
name = self.columns[col].name
_data = []
for row in self.data:
rowname, entry = row
_data.append((entry.get(name, None), row))
_data.sort()
self.data =... |
Associate the header to the control ( it could be recreated ) | def set_parent(self, new_parent, init=False):
"Associate the header to the control (it could be recreated)"
self._created = False
SubComponent.set_parent(self, new_parent, init)
# if index not given, append the column at the last position:
if self.index == -1 or self.index >... |
Insert a number of rows into the grid ( and associated table ) | def insert(self, pos, values):
"Insert a number of rows into the grid (and associated table)"
if isinstance(values, dict):
row = GridRow(self, **values)
else:
row = GridRow(self, *values)
list.insert(self, pos, row)
self._grid_view.wx_obj.InsertRows... |
Insert a number of rows into the grid ( and associated table ) | def append(self, values):
"Insert a number of rows into the grid (and associated table)"
if isinstance(values, dict):
row = GridRow(self, **values)
else:
row = GridRow(self, *values)
list.append(self, row)
self._grid_view.wx_obj.AppendRows(numRows=1... |
Remove all rows and reset internal structures | def clear(self):
"Remove all rows and reset internal structures"
## list has no clear ... remove items in reverse order
for i in range(len(self)-1, -1, -1):
del self[i]
self._key = 0
if hasattr(self._grid_view, "wx_obj"):
self._grid_view.wx_obj.Clea... |
Called to create the control which must derive from wxControl. | def Create(self, parent, id, evtHandler):
"Called to create the control, which must derive from wxControl."
self._tc = wx.ComboBox(parent, id, "", (100, 50))
self.SetControl(self._tc)
# pushing a different event handler instead evtHandler:
self._tc.PushEventHandler(w... |
Called to position/ size the edit control within the cell rectangle. | def SetSize(self, rect):
"Called to position/size the edit control within the cell rectangle."
self._tc.SetDimensions(rect.x, rect.y, rect.width+2, rect.height+2,
wx.SIZE_ALLOW_MINUS_ONE) |
Fetch the value from the table and prepare the edit control | def BeginEdit(self, row, col, grid):
"Fetch the value from the table and prepare the edit control"
self.startValue = grid.GetTable().GetValue(row, col)
choices = grid.GetTable().columns[col]._choices
self._tc.Clear()
self._tc.AppendItems(choices)
self._tc.SetStringS... |
Complete the editing of the current cell. Returns True if changed | def EndEdit(self, row, col, grid, val=None):
"Complete the editing of the current cell. Returns True if changed"
changed = False
val = self._tc.GetStringSelection()
print "val", val, row, col, self.startValue
if val != self.startValue:
changed = True
... |
Return True to allow the given key to start editing | def IsAcceptedKey(self, evt):
"Return True to allow the given key to start editing"
## Oops, there's a bug here, we'll have to do it ourself..
##return self.base_IsAcceptedKey(evt)
return (not (evt.ControlDown() or evt.AltDown()) and
evt.GetKeyCode() != wx.WXK_SHIFT) |
This will be called to let the editor do something with the first key | def StartingKey(self, evt):
"This will be called to let the editor do something with the first key"
key = evt.GetKeyCode()
ch = None
if key in [wx.WXK_NUMPAD0, wx.WXK_NUMPAD1, wx.WXK_NUMPAD2, wx.WXK_NUMPAD3, wx.WXK_NUMPAD4,
wx.WXK_NUMPAD5, wx.WXK_NUMPAD6, wx.WXK_N... |
A metaclass generator. Returns a metaclass which will register it s class as the class that handles input type = typeName | def TypeHandler(type_name):
""" A metaclass generator. Returns a metaclass which
will register it's class as the class that handles input type=typeName
"""
def metaclass(name, bases, dict):
klass = type(name, bases, dict)
form.FormTagHandler.register_type(type_name.upper(), klass)
... |
enable or disable all menu items | def Enable(self, value):
"enable or disable all menu items"
for i in range(self.GetMenuItemCount()):
it = self.FindItemByPosition(i)
it.Enable(value) |
check if all menu items are enabled | def IsEnabled(self, *args, **kwargs):
"check if all menu items are enabled"
for i in range(self.GetMenuItemCount()):
it = self.FindItemByPosition(i)
if not it.IsEnabled():
return False
return True |
Recursively find a menu item by its id ( useful for event handlers ) | def find(self, item_id=None):
"Recursively find a menu item by its id (useful for event handlers)"
for it in self:
if it.id == item_id:
return it
elif isinstance(it, Menu):
found = it.find(item_id)
if found:
... |
enable or disable all top menus | def Enable(self, value):
"enable or disable all top menus"
for i in range(self.GetMenuCount()):
self.EnableTop(i, value) |
check if all top menus are enabled | def IsEnabled(self, *args, **kwargs):
"check if all top menus are enabled"
for i in range(self.GetMenuCount()):
if not self.IsEnabledTop(i):
return False
return True |
Helper method to remove a menu avoiding using its position | def RemoveItem(self, menu):
"Helper method to remove a menu avoiding using its position"
menus = self.GetMenus() # get the list of (menu, title)
menus = [submenu for submenu in menus if submenu[0] != menu]
self.SetMenus(menus) |
Recursively find a menu item by its id ( useful for event handlers ) | def find(self, item_id=None):
"Recursively find a menu item by its id (useful for event handlers)"
for it in self:
found = it.find(item_id)
if found:
return found |
Process form submission | def submit(self, btn=None):
"Process form submission"
data = self.build_data_set()
if btn and btn.name:
data[btn.name] = btn.name
evt = FormSubmitEvent(self, data)
self.container.ProcessEvent(evt) |
Construct a sequence of name/ value pairs from controls | def build_data_set(self):
"Construct a sequence of name/value pairs from controls"
data = {}
for field in self.fields:
if field.name:# and field.enabled: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
val = field.get_value()
if val is None:
... |
Add a tag attribute to the wx window | def setObjectTag(self, object, tag):
""" Add a tag attribute to the wx window """
object._attributes = {}
object._name = tag.GetName().lower()
for name in self.attributes:
object._attributes["_%s" % name] = tag.GetParam(name)
if object._attributes["_%s" % name] ==... |
Insert items described in autosummary:: to the TOC tree but do not generate the toctree:: list. | def process_autosummary_toc(app, doctree):
"""Insert items described in autosummary:: to the TOC tree, but do
not generate the toctree:: list.
"""
env = app.builder.env
crawled = {}
def crawl_toc(node, depth=1):
crawled[node] = True
for j, subnode in enumerate(node):
... |
Make the first column of the table non - breaking. | def autosummary_table_visit_html(self, node):
"""Make the first column of the table non-breaking."""
try:
tbody = node[0][0][-1]
for row in tbody:
col1_entry = row[0]
par = col1_entry[0]
for j, subnode in enumerate(list(par)):
if isinstance(sub... |
Get an autodoc. Documenter class suitable for documenting the given object. | def get_documenter(obj, parent):
"""Get an autodoc.Documenter class suitable for documenting the given
object.
*obj* is the Python object to be documented, and *parent* is an
another Python object (e.g. a module or a class) to which *obj*
belongs to.
"""
from sphinx.ext.autodoc import AutoD... |
Reformat a function signature to a more compact form. | def mangle_signature(sig, max_chars=30):
"""Reformat a function signature to a more compact form."""
s = re.sub(r"^\((.*)\)$", r"\1", sig).strip()
# Strip strings (which can contain things that confuse the code below)
s = re.sub(r"\\\\", "", s)
s = re.sub(r"\\'", "", s)
s = re.sub(r"'[^']*'", "... |
Join a number of strings to one limiting the length to * max_chars *. | def limited_join(sep, items, max_chars=30, overflow_marker="..."):
"""Join a number of strings to one, limiting the length to *max_chars*.
If the string overflows this limit, replace the last fitting item by
*overflow_marker*.
Returns: joined_string
"""
full_str = sep.join(items)
if len(fu... |
Obtain current Python import prefixes ( for import_by_name ) from document. env | def get_import_prefixes_from_env(env):
"""
Obtain current Python import prefixes (for `import_by_name`)
from ``document.env``
"""
prefixes = [None]
currmodule = env.temp_data.get('py:module')
if currmodule:
prefixes.insert(0, currmodule)
currclass = env.temp_data.get('py:class'... |
Import a Python object that has the given * name * under one of the * prefixes *. The first name that succeeds is used. | def import_by_name(name, prefixes=[None]):
"""Import a Python object that has the given *name*, under one of the
*prefixes*. The first name that succeeds is used.
"""
tried = []
for prefix in prefixes:
try:
if prefix:
prefixed_name = '.'.join([prefix, name])
... |
Import a Python object given its full name. | def _import_by_name(name):
"""Import a Python object given its full name."""
try:
name_parts = name.split('.')
# try first interpret `name` as MODNAME.OBJ
modname = '.'.join(name_parts[:-1])
if modname:
try:
__import__(modname)
mod = s... |
Smart linking role. | def autolink_role(typ, rawtext, etext, lineno, inliner,
options={}, content=[]):
"""Smart linking role.
Expands to ':obj:`text`' if `text` is an object that can be imported;
otherwise expands to '*text*'.
"""
env = inliner.document.settings.env
r = env.get_domain('py').role('o... |
Try to import the given names and return a list of [ ( name signature summary_string real_name )... ]. | def get_items(self, names):
"""Try to import the given names, and return a list of
``[(name, signature, summary_string, real_name), ...]``.
"""
env = self.state.document.settings.env
prefixes = get_import_prefixes_from_env(env)
items = []
max_item_chars = 50
... |
Generate a proper list of table nodes for autosummary:: directive. | def get_table(self, items):
"""Generate a proper list of table nodes for autosummary:: directive.
*items* is a list produced by :meth:`get_items`.
"""
table_spec = addnodes.tabular_col_spec()
table_spec['spec'] = 'll'
table = autosummary_table('')
real_table = n... |
Show a simple pop - up modal dialog | def alert(message, title="", parent=None, scrolled=False, icon="exclamation"):
"Show a simple pop-up modal dialog"
if not scrolled:
icons = {'exclamation': wx.ICON_EXCLAMATION, 'error': wx.ICON_ERROR,
'question': wx.ICON_QUESTION, 'info': wx.ICON_INFORMATION}
style = wx.OK | ic... |
Modal dialog asking for an input returns string or None if cancelled | def prompt(message="", title="", default="", multiline=False, password=None,
parent=None):
"Modal dialog asking for an input, returns string or None if cancelled"
if password:
style = wx.TE_PASSWORD | wx.OK | wx.CANCEL
result = dialogs.textEntryDialog(parent, message, title, def... |
Ask for confirmation ( yes/ no or ok and cancel ) returns True or False | def confirm(message="", title="", default=False, ok=False, cancel=False,
parent=None):
"Ask for confirmation (yes/no or ok and cancel), returns True or False"
style = wx.CENTRE
if ok:
style |= wx.OK
else:
style |= wx.YES | wx.NO
if default:
style... |
Show a dialog to select a font | def select_font(message="", title="", font=None, parent=None):
"Show a dialog to select a font"
if font is not None:
wx_font = font._get_wx_font() # use as default
else:
wx_font = None
font = Font() # create an empty font
... |
Show a dialog to pick a color | def select_color(message="", title="", color=None, parent=None):
"Show a dialog to pick a color"
result = dialogs.colorDialog(parent, color=color)
return result.accepted and result.color |
Show a dialog to select files to open return path ( s ) if accepted | def open_file(title="Open", directory='', filename='',
wildcard='All Files (*.*)|*.*', multiple=False, parent=None):
"Show a dialog to select files to open, return path(s) if accepted"
style = wx.OPEN
if multiple:
style |= wx.MULTIPLE
result = dialogs.fileDialog(parent, ti... |
Show a dialog to select file to save return path ( s ) if accepted | def save_file(title="Save", directory='', filename='',
wildcard='All Files (*.*)|*.*', overwrite=False, parent=None):
"Show a dialog to select file to save, return path(s) if accepted"
style = wx.SAVE
if not overwrite:
style |= wx.OVERWRITE_PROMPT
result = dialogs.fileDial... |
Show a dialog to choose a directory | def choose_directory(message='Choose a directory', path="", parent=None):
"Show a dialog to choose a directory"
result = dialogs.directoryDialog(parent, message, path)
return result.path |
Shows a find text dialog | def find(default='', whole_words=0, case_sensitive=0, parent=None):
"Shows a find text dialog"
result = dialogs.findDialog(parent, default, whole_words, case_sensitive)
return {'text': result.searchText, 'whole_words': result.wholeWordsOnly,
'case_sensitive': result.caseSensitive} |
Remove all items and reset internal structures | def clear(self):
"Remove all items and reset internal structures"
dict.clear(self)
self._key = 0
if hasattr(self._tree_view, "wx_obj"):
self._tree_view.wx_obj.DeleteAllItems() |
Force appearance of the button next to the item | def set_has_children(self, has_children=True):
"Force appearance of the button next to the item"
# This is useful to allow the user to expand the items which don't have
# any children now, but instead adding them only when needed, thus
# minimizing memory usage and loading time.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.