desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'True if client can accept status and headers'
| def client_is_modern(self):
| return (self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9')
|
'Log the \'exc_info\' tuple in the server log
Subclasses may override to retarget the output or change its format.'
| def log_exception(self, exc_info):
| try:
from traceback import print_exception
stderr = self.get_stderr()
print_exception(exc_info[0], exc_info[1], exc_info[2], self.traceback_limit, stderr)
stderr.flush()
finally:
exc_info = None
|
'Log current error, and send error output to client if possible'
| def handle_error(self):
| self.log_exception(sys.exc_info())
if (not self.headers_sent):
self.result = self.error_output(self.environ, self.start_response)
self.finish_response()
|
'WSGI mini-app to create error output
By default, this just uses the \'error_status\', \'error_headers\',
and \'error_body\' attributes to generate an output page. It can
be overridden in a subclass to dynamically generate diagnostics,
choose an appropriate message for the user\'s preferred language, etc.
Note, howeve... | def error_output(self, environ, start_response):
| start_response(self.error_status, self.error_headers[:], sys.exc_info())
return [self.error_body]
|
'Override in subclass to buffer data for send to client
It\'s okay if this method actually transmits the data; BaseHandler
just separates write and flush operations for greater efficiency
when the underlying system actually has such a distinction.'
| def _write(self, data):
| raise NotImplementedError
|
'Override in subclass to force sending of recent \'_write()\' calls
It\'s okay if this method is a no-op (i.e., if \'_write()\' actually
sends the data.'
| def _flush(self):
| raise NotImplementedError
|
'Override in subclass to return suitable \'wsgi.input\''
| def get_stdin(self):
| raise NotImplementedError
|
'Override in subclass to return suitable \'wsgi.errors\''
| def get_stderr(self):
| raise NotImplementedError
|
'Override in subclass to insert CGI variables in \'self.environ\''
| def add_cgi_vars(self):
| raise NotImplementedError
|
'Override this method to support alternative .mo formats.'
| def _parse(self, fp):
| unpack = struct.unpack
filename = getattr(fp, 'name', '')
self._catalog = catalog = {}
self.plural = (lambda n: int((n != 1)))
buf = fp.read()
buflen = len(buf)
magic = unpack('<I', buf[:4])[0]
if (magic == self.LE_MAGIC):
(version, msgcount, masteridx, transidx) = unpack('<4I', ... |
'This tests the improved concurrency with pysqlite 2.3.4. You needed
to roll back con2 before you could commit con1.'
| def CheckLocking(self):
| if (sqlite.sqlite_version_info < (3, 2, 2)):
return
self.cur1.execute('create table test(i)')
self.cur1.execute('insert into test(i) values (5)')
try:
self.cur2.execute('insert into test(i) values (5)')
self.fail('should have raised an Op... |
'Checks if cursors on the connection are set into a "reset" state
when a rollback is done on the connection.'
| def CheckRollbackCursorConsistency(self):
| con = sqlite.connect(':memory:')
cur = con.cursor()
cur.execute('create table test(x)')
cur.execute('insert into test(x) values (5)')
cur.execute('select 1 union select 2 union select 3')
con.rollback()
try:
cur.fetchall()
self.fail('Int... |
'Checks if the row object is iterable'
| def CheckSqliteRowIter(self):
| self.con.row_factory = sqlite.Row
row = self.con.execute('select 1 as a, 2 as b').fetchone()
for col in row:
pass
|
'Checks if the row object can be converted to a tuple'
| def CheckSqliteRowAsTuple(self):
| self.con.row_factory = sqlite.Row
row = self.con.execute('select 1 as a, 2 as b').fetchone()
t = tuple(row)
self.assertEqual(t, (row['a'], row['b']))
|
'Checks if the row object can be correctly converted to a dictionary'
| def CheckSqliteRowAsDict(self):
| self.con.row_factory = sqlite.Row
row = self.con.execute('select 1 as a, 2 as b').fetchone()
d = dict(row)
self.assertEqual(d['a'], row['a'])
self.assertEqual(d['b'], row['b'])
|
'Checks if the row object compares and hashes correctly'
| def CheckSqliteRowHashCmp(self):
| self.con.row_factory = sqlite.Row
row_1 = self.con.execute('select 1 as a, 2 as b').fetchone()
row_2 = self.con.execute('select 1 as a, 2 as b').fetchone()
row_3 = self.con.execute('select 1 as a, 3 as b').fetchone()
self.assertEqual(row_1, row_1... |
'Checks if the row object can act like a sequence'
| def CheckSqliteRowAsSequence(self):
| self.con.row_factory = sqlite.Row
row = self.con.execute('select 1 as a, 2 as b').fetchone()
as_tuple = tuple(row)
self.assertEqual(list(reversed(row)), list(reversed(as_tuple)))
self.assertIsInstance(row, Sequence)
|
'A commit should also work when no changes were made to the database.'
| def CheckCommitAfterNoChanges(self):
| self.cx.commit()
self.cx.commit()
|
'A rollback should also work when no changes were made to the database.'
| def CheckRollbackAfterNoChanges(self):
| self.cx.rollback()
self.cx.rollback()
|
'pysqlite does not know the rowcount of SELECT statements, because we
don\'t fetch all rows after executing the select statement. The rowcount
has thus to be -1.'
| def CheckRowcountSelect(self):
| self.cu.execute('select 5 union select 6')
self.assertEqual(self.cu.rowcount, (-1))
|
'Checks if fetchmany works with keyword arguments'
| def CheckFetchmanyKwArg(self):
| self.cu.execute('select name from test')
res = self.cu.fetchmany(size=100)
self.assertEqual(len(res), 1)
|
'Checks whether converter names are cut off at \'(\' characters'
| def CheckNumber2(self):
| self.cur.execute('insert into test(n2) values (5)')
value = self.cur.execute('select n2 from test').fetchone()[0]
self.assertEqual(type(value), float)
|
'Assures that the declared type is not used when PARSE_DECLTYPES
is not set.'
| def CheckDeclTypeNotUsed(self):
| self.cur.execute('insert into test(x) values (?)', ('xxx',))
self.cur.execute('select x from test')
val = self.cur.fetchone()[0]
self.assertEqual(val, 'xxx')
|
'cursor.description should at least provide the column name(s), even if
no row returned.'
| def CheckCursorDescriptionNoRow(self):
| self.cur.execute('select * from test where 0 = 1')
self.assertEqual(self.cur.description[0][0], 'x')
|
'pysqlite would crash with older SQLite versions unless
a workaround is implemented.'
| def CheckWorkaroundForBuggySqliteTransferBindings(self):
| self.con.execute('create table foo(bar)')
self.con.execute('drop table foo')
self.con.execute('create table foo(bar)')
|
'pysqlite used to segfault with SQLite versions 3.5.x. These return NULL
for "no-operation" statements'
| def CheckEmptyStatement(self):
| self.con.execute('')
|
'pysqlite until 2.4.1 did not rebuild the row_cast_map when recompiling
a statement. This test exhibits the problem.'
| def CheckTypeMapUsage(self):
| SELECT = 'select * from foo'
con = sqlite.connect(':memory:', detect_types=sqlite.PARSE_DECLTYPES)
con.execute('create table foo(bar timestamp)')
con.execute('insert into foo(bar) values (?)', (datetime.datetime.now(),))
con.execute(SELECT)
con.execute('drop tabl... |
'See issue 3312.'
| def CheckRegisterAdapter(self):
| self.assertRaises(TypeError, sqlite.register_adapter, {}, None)
|
'See issue 3312.'
| def CheckSetIsolationLevel(self):
| con = sqlite.connect(':memory:')
setattr(con, 'isolation_level', '\xe9')
|
'Verifies that cursor methods check whether base class __init__ was
called.'
| def CheckCursorConstructorCallCheck(self):
| class Cursor(sqlite.Cursor, ):
def __init__(self, con):
pass
con = sqlite.connect(':memory:')
cur = Cursor(con)
try:
cur.execute('select 4+5').fetchall()
self.fail('should have raised ProgrammingError')
except sqlite.ProgrammingError:
pass
... |
'The Python 3.0 port of the module didn\'t cope with values of subclasses of str.'
| def CheckStrSubclass(self):
| class MyStr(str, ):
pass
self.con.execute('select ?', (MyStr('abc'),))
|
'Verifies that connection methods check whether base class __init__ was
called.'
| def CheckConnectionConstructorCallCheck(self):
| class Connection(sqlite.Connection, ):
def __init__(self, name):
pass
con = Connection(':memory:')
try:
cur = con.cursor()
self.fail('should have raised ProgrammingError')
except sqlite.ProgrammingError:
pass
except:
self.fail('should h... |
'Verifies that subclassed cursor classes are correctly registered with
the connection object, too. (fetch-across-rollback problem)'
| def CheckCursorRegistration(self):
| class Connection(sqlite.Connection, ):
def cursor(self):
return Cursor(self)
class Cursor(sqlite.Cursor, ):
def __init__(self, con):
sqlite.Cursor.__init__(self, con)
con = Connection(':memory:')
cur = con.cursor()
cur.execute('create table foo(x)')
... |
'Verifies that creating a connection in autocommit mode works.
2.5.3 introduced a regression so that these could no longer
be created.'
| def CheckAutoCommit(self):
| con = sqlite.connect(':memory:', isolation_level=None)
|
'Verifies that running a PRAGMA statement that does an autocommit does
work. This did not work in 2.5.3/2.5.4.'
| def CheckPragmaAutocommit(self):
| cur = self.con.cursor()
cur.execute('create table foo(bar)')
cur.execute('insert into foo(bar) values (5)')
cur.execute('pragma page_size')
row = cur.fetchone()
|
'See http://bugs.python.org/issue7478
It was possible to successfully register callbacks that could not be
hashed. Return codes of PyDict_SetItem were not checked properly.'
| def CheckSetDict(self):
| class NotHashable:
def __call__(self, *args, **kw):
pass
def __hash__(self):
raise TypeError()
var = NotHashable()
self.assertRaises(TypeError, self.con.create_function, var)
self.assertRaises(TypeError, self.con.create_aggregate, var)
self.assertRaises(TypeEr... |
'Call a connection with a non-string SQL request: check error handling
of the statement constructor.'
| def CheckConnectionCall(self):
| self.assertRaises(sqlite.Warning, self.con, 1)
|
'http://bugs.python.org/issue10811
Recursively using a cursor, such as when reusing it from a generator led to segfaults.
Now we catch recursive cursor usage and raise a ProgrammingError.'
| def CheckRecursiveCursorUse(self):
| con = sqlite.connect(':memory:')
cur = con.cursor()
cur.execute('create table a (bar)')
cur.execute('create table b (baz)')
def foo():
cur.execute('insert into a (bar) values (?)', (1,))
(yield 1)
with self.assertRaises(sqlite.ProgrammingError):
... |
'http://bugs.python.org/issue14720
The microsecond parsing of convert_timestamp() should pad with zeros,
since the microsecond string "456" actually represents "456000".'
| def CheckConvertTimestampMicrosecondPadding(self):
| con = sqlite.connect(':memory:', detect_types=sqlite.PARSE_DECLTYPES)
cur = con.cursor()
cur.execute('CREATE TABLE t (x TIMESTAMP)')
cur.execute("INSERT INTO t (x) VALUES ('2012-04-04 15:06:00.456')")
cur.execute("INSERT INTO t (x) VALUES ('2012-04-04 ... |
'Add a mapping between a type and an extension.
When the extension is already known, the new
type will replace the old one. When the type
is already known the extension will be added
to the list of known extensions.
If strict is true, information will be added to
list of standard types, else to the list of non-standard... | def add_type(self, type, ext, strict=True):
| self.types_map[strict][ext] = type
exts = self.types_map_inv[strict].setdefault(type, [])
if (ext not in exts):
exts.append(ext)
|
'Guess the type of a file based on its URL.
Return value is a tuple (type, encoding) where type is None if
the type can\'t be guessed (no or unknown suffix) or a string
of the form type/subtype, usable for a MIME Content-type
header; and encoding is None for no encoding or the name of
the program used to encode (e.g. c... | def guess_type(self, url, strict=True):
| (scheme, url) = urllib.parse.splittype(url)
if (scheme == 'data'):
comma = url.find(',')
if (comma < 0):
return (None, None)
semi = url.find(';', 0, comma)
if (semi >= 0):
type = url[:semi]
else:
type = url[:comma]
if (('=' in t... |
'Guess the extensions for a file based on its MIME type.
Return value is a list of strings giving the possible filename
extensions, including the leading dot (\'.\'). The extension is not
guaranteed to have been associated with any particular data stream,
but would be mapped to the MIME type `type\' by guess_type().
O... | def guess_all_extensions(self, type, strict=True):
| type = type.lower()
extensions = self.types_map_inv[True].get(type, [])
if (not strict):
for ext in self.types_map_inv[False].get(type, []):
if (ext not in extensions):
extensions.append(ext)
return extensions
|
'Guess the extension for a file based on its MIME type.
Return value is a string giving a filename extension,
including the leading dot (\'.\'). The extension is not
guaranteed to have been associated with any particular data
stream, but would be mapped to the MIME type `type\' by
guess_type(). If no extension can be... | def guess_extension(self, type, strict=True):
| extensions = self.guess_all_extensions(type, strict)
if (not extensions):
return None
return extensions[0]
|
'Read a single mime.types-format file, specified by pathname.
If strict is true, information will be added to
list of standard types, else to the list of non-standard
types.'
| def read(self, filename, strict=True):
| with open(filename, encoding='utf-8') as fp:
self.readfp(fp, strict)
|
'Read a single mime.types-format file.
If strict is true, information will be added to
list of standard types, else to the list of non-standard
types.'
| def readfp(self, fp, strict=True):
| while 1:
line = fp.readline()
if (not line):
break
words = line.split()
for i in range(len(words)):
if (words[i][0] == '#'):
del words[i:]
break
if (not words):
continue
(type, suffixes) = (words[0], ... |
'Load the MIME types database from Windows registry.
If strict is true, information will be added to
list of standard types, else to the list of non-standard
types.'
| def read_windows_registry(self, strict=True):
| if (not _winreg):
return
def enum_types(mimedb):
i = 0
while True:
try:
ctype = _winreg.EnumKey(mimedb, i)
except EnvironmentError:
break
else:
(yield ctype)
i += 1
with _winreg.OpenKey(_w... |
'rotate self counterclockwise by angle'
| def rotate(self, angle):
| perp = Vec2D((- self[1]), self[0])
angle = ((angle * math.pi) / 180.0)
(c, s) = (math.cos(angle), math.sin(angle))
return Vec2D(((self[0] * c) + (perp[0] * s)), ((self[1] * c) + (perp[1] * s)))
|
'Adjust canvas and scrollbars according to given canvas size.'
| def reset(self, canvwidth=None, canvheight=None, bg=None):
| if canvwidth:
self.canvwidth = canvwidth
if canvheight:
self.canvheight = canvheight
if bg:
self.bg = bg
self._canvas.config(bg=bg, scrollregion=(((- self.canvwidth) // 2), ((- self.canvheight) // 2), (self.canvwidth // 2), (self.canvheight // 2)))
self._canvas.xview_moveto((... |
'Adjust scrollbars according to window- and canvas-size.'
| def adjustScrolls(self):
| cwidth = self._canvas.winfo_width()
cheight = self._canvas.winfo_height()
self._canvas.xview_moveto(((0.5 * (self.canvwidth - cwidth)) / self.canvwidth))
self._canvas.yview_moveto(((0.5 * (self.canvheight - cheight)) / self.canvheight))
if ((cwidth < self.canvwidth) or (cheight < self.canvheight)):
... |
'self-explanatory'
| def onResize(self, event):
| self.adjustScrolls()
|
'\'forward\' method, which canvas itself has inherited...'
| def bbox(self, *args):
| return self._canvas.bbox(*args)
|
'\'forward\' method, which canvas itself has inherited...'
| def cget(self, *args, **kwargs):
| return self._canvas.cget(*args, **kwargs)
|
'\'forward\' method, which canvas itself has inherited...'
| def config(self, *args, **kwargs):
| self._canvas.config(*args, **kwargs)
|
'\'forward\' method, which canvas itself has inherited...'
| def bind(self, *args, **kwargs):
| self._canvas.bind(*args, **kwargs)
|
'\'forward\' method, which canvas itself has inherited...'
| def unbind(self, *args, **kwargs):
| self._canvas.unbind(*args, **kwargs)
|
'\'forward\' method, which canvas itself has inherited...'
| def focus_force(self):
| self._canvas.focus_force()
|
'return a blank image object'
| @staticmethod
def _blankimage():
| img = TK.PhotoImage(width=1, height=1)
img.blank()
return img
|
'return an image object containing the
imagedata from a gif-file named filename.'
| @staticmethod
def _image(filename):
| return TK.PhotoImage(file=filename)
|
'Create an invisible polygon item on canvas self.cv)'
| def _createpoly(self):
| return self.cv.create_polygon((0, 0, 0, 0, 0, 0), fill='', outline='')
|
'Configure polygonitem polyitem according to provided
arguments:
coordlist is sequence of coordinates
fill is filling color
outline is outline color
top is a boolean value, which specifies if polyitem
will be put on top of the canvas\' displaylist so it
will not be covered by other items.'
| def _drawpoly(self, polyitem, coordlist, fill=None, outline=None, width=None, top=False):
| cl = []
for (x, y) in coordlist:
cl.append((x * self.xscale))
cl.append(((- y) * self.yscale))
self.cv.coords(polyitem, *cl)
if (fill is not None):
self.cv.itemconfigure(polyitem, fill=fill)
if (outline is not None):
self.cv.itemconfigure(polyitem, outline=outline)
... |
'Create an invisible line item on canvas self.cv)'
| def _createline(self):
| return self.cv.create_line(0, 0, 0, 0, fill='', width=2, capstyle=TK.ROUND)
|
'Configure lineitem according to provided arguments:
coordlist is sequence of coordinates
fill is drawing color
width is width of drawn line.
top is a boolean value, which specifies if polyitem
will be put on top of the canvas\' displaylist so it
will not be covered by other items.'
| def _drawline(self, lineitem, coordlist=None, fill=None, width=None, top=False):
| if (coordlist is not None):
cl = []
for (x, y) in coordlist:
cl.append((x * self.xscale))
cl.append(((- y) * self.yscale))
self.cv.coords(lineitem, *cl)
if (fill is not None):
self.cv.itemconfigure(lineitem, fill=fill)
if (width is not None):
s... |
'Delete graphics item from canvas.
If item is"all" delete all graphics items.'
| def _delete(self, item):
| self.cv.delete(item)
|
'Redraw graphics items on canvas'
| def _update(self):
| self.cv.update()
|
'Delay subsequent canvas actions for delay ms.'
| def _delay(self, delay):
| self.cv.after(delay)
|
'Check if the string color is a legal Tkinter color string.'
| def _iscolorstring(self, color):
| try:
rgb = self.cv.winfo_rgb(color)
ok = True
except TK.TclError:
ok = False
return ok
|
'Set canvas\' backgroundcolor if color is not None,
else return backgroundcolor.'
| def _bgcolor(self, color=None):
| if (color is not None):
self.cv.config(bg=color)
self._update()
else:
return self.cv.cget('bg')
|
'Write txt at pos in canvas with specified font
and color.
Return text item and x-coord of right bottom corner
of text\'s bounding box.'
| def _write(self, pos, txt, align, font, pencolor):
| (x, y) = pos
x = (x * self.xscale)
y = (y * self.yscale)
anchor = {'left': 'sw', 'center': 's', 'right': 'se'}
item = self.cv.create_text((x - 1), (- y), text=txt, anchor=anchor[align], fill=pencolor, font=font)
(x0, y0, x1, y1) = self.cv.bbox(item)
self.cv.update()
return (item, (x1 - 1... |
'Bind fun to mouse-click event on turtle.
fun must be a function with two arguments, the coordinates
of the clicked point on the canvas.
num, the number of the mouse-button defaults to 1'
| def _onclick(self, item, fun, num=1, add=None):
| if (fun is None):
self.cv.tag_unbind(item, ('<Button-%s>' % num))
else:
def eventfun(event):
(x, y) = ((self.cv.canvasx(event.x) / self.xscale), ((- self.cv.canvasy(event.y)) / self.yscale))
fun(x, y)
self.cv.tag_bind(item, ('<Button-%s>' % num), eventfun, add)
|
'Bind fun to mouse-button-release event on turtle.
fun must be a function with two arguments, the coordinates
of the point on the canvas where mouse button is released.
num, the number of the mouse-button defaults to 1
If a turtle is clicked, first _onclick-event will be performed,
then _onscreensclick-event.'
| def _onrelease(self, item, fun, num=1, add=None):
| if (fun is None):
self.cv.tag_unbind(item, ('<Button%s-ButtonRelease>' % num))
else:
def eventfun(event):
(x, y) = ((self.cv.canvasx(event.x) / self.xscale), ((- self.cv.canvasy(event.y)) / self.yscale))
fun(x, y)
self.cv.tag_bind(item, ('<Button%s-ButtonRelease>'... |
'Bind fun to mouse-move-event (with pressed mouse button) on turtle.
fun must be a function with two arguments, the coordinates of the
actual mouse position on the canvas.
num, the number of the mouse-button defaults to 1
Every sequence of mouse-move-events on a turtle is preceded by a
mouse-click event on that turtle.... | def _ondrag(self, item, fun, num=1, add=None):
| if (fun is None):
self.cv.tag_unbind(item, ('<Button%s-Motion>' % num))
else:
def eventfun(event):
try:
(x, y) = ((self.cv.canvasx(event.x) / self.xscale), ((- self.cv.canvasy(event.y)) / self.yscale))
fun(x, y)
except:
pass... |
'Bind fun to mouse-click event on canvas.
fun must be a function with two arguments, the coordinates
of the clicked point on the canvas.
num, the number of the mouse-button defaults to 1
If a turtle is clicked, first _onclick-event will be performed,
then _onscreensclick-event.'
| def _onscreenclick(self, fun, num=1, add=None):
| if (fun is None):
self.cv.unbind(('<Button-%s>' % num))
else:
def eventfun(event):
(x, y) = ((self.cv.canvasx(event.x) / self.xscale), ((- self.cv.canvasy(event.y)) / self.yscale))
fun(x, y)
self.cv.bind(('<Button-%s>' % num), eventfun, add)
|
'Bind fun to key-release event of key.
Canvas must have focus. See method listen'
| def _onkeyrelease(self, fun, key):
| if (fun is None):
self.cv.unbind(('<KeyRelease-%s>' % key), None)
else:
def eventfun(event):
fun()
self.cv.bind(('<KeyRelease-%s>' % key), eventfun)
|
'If key is given, bind fun to key-press event of key.
Otherwise bind fun to any key-press.
Canvas must have focus. See method listen.'
| def _onkeypress(self, fun, key=None):
| if (fun is None):
if (key is None):
self.cv.unbind('<KeyPress>', None)
else:
self.cv.unbind(('<KeyPress-%s>' % key), None)
else:
def eventfun(event):
fun()
if (key is None):
self.cv.bind('<KeyPress>', eventfun)
else:
... |
'Set focus on canvas (in order to collect key-events)'
| def _listen(self):
| self.cv.focus_force()
|
'Install a timer, which calls fun after t milliseconds.'
| def _ontimer(self, fun, t):
| if (t == 0):
self.cv.after_idle(fun)
else:
self.cv.after(t, fun)
|
'Create and return image item on canvas.'
| def _createimage(self, image):
| return self.cv.create_image(0, 0, image=image)
|
'Configure image item as to draw image object
at position (x,y) on canvas)'
| def _drawimage(self, item, pos, image):
| (x, y) = pos
self.cv.coords(item, ((x * self.xscale), ((- y) * self.yscale)))
self.cv.itemconfig(item, image=image)
|
'Configure image item as to draw image object
at center of canvas. Set item to the first item
in the displaylist, so it will be drawn below
any other item .'
| def _setbgpic(self, item, image):
| self.cv.itemconfig(item, image=image)
self.cv.tag_lower(item)
|
'Return \'line\' or \'polygon\' or \'image\' depending on
type of item.'
| def _type(self, item):
| return self.cv.type(item)
|
'returns list of coordinate-pairs of points of item
Example (for insiders):
>>> from turtle import *
>>> getscreen()._pointlist(getturtle().turtle._item)
[(0.0, 9.9999999999999982), (0.0, -9.9999999999999982),
(9.9999999999999982, 0.0)]'
| def _pointlist(self, item):
| cl = self.cv.coords(item)
pl = [(cl[i], (- cl[(i + 1)])) for i in range(0, len(cl), 2)]
return pl
|
'Resize the canvas the turtles are drawing on. Does
not alter the drawing window.'
| def _resize(self, canvwidth=None, canvheight=None, bg=None):
| if (not isinstance(self.cv, ScrolledCanvas)):
return (self.canvwidth, self.canvheight)
if (canvwidth is canvheight is bg is None):
return (self.cv.canvwidth, self.cv.canvheight)
if (canvwidth is not None):
self.canvwidth = canvwidth
if (canvheight is not None):
self.canvh... |
'Return the width and height of the turtle window.'
| def _window_size(self):
| width = self.cv.winfo_width()
if (width <= 1):
width = self.cv['width']
height = self.cv.winfo_height()
if (height <= 1):
height = self.cv['height']
return (width, height)
|
'Starts event loop - calling Tkinter\'s mainloop function.
No argument.
Must be last statement in a turtle graphics program.
Must NOT be used if a script is run from within IDLE in -n mode
(No subprocess) - for interactive use of turtle graphics.
Example (for a TurtleScreen instance named screen):
>>> screen.mainloop()... | def mainloop(self):
| TK.mainloop()
|
'Pop up a dialog window for input of a string.
Arguments: title is the title of the dialog window,
prompt is a text mostly describing what information to input.
Return the string input
If the dialog is canceled, return None.
Example (for a TurtleScreen instance named screen):
>>> screen.textinput("NIM", "Name of first ... | def textinput(self, title, prompt):
| return simpledialog.askstring(title, prompt)
|
'Pop up a dialog window for input of a number.
Arguments: title is the title of the dialog window,
prompt is a text mostly describing what numerical information to input.
default: default value
minval: minimum value for imput
maxval: maximum value for input
The number input must be in the range minval .. maxval if thes... | def numinput(self, title, prompt, default=None, minval=None, maxval=None):
| return simpledialog.askfloat(title, prompt, initialvalue=default, minvalue=minval, maxvalue=maxval)
|
'Add component to a shape of type compound.
Arguments: poly is a polygon, i. e. a tuple of number pairs.
fill is the fillcolor of the component,
outline is the outline color of the component.
call (for a Shapeobject namend s):
-- s.addcomponent(((0,0), (10,10), (-10,10)), "red", "blue")
Example:
>>> poly = ((0,0),(10... | def addcomponent(self, poly, fill, outline=None):
| if (self._type != 'compound'):
raise TurtleGraphicsError(('Cannot add component to %s Shape' % self._type))
if (outline is None):
outline = fill
self._data.append([poly, fill, outline])
|
'Delete all drawings and all turtles from the TurtleScreen.
No argument.
Reset empty TurtleScreen to its initial state: white background,
no backgroundimage, no eventbindings and tracing on.
Example (for a TurtleScreen instance named screen):
>>> screen.clear()
Note: this method is not available as function.'
| def clear(self):
| self._delayvalue = _CFG['delay']
self._colormode = _CFG['colormode']
self._delete('all')
self._bgpic = self._createimage('')
self._bgpicname = 'nopic'
self._tracing = 1
self._updatecounter = 0
self._turtles = []
self.bgcolor('white')
for btn in (1, 2, 3):
self.onclick(Non... |
'Set turtle-mode (\'standard\', \'logo\' or \'world\') and perform reset.
Optional argument:
mode -- on of the strings \'standard\', \'logo\' or \'world\'
Mode \'standard\' is compatible with turtle.py.
Mode \'logo\' is compatible with most Logo-Turtle-Graphics.
Mode \'world\' uses userdefined \'worldcoordinates\'. *At... | def mode(self, mode=None):
| if (mode is None):
return self._mode
mode = mode.lower()
if (mode not in ['standard', 'logo', 'world']):
raise TurtleGraphicsError(('No turtle-graphics-mode %s' % mode))
self._mode = mode
if (mode in ['standard', 'logo']):
self._setscrollregion(((- self.canvwidth) // 2)... |
'Set up a user defined coordinate-system.
Arguments:
llx -- a number, x-coordinate of lower left corner of canvas
lly -- a number, y-coordinate of lower left corner of canvas
urx -- a number, x-coordinate of upper right corner of canvas
ury -- a number, y-coordinate of upper right corner of canvas
Set up user coodinat-... | def setworldcoordinates(self, llx, lly, urx, ury):
| if (self.mode() != 'world'):
self.mode('world')
xspan = float((urx - llx))
yspan = float((ury - lly))
(wx, wy) = self._window_size()
self.screensize((wx - 20), (wy - 20))
(oldxscale, oldyscale) = (self.xscale, self.yscale)
self.xscale = (self.canvwidth / xspan)
self.yscale = (sel... |
'Adds a turtle shape to TurtleScreen\'s shapelist.
Arguments:
(1) name is the name of a gif-file and shape is None.
Installs the corresponding image shape.
!! Image-shapes DO NOT rotate when turning the turtle,
!! so they do not display the heading of the turtle!
(2) name is an arbitrary string and shape is a tuple
of ... | def register_shape(self, name, shape=None):
| if (shape is None):
if name.lower().endswith('.gif'):
shape = Shape('image', self._image(name))
else:
raise TurtleGraphicsError(('Bad arguments for register_shape.\n' + 'Use help(register_shape)'))
elif isinstance(shape, tuple):
shape = Shape('poly... |
'Return color string corresponding to args.
Argument may be a string or a tuple of three
numbers corresponding to actual colormode,
i.e. in the range 0<=n<=colormode.
If the argument doesn\'t represent a color,
an error is raised.'
| def _colorstr(self, color):
| if (len(color) == 1):
color = color[0]
if isinstance(color, str):
if (self._iscolorstring(color) or (color == '')):
return color
else:
raise TurtleGraphicsError(('bad color string: %s' % str(color)))
try:
(r, g, b) = color
except:
... |
'Return the colormode or set it to 1.0 or 255.
Optional argument:
cmode -- one of the values 1.0 or 255
r, g, b values of colortriples have to be in range 0..cmode.
Example (for a TurtleScreen instance named screen):
>>> screen.colormode()
1.0
>>> screen.colormode(255)
>>> pencolor(240,160,80)'
| def colormode(self, cmode=None):
| if (cmode is None):
return self._colormode
if (cmode == 1.0):
self._colormode = float(cmode)
elif (cmode == 255):
self._colormode = int(cmode)
|
'Reset all Turtles on the Screen to their initial state.
No argument.
Example (for a TurtleScreen instance named screen):
>>> screen.reset()'
| def reset(self):
| for turtle in self._turtles:
turtle._setmode(self._mode)
turtle.reset()
|
'Return the list of turtles on the screen.
Example (for a TurtleScreen instance named screen):
>>> screen.turtles()
[<turtle.Turtle object at 0x00E11FB0>]'
| def turtles(self):
| return self._turtles
|
'Set or return backgroundcolor of the TurtleScreen.
Arguments (if given): a color string or three numbers
in the range 0..colormode or a 3-tuple of such numbers.
Example (for a TurtleScreen instance named screen):
>>> screen.bgcolor("orange")
>>> screen.bgcolor()
\'orange\'
>>> screen.bgcolor(0.5,0,0.5)
>>> screen.bgco... | def bgcolor(self, *args):
| if args:
color = self._colorstr(args)
else:
color = None
color = self._bgcolor(color)
if (color is not None):
color = self._color(color)
return color
|
'Turns turtle animation on/off and set delay for update drawings.
Optional arguments:
n -- nonnegative integer
delay -- nonnegative integer
If n is given, only each n-th regular screen update is really performed.
(Can be used to accelerate the drawing of complex graphics.)
Second arguments sets delay value (see RawTu... | def tracer(self, n=None, delay=None):
| if (n is None):
return self._tracing
self._tracing = int(n)
self._updatecounter = 0
if (delay is not None):
self._delayvalue = int(delay)
if self._tracing:
self.update()
|
'Return or set the drawing delay in milliseconds.
Optional argument:
delay -- positive integer
Example (for a TurtleScreen instance named screen):
>>> screen.delay(15)
>>> screen.delay()
15'
| def delay(self, delay=None):
| if (delay is None):
return self._delayvalue
self._delayvalue = int(delay)
|
'Increment update counter.'
| def _incrementudc(self):
| if (not TurtleScreen._RUNNING):
TurtleScreen._RUNNNING = True
raise Terminator
if (self._tracing > 0):
self._updatecounter += 1
self._updatecounter %= self._tracing
|
'Perform a TurtleScreen update.'
| def update(self):
| tracing = self._tracing
self._tracing = True
for t in self.turtles():
t._update_data()
t._drawturtle()
self._tracing = tracing
self._update()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.