desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Inserts a pane at the specified positions.
pos is either the string end, and integer index, or the name
of a child. If child is already managed by the paned window,
moves it to the specified position.'
| def insert(self, pos, child, **kw):
| self.tk.call(self._w, 'insert', pos, child, *_format_optdict(kw))
|
'Query or modify the options of the specified pane.
pane is either an integer index or the name of a managed subwindow.
If kw is not given, returns a dict of the pane option values. If
option is specified then the value for that option is returned.
Otherwise, sets the options to the corresponding values.'
| def pane(self, pane, option=None, **kw):
| if (option is not None):
kw[option] = None
return _val_or_dict(kw, self.tk.call, self._w, 'pane', pane)
|
'If newpos is specified, sets the position of sash number index.
May adjust the positions of adjacent sashes to ensure that
positions are monotonically increasing. Sash positions are further
constrained to be between 0 and the total size of the widget.
Returns the new position of sash number index.'
| def sashpos(self, index, newpos=None):
| return self.tk.call(self._w, 'sashpos', index, newpos)
|
'Construct a Ttk Progressbar with parent master.
STANDARD OPTIONS
class, cursor, style, takefocus
WIDGET-SPECIFIC OPTIONS
orient, length, mode, maximum, value, variable, phase'
| def __init__(self, master=None, **kw):
| Widget.__init__(self, master, 'ttk::progressbar', kw)
|
'Begin autoincrement mode: schedules a recurring timer event
that calls method step every interval milliseconds.
interval defaults to 50 milliseconds (20 steps/second) if ommited.'
| def start(self, interval=None):
| self.tk.call(self._w, 'start', interval)
|
'Increments the value option by amount.
amount defaults to 1.0 if omitted.'
| def step(self, amount=None):
| self.tk.call(self._w, 'step', amount)
|
'Stop autoincrement mode: cancels any recurring timer event
initiated by start.'
| def stop(self):
| self.tk.call(self._w, 'stop')
|
'Construct a Ttk Radiobutton with parent master.
STANDARD OPTIONS
class, compound, cursor, image, state, style, takefocus,
text, textvariable, underline, width
WIDGET-SPECIFIC OPTIONS
command, value, variable'
| def __init__(self, master=None, **kw):
| Widget.__init__(self, master, 'ttk::radiobutton', kw)
|
'Sets the option variable to the option value, selects the
widget, and invokes the associated command.
Returns the result of the command, or an empty string if
no command is specified.'
| def invoke(self):
| return self.tk.call(self._w, 'invoke')
|
'Construct a Ttk Scale with parent master.
STANDARD OPTIONS
class, cursor, style, takefocus
WIDGET-SPECIFIC OPTIONS
command, from, length, orient, to, value, variable'
| def __init__(self, master=None, **kw):
| Widget.__init__(self, master, 'ttk::scale', kw)
|
'Modify or query scale options.
Setting a value for any of the "from", "from_" or "to" options
generates a <<RangeChanged>> event.'
| def configure(self, cnf=None, **kw):
| if cnf:
kw.update(cnf)
Widget.configure(self, **kw)
if any([('from' in kw), ('from_' in kw), ('to' in kw)]):
self.event_generate('<<RangeChanged>>')
|
'Get the current value of the value option, or the value
corresponding to the coordinates x, y if they are specified.
x and y are pixel coordinates relative to the scale widget
origin.'
| def get(self, x=None, y=None):
| return self.tk.call(self._w, 'get', x, y)
|
'Construct a Ttk Scrollbar with parent master.
STANDARD OPTIONS
class, cursor, style, takefocus
WIDGET-SPECIFIC OPTIONS
command, orient'
| def __init__(self, master=None, **kw):
| Widget.__init__(self, master, 'ttk::scrollbar', kw)
|
'Construct a Ttk Separator with parent master.
STANDARD OPTIONS
class, cursor, style, takefocus
WIDGET-SPECIFIC OPTIONS
orient'
| def __init__(self, master=None, **kw):
| Widget.__init__(self, master, 'ttk::separator', kw)
|
'Construct a Ttk Sizegrip with parent master.
STANDARD OPTIONS
class, cursor, state, style, takefocus'
| def __init__(self, master=None, **kw):
| Widget.__init__(self, master, 'ttk::sizegrip', kw)
|
'Construct a Ttk Treeview with parent master.
STANDARD OPTIONS
class, cursor, style, takefocus, xscrollcommand,
yscrollcommand
WIDGET-SPECIFIC OPTIONS
columns, displaycolumns, height, padding, selectmode, show
ITEM OPTIONS
text, image, values, open, tags
TAG OPTIONS
foreground, background, font, image'
| def __init__(self, master=None, **kw):
| Widget.__init__(self, master, 'ttk::treeview', kw)
|
'Returns the bounding box (relative to the treeview widget\'s
window) of the specified item in the form x y width height.
If column is specified, returns the bounding box of that cell.
If the item is not visible (i.e., if it is a descendant of a
closed item or is scrolled offscreen), returns an empty string.'
| def bbox(self, item, column=None):
| return self.tk.call(self._w, 'bbox', item, column)
|
'Returns a tuple of children belonging to item.
If item is not specified, returns root children.'
| def get_children(self, item=None):
| return (self.tk.call(self._w, 'children', (item or '')) or ())
|
'Replaces item\'s child with newchildren.
Children present in item that are not present in newchildren
are detached from tree. No items in newchildren may be an
ancestor of item.'
| def set_children(self, item, *newchildren):
| self.tk.call(self._w, 'children', item, newchildren)
|
'Query or modify the options for the specified column.
If kw is not given, returns a dict of the column option values. If
option is specified then the value for that option is returned.
Otherwise, sets the options to the corresponding values.'
| def column(self, column, option=None, **kw):
| if (option is not None):
kw[option] = None
return _val_or_dict(kw, self.tk.call, self._w, 'column', column)
|
'Delete all specified items and all their descendants. The root
item may not be deleted.'
| def delete(self, *items):
| self.tk.call(self._w, 'delete', items)
|
'Unlinks all of the specified items from the tree.
The items and all of their descendants are still present, and may
be reinserted at another point in the tree, but will not be
displayed. The root item may not be detached.'
| def detach(self, *items):
| self.tk.call(self._w, 'detach', items)
|
'Returns True if the specified item is present in the three,
False otherwise.'
| def exists(self, item):
| return bool(self.tk.call(self._w, 'exists', item))
|
'If item is specified, sets the focus item to item. Otherwise,
returns the current focus item, or \'\' if there is none.'
| def focus(self, item=None):
| return self.tk.call(self._w, 'focus', item)
|
'Query or modify the heading options for the specified column.
If kw is not given, returns a dict of the heading option values. If
option is specified then the value for that option is returned.
Otherwise, sets the options to the corresponding values.
Valid options/values are:
text: text
The text to display in the column heading
image: image_name
Specifies an image to display to the right of the column
heading
anchor: anchor
Specifies how the heading text should be aligned. One of
the standard Tk anchor values
command: callback
A callback to be invoked when the heading label is
pressed.
To configure the tree column heading, call this with column = "#0"'
| def heading(self, column, option=None, **kw):
| cmd = kw.get('command')
if (cmd and (not isinstance(cmd, basestring))):
kw['command'] = self.master.register(cmd, self._substitute)
if (option is not None):
kw[option] = None
return _val_or_dict(kw, self.tk.call, self._w, 'heading', column)
|
'Returns a description of the specified component under the
point given by x and y, or the empty string if no such component
is present at that position.'
| def identify(self, component, x, y):
| return self.tk.call(self._w, 'identify', component, x, y)
|
'Returns the item ID of the item at position y.'
| def identify_row(self, y):
| return self.identify('row', 0, y)
|
'Returns the data column identifier of the cell at position x.
The tree column has ID #0.'
| def identify_column(self, x):
| return self.identify('column', x, 0)
|
'Returns one of:
heading: Tree heading area.
separator: Space between two columns headings;
tree: The tree area.
cell: A data cell.
* Availability: Tk 8.6'
| def identify_region(self, x, y):
| return self.identify('region', x, y)
|
'Returns the element at position x, y.
* Availability: Tk 8.6'
| def identify_element(self, x, y):
| return self.identify('element', x, y)
|
'Returns the integer index of item within its parent\'s list
of children.'
| def index(self, item):
| return self.tk.call(self._w, 'index', item)
|
'Creates a new item and return the item identifier of the newly
created item.
parent is the item ID of the parent item, or the empty string
to create a new top-level item. index is an integer, or the value
end, specifying where in the list of parent\'s children to insert
the new item. If index is less than or equal to zero, the new node
is inserted at the beginning, if index is greater than or equal to
the current number of children, it is inserted at the end. If iid
is specified, it is used as the item identifier, iid must not
already exist in the tree. Otherwise, a new unique identifier
is generated.'
| def insert(self, parent, index, iid=None, **kw):
| opts = _format_optdict(kw)
if iid:
res = self.tk.call(self._w, 'insert', parent, index, '-id', iid, *opts)
else:
res = self.tk.call(self._w, 'insert', parent, index, *opts)
return res
|
'Query or modify the options for the specified item.
If no options are given, a dict with options/values for the item
is returned. If option is specified then the value for that option
is returned. Otherwise, sets the options to the corresponding
values as given by kw.'
| def item(self, item, option=None, **kw):
| if (option is not None):
kw[option] = None
return _val_or_dict(kw, self.tk.call, self._w, 'item', item)
|
'Moves item to position index in parent\'s list of children.
It is illegal to move an item under one of its descendants. If
index is less than or equal to zero, item is moved to the
beginning, if greater than or equal to the number of children,
it is moved to the end. If item was detached it is reattached.'
| def move(self, item, parent, index):
| self.tk.call(self._w, 'move', item, parent, index)
|
'Returns the identifier of item\'s next sibling, or \'\' if item
is the last child of its parent.'
| def next(self, item):
| return self.tk.call(self._w, 'next', item)
|
'Returns the ID of the parent of item, or \'\' if item is at the
top level of the hierarchy.'
| def parent(self, item):
| return self.tk.call(self._w, 'parent', item)
|
'Returns the identifier of item\'s previous sibling, or \'\' if
item is the first child of its parent.'
| def prev(self, item):
| return self.tk.call(self._w, 'prev', item)
|
'Ensure that item is visible.
Sets all of item\'s ancestors open option to True, and scrolls
the widget if necessary so that item is within the visible
portion of the tree.'
| def see(self, item):
| self.tk.call(self._w, 'see', item)
|
'If selop is not specified, returns selected items.'
| def selection(self, selop=None, items=None):
| return self.tk.call(self._w, 'selection', selop, items)
|
'items becomes the new selection.'
| def selection_set(self, items):
| self.selection('set', items)
|
'Add items to the selection.'
| def selection_add(self, items):
| self.selection('add', items)
|
'Remove items from the selection.'
| def selection_remove(self, items):
| self.selection('remove', items)
|
'Toggle the selection state of each item in items.'
| def selection_toggle(self, items):
| self.selection('toggle', items)
|
'With one argument, returns a dictionary of column/value pairs
for the specified item. With two arguments, returns the current
value of the specified column. With three arguments, sets the
value of given column in given item to the specified value.'
| def set(self, item, column=None, value=None):
| res = self.tk.call(self._w, 'set', item, column, value)
if ((column is None) and (value is None)):
return _dict_from_tcltuple(res, False)
else:
return res
|
'Bind a callback for the given event sequence to the tag tagname.
When an event is delivered to an item, the callbacks for each
of the item\'s tags option are called.'
| def tag_bind(self, tagname, sequence=None, callback=None):
| self._bind((self._w, 'tag', 'bind', tagname), sequence, callback, add=0)
|
'Query or modify the options for the specified tagname.
If kw is not given, returns a dict of the option settings for tagname.
If option is specified, returns the value for that option for the
specified tagname. Otherwise, sets the options to the corresponding
values for the given tagname.'
| def tag_configure(self, tagname, option=None, **kw):
| if (option is not None):
kw[option] = None
return _val_or_dict(kw, self.tk.call, self._w, 'tag', 'configure', tagname)
|
'If item is specified, returns 1 or 0 depending on whether the
specified item has the given tagname. Otherwise, returns a list of
all items which have the specified tag.
* Availability: Tk 8.6'
| def tag_has(self, tagname, item=None):
| return self.tk.call(self._w, 'tag', 'has', tagname, item)
|
'Construct an horizontal LabeledScale with parent master, a
variable to be associated with the Ttk Scale widget and its range.
If variable is not specified, a Tkinter.IntVar is created.
WIDGET-SPECIFIC OPTIONS
compound: \'top\' or \'bottom\'
Specifies how to display the label relative to the scale.
Defaults to \'top\'.'
| def __init__(self, master=None, variable=None, from_=0, to=10, **kw):
| self._label_top = (kw.pop('compound', 'top') == 'top')
Frame.__init__(self, master, **kw)
self._variable = (variable or Tkinter.IntVar(master))
self._variable.set(from_)
self._last_valid = from_
self.label = Label(self)
self.scale = Scale(self, variable=self._variable, from_=from_, to=to)
self.scale.bind('<<RangeChanged>>', self._adjust)
scale_side = ('bottom' if self._label_top else 'top')
label_side = ('top' if (scale_side == 'bottom') else 'bottom')
self.scale.pack(side=scale_side, fill='x')
tmp = Label(self).pack(side=label_side)
self.label.place(anchor=('n' if (label_side == 'top') else 's'))
self.__tracecb = self._variable.trace_variable('w', self._adjust)
self.bind('<Configure>', self._adjust)
self.bind('<Map>', self._adjust)
|
'Destroy this widget and possibly its associated variable.'
| def destroy(self):
| try:
self._variable.trace_vdelete('w', self.__tracecb)
except AttributeError:
pass
else:
del self._variable
Frame.destroy(self)
|
'Adjust the label position according to the scale.'
| def _adjust(self, *args):
| def adjust_label():
self.update_idletasks()
(x, y) = self.scale.coords()
if self._label_top:
y = (self.scale.winfo_y() - self.label.winfo_reqheight())
else:
y = (self.scale.winfo_reqheight() + self.label.winfo_reqheight())
self.label.place_configure(x=x, y=y)
(from_, to) = (self.scale['from'], self.scale['to'])
if (to < from_):
(from_, to) = (to, from_)
newval = self._variable.get()
if (not (from_ <= newval <= to)):
self.value = self._last_valid
return
self._last_valid = newval
self.label['text'] = newval
self.after_idle(adjust_label)
|
'Return current scale value.'
| def _get_value(self):
| return self._variable.get()
|
'Set new scale value.'
| def _set_value(self, val):
| self._variable.set(val)
|
'Construct a themed OptionMenu widget with master as the parent,
the resource textvariable set to variable, the initially selected
value specified by the default parameter, the menu values given by
*values and additional keywords.
WIDGET-SPECIFIC OPTIONS
style: stylename
Menubutton style.
direction: \'above\', \'below\', \'left\', \'right\', or \'flush\'
Menubutton direction.
command: callback
A callback that will be invoked after selecting an item.'
| def __init__(self, master, variable, default=None, *values, **kwargs):
| kw = {'textvariable': variable, 'style': kwargs.pop('style', None), 'direction': kwargs.pop('direction', None)}
Menubutton.__init__(self, master, **kw)
self['menu'] = Tkinter.Menu(self, tearoff=False)
self._variable = variable
self._callback = kwargs.pop('command', None)
if kwargs:
raise Tkinter.TclError(('unknown option -%s' % kwargs.iterkeys().next()))
self.set_menu(default, *values)
|
'Build a new menu of radiobuttons with *values and optionally
a default value.'
| def set_menu(self, default=None, *values):
| menu = self['menu']
menu.delete(0, 'end')
for val in values:
menu.add_radiobutton(label=val, command=Tkinter._setit(self._variable, val, self._callback))
if default:
self._variable.set(default)
|
'Destroy this widget and its associated variable.'
| def destroy(self):
| del self._variable
Menubutton.destroy(self)
|
'Initialize a dialog.
Arguments:
parent -- a parent window (the application window)
title -- the dialog title'
| def __init__(self, parent, title=None):
| Toplevel.__init__(self, parent)
self.withdraw()
if parent.winfo_viewable():
self.transient(parent)
if title:
self.title(title)
self.parent = parent
self.result = None
body = Frame(self)
self.initial_focus = self.body(body)
body.pack(padx=5, pady=5)
self.buttonbox()
if (not self.initial_focus):
self.initial_focus = self
self.protocol('WM_DELETE_WINDOW', self.cancel)
if (self.parent is not None):
self.geometry(('+%d+%d' % ((parent.winfo_rootx() + 50), (parent.winfo_rooty() + 50))))
self.deiconify()
self.initial_focus.focus_set()
self.wait_visibility()
self.grab_set()
self.wait_window(self)
|
'Destroy the window'
| def destroy(self):
| self.initial_focus = None
Toplevel.destroy(self)
|
'create dialog body.
return widget that should have initial focus.
This method should be overridden, and is called
by the __init__ method.'
| def body(self, master):
| pass
|
'add standard button box.
override if you do not want the standard buttons'
| def buttonbox(self):
| box = Frame(self)
w = Button(box, text='OK', width=10, command=self.ok, default=ACTIVE)
w.pack(side=LEFT, padx=5, pady=5)
w = Button(box, text='Cancel', width=10, command=self.cancel)
w.pack(side=LEFT, padx=5, pady=5)
self.bind('<Return>', self.ok)
self.bind('<Escape>', self.cancel)
box.pack()
|
'validate the data
This method is called automatically to validate the data before the
dialog is destroyed. By default, it always validates OK.'
| def validate(self):
| return 1
|
'process the data
This method is called automatically to process the data, *after*
the dialog is destroyed. By default, it does nothing.'
| def apply(self):
| pass
|
'_munge_whitespace(text : string) -> string
Munge whitespace in text: expand tabs and convert all other
whitespace characters to spaces. Eg. " foo bar
baz"
becomes " foo bar baz".'
| def _munge_whitespace(self, text):
| if self.expand_tabs:
text = text.expandtabs()
if self.replace_whitespace:
if isinstance(text, str):
text = text.translate(self.whitespace_trans)
elif isinstance(text, unicode):
text = text.translate(self.unicode_whitespace_trans)
return text
|
'_split(text : string) -> [string]
Split the text to wrap into indivisible chunks. Chunks are
not quite the same as words; see _wrap_chunks() for full
details. As an example, the text
Look, goof-ball -- use the -b option!
breaks into the following chunks:
\'Look,\', \' \', \'goof-\', \'ball\', \' \', \'--\', \' \',
\'use\', \' \', \'the\', \' \', \'-b\', \' \', \'option!\'
if break_on_hyphens is True, or in:
\'Look,\', \' \', \'goof-ball\', \' \', \'--\', \' \',
\'use\', \' \', \'the\', \' \', \'-b\', \' \', option!\'
otherwise.'
| def _split(self, text):
| if isinstance(text, unicode):
if self.break_on_hyphens:
pat = self.wordsep_re_uni
else:
pat = self.wordsep_simple_re_uni
elif self.break_on_hyphens:
pat = self.wordsep_re
else:
pat = self.wordsep_simple_re
chunks = pat.split(text)
chunks = filter(None, chunks)
return chunks
|
'_fix_sentence_endings(chunks : [string])
Correct for sentence endings buried in \'chunks\'. Eg. when the
original text contains "... foo.
Bar ...", munge_whitespace()
and split() will convert that to [..., "foo.", " ", "Bar", ...]
which has one too few spaces; this method simply changes the one
space to two.'
| def _fix_sentence_endings(self, chunks):
| i = 0
patsearch = self.sentence_end_re.search
while (i < (len(chunks) - 1)):
if ((chunks[(i + 1)] == ' ') and patsearch(chunks[i])):
chunks[(i + 1)] = ' '
i += 2
else:
i += 1
|
'_handle_long_word(chunks : [string],
cur_line : [string],
cur_len : int, width : int)
Handle a chunk of text (most likely a word, not whitespace) that
is too long to fit in any line.'
| def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
| if (width < 1):
space_left = 1
else:
space_left = (width - cur_len)
if self.break_long_words:
cur_line.append(reversed_chunks[(-1)][:space_left])
reversed_chunks[(-1)] = reversed_chunks[(-1)][space_left:]
elif (not cur_line):
cur_line.append(reversed_chunks.pop())
|
'_wrap_chunks(chunks : [string]) -> [string]
Wrap a sequence of text chunks and return a list of lines of
length \'self.width\' or less. (If \'break_long_words\' is false,
some lines may be longer than this.) Chunks correspond roughly
to words and the whitespace between them: each chunk is
indivisible (modulo \'break_long_words\'), but a line break can
come between any two chunks. Chunks should not have internal
whitespace; ie. a chunk is either all whitespace or a "word".
Whitespace chunks will be removed from the beginning and end of
lines, but apart from that whitespace is preserved.'
| def _wrap_chunks(self, chunks):
| lines = []
if (self.width <= 0):
raise ValueError(('invalid width %r (must be > 0)' % self.width))
chunks.reverse()
while chunks:
cur_line = []
cur_len = 0
if lines:
indent = self.subsequent_indent
else:
indent = self.initial_indent
width = (self.width - len(indent))
if (self.drop_whitespace and (chunks[(-1)].strip() == '') and lines):
del chunks[(-1)]
while chunks:
l = len(chunks[(-1)])
if ((cur_len + l) <= width):
cur_line.append(chunks.pop())
cur_len += l
else:
break
if (chunks and (len(chunks[(-1)]) > width)):
self._handle_long_word(chunks, cur_line, cur_len, width)
if (self.drop_whitespace and cur_line and (cur_line[(-1)].strip() == '')):
del cur_line[(-1)]
if cur_line:
lines.append((indent + ''.join(cur_line)))
return lines
|
'wrap(text : string) -> [string]
Reformat the single paragraph in \'text\' so it fits in lines of
no more than \'self.width\' columns, and return a list of wrapped
lines. Tabs in \'text\' are expanded with string.expandtabs(),
and all other whitespace characters (including newline) are
converted to space.'
| def wrap(self, text):
| text = self._munge_whitespace(text)
chunks = self._split(text)
if self.fix_sentence_endings:
self._fix_sentence_endings(chunks)
return self._wrap_chunks(chunks)
|
'fill(text : string) -> string
Reformat the single paragraph in \'text\' to fit in lines of no
more than \'self.width\' columns, and return a new string
containing the entire wrapped paragraph.'
| def fill(self, text):
| return '\n'.join(self.wrap(text))
|
'Mark up some plain text, given a context of symbols to look for.
Each context dictionary maps object names to anchor names.'
| def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
| escape = (escape or self.escape)
results = []
here = 0
pattern = re.compile('\\b((http|ftp)://\\S+[\\w/]|RFC[- ]?(\\d+)|PEP[- ]?(\\d+)|(self\\.)?((?:\\w|\\.)+))\\b')
while 1:
match = pattern.search(text, here)
if (not match):
break
(start, end) = match.span()
results.append(escape(text[here:start]))
(all, scheme, rfc, pep, selfdot, name) = match.groups()
if scheme:
url = escape(all).replace('"', '"')
results.append(('<a href="%s">%s</a>' % (url, url)))
elif rfc:
url = ('http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc))
results.append(('<a href="%s">%s</a>' % (url, escape(all))))
elif pep:
url = ('http://www.python.org/dev/peps/pep-%04d/' % int(pep))
results.append(('<a href="%s">%s</a>' % (url, escape(all))))
elif (text[end:(end + 1)] == '('):
results.append(self.namelink(name, methods, funcs, classes))
elif selfdot:
results.append(('self.<strong>%s</strong>' % name))
else:
results.append(self.namelink(name, classes))
here = end
results.append(escape(text[here:]))
return ''.join(results)
|
'Produce HTML documentation for a function or method object.'
| def docroutine(self, object, name, mod=None, funcs={}, classes={}, methods={}, cl=None):
| anchor = ((((cl and cl.__name__) or '') + '-') + name)
note = ''
title = ('<a name="%s"><strong>%s</strong></a>' % (self.escape(anchor), self.escape(name)))
if inspect.ismethod(object):
(args, varargs, varkw, defaults) = inspect.getargspec(object.im_func)
argspec = inspect.formatargspec(args[1:], varargs, varkw, defaults, formatvalue=self.formatvalue)
elif inspect.isfunction(object):
(args, varargs, varkw, defaults) = inspect.getargspec(object)
argspec = inspect.formatargspec(args, varargs, varkw, defaults, formatvalue=self.formatvalue)
else:
argspec = '(...)'
if isinstance(object, tuple):
argspec = (object[0] or argspec)
docstring = (object[1] or '')
else:
docstring = pydoc.getdoc(object)
decl = ((title + argspec) + (note and self.grey(('<font face="helvetica, arial">%s</font>' % note))))
doc = self.markup(docstring, self.preformat, funcs, classes, methods)
doc = (doc and ('<dd><tt>%s</tt></dd>' % doc))
return ('<dl><dt>%s</dt>%s</dl>\n' % (decl, doc))
|
'Produce HTML documentation for an XML-RPC server.'
| def docserver(self, server_name, package_documentation, methods):
| fdict = {}
for (key, value) in methods.items():
fdict[key] = ('#-' + key)
fdict[value] = fdict[key]
server_name = self.escape(server_name)
head = ('<big><big><strong>%s</strong></big></big>' % server_name)
result = self.heading(head, '#ffffff', '#7799ee')
doc = self.markup(package_documentation, self.preformat, fdict)
doc = (doc and ('<tt>%s</tt>' % doc))
result = (result + ('<p>%s</p>\n' % doc))
contents = []
method_items = sorted(methods.items())
for (key, value) in method_items:
contents.append(self.docroutine(value, key, funcs=fdict))
result = (result + self.bigsection('Methods', '#ffffff', '#eeaa77', pydoc.join(contents)))
return result
|
'Set the HTML title of the generated server documentation'
| def set_server_title(self, server_title):
| self.server_title = server_title
|
'Set the name of the generated HTML server documentation'
| def set_server_name(self, server_name):
| self.server_name = server_name
|
'Set the documentation string for the entire server.'
| def set_server_documentation(self, server_documentation):
| self.server_documentation = server_documentation
|
'generate_html_documentation() => html documentation for the server
Generates HTML documentation for the server using introspection for
installed functions and instances that do not implement the
_dispatch method. Alternatively, instances can choose to implement
the _get_method_argstring(method_name) method to provide the
argument string used in the documentation and the
_methodHelp(method_name) method to provide the help text used
in the documentation.'
| def generate_html_documentation(self):
| methods = {}
for method_name in self.system_listMethods():
if (method_name in self.funcs):
method = self.funcs[method_name]
elif (self.instance is not None):
method_info = [None, None]
if hasattr(self.instance, '_get_method_argstring'):
method_info[0] = self.instance._get_method_argstring(method_name)
if hasattr(self.instance, '_methodHelp'):
method_info[1] = self.instance._methodHelp(method_name)
method_info = tuple(method_info)
if (method_info != (None, None)):
method = method_info
elif (not hasattr(self.instance, '_dispatch')):
try:
method = resolve_dotted_attribute(self.instance, method_name)
except AttributeError:
method = method_info
else:
method = method_info
else:
assert 0, 'Could not find method in self.functions and no instance installed'
methods[method_name] = method
documenter = ServerHTMLDoc()
documentation = documenter.docserver(self.server_name, self.server_documentation, methods)
return documenter.page(self.server_title, documentation)
|
'Handles the HTTP GET request.
Interpret all HTTP GET requests as requests for server
documentation.'
| def do_GET(self):
| if (not self.is_rpc_path_valid()):
self.report_404()
return
response = self.server.generate_html_documentation()
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.send_header('Content-length', str(len(response)))
self.end_headers()
self.wfile.write(response)
|
'Handles the HTTP GET request.
Interpret all HTTP GET requests as requests for server
documentation.'
| def handle_get(self):
| response = self.generate_html_documentation()
print 'Content-Type: text/html'
print ('Content-Length: %d' % len(response))
print
sys.stdout.write(response)
|
'Read at least wtd bytes (or until EOF)'
| def read(self, totalwtd):
| decdata = ''
wtd = totalwtd
while (wtd > 0):
if self.eof:
return decdata
wtd = (((wtd + 2) // 3) * 4)
data = self.ifp.read(wtd)
while 1:
try:
(decdatacur, self.eof) = binascii.a2b_hqx(data)
break
except binascii.Incomplete:
pass
newdata = self.ifp.read(1)
if (not newdata):
raise Error, 'Premature EOF on binhex file'
data = (data + newdata)
decdata = (decdata + decdatacur)
wtd = (totalwtd - len(decdata))
if ((not decdata) and (not self.eof)):
raise Error, 'Premature EOF on binhex file'
return decdata
|
'Initialize and reset this instance.'
| def __init__(self, verbose=0):
| self.verbose = verbose
self.reset()
|
'Reset this instance. Loses all unprocessed data.'
| def reset(self):
| self.__starttag_text = None
self.rawdata = ''
self.stack = []
self.lasttag = '???'
self.nomoretags = 0
self.literal = 0
markupbase.ParserBase.reset(self)
|
'Enter literal mode (CDATA) till EOF.
Intended for derived classes only.'
| def setnomoretags(self):
| self.nomoretags = self.literal = 1
|
'Enter literal mode (CDATA).
Intended for derived classes only.'
| def setliteral(self, *args):
| self.literal = 1
|
'Feed some data to the parser.
Call this as often as you want, with as little or as much text
as you want (may include \'
\'). (This just saves the text,
all the processing is done by goahead().)'
| def feed(self, data):
| self.rawdata = (self.rawdata + data)
self.goahead(0)
|
'Handle the remaining data.'
| def close(self):
| self.goahead(1)
|
'Convert character reference, may be overridden.'
| def convert_charref(self, name):
| try:
n = int(name)
except ValueError:
return
if (not (0 <= n <= 127)):
return
return self.convert_codepoint(n)
|
'Handle character reference, no need to override.'
| def handle_charref(self, name):
| replacement = self.convert_charref(name)
if (replacement is None):
self.unknown_charref(name)
else:
self.handle_data(replacement)
|
'Convert entity references.
As an alternative to overriding this method; one can tailor the
results by setting up the self.entitydefs mapping appropriately.'
| def convert_entityref(self, name):
| table = self.entitydefs
if (name in table):
return table[name]
else:
return
|
'Handle entity references, no need to override.'
| def handle_entityref(self, name):
| replacement = self.convert_entityref(name)
if (replacement is None):
self.unknown_entityref(name)
else:
self.handle_data(replacement)
|
'Create the generator for message flattening.
outfp is the output file-like object for writing the message to. It
must have a write() method.
Optional mangle_from_ is a flag that, when True (the default), escapes
From_ lines in the body of the message by putting a `>\' in front of
them.
Optional maxheaderlen specifies the longest length for a non-continued
header. When a header line is longer (in characters, with tabs
expanded to 8 spaces) than maxheaderlen, the header will split as
defined in the Header class. Set maxheaderlen to zero to disable
header wrapping. The default is 78, as recommended (but not required)
by RFC 2822.'
| def __init__(self, outfp, mangle_from_=True, maxheaderlen=78):
| self._fp = outfp
self._mangle_from_ = mangle_from_
self._maxheaderlen = maxheaderlen
|
'Print the message object tree rooted at msg to the output file
specified when the Generator instance was created.
unixfrom is a flag that forces the printing of a Unix From_ delimiter
before the first object in the message tree. If the original message
has no From_ delimiter, a `standard\' one is crafted. By default, this
is False to inhibit the printing of any From_ delimiter.
Note that for subobjects, no From_ line is printed.'
| def flatten(self, msg, unixfrom=False):
| if unixfrom:
ufrom = msg.get_unixfrom()
if (not ufrom):
ufrom = ('From nobody ' + time.ctime(time.time()))
print >>self._fp, ufrom
self._write(msg)
|
'Clone this generator with the exact same options.'
| def clone(self, fp):
| return self.__class__(fp, self._mangle_from_, self._maxheaderlen)
|
'Like Generator.__init__() except that an additional optional
argument is allowed.
Walks through all subparts of a message. If the subpart is of main
type `text\', then it prints the decoded payload of the subpart.
Otherwise, fmt is a format string that is used instead of the message
payload. fmt is expanded with the following keywords (in
%(keyword)s format):
type : Full MIME type of the non-text part
maintype : Main MIME type of the non-text part
subtype : Sub-MIME type of the non-text part
filename : Filename of the non-text part
description: Description associated with the non-text part
encoding : Content transfer encoding of the non-text part
The default value for fmt is None, meaning
[Non-text (%(type)s) part of message omitted, filename %(filename)s]'
| def __init__(self, outfp, mangle_from_=True, maxheaderlen=78, fmt=None):
| Generator.__init__(self, outfp, mangle_from_, maxheaderlen)
if (fmt is None):
self._fmt = _FMT
else:
self._fmt = fmt
|
'Parser of RFC 2822 and MIME email messages.
Creates an in-memory object tree representing the email message, which
can then be manipulated and turned over to a Generator to return the
textual representation of the message.
The string must be formatted as a block of RFC 2822 headers and header
continuation lines, optionally preceeded by a `Unix-from\' header. The
header block is terminated either by the end of the string or by a
blank line.
_class is the class to instantiate for new message objects when they
must be created. This class must have a constructor that can take
zero arguments. Default is Message.Message.'
| def __init__(self, *args, **kws):
| if (len(args) >= 1):
if ('_class' in kws):
raise TypeError("Multiple values for keyword arg '_class'")
kws['_class'] = args[0]
if (len(args) == 2):
if ('strict' in kws):
raise TypeError("Multiple values for keyword arg 'strict'")
kws['strict'] = args[1]
if (len(args) > 2):
raise TypeError('Too many arguments')
if ('_class' in kws):
self._class = kws['_class']
del kws['_class']
else:
self._class = Message
if ('strict' in kws):
warnings.warn("'strict' argument is deprecated (and ignored)", DeprecationWarning, 2)
del kws['strict']
if kws:
raise TypeError('Unexpected keyword arguments')
|
'Create a message structure from the data in a file.
Reads all the data from the file and returns the root of the message
structure. Optional headersonly is a flag specifying whether to stop
parsing after reading the headers or not. The default is False,
meaning it parses the entire contents of the file.'
| def parse(self, fp, headersonly=False):
| feedparser = FeedParser(self._class)
if headersonly:
feedparser._set_headersonly()
while True:
data = fp.read(8192)
if (not data):
break
feedparser.feed(data)
return feedparser.close()
|
'Create a message structure from a string.
Returns the root of the message structure. Optional headersonly is a
flag specifying whether to stop parsing after reading the headers or
not. The default is False, meaning it parses the entire contents of
the file.'
| def parsestr(self, text, headersonly=False):
| return self.parse(StringIO(text), headersonly=headersonly)
|
'Push some new data into this object.'
| def push(self, data):
| (data, self._partial) = ((self._partial + data), '')
parts = NLCRE_crack.split(data)
self._partial = parts.pop()
if ((not self._partial) and parts and parts[(-1)].endswith('\r')):
self._partial = (parts.pop((-2)) + parts.pop())
lines = []
for i in range((len(parts) // 2)):
lines.append((parts[(i * 2)] + parts[((i * 2) + 1)]))
self.pushlines(lines)
|
'_factory is called with no arguments to create a new message obj'
| def __init__(self, _factory=message.Message):
| self._factory = _factory
self._input = BufferedSubFile()
self._msgstack = []
self._parse = self._parsegen().next
self._cur = None
self._last = None
self._headersonly = False
|
'Push more data into the parser.'
| def feed(self, data):
| self._input.push(data)
self._call_parse()
|
'Parse all remaining data and return the root message object.'
| def close(self):
| self._input.close()
self._call_parse()
root = self._pop_message()
assert (not self._msgstack)
if ((root.get_content_maintype() == 'multipart') and (not root.is_multipart())):
root.defects.append(errors.MultipartInvariantViolationDefect())
return root
|
'Initialize a new instance.
`field\' is an unparsed address header field, containing
one or more addresses.'
| def __init__(self, field):
| self.specials = '()<>@,:;."[]'
self.pos = 0
self.LWS = ' DCTB '
self.CR = '\r\n'
self.FWS = (self.LWS + self.CR)
self.atomends = ((self.specials + self.LWS) + self.CR)
self.phraseends = self.atomends.replace('.', '')
self.field = field
self.commentlist = []
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.