_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q21700 | Apps.get_cdn_auth_token | train | def get_cdn_auth_token(self, app_id, hostname):
"""Get CDN authentication token
:param app_id: app id
:type app_id: :class:`int`
:param hostname: cdn hostname
:type hostname: :class:`str`
:return: `CMsgClientGetCDNAuthTokenResponse <https://github.com/ValvePython/steam/blob/39627fe883feeed2206016bacd92cf0e4580ead6/protobufs/steammessages_clientserver_2.proto#L585-L589>`_
| python | {
"resource": ""
} |
q21701 | Apps.get_product_access_tokens | train | def get_product_access_tokens(self, app_ids=[], package_ids=[]):
"""Get access tokens
:param app_ids: list of app ids
:type app_ids: :class:`list`
:param package_ids: list of package ids
:type package_ids: :class:`list`
:return: dict with ``apps`` and ``packages`` containing their access tokens, see example below
:rtype: :class:`dict`, :class:`None`
.. code:: python
{'apps': {123: 'token', ...},
'packages': {456: 'token', ...}
}
"""
if not app_ids and not package_ids: return
resp = self.send_job_and_wait(MsgProto(EMsg.ClientPICSAccessTokenRequest),
{
'appids': map(int, app_ids),
| python | {
"resource": ""
} |
q21702 | a2s_players | train | def a2s_players(server_addr, timeout=2, challenge=0):
"""Get list of players and their info
:param server_addr: (ip, port) for the server
:type server_addr: tuple
:param timeout: (optional) timeout in seconds
:type timeout: float
:param challenge: (optional) challenge number
:type challenge: int
:raises: :class:`RuntimeError`, :class:`socket.timeout`
:returns: a list of players
:rtype: :class:`list`
"""
ss = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ss.connect(server_addr)
ss.settimeout(timeout)
# request challenge number
header = None
if challenge in (-1, 0):
ss.send(_pack('<lci', -1, b'U', challenge))
try:
data = ss.recv(512)
_, header, challenge = _unpack_from('<lcl', data)
except:
ss.close()
raise
if header not in b'AD': # work around for CSGO sending only max players
raise RuntimeError("Unexpected challenge response - %s" % repr(header))
# request player info
if header == b'D': # work around for CSGO sending only max players
data = StructReader(data)
else:
ss.send(_pack('<lci', -1, b'U', challenge))
| python | {
"resource": ""
} |
q21703 | a2s_rules | train | def a2s_rules(server_addr, timeout=2, challenge=0):
"""Get rules from server
:param server_addr: (ip, port) for the server
:type server_addr: tuple
:param timeout: (optional) timeout in seconds
:type timeout: float
:param challenge: (optional) challenge number
:type challenge: int
:raises: :class:`RuntimeError`, :class:`socket.timeout`
:returns: a list of players
:rtype: :class:`list`
"""
ss = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ss.connect(server_addr)
ss.settimeout(timeout)
# request challenge number
if challenge in (-1, 0):
ss.send(_pack('<lci', -1, b'V', challenge))
try:
_, header, challenge = _unpack_from('<lcl', ss.recv(512))
except:
ss.close()
raise
if header != b'A':
raise RuntimeError("Unexpected challenge response")
# request player info
ss.send(_pack('<lci', -1, b'V', challenge))
try:
data = StructReader(_handle_a2s_response(ss))
finally:
ss.close() | python | {
"resource": ""
} |
q21704 | a2s_ping | train | def a2s_ping(server_addr, timeout=2):
"""Ping a server
.. warning::
This method for pinging is considered deprecated and may not work on certian servers.
Use :func:`.a2s_info` instead.
:param server_addr: (ip, port) for the server
:type server_addr: tuple
:param timeout: (optional) timeout in seconds
:type timeout: float
:raises: :class:`RuntimeError`, :class:`socket.timeout`
:returns: ping response in milliseconds or `None` for timeout
:rtype: :class:`float`
"""
| python | {
"resource": ""
} |
q21705 | get_cmsg | train | def get_cmsg(emsg):
"""Get protobuf for a given EMsg
:param emsg: EMsg
:type emsg: :class:`steam.enums.emsg.EMsg`, :class:`int`
:return: protobuf message
"""
if not isinstance(emsg, EMsg):
emsg = EMsg(emsg)
if emsg in cmsg_lookup_predefined:
return cmsg_lookup_predefined[emsg]
else:
enum_name = emsg.name.lower() | python | {
"resource": ""
} |
q21706 | Web.get_web_session_cookies | train | def get_web_session_cookies(self):
"""Get web authentication cookies via WebAPI's ``AuthenticateUser``
.. note::
The cookies are valid only while :class:`.SteamClient` instance is logged on.
:return: dict with authentication cookies
:rtype: :class:`dict`, :class:`None`
"""
if not self.logged_on: return None
resp = self.send_job_and_wait(MsgProto(EMsg.ClientRequestWebAPIAuthenticateUserNonce), timeout=7)
if resp is None: return None
skey, ekey = generate_session_key()
data = {
'steamid': self.steam_id,
'sessionkey': ekey,
| python | {
"resource": ""
} |
q21707 | User.change_status | train | def change_status(self, **kwargs):
"""
Set name, persona state, flags
.. note::
Changing persona state will also change :attr:`persona_state`
:param persona_state: persona state (Online/Offlane/Away/etc)
:type persona_state: :class:`.EPersonaState`
| python | {
"resource": ""
} |
q21708 | User.request_persona_state | train | def request_persona_state(self, steam_ids, state_flags=863):
"""Request persona state data
:param steam_ids: list of steam ids
:type steam_ids: :class:`list`
:param state_flags: client state flags
:type state_flags: :class:`.EClientPersonaStateFlag`
"""
| python | {
"resource": ""
} |
q21709 | User.games_played | train | def games_played(self, app_ids):
"""
Set the apps being played by the user
:param app_ids: a list of application ids
:type app_ids: :class:`list`
These app ids will be recorded in :attr:`current_games_played`.
"""
if not isinstance(app_ids, list):
raise ValueError("Expected app_ids | python | {
"resource": ""
} |
q21710 | GlobalID.new | train | def new(sequence_count, start_time, process_id, box_id):
"""Make new GlobalID
:param sequence_count: sequence count
:type sequence_count: :class:`int`
:param start_time: start date time of server (must be after 2005-01-01)
:type start_time: :class:`str`, :class:`datetime`
:param process_id: process id
:type process_id: :class:`int`
:param box_id: box id
:type box_id: :class:`int`
:return: Global ID integer
:rtype: :class:`int`
"""
| python | {
"resource": ""
} |
q21711 | Service.get_shared_people | train | def get_shared_people(self):
"""Retrieves all people that share their location with this account"""
people = []
output = self._get_data()
self._logger.debug(output)
| python | {
"resource": ""
} |
q21712 | Service.get_authenticated_person | train | def get_authenticated_person(self):
"""Retrieves the person associated with this account"""
try:
output = self._get_data()
self._logger.debug(output)
person = Person([
self.email,
output[9][1],
None,
None,
None,
None,
[
None,
None,
self.email,
self.email
],
None,
| python | {
"resource": ""
} |
q21713 | Service.get_person_by_nickname | train | def get_person_by_nickname(self, nickname):
"""Retrieves a person by nickname"""
return next((person for person in self.get_all_people()
| python | {
"resource": ""
} |
q21714 | Service.get_person_by_full_name | train | def get_person_by_full_name(self, name):
"""Retrieves a person by full name"""
| python | {
"resource": ""
} |
q21715 | Service.get_coordinates_by_nickname | train | def get_coordinates_by_nickname(self, nickname):
"""Retrieves a person's coordinates by nickname"""
person = self.get_person_by_nickname(nickname)
| python | {
"resource": ""
} |
q21716 | Service.get_coordinates_by_full_name | train | def get_coordinates_by_full_name(self, name):
"""Retrieves a person's coordinates by full name"""
person = self.get_person_by_full_name(name)
| python | {
"resource": ""
} |
q21717 | Person.datetime | train | def datetime(self):
"""A datetime representation of the location retrieval"""
| python | {
"resource": ""
} |
q21718 | xnormpath | train | def xnormpath(path):
""" Cross-platform version of os.path.normpath """
# replace escapes | python | {
"resource": ""
} |
q21719 | xstrip | train | def xstrip(filename):
""" Make relative path out of absolute by stripping
prefixes used on Linux, OS X and Windows.
This function is critical for security.
"""
while xisabs(filename):
# strip windows drive with all slashes
if re.match(b'\\w:[\\\\/]', filename): | python | {
"resource": ""
} |
q21720 | pathstrip | train | def pathstrip(path, n):
""" Strip n leading components from the given path """
pathlist = [path]
while os.path.dirname(pathlist[0]) != b'':
| python | {
"resource": ""
} |
q21721 | PatchSet._detect_type | train | def _detect_type(self, p):
""" detect and return type for the specified Patch object
analyzes header and filenames info
NOTE: must be run before filenames are normalized
"""
# check for SVN
# - header starts with Index:
# - next line is ===... delimiter
# - filename is followed by revision number
# TODO add SVN revision
if (len(p.header) > 1 and p.header[-2].startswith(b"Index: ")
and p.header[-1].startswith(b"="*67)):
return SVN
# common checks for both HG and GIT
DVCS = ((p.source.startswith(b'a/') or p.source == b'/dev/null')
and (p.target.startswith(b'b/') or p.target == b'/dev/null'))
# GIT type check
# - header[-2] is like "diff --git a/oldname b/newname"
# - header[-1] is like "index <hash>..<hash> <mode>"
# TODO add git rename diffs and add/remove diffs
# add git diff with spaced filename
# TODO http://www.kernel.org/pub/software/scm/git/docs/git-diff.html
# Git patch header len is 2 min
if len(p.header) > 1:
# detect the start of diff header - there might be some comments before
for idx in reversed(range(len(p.header))):
if p.header[idx].startswith(b"diff --git"):
break
if p.header[idx].startswith(b'diff --git a/'):
if (idx+1 < len(p.header)
and re.match(b'index \\w{7}..\\w{7} \\d{6}', p.header[idx+1])):
if DVCS:
| python | {
"resource": ""
} |
q21722 | PatchSet.findfile | train | def findfile(self, old, new):
""" return name of file to be patched or None """
if exists(old):
return old
elif exists(new):
return new
else:
# [w] Google Code generates broken patches with its online editor
debug("broken patch from Google Code, stripping prefixes..")
if old.startswith(b'a/') and new.startswith(b'b/'):
old, new = old[2:], | python | {
"resource": ""
} |
q21723 | PatchSet.revert | train | def revert(self, strip=0, root=None):
""" apply patch in reverse order """
reverted = copy.deepcopy(self)
| python | {
"resource": ""
} |
q21724 | PatchSet.can_patch | train | def can_patch(self, filename):
""" Check if specified filename can be patched. Returns None if file can
not be found among source filenames. False if patch can not be applied
clearly. True otherwise.
:returns: True, False or None
"""
filename = abspath(filename)
for | python | {
"resource": ""
} |
q21725 | PatchSet.patch_stream | train | def patch_stream(self, instream, hunks):
""" Generator that yields stream patched with hunks iterable
Converts lineends in hunk lines to the best suitable format
autodetected from input
"""
# todo: At the moment substituted lineends may not be the same
# at the start and at the end of patching. Also issue a
# warning/throw about mixed lineends (is it really needed?)
hunks = iter(hunks)
srclineno = 1
lineends = {b'\n':0, b'\r\n':0, b'\r':0}
def get_line():
"""
local utility function - return line from source stream
collecting line end statistics on the way
"""
line = instream.readline()
# 'U' mode works only with text files
if line.endswith(b"\r\n"):
lineends[b"\r\n"] += 1
elif line.endswith(b"\n"):
lineends[b"\n"] += 1
elif line.endswith(b"\r"):
lineends[b"\r"] += 1
return line
for hno, h in enumerate(hunks):
debug("hunk %d" % (hno+1))
# skip to line just before hunk starts
while srclineno < h.startsrc:
yield get_line()
srclineno += 1
for hline in h.text:
| python | {
"resource": ""
} |
q21726 | cd | train | def cd(new_directory, clean_up=lambda: True): # pylint: disable=invalid-name
"""Changes into a given directory and cleans up after it is done
Args:
new_directory: The directory to change | python | {
"resource": ""
} |
q21727 | tempdir | train | def tempdir():
"""Creates a temporary directory"""
directory_path = tempfile.mkdtemp()
def clean_up(): # pylint: disable=missing-docstring
| python | {
"resource": ""
} |
q21728 | ScrolledListbox._grid_widgets | train | def _grid_widgets(self):
"""Puts the two whole widgets in the correct position depending on compound."""
scrollbar_column = | python | {
"resource": ""
} |
q21729 | ItemsCanvas.left_press | train | def left_press(self, event):
"""
Callback for the press of the left mouse button.
Selects a new item and sets its highlightcolor.
:param event: Tkinter event
"""
self.current_coords = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
| python | {
"resource": ""
} |
q21730 | ItemsCanvas.left_release | train | def left_release(self, event):
"""
Callback for the release of the left button.
:param event: Tkinter event
"""
self.config(cursor="")
| python | {
"resource": ""
} |
q21731 | ItemsCanvas.left_motion | train | def left_motion(self, event):
"""
Callback for the B1-Motion event, or the dragging of an item.
Moves the item to the desired location, but limits its movement to a
place on the actual Canvas. The item cannot be moved outside of the Canvas.
:param event: Tkinter event
"""
self.set_current()
results = self.canvas.find_withtag(tk.CURRENT)
if len(results) is 0:
return
item = results[0]
rectangle = self.items[item]
self.config(cursor="exchange")
self.canvas.itemconfigure(item, fill="blue")
xc, yc = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
dx, dy = xc - self.current_coords[0], yc - self.current_coords[1]
| python | {
"resource": ""
} |
q21732 | ItemsCanvas.del_item | train | def del_item(self):
"""Delete the current item on the Canvas."""
item = self.current
rectangle = self.items[item]
self.canvas.delete(item, rectangle)
| python | {
"resource": ""
} |
q21733 | DebugWindow.save | train | def save(self):
"""Save widget content."""
file_name = fd.asksaveasfilename()
if | python | {
"resource": ""
} |
q21734 | LimitVar.get | train | def get(self):
"""
Convert the content to int between the limits of the variable.
If the content is not an integer between the limits, the value is
corrected and the corrected result is returned.
"""
val = tk.StringVar.get(self)
try:
val = int(val)
if val < self._from:
val = self._from
| python | {
"resource": ""
} |
q21735 | askcolor | train | def askcolor(color="red", parent=None, title=_("Color Chooser"), alpha=False):
"""
Open a ColorPicker dialog and return the chosen color.
:return: the selected color in RGB(A) and hexadecimal #RRGGBB(AA) formats.
(None, None) is returned if the color selection is cancelled.
:param color: initially selected color (RGB(A), HEX or tkinter color name)
:type color: sequence[int] or str
:param parent: parent widget
:type parent: widget
| python | {
"resource": ""
} |
q21736 | ColorPicker._unfocus | train | def _unfocus(self, event):
"""Unfocus palette items when click on bar or square."""
w = self.focus_get()
| python | {
"resource": ""
} |
q21737 | ColorPicker._update_preview | train | def _update_preview(self):
"""Update color preview."""
color = self.hexa.get()
if self.alpha_channel:
prev = overlay(self._transparent_bg, hexa_to_rgb(color))
self._im_color = ImageTk.PhotoImage(prev, master=self)
| python | {
"resource": ""
} |
q21738 | ColorPicker._change_sel_color | train | def _change_sel_color(self, event):
"""Respond to motion of the color selection cross."""
(r, g, b), (h, s, v), color = self.square.get()
self.red.set(r)
self.green.set(g)
self.blue.set(b)
self.saturation.set(s)
self.value.set(v)
self.hexa.delete(0, "end")
self.hexa.insert(0, color.upper()) | python | {
"resource": ""
} |
q21739 | ColorPicker._change_color | train | def _change_color(self, event):
"""Respond to motion of the hsv cursor."""
h = self.bar.get()
self.square.set_hue(h)
(r, g, b), (h, s, v), sel_color = self.square.get()
self.red.set(r)
self.green.set(g)
self.blue.set(b)
self.hue.set(h)
self.saturation.set(s)
self.value.set(v)
self.hexa.delete(0, | python | {
"resource": ""
} |
q21740 | ColorPicker._update_color_hexa | train | def _update_color_hexa(self, event=None):
"""Update display after a change in the HEX entry."""
color = self.hexa.get().upper()
self.hexa.delete(0, 'end')
self.hexa.insert(0, color)
if re.match(r"^#[0-9A-F]{6}$", color):
r, g, b = hexa_to_rgb(color)
self.red.set(r)
self.green.set(g)
self.blue.set(b)
h, s, v = rgb_to_hsv(r, g, b)
self.hue.set(h)
self.saturation.set(s)
self.value.set(v)
self.bar.set(h)
| python | {
"resource": ""
} |
q21741 | ColorPicker._update_alpha | train | def _update_alpha(self, event=None):
"""Update display after a change in the alpha spinbox."""
a = self.alpha.get()
hexa = self.hexa.get()
hexa = hexa[:7] | python | {
"resource": ""
} |
q21742 | ColorPicker._update_color_hsv | train | def _update_color_hsv(self, event=None):
"""Update display after a change in the HSV spinboxes."""
if event is None or event.widget.old_value != event.widget.get():
h = self.hue.get()
s = self.saturation.get()
v = self.value.get()
sel_color = hsv_to_rgb(h, s, v)
self.red.set(sel_color[0])
self.green.set(sel_color[1])
self.blue.set(sel_color[2])
if self.alpha_channel:
sel_color += (self.alpha.get(),) | python | {
"resource": ""
} |
q21743 | ColorPicker._update_color_rgb | train | def _update_color_rgb(self, event=None):
"""Update display after a change in the RGB spinboxes."""
if event is None or event.widget.old_value != event.widget.get():
r = self.red.get()
g = self.green.get()
b = self.blue.get()
h, s, v = rgb_to_hsv(r, g, b)
self.hue.set(h)
self.saturation.set(s)
self.value.set(v)
args = (r, g, b)
if self.alpha_channel:
| python | {
"resource": ""
} |
q21744 | ColorPicker.ok | train | def ok(self):
"""Validate color selection and destroy dialog."""
rgb, hsv, hexa = self.square.get()
if self.alpha_channel:
hexa = self.hexa.get()
| python | {
"resource": ""
} |
q21745 | AlphaBar._draw_gradient | train | def _draw_gradient(self, alpha, color):
"""Draw the gradient and put the cursor on alpha."""
self.delete("gradient")
self.delete("cursor")
del self.gradient
width = self.winfo_width()
height = self.winfo_height()
bg = create_checkered_image(width, height)
r, g, b = color
w = width - 1.
gradient = Image.new("RGBA", (width, height))
for i in range(width):
for j in range(height):
gradient.putpixel((i, j), (r, g, b, round2(i / w * 255)))
self.gradient = ImageTk.PhotoImage(Image.alpha_composite(bg, gradient),
| python | {
"resource": ""
} |
q21746 | AlphaBar.set | train | def set(self, alpha):
"""
Set cursor position on the color corresponding to the alpha value.
:param alpha: new alpha value (between 0 and 255)
:type alpha: int
"""
if alpha > 255:
alpha = 255
elif alpha < 0:
alpha = 0
| python | {
"resource": ""
} |
q21747 | AlphaBar.set_color | train | def set_color(self, color):
"""
Change gradient color and change cursor position if an alpha value is supplied.
:param color: new gradient color in RGB(A) format
:type color: tuple[int]
"""
if len(color) == | python | {
"resource": ""
} |
q21748 | FontChooser._grid_widgets | train | def _grid_widgets(self):
"""Puts all the child widgets in the correct position."""
self._font_family_header.grid(row=0, column=1, sticky="nswe", padx=5, pady=5)
self._font_label.grid(row=1, column=1, sticky="nswe", padx=5, pady=(0, 5))
self._font_family_list.grid(row=2, rowspan=3, column=1, sticky="nswe", padx=5, pady=(0, 5))
self._font_properties_header.grid(row=0, column=2, sticky="nswe", padx=5, pady=5)
self._font_properties_frame.grid(row=1, rowspan=2, column=2, sticky="we", padx=5, pady=5)
self._font_size_header.grid(row=3, column=2, sticky="we", padx=5, pady=5)
| python | {
"resource": ""
} |
q21749 | FontChooser._on_change | train | def _on_change(self):
"""Callback if any of the values are changed."""
font | python | {
"resource": ""
} |
q21750 | GradientBar._draw_gradient | train | def _draw_gradient(self, hue):
"""Draw the gradient and put the cursor on hue."""
self.delete("gradient")
self.delete("cursor")
del self.gradient
width = self.winfo_width()
height = self.winfo_height()
self.gradient = tk.PhotoImage(master=self, width=width, height=height)
| python | {
"resource": ""
} |
q21751 | GradientBar._on_click | train | def _on_click(self, event):
"""Move selection cursor on click."""
x = event.x
self.coords('cursor', | python | {
"resource": ""
} |
q21752 | GradientBar._on_move | train | def _on_move(self, event):
"""Make selection cursor follow the cursor."""
w = self.winfo_width()
x = min(max(event.x, 0), w)
| python | {
"resource": ""
} |
q21753 | FontSelectFrame._grid_widgets | train | def _grid_widgets(self):
"""
Puts all the widgets in the correct place.
"""
self._family_dropdown.grid(row=0, column=0, sticky="nswe")
| python | {
"resource": ""
} |
q21754 | FontSelectFrame._on_change | train | def _on_change(self):
"""Call callback if any property is changed."""
if callable(self.__callback):
| python | {
"resource": ""
} |
q21755 | LinkLabel._on_enter | train | def _on_enter(self, *args):
"""Set the text color to the hover color."""
| python | {
"resource": ""
} |
q21756 | LinkLabel._on_leave | train | def _on_leave(self, *args):
"""Set the text color to either the normal color when not clicked or the clicked color when clicked."""
if self.__clicked:
| python | {
"resource": ""
} |
q21757 | LinkLabel.open_link | train | def open_link(self, *args):
"""Open the link in the web browser."""
if "disabled" not | python | {
"resource": ""
} |
q21758 | LinkLabel.keys | train | def keys(self):
"""Return a list of all resource names of this widget."""
| python | {
"resource": ""
} |
q21759 | Table._move_dragged_row | train | def _move_dragged_row(self, item):
"""Insert dragged row at item's position."""
self.move(self._dragged_row, '', self.index(item))
self.see(self._dragged_row)
bbox | python | {
"resource": ""
} |
q21760 | Table._start_drag_col | train | def _start_drag_col(self, event):
"""Start dragging a column"""
# identify dragged column
col = self.identify_column(event.x)
self._dragged_col = ttk.Treeview.column(self, col, 'id')
# get column width
self._dragged_col_width = w = ttk.Treeview.column(self, col, 'width')
# get x coordinate of the left side of the column
x = event.x
while self.identify_region(x, event.y) == 'heading':
# decrease x until reaching the separator
x -= 1
x_sep = x
w_sep = 0
# determine separator width
while self.identify_region(x_sep, event.y) == 'separator':
w_sep += 1
x_sep -= 1
if event.x - x <= self._im_drag.width():
# start dragging if mouse click was on dragging icon
x = x - w_sep // 2 - 1
self._dragged_col_x = x
# get neighboring column widths
displayed_cols = self._displayed_cols
self._dragged_col_index = i1 = displayed_cols.index(self._dragged_col)
if i1 > 0:
left = ttk.Treeview.column(self, displayed_cols[i1 - 1], 'width')
else:
left = None
if i1 < len(displayed_cols) - 1:
right | python | {
"resource": ""
} |
q21761 | Table._start_drag_row | train | def _start_drag_row(self, event):
"""Start dragging a row"""
self._dragged_row = self.identify_row(event.y) # identify dragged row
bbox = self.bbox(self._dragged_row)
self._dy = bbox[1] - event.y # distance between cursor and row upper border
self._dragged_row_y = bbox[1] # y coordinate of dragged row upper border
self._dragged_row_height = bbox[3]
# configure dragged row preview
self._visual_drag.configure(displaycolumns=self['displaycolumns'],
| python | {
"resource": ""
} |
q21762 | Table._on_release | train | def _on_release(self, event):
"""Stop dragging."""
if self._drag_cols or self._drag_rows:
self._visual_drag.place_forget()
| python | {
"resource": ""
} |
q21763 | Table._on_motion | train | def _on_motion(self, event):
"""Drag around label if visible."""
if not self._visual_drag.winfo_ismapped():
return
if self._drag_cols and self._dragged_col is not None: | python | {
"resource": ""
} |
q21764 | Table._drag_col | train | def _drag_col(self, event):
"""Continue dragging a column"""
x = self._dx + event.x # get dragged column new left x coordinate
self._visual_drag.place_configure(x=x) # update column preview position
# if one border of the dragged column is beyon the middle of the
# neighboring column, swap them
if (self._dragged_col_neighbor_widths[0] is not None and
x < self._dragged_col_x - self._dragged_col_neighbor_widths[0] / 2):
self._swap_columns('left')
elif (self._dragged_col_neighbor_widths[1] is not None and
x > self._dragged_col_x + self._dragged_col_neighbor_widths[1] / 2):
self._swap_columns('right')
# horizontal scrolling if | python | {
"resource": ""
} |
q21765 | Table._drag_row | train | def _drag_row(self, event):
"""Continue dragging a row"""
y = self._dy + event.y # get dragged row new upper y coordinate
self._visual_drag.place_configure(y=y) # update row preview position
if y > self._dragged_row_y:
# moving downward
item = self.identify_row(y + self._dragged_row_height)
if item != '':
bbox = self.bbox(item)
if not bbox:
# the item is not visible so make it visible
self.see(item)
self.update_idletasks()
bbox = self.bbox(item)
if y > self._dragged_row_y + bbox[3] / 2:
# the row is beyond half of item, so insert it below
self._move_dragged_row(item)
elif item != self.next(self._dragged_row):
# item is not the lower neighbor of the dragged row so insert the row above
self._move_dragged_row(self.prev(item))
elif y < self._dragged_row_y:
# moving upward
item = self.identify_row(y)
| python | {
"resource": ""
} |
q21766 | Table._sort_column | train | def _sort_column(self, column, reverse):
"""Sort a column by its values"""
if tk.DISABLED in self.state():
return
# get list of (value, item) tuple where value is the value in column for the item
l = [(self.set(child, column), child) for child in self.get_children('')]
# sort list using the column type
l.sort(reverse=reverse, key=lambda x: self._column_types[column](x[0]))
| python | {
"resource": ""
} |
q21767 | Table.column | train | def column(self, column, option=None, **kw):
"""
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.
:param id: the column's identifier (read-only option)
:param anchor: "n", "ne", "e", "se", "s", "sw", "w", "nw", or "center":
alignment of the text in this column with respect to the cell
:param minwidth: minimum width of the column in pixels
:type minwidth: int
:param stretch: whether the column's width should be adjusted when the widget is resized
:type stretch: bool
:param width: width of the column in pixels
:type width: int
:param type: column's content type (for sorting), default type is `str`
:type type: type
"""
config = False
if option == 'type':
| python | {
"resource": ""
} |
q21768 | Table._config_options | train | def _config_options(self):
"""Apply options set in attributes to Treeview"""
| python | {
"resource": ""
} |
q21769 | Table._config_sortable | train | def _config_sortable(self, sortable):
"""Configure a new sortable state"""
for col in self["columns"]:
command = (lambda c=col: self._sort_column(c, True)) | python | {
"resource": ""
} |
q21770 | Table._config_drag_cols | train | def _config_drag_cols(self, drag_cols):
"""Configure a new drag_cols state"""
self._drag_cols = drag_cols
# remove/display drag icon
if self._drag_cols:
self._im_drag.paste(self._im_draggable)
else:
| python | {
"resource": ""
} |
q21771 | Table.delete | train | def delete(self, *items):
"""
Delete all specified items and all their descendants. The root item may not be deleted.
:param items: list of item identifiers
| python | {
"resource": ""
} |
q21772 | Table.detach | train | def detach(self, *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.
:param | python | {
"resource": ""
} |
q21773 | Table.heading | train | def heading(self, column, option=None, **kw):
"""
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.
:param text: text to display in the column heading
:type text: str
:param image: image to display to the right of the column heading
:type image: PhotoImage
:param anchor: "n", "ne", "e", "se", "s", "sw", "w", "nw", or "center":
alignement of the heading text
| python | {
"resource": ""
} |
q21774 | Table.item | train | def item(self, item, option=None, **kw):
"""
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`.
:param text: item's label
:type text: str
:param image: image to be displayed on the left of the item's label
:type image: PhotoImage
:param values: values to put in the columns
:type values: sequence | python | {
"resource": ""
} |
q21775 | Table.set | train | def set(self, item, column=None, value=None):
"""
Query or set the value of given item.
With one argument, return a dictionary of column/value pairs for the
specified item. With two arguments, return the current value of the
specified column. With three arguments, set the value of | python | {
"resource": ""
} |
q21776 | ScaleEntry._on_scale | train | def _on_scale(self, event):
"""
Callback for the Scale widget, inserts an int value into the Entry. | python | {
"resource": ""
} |
q21777 | ScaleEntry.config_scale | train | def config_scale(self, cnf={}, **kwargs):
"""Configure resources of the Scale widget."""
self._scale.config(cnf, **kwargs)
# Update self._variable limits in | python | {
"resource": ""
} |
q21778 | Balloon._grid_widgets | train | def _grid_widgets(self):
"""Place the widgets in the Toplevel."""
self._canvas.grid(sticky="nswe")
self.header_label.grid(row=1, | python | {
"resource": ""
} |
q21779 | Balloon.show | train | def show(self):
"""
Create the Toplevel widget and its child widgets to show in the spot of the cursor.
This is the callback for the delayed :obj:`<Enter>` event (see :meth:`~Balloon._on_enter`).
"""
self._toplevel = tk.Toplevel(self.master)
self._canvas = tk.Canvas(self._toplevel, background=self.__background)
self.header_label = ttk.Label(self._canvas, text=self.__headertext, background=self.__background,
image=self._photo_image, compound=tk.LEFT)
self.text_label = ttk.Label(self._canvas, text=self.__text, wraplength=self.__width,
| python | {
"resource": ""
} |
q21780 | FontPropertiesFrame._on_click | train | def _on_click(self):
"""Handles clicks and calls callback."""
if callable(self.__callback):
| python | {
"resource": ""
} |
q21781 | rgb_to_hsv | train | def rgb_to_hsv(r, g, b):
"""Convert RGB color to HSV."""
h, s, v = colorsys.rgb_to_hsv(r / 255., g / 255., b / 255.) | python | {
"resource": ""
} |
q21782 | hexa_to_rgb | train | def hexa_to_rgb(color):
"""Convert hexadecimal color to RGB."""
r = int(color[1:3], 16)
g = int(color[3:5], 16)
b = int(color[5:7], 16)
if len(color) == 7:
return r, g, b
elif len(color) == 9:
| python | {
"resource": ""
} |
q21783 | col2hue | train | def col2hue(r, g, b):
"""Return hue value corresponding to given RGB color."""
return round2(180 / | python | {
"resource": ""
} |
q21784 | create_checkered_image | train | def create_checkered_image(width, height, c1=(154, 154, 154, 255),
c2=(100, 100, 100, 255), s=6):
"""
Return a checkered image of size width x height.
Arguments:
* width: image width
* height: image height
* c1: first color (RGBA)
* c2: second color (RGBA)
* s: size of the squares
"""
im = Image.new("RGBA", (width, height), c1)
draw = ImageDraw.Draw(im, "RGBA")
for i in range(s, width, 2 * s):
for j in range(0, height, 2 * s):
| python | {
"resource": ""
} |
q21785 | TimeLine.grid_widgets | train | def grid_widgets(self):
"""
Configure all widgets using the grid geometry manager
Automatically called by the :meth:`__init__` method.
Does not have to be called by the user except in extraordinary
cases.
"""
# Categories
for index, label in enumerate(self._category_labels.values()):
label.grid(column=0, row=index, padx=5, sticky="nw", pady=(1, 0) if index == 0 else 0)
# Canvas widgets
self._canvas_scroll.grid(column=1, row=0, padx=(0, 5), pady=5, | python | {
"resource": ""
} |
q21786 | TimeLine.draw_timeline | train | def draw_timeline(self):
"""Draw the contents of the whole TimeLine Canvas"""
# Configure the canvas
self.clear_timeline()
self.create_scroll_region()
self._timeline.config(width=self.pixel_width)
self._canvas_scroll.config(width=self._width, height=self._height)
| python | {
"resource": ""
} |
q21787 | TimeLine.draw_time_marker | train | def draw_time_marker(self):
"""Draw the time marker on the TimeLine Canvas"""
self._time_marker_image = self._canvas_ticks.create_image((2, 16), image=self._time_marker)
self._time_marker_line = self._timeline.create_line(
| python | {
"resource": ""
} |
q21788 | TimeLine.draw_categories | train | def draw_categories(self):
"""Draw the category labels on the Canvas"""
for label in self._category_labels.values():
label.destroy()
self._category_labels.clear()
canvas_width = 0
for category in (sorted(self._categories.keys() if isinstance(self._categories, dict) else self._categories)
if not isinstance(self._categories, OrderedDict)
else self._categories):
kwargs = self._categories[category] if isinstance(self._categories, dict) else {"text": category}
kwargs["background"] = kwargs.get("background", self._background)
kwargs["justify"] = kwargs.get("justify", tk.LEFT)
label = ttk.Label(self._frame_categories, **kwargs)
| python | {
"resource": ""
} |
q21789 | TimeLine.create_scroll_region | train | def create_scroll_region(self):
"""Setup the scroll region on the Canvas"""
canvas_width = 0
canvas_height = 0
for label in self._category_labels.values():
width = label.winfo_reqwidth()
canvas_height += label.winfo_reqheight()
| python | {
"resource": ""
} |
q21790 | TimeLine.clear_timeline | train | def clear_timeline(self):
"""
Clear the contents of the TimeLine Canvas
Does not modify the actual markers dictionary and thus after
redrawing all markers are visible | python | {
"resource": ""
} |
q21791 | TimeLine.draw_ticks | train | def draw_ticks(self):
"""Draw the time tick markers on the TimeLine Canvas"""
self._canvas_ticks.create_line((0, 10, self.pixel_width, 10), fill="black")
self._ticks = list(TimeLine.range(self._start, self._finish, self._tick_resolution / self._zoom_factor))
for tick in self._ticks:
string = TimeLine.get_time_string(tick, self._unit)
x = self.get_time_position(tick)
x_tick = x + 1 if x == 0 else (x - 1 if x == self.pixel_width else x)
x_text = x + 15 if x - 15 <= 0 else (x - | python | {
"resource": ""
} |
q21792 | TimeLine.draw_separators | train | def draw_separators(self):
"""Draw the lines separating the categories on the Canvas"""
total = 1
self._timeline.create_line((0, 1, self.pixel_width, 1))
for index, (category, label) in enumerate(self._category_labels.items()):
height = label.winfo_reqheight()
self._rows[category] = (total, total + height)
| python | {
"resource": ""
} |
q21793 | TimeLine.draw_markers | train | def draw_markers(self):
"""Draw all created markers on the TimeLine Canvas"""
self._canvas_markers.clear()
for marker in self._markers.values():
| python | {
"resource": ""
} |
q21794 | TimeLine.__configure_timeline | train | def __configure_timeline(self, *args):
"""Function from ScrolledFrame, adapted for the _timeline"""
# Resize the canvas scrollregion to | python | {
"resource": ""
} |
q21795 | TimeLine.create_marker | train | def create_marker(self, category, start, finish, marker=None, **kwargs):
"""
Create a new marker in the TimeLine with the specified options
:param category: Category identifier, key as given in categories
dictionary upon initialization
:type category: Any
:param start: Start time for the marker
:type start: float
:param finish: Finish time for the marker
:type finish: float
:param marker: marker dictionary (replaces kwargs)
:type marker: dict[str, Any]
**Marker Options**
Options can be given either in the marker dictionary argument,
or as keyword arguments. Given keyword arguments take precedence
over tag options, which take precedence over default options.
:param text: Text to show in the marker. Text may not be
displayed fully if the zoom level does not allow the marker
to be wide enough. Updates when resizing the marker.
:type text: str
:param background: Background color for the marker
:type background: str
:param foreground: Foreground (text) color for the marker
:type foreground: str
:param outline: Outline color for the marker
:type outline: str
:param border: The width of the border (for which outline is the
color)
:type border: int
:param font: Font tuple to set for the marker
:type font: tuple
:param iid: Unique marker identifier to use. A marker is
generated if not given, and its value is returned. Use this
option if keeping track of markers in a different manner
than with auto-generated iid's is necessary.
:type iid: str
:param tags: Set of tags to apply to this marker, allowing
callbacks to be set and other options to be configured. The
option precedence is from the first to the last item, so
the options of the last item overwrite those of the one
before, and those of the one before that, and so on.
:type tags: tuple[str]
:param move: Whether the marker is allowed to be moved
:type move: bool
Additionally, all the options with the ``marker_`` prefix from
:meth:`__init__`, but without the prefix, are supported. Active state
options are also available, with the ``active_`` prefix for
``background``, ``foreground``, ``outline``, ``border``. These
options are also available for the hover state with the
``hover_`` prefix.
:return: identifier of the created marker
:rtype: str
:raise ValueError: One of the specified arguments is invalid
"""
kwargs = kwargs if marker is None else marker
if category not in self._categories:
raise ValueError("category argument not a valid category: {}".format(category))
if start < self._start or finish > self._finish:
raise ValueError("time out of bounds")
self.check_marker_kwargs(kwargs)
# Update the options based on the tags. The last tag always takes precedence over the ones before it, and the
# marker specific options take precedence over tag options
tags = kwargs.get("tags", ())
options = kwargs.copy()
| python | {
"resource": ""
} |
q21796 | TimeLine._draw_text | train | def _draw_text(self, coords, text, foreground, font):
"""Draw the text and shorten it if required"""
if text is None:
return None
x1_r, _, x2_r, _ = coords
while True:
text_id = self._timeline.create_text(
(0, 0), text=text,
fill=foreground if foreground != "default" else self._marker_foreground,
font=font if font != "default" else self._marker_font,
tags=("marker",)
)
x1_t, _, x2_t, _ | python | {
"resource": ""
} |
q21797 | TimeLine.update_marker | train | def update_marker(self, iid, **kwargs):
"""
Change the options for a certain marker and redraw the marker
:param iid: identifier of the marker to change
:type iid: str
:param kwargs: Dictionary of options to update
:type kwargs: dict
:raises: ValueError
"""
if iid not in self._markers:
| python | {
"resource": ""
} |
q21798 | TimeLine.delete_marker | train | def delete_marker(self, iid):
"""
Delete a marker from the TimeLine
:param iid: marker identifier
:type iid: str
"""
if iid == tk.ALL:
for iid in self.markers.keys():
self.delete_marker(iid)
return
| python | {
"resource": ""
} |
q21799 | TimeLine.zoom_in | train | def zoom_in(self):
"""Increase zoom factor and redraw TimeLine"""
index = self._zoom_factors.index(self._zoom_factor)
if index + 1 == len(self._zoom_factors):
# Already zoomed in all the way
return
self._zoom_factor = self._zoom_factors[index + 1]
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.