_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 31
13.1k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q275100
|
wx_Menu.Enable
|
test
|
def Enable(self, value):
"enable or disable all menu items"
for
|
python
|
{
"resource": ""
}
|
q275101
|
wx_Menu.IsEnabled
|
test
|
def IsEnabled(self, *args, **kwargs):
"check if all menu items are enabled"
for i in range(self.GetMenuItemCount()):
it = self.FindItemByPosition(i)
|
python
|
{
"resource": ""
}
|
q275102
|
wx_MenuBar.Enable
|
test
|
def Enable(self, value):
"enable or disable all top menus"
|
python
|
{
"resource": ""
}
|
q275103
|
wx_MenuBar.IsEnabled
|
test
|
def IsEnabled(self, *args, **kwargs):
"check if all top menus are enabled"
for i in range(self.GetMenuCount()):
|
python
|
{
"resource": ""
}
|
q275104
|
wx_MenuBar.RemoveItem
|
test
|
def RemoveItem(self, menu):
"Helper method to remove a menu avoiding using its position"
menus = self.GetMenus() # get the list of (menu, title)
|
python
|
{
"resource": ""
}
|
q275105
|
HTMLForm.submit
|
test
|
def submit(self, btn=None):
"Process form submission"
data = self.build_data_set()
|
python
|
{
"resource": ""
}
|
q275106
|
FormTagHandler.setObjectTag
|
test
|
def setObjectTag(self, object, tag):
""" Add a tag attribute to the wx window """
object._attributes = {}
object._name = tag.GetName().lower()
for name in self.attributes:
|
python
|
{
"resource": ""
}
|
q275107
|
autosummary_table_visit_html
|
test
|
def autosummary_table_visit_html(self, node):
"""Make the first column of the table non-breaking."""
try:
tbody = node[0][0][-1]
for row in tbody:
col1_entry = row[0]
par = col1_entry[0]
for j, subnode in enumerate(list(par)):
if
|
python
|
{
"resource": ""
}
|
q275108
|
get_documenter
|
test
|
def get_documenter(obj, parent):
"""Get an autodoc.Documenter class suitable for documenting the given
object.
*obj* is the Python object to be documented, and *parent* is an
another Python object (e.g. a module or a class) to which *obj*
belongs to.
"""
from sphinx.ext.autodoc import AutoDirective, DataDocumenter, \
ModuleDocumenter
if inspect.ismodule(obj):
# ModuleDocumenter.can_document_member always returns False
return ModuleDocumenter
# Construct a fake documenter for *parent*
if parent is not None:
parent_doc_cls = get_documenter(parent, None)
else:
parent_doc_cls = ModuleDocumenter
if hasattr(parent, '__name__'):
|
python
|
{
"resource": ""
}
|
q275109
|
mangle_signature
|
test
|
def mangle_signature(sig, max_chars=30):
"""Reformat a function signature to a more compact form."""
s = re.sub(r"^\((.*)\)$", r"\1", sig).strip()
# Strip strings (which can contain things that confuse the code below)
s = re.sub(r"\\\\", "", s)
s = re.sub(r"\\'", "", s)
s = re.sub(r"'[^']*'", "", s)
# Parse the signature to arguments + options
args = []
opts = []
opt_re = re.compile(r"^(.*, |)([a-zA-Z0-9_*]+)=")
while s:
m = opt_re.search(s)
if not m:
# The rest are arguments
args = s.split(', ')
|
python
|
{
"resource": ""
}
|
q275110
|
_import_by_name
|
test
|
def _import_by_name(name):
"""Import a Python object given its full name."""
try:
name_parts = name.split('.')
# try first interpret `name` as MODNAME.OBJ
modname = '.'.join(name_parts[:-1])
if modname:
try:
__import__(modname)
mod = sys.modules[modname]
return getattr(mod, name_parts[-1]), mod
except (ImportError, IndexError, AttributeError):
pass
# ... then as MODNAME, MODNAME.OBJ1, MODNAME.OBJ1.OBJ2, ...
last_j = 0
modname = None
for j in reversed(range(1, len(name_parts)+1)):
last_j = j
modname = '.'.join(name_parts[:j])
try:
__import__(modname)
except:# ImportError:
continue
if modname in sys.modules:
|
python
|
{
"resource": ""
}
|
q275111
|
autolink_role
|
test
|
def autolink_role(typ, rawtext, etext, lineno, inliner,
options={}, content=[]):
"""Smart linking role.
Expands to ':obj:`text`' if `text` is an object that can be imported;
otherwise expands to '*text*'.
"""
env = inliner.document.settings.env
r = env.get_domain('py').role('obj')(
'obj', rawtext, etext, lineno, inliner, options, content)
pnode = r[0][0]
prefixes = get_import_prefixes_from_env(env)
try:
|
python
|
{
"resource": ""
}
|
q275112
|
alert
|
test
|
def alert(message, title="", parent=None, scrolled=False, icon="exclamation"):
"Show a simple pop-up modal dialog"
if not scrolled:
icons = {'exclamation': wx.ICON_EXCLAMATION, 'error': wx.ICON_ERROR,
'question': wx.ICON_QUESTION, 'info': wx.ICON_INFORMATION}
style = wx.OK | icons[icon]
|
python
|
{
"resource": ""
}
|
q275113
|
prompt
|
test
|
def prompt(message="", title="", default="", multiline=False, password=None,
parent=None):
"Modal dialog asking for an input, returns string or None if cancelled"
if password:
style = wx.TE_PASSWORD | wx.OK | wx.CANCEL
result = dialogs.textEntryDialog(parent, message, title, default, style)
elif multiline:
style = wx.TE_MULTILINE | wx.OK | wx.CANCEL
result = dialogs.textEntryDialog(parent,
|
python
|
{
"resource": ""
}
|
q275114
|
select_font
|
test
|
def select_font(message="", title="", font=None, parent=None):
"Show a dialog to select a font"
if font is not None:
wx_font = font._get_wx_font() # use as default
else:
wx_font = None
font = Font()
|
python
|
{
"resource": ""
}
|
q275115
|
select_color
|
test
|
def select_color(message="", title="", color=None, parent=None):
"Show a dialog to pick a color"
result
|
python
|
{
"resource": ""
}
|
q275116
|
choose_directory
|
test
|
def choose_directory(message='Choose a directory', path="", parent=None):
"Show a dialog to choose a directory"
|
python
|
{
"resource": ""
}
|
q275117
|
find
|
test
|
def find(default='', whole_words=0, case_sensitive=0, parent=None):
"Shows a find text dialog"
result = dialogs.findDialog(parent, default, whole_words, case_sensitive)
return {'text':
|
python
|
{
"resource": ""
}
|
q275118
|
TreeItem.set_has_children
|
test
|
def set_has_children(self, has_children=True):
"Force appearance of the button next to the item"
# This is useful to allow the user to expand the items which don't have
# any children now, but instead adding them only when needed, thus
# minimizing memory usage and loading time.
|
python
|
{
"resource": ""
}
|
q275119
|
Window._set_icon
|
test
|
def _set_icon(self, icon=None):
"""Set icon based on resource values"""
if icon is not None:
try:
wx_icon = wx.Icon(icon, wx.BITMAP_TYPE_ICO)
|
python
|
{
"resource": ""
}
|
q275120
|
Window.show
|
test
|
def show(self, value=True, modal=None):
"Display or hide the window, optionally disabling all other windows"
self.wx_obj.Show(value)
if modal:
# disable all top level windows of this application (MakeModal)
disabler = wx.WindowDisabler(self.wx_obj)
# create an event loop to stop execution
eventloop = wx.EventLoop()
def on_close_modal(evt):
evt.Skip()
|
python
|
{
"resource": ""
}
|
q275121
|
parse
|
test
|
def parse(filename=""):
"Open, read and eval the resource from the source file"
# use the provided resource file:
s = open(filename).read()
|
python
|
{
"resource": ""
}
|
q275122
|
save
|
test
|
def save(filename, rsrc):
"Save the resource to the source file"
s = pprint.pformat(rsrc)
|
python
|
{
"resource": ""
}
|
q275123
|
build_window
|
test
|
def build_window(res):
"Create a gui2py window based on the python resource"
# windows specs (parameters)
kwargs = dict(res.items())
wintype = kwargs.pop('type')
menubar = kwargs.pop('menubar', None)
components = kwargs.pop('components')
panel = kwargs.pop('panel', {})
from gui import registry
import gui
winclass = registry.WINDOWS[wintype]
win = winclass(**kwargs)
# add an implicit panel by default (as pythoncard had)
if False and panel is not None:
panel['name'] = 'panel'
p = gui.Panel(win, **panel)
else:
|
python
|
{
"resource": ""
}
|
q275124
|
build_component
|
test
|
def build_component(res, parent=None):
"Create a gui2py control based on the python resource"
# control specs (parameters)
kwargs = dict(res.items())
comtype = kwargs.pop('type')
if 'components' in res:
components = kwargs.pop('components')
elif comtype == 'Menu' and 'items' in res:
components = kwargs.pop('items')
else:
components = []
from gui import registry
if comtype in registry.CONTROLS:
comclass = registry.CONTROLS[comtype]
elif comtype in registry.MENU:
comclass = registry.MENU[comtype]
elif comtype in registry.MISC:
|
python
|
{
"resource": ""
}
|
q275125
|
connect
|
test
|
def connect(component, controller=None):
"Associate event handlers "
# get the controller functions and names (module or class)
if not controller or isinstance(controller, dict):
if not controller:
controller = util.get_caller_module_dict()
controller_name = controller['__name__']
controller_dict = controller
else:
controller_name = controller.__class__.__name__
controller_dict = dict([(k, getattr(controller, k)) for k
in dir(controller) if k.startswith("on_")])
for fn in [n for n in controller_dict if n.startswith("on_")]:
# on_mypanel_mybutton_click -> ['mypanel']['mybutton'].onclick
names = fn.split("_")
event_name = names.pop(0) + names.pop(-1)
# find the control
obj = component
for name in names:
try:
obj = obj[name]
except KeyError:
obj = None
break
if not obj:
from .component import COMPONENTS
for key, obj in COMPONENTS.items():
if obj.name == name:
print "WARNING: %s should be %s" % (name, key.replace(".", "_"))
break
else:
raise NameError("'%s' component not found (%s.%s)" %
|
python
|
{
"resource": ""
}
|
q275126
|
PythonCardWrapper.convert
|
test
|
def convert(self, name):
"translate gui2py attribute name from pythoncard legacy code"
new_name = PYTHONCARD_PROPERTY_MAP.get(name)
if new_name:
|
python
|
{
"resource": ""
}
|
q275127
|
set_data
|
test
|
def set_data(data):
"Write content to the clipboard, data can be either a string or a bitmap"
try:
if wx.TheClipboard.Open():
if isinstance(data, (str, unicode)):
do = wx.TextDataObject()
|
python
|
{
"resource": ""
}
|
q275128
|
find_autosummary_in_docstring
|
test
|
def find_autosummary_in_docstring(name, module=None, filename=None):
"""Find out what items are documented in the given object's docstring.
See `find_autosummary_in_lines`.
"""
try:
real_name, obj, parent = import_by_name(name)
lines = pydoc.getdoc(obj).splitlines()
|
python
|
{
"resource": ""
}
|
q275129
|
InspectorPanel.load_object
|
test
|
def load_object(self, obj=None):
"Add the object and all their childs"
# if not obj is given, do a full reload using the current root
if obj:
self.root_obj = obj
else:
obj = self.root_obj
self.tree.DeleteAllItems()
self.root = self.tree.AddRoot("application")
self.tree.SetItemText(self.root, "App", 1)
self.tree.SetItemText(self.root, "col 2 root", 2)
|
python
|
{
"resource": ""
}
|
q275130
|
InspectorPanel.inspect
|
test
|
def inspect(self, obj, context_menu=False, edit_prop=False, mouse_pos=None):
"Select the object and show its properties"
child = self.tree.FindItem(self.root, obj.name)
if DEBUG: print "inspect child", child
if child:
self.tree.ScrollTo(child)
|
python
|
{
"resource": ""
}
|
q275131
|
InspectorPanel.activate_item
|
test
|
def activate_item(self, child, edit_prop=False, select=False):
"load the selected item in the property editor"
d = self.tree.GetItemData(child)
if d:
o = d.GetData()
self.selected_obj = o
callback = lambda o=o, **kwargs: self.update(o, **kwargs)
self.propeditor.load_object(o, callback)
|
python
|
{
"resource": ""
}
|
q275132
|
InspectorPanel.update
|
test
|
def update(self, obj, **kwargs):
"Update the tree item when the object name changes"
# search for the old name:
child = self.tree.FindItem(self.root, kwargs['name'])
if DEBUG: print "update child", child, kwargs
if child:
self.tree.ScrollTo(child)
|
python
|
{
"resource": ""
}
|
q275133
|
InspectorPanel.show_context_menu
|
test
|
def show_context_menu(self, item, mouse_pos=None):
"Open a popup menu with options regarding the selected object"
if item:
d = self.tree.GetItemData(item)
if d:
obj = d.GetData()
if obj:
# highligh and store the selected object:
self.highlight(obj.wx_obj)
self.obj = obj
# make the context menu
menu = wx.Menu()
id_del, id_dup, id_raise, id_lower = [wx.NewId() for i
in range(4)]
menu.Append(id_del, "Delete")
menu.Append(id_dup, "Duplicate")
menu.Append(id_raise, "Bring to Front")
menu.Append(id_lower, "Send to Back")
# make submenu!
sm = wx.Menu()
for ctrl in sorted(obj._meta.valid_children,
key=lambda c:
registry.ALL.index(c._meta.name)):
new_id = wx.NewId()
sm.Append(new_id, ctrl._meta.name)
self.Bind(wx.EVT_MENU,
|
python
|
{
"resource": ""
}
|
q275134
|
HyperlinkedSorlImageField.to_representation
|
test
|
def to_representation(self, value):
"""
Perform the actual serialization.
Args:
value: the image to transform
Returns:
a url pointing at a scaled and cached image
"""
if not value:
return None
image = get_thumbnail(value, self.geometry_string, **self.options)
|
python
|
{
"resource": ""
}
|
q275135
|
SelectorFactory.expression_filter
|
test
|
def expression_filter(self, name, **kwargs):
"""
Returns a decorator function for adding an expression filter.
Args:
name (str): The name of the filter.
**kwargs: Variable keyword arguments for the filter.
Returns:
Callable[[Callable[[AbstractExpression, Any], AbstractExpression]]]: A decorator
|
python
|
{
"resource": ""
}
|
q275136
|
SelectorFactory.node_filter
|
test
|
def node_filter(self, name, **kwargs):
"""
Returns a decorator function for adding a node filter.
Args:
name (str): The name of the filter.
**kwargs: Variable keyword arguments for the filter.
Returns:
Callable[[Callable[[Element, Any], bool]]]: A decorator function for adding a
|
python
|
{
"resource": ""
}
|
q275137
|
SessionMatchersMixin.assert_current_path
|
test
|
def assert_current_path(self, path, **kwargs):
"""
Asserts that the page has the given path. By default this will compare against the
path+query portion of the full URL.
Args:
path (str | RegexObject): The string or regex that the current "path" should match.
**kwargs: Arbitrary keyword arguments for :class:`CurrentPathQuery`.
Returns:
True
Raises:
ExpectationNotMet: If the assertion hasn't succeeded during the wait time.
"""
|
python
|
{
"resource": ""
}
|
q275138
|
SessionMatchersMixin.assert_no_current_path
|
test
|
def assert_no_current_path(self, path, **kwargs):
"""
Asserts that the page doesn't have the given path.
Args:
path (str | RegexObject): The string or regex that the current "path" should match.
**kwargs: Arbitrary keyword arguments for :class:`CurrentPathQuery`.
Returns:
True
Raises:
ExpectationNotMet: If the assertion hasn't succeeded during the wait time.
"""
|
python
|
{
"resource": ""
}
|
q275139
|
SessionMatchersMixin.has_current_path
|
test
|
def has_current_path(self, path, **kwargs):
"""
Checks if the page has the given path.
Args:
path (str | RegexObject): The string or regex that the current "path" should match.
**kwargs: Arbitrary keyword arguments for :class:`CurrentPathQuery`.
Returns:
|
python
|
{
"resource": ""
}
|
q275140
|
SessionMatchersMixin.has_no_current_path
|
test
|
def has_no_current_path(self, path, **kwargs):
"""
Checks if the page doesn't have the given path.
Args:
path (str | RegexObject): The string or regex that the current "path" should match.
**kwargs: Arbitrary keyword arguments for :class:`CurrentPathQuery`.
Returns:
|
python
|
{
"resource": ""
}
|
q275141
|
Element.select_option
|
test
|
def select_option(self):
""" Select this node if it is an option element inside a select tag. """
if self.disabled:
|
python
|
{
"resource": ""
}
|
q275142
|
ExpressionFilter.apply_filter
|
test
|
def apply_filter(self, expr, value):
"""
Returns the given expression filtered by the given value.
Args:
expr (xpath.expression.AbstractExpression): The expression to filter.
value (object): The desired value with which the expression should be filtered.
Returns:
xpath.expression.AbstractExpression: The filtered expression.
"""
if self.skip(value):
return expr
if not self._valid_value(value):
msg = "Invalid value {value} passed to filter {name} - ".format(
|
python
|
{
"resource": ""
}
|
q275143
|
get_browser
|
test
|
def get_browser(browser_name, capabilities=None, **options):
"""
Returns an instance of the given browser with the given capabilities.
Args:
browser_name (str): The name of the desired browser.
capabilities (Dict[str, str | bool], optional): The desired capabilities of the browser.
Defaults to None.
options: Arbitrary keyword arguments for the browser-specific subclass of
:class:`webdriver.Remote`.
Returns:
WebDriver: An instance of the desired browser.
"""
if browser_name == "chrome":
|
python
|
{
"resource": ""
}
|
q275144
|
SelectorQuery.xpath
|
test
|
def xpath(self, exact=None):
"""
Returns the XPath query for this selector.
Args:
exact (bool, optional): Whether to exactly match text.
Returns:
str: The XPath query for this selector.
"""
exact = exact if exact is not None else self.exact
|
python
|
{
"resource": ""
}
|
q275145
|
SelectorQuery.matches_filters
|
test
|
def matches_filters(self, node):
"""
Returns whether the given node matches all filters.
Args:
node (Element): The node to evaluate.
Returns:
bool: Whether the given node matches.
"""
visible = self.visible
if self.options["text"]:
if isregex(self.options["text"]):
regex = self.options["text"]
elif self.exact_text is True:
regex = re.compile(r"\A{}\Z".format(re.escape(self.options["text"])))
else:
regex = toregex(self.options["text"])
text = normalize_text(
node.all_text if visible == "all" else node.visible_text)
if not regex.search(text):
return False
if isinstance(self.exact_text, (bytes_, str_)):
regex = re.compile(r"\A{}\Z".format(re.escape(self.exact_text)))
text = normalize_text(
node.all_text if visible == "all" else node.visible_text)
if not regex.search(text):
return False
if visible
|
python
|
{
"resource": ""
}
|
q275146
|
Session.switch_to_frame
|
test
|
def switch_to_frame(self, frame):
"""
Switch to the given frame.
If you use this method you are responsible for making sure you switch back to the parent
frame when done in the frame changed to. :meth:`frame` is preferred over this method and
should be used when possible. May not be supported by all drivers.
Args:
frame (Element | str): The iframe/frame element to switch to.
"""
if isinstance(frame, Element):
self.driver.switch_to_frame(frame)
self._scopes.append("frame")
elif frame == "parent":
if self._scopes[-1] != "frame":
raise ScopeError("`switch_to_frame(\"parent\")` cannot be called "
"from inside a descendant frame's `scope` context.")
self._scopes.pop()
self.driver.switch_to_frame("parent")
elif frame == "top":
if "frame" in self._scopes:
idx = self._scopes.index("frame")
|
python
|
{
"resource": ""
}
|
q275147
|
Session.accept_alert
|
test
|
def accept_alert(self, text=None, wait=None):
"""
Execute the wrapped code, accepting an alert.
Args:
text (str | RegexObject, optional): Text to match against the text in the modal.
wait (int | float, optional): Maximum time to wait for the modal to appear after
executing the wrapped code.
|
python
|
{
"resource": ""
}
|
q275148
|
Session.accept_confirm
|
test
|
def accept_confirm(self, text=None, wait=None):
"""
Execute the wrapped code, accepting a confirm.
Args:
text (str | RegexObject, optional): Text to match against the text in the modal.
wait (int | float, optional): Maximum time to wait for the modal to appear after
|
python
|
{
"resource": ""
}
|
q275149
|
Session.dismiss_confirm
|
test
|
def dismiss_confirm(self, text=None, wait=None):
"""
Execute the wrapped code, dismissing a confirm.
Args:
text (str | RegexObject, optional): Text to match against the text in the modal.
wait (int | float, optional): Maximum time to wait for the modal to appear after
|
python
|
{
"resource": ""
}
|
q275150
|
Session.accept_prompt
|
test
|
def accept_prompt(self, text=None, response=None, wait=None):
"""
Execute the wrapped code, accepting a prompt, optionally responding to the prompt.
Args:
text (str | RegexObject, optional): Text to match against the text in the modal.
|
python
|
{
"resource": ""
}
|
q275151
|
Session.dismiss_prompt
|
test
|
def dismiss_prompt(self, text=None, wait=None):
"""
Execute the wrapped code, dismissing a prompt.
Args:
text (str | RegexObject, optional): Text to match against the text in the modal.
wait (int | float, optional): Maximum time to wait for the modal to appear after
|
python
|
{
"resource": ""
}
|
q275152
|
Session.save_page
|
test
|
def save_page(self, path=None):
"""
Save a snapshot of the page.
If invoked without arguments, it will save a file to :data:`capybara.save_path` and the
file will be given a randomly generated filename. If invoked with a relative path, the path
|
python
|
{
"resource": ""
}
|
q275153
|
Session.save_screenshot
|
test
|
def save_screenshot(self, path=None, **kwargs):
"""
Save a screenshot of the page.
If invoked without arguments, it will save a file to :data:`capybara.save_path` and the
file will be given a randomly generated filename. If invoked with a relative path, the path
|
python
|
{
"resource": ""
}
|
q275154
|
Session.raise_server_error
|
test
|
def raise_server_error(self):
""" Raise errors encountered by the server. """
if self.server and self.server.error:
try:
if capybara.raise_server_errors:
|
python
|
{
"resource": ""
}
|
q275155
|
NodeFilter.matches
|
test
|
def matches(self, node, value):
"""
Returns whether the given node matches the filter rule with the given value.
Args:
node (Element): The node to filter.
value (object): The desired value with which the node should be evaluated.
Returns:
bool: Whether the given node matches.
"""
if self.skip(value):
return True
if not self._valid_value(value):
msg = "Invalid value {value} passed to filter {name} - ".format(
|
python
|
{
"resource": ""
}
|
q275156
|
MatchersMixin.has_checked_field
|
test
|
def has_checked_field(self, locator, **kwargs):
"""
Checks if the page or current node has a radio button or checkbox with the given label,
value, or id, that is currently checked.
Args:
locator (str): The label, name, or id of a checked field.
|
python
|
{
"resource": ""
}
|
q275157
|
MatchersMixin.has_no_checked_field
|
test
|
def has_no_checked_field(self, locator, **kwargs):
"""
Checks if the page or current node has no radio button or checkbox with the given label,
value, or id that is currently checked.
Args:
locator (str): The label, name, or id of a checked field.
|
python
|
{
"resource": ""
}
|
q275158
|
MatchersMixin.has_unchecked_field
|
test
|
def has_unchecked_field(self, locator, **kwargs):
"""
Checks if the page or current node has a radio button or checkbox with the given label,
value, or id, that is currently unchecked.
Args:
locator (str): The label, name, or id of an unchecked field.
|
python
|
{
"resource": ""
}
|
q275159
|
MatchersMixin.has_no_unchecked_field
|
test
|
def has_no_unchecked_field(self, locator, **kwargs):
"""
Checks if the page or current node has no radio button or checkbox with the given label,
value, or id, that is currently unchecked.
Args:
locator (str): The label, name, or id of an unchecked field.
|
python
|
{
"resource": ""
}
|
q275160
|
MatchersMixin.assert_text
|
test
|
def assert_text(self, *args, **kwargs):
"""
Asserts that the page or current node has the given text content, ignoring any HTML tags.
Args:
*args: Variable length argument list for :class:`TextQuery`.
**kwargs: Arbitrary keyword arguments for :class:`TextQuery`.
Returns:
True
Raises:
ExpectationNotMet: If the assertion hasn't succeeded during the wait time.
"""
query = TextQuery(*args, **kwargs)
@self.synchronize(wait=query.wait)
def
|
python
|
{
"resource": ""
}
|
q275161
|
MatchersMixin.assert_no_text
|
test
|
def assert_no_text(self, *args, **kwargs):
"""
Asserts that the page or current node doesn't have the given text content, ignoring any
HTML tags.
Args:
*args: Variable length argument list for :class:`TextQuery`.
**kwargs: Arbitrary keyword arguments for :class:`TextQuery`.
Returns:
True
Raises:
ExpectationNotMet: If the assertion hasn't succeeded during the wait time.
"""
query = TextQuery(*args, **kwargs)
@self.synchronize(wait=query.wait)
|
python
|
{
"resource": ""
}
|
q275162
|
DocumentMatchersMixin.assert_title
|
test
|
def assert_title(self, title, **kwargs):
"""
Asserts that the page has the given title.
Args:
title (str | RegexObject): The string or regex that the title should match.
**kwargs: Arbitrary keyword arguments for :class:`TitleQuery`.
Returns:
True
Raises:
ExpectationNotMet: If the assertion hasn't succeeded during the wait time.
"""
query = TitleQuery(title, **kwargs)
|
python
|
{
"resource": ""
}
|
q275163
|
DocumentMatchersMixin.assert_no_title
|
test
|
def assert_no_title(self, title, **kwargs):
"""
Asserts that the page doesn't have the given title.
Args:
title (str | RegexObject): The string that the title should include.
**kwargs: Arbitrary keyword arguments for :class:`TitleQuery`.
Returns:
True
Raises:
ExpectationNotMet: If the assertion hasn't succeeded during the wait time.
"""
query = TitleQuery(title, **kwargs)
|
python
|
{
"resource": ""
}
|
q275164
|
DocumentMatchersMixin.has_title
|
test
|
def has_title(self, title, **kwargs):
"""
Checks if the page has the given title.
Args:
title (str | RegexObject): The string or regex that the title should match.
**kwargs: Arbitrary keyword arguments for :class:`TitleQuery`.
Returns:
|
python
|
{
"resource": ""
}
|
q275165
|
DocumentMatchersMixin.has_no_title
|
test
|
def has_no_title(self, title, **kwargs):
"""
Checks if the page doesn't have the given title.
Args:
title (str | RegexObject): The string that the title should include.
**kwargs: Arbitrary keyword arguments for :class:`TitleQuery`.
Returns:
|
python
|
{
"resource": ""
}
|
q275166
|
FindersMixin.find_all
|
test
|
def find_all(self, *args, **kwargs):
"""
Find all elements on the page matching the given selector and options.
Both XPath and CSS expressions are supported, but Capybara does not try to automatically
distinguish between them. The following statements are equivalent::
page.find_all("css", "a#person_123")
page.find_all("xpath", "//a[@id='person_123']")
If the type of selector is left out, Capybara uses :data:`capybara.default_selector`. It's
set to ``"css"`` by default. ::
page.find_all("a#person_123")
capybara.default_selector = "xpath"
page.find_all("//a[@id='person_123']")
The set of found elements can further be restricted by specifying options. It's possible to
select elements by their text or visibility::
page.find_all("a", text="Home")
page.find_all("#menu li", visible=True)
By default if no elements are found, an empty list is returned; however, expectations can be
set on the number of elements to be found which will trigger Capybara's waiting behavior for
the expectations to match. The expectations can be set using::
page.assert_selector("p#foo", count=4)
page.assert_selector("p#foo", maximum=10)
page.assert_selector("p#foo", minimum=1)
page.assert_selector("p#foo", between=range(1, 11))
|
python
|
{
"resource": ""
}
|
q275167
|
FindersMixin.find_first
|
test
|
def find_first(self, *args, **kwargs):
"""
Find the first element on the page matching the given selector and options, or None if no
element matches.
By default, no waiting behavior occurs. However, if ``capybara.wait_on_first_by_default``
is set to true, it will trigger Capybara's waiting behavior for a minimum of 1 matching
element to be found.
Args:
*args: Variable length argument list for :class:`SelectorQuery`.
**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.
Returns:
|
python
|
{
"resource": ""
}
|
q275168
|
inner_content
|
test
|
def inner_content(node):
"""
Returns the inner content of a given XML node, including tags.
Args:
node (lxml.etree.Element): The node whose inner content is desired.
Returns:
str: The inner content of the node.
"""
from lxml import etree
# Include text content at the start of the node.
parts = [node.text]
for child in node.getchildren():
|
python
|
{
"resource": ""
}
|
q275169
|
inner_text
|
test
|
def inner_text(node):
"""
Returns the inner text of a given XML node, excluding tags.
Args:
node: (lxml.etree.Element): The node whose inner text is desired.
Returns:
str: The inner text of the node.
"""
from lxml import etree
# Include text content at the start of the node.
parts = [node.text]
for child in node.getchildren():
# Include the raw
|
python
|
{
"resource": ""
}
|
q275170
|
normalize_url
|
test
|
def normalize_url(url):
"""
Returns the given URL with all query keys properly escaped.
Args:
url (str): The URL to normalize.
Returns:
str: The normalized URL.
"""
uri = urlparse(url)
query = uri.query or ""
pairs = parse_qsl(query)
|
python
|
{
"resource": ""
}
|
q275171
|
setter_decorator
|
test
|
def setter_decorator(fset):
"""
Define a write-only property that, in addition to the given setter function, also
provides a setter decorator defined as the property's getter function.
This allows one to set the property either through traditional assignment, as a
method argument, or through decoration::
class Widget(object):
@setter_decorator
def handler(self, value):
self._handler = value
widget = Widget()
# Method 1: Traditional assignment
widget.handler = lambda input: process(input)
# Method 2: Assignment via method argument
widget.handler(lambda input: process(input))
# Method 3: Assignment via decoration
@widget.handler
def handler(input):
return process(input)
# Method 3b: Assignment via decoration with extraneous parens
@widget.handler()
def handler(input):
return process(input)
"""
def fget(self):
def inner(value):
|
python
|
{
"resource": ""
}
|
q275172
|
Base.synchronize
|
test
|
def synchronize(self, func=None, wait=None, errors=()):
"""
This method is Capybara's primary defense against asynchronicity problems. It works by
attempting to run a given decorated function until it succeeds. The exact behavior of this
method depends on a number of factors. Basically there are certain exceptions which, when
raised from the decorated function, instead of bubbling up, are caught, and the function is
re-run.
Certain drivers have no support for asynchronous processes. These drivers run the function,
and any error raised bubbles up immediately. This allows faster turn around in the case
where an expectation fails.
Only exceptions that are :exc:`ElementNotFound` or any subclass thereof cause the block to
be rerun. Drivers may specify additional exceptions which also cause reruns. This usually
occurs when a node is manipulated which no longer exists on the page. For example, the
Selenium driver specifies ``selenium.common.exceptions.StateElementReferenceException``.
As long as any of these exceptions are thrown, the function is re-run, until a certain
amount of time passes. The amount of time defaults to :data:`capybara.default_max_wait_time`
and can be overridden through the ``wait`` argument. This time is compared with the system
time to see how much time has passed. If the return value of ``time.time()`` is stubbed
out, Capybara will raise :exc:`FrozenInTime`.
Args:
func (Callable, optional): The function to decorate.
wait (int, optional): Number of seconds to retry this function.
errors (Tuple[Type[Exception]], optional): Exception types that cause the function to be
rerun. Defaults to ``driver.invalid_element_errors`` + :exc:`ElementNotFound`.
Returns:
Callable: The decorated function, or a decorator function.
Raises:
FrozenInTime: If the return value of ``time.time()`` appears stuck.
"""
def decorator(func):
@wraps(func)
def outer(*args, **kwargs):
seconds = wait if wait is not None else capybara.default_max_wait_time
def inner():
return func(*args, **kwargs)
|
python
|
{
"resource": ""
}
|
q275173
|
Base._should_catch_error
|
test
|
def _should_catch_error(self, error, errors=()):
"""
Returns whether to catch the given error.
Args:
error (Exception): The error to consider.
errors (Tuple[Type[Exception], ...], optional): The exception types that should be
|
python
|
{
"resource": ""
}
|
q275174
|
Result.compare_count
|
test
|
def compare_count(self):
"""
Returns how the result count compares to the query options.
The return value is negative if too few results were found, zero if enough were found, and
positive if too many were found.
Returns:
int: -1, 0, or 1.
"""
if self.query.options["count"] is not None:
count_opt = int(self.query.options["count"])
self._cache_at_least(count_opt + 1)
return cmp(len(self._result_cache), count_opt)
if self.query.options["minimum"] is not None:
min_opt = int(self.query.options["minimum"])
if not self._cache_at_least(min_opt):
return -1
if
|
python
|
{
"resource": ""
}
|
q275175
|
Result._cache_at_least
|
test
|
def _cache_at_least(self, size):
"""
Attempts to fill the result cache with at least the given number of results.
Returns:
bool: Whether the cache contains at least the given size.
"""
try:
|
python
|
{
"resource": ""
}
|
q275176
|
expects_none
|
test
|
def expects_none(options):
"""
Returns whether the given query options expect a possible count of zero.
Args:
options (Dict[str, int | Iterable[int]]): A dictionary of query options.
Returns:
bool: Whether a possible count of zero is expected.
"""
|
python
|
{
"resource": ""
}
|
q275177
|
failure_message
|
test
|
def failure_message(description, options):
"""
Returns a expectation failure message for the given query description.
Args:
description (str): A description of the failed query.
options (Dict[str, Any]): The query options.
Returns:
str: A message describing the failure.
"""
message = "expected to find {}".format(description)
if options["count"] is not None:
message += " {count} {times}".format(
count=options["count"],
times=declension("time", "times", options["count"]))
elif options["between"] is not None:
between = options["between"]
if between:
first, last = between[0], between[-1]
else:
first, last =
|
python
|
{
"resource": ""
}
|
q275178
|
matches_count
|
test
|
def matches_count(count, options):
"""
Returns whether the given count matches the given query options.
If no quantity options are specified, any count is considered acceptable.
Args:
count (int): The count to be validated.
options (Dict[str, int | Iterable[int]]): A dictionary of query options.
Returns:
bool: Whether the count matches the options.
"""
if options.get("count") is not None:
|
python
|
{
"resource": ""
}
|
q275179
|
normalize_text
|
test
|
def normalize_text(value):
"""
Normalizes the given value to a string of text with extra whitespace removed.
Byte sequences are decoded. ``None`` is converted to an empty string. Everything else
is simply cast to a string.
Args:
value (Any): The data to normalize.
|
python
|
{
"resource": ""
}
|
q275180
|
normalize_whitespace
|
test
|
def normalize_whitespace(text):
"""
Returns the given text with outer whitespace removed and inner whitespace collapsed.
|
python
|
{
"resource": ""
}
|
q275181
|
toregex
|
test
|
def toregex(text, exact=False):
"""
Returns a compiled regular expression for the given text.
Args:
text (str | RegexObject): The text to match.
exact (bool, optional): Whether the generated regular expression should match exact
strings. Defaults to False.
Returns:
RegexObject: A compiled
|
python
|
{
"resource": ""
}
|
q275182
|
CurrentPathQuery.resolves_for
|
test
|
def resolves_for(self, session):
"""
Returns whether this query resolves for the given session.
Args:
session (Session): The session for which this query should be executed.
Returns:
bool: Whether this query resolves.
"""
if self.url:
self.actual_path = session.current_url
else:
result = urlparse(session.current_url)
if self.only_path:
self.actual_path = result.path
else:
|
python
|
{
"resource": ""
}
|
q275183
|
Window.resize_to
|
test
|
def resize_to(self, width, height):
"""
Resizes the window to the given dimensions.
If this method was called for a window that is not current, then after calling this method
the current window should remain the same as it was before calling this method.
Args:
|
python
|
{
"resource": ""
}
|
q275184
|
Server.boot
|
test
|
def boot(self):
"""
Boots a server for the app, if it isn't already booted.
Returns:
Server: This server.
"""
if not self.responsive:
# Remember the port so we can reuse it if we try to serve this same app again.
type(self)._ports[self.port_key] = self.port
init_func = capybara.servers[capybara.server_name]
init_args = (self.middleware, self.port, self.host)
self.server_thread = Thread(target=init_func, args=init_args)
# Inform Python that it shouldn't wait for this thread to terminate before
# exiting. (It will still be appropriately terminated when the process exits.)
|
python
|
{
"resource": ""
}
|
q275185
|
AdvancedProperty.cgetter
|
test
|
def cgetter(self, fcget: typing.Optional[typing.Callable[[typing.Any], typing.Any]]) -> "AdvancedProperty":
"""Descriptor to change the class wide getter on a property.
:param fcget: new class-wide getter.
|
python
|
{
"resource": ""
}
|
q275186
|
SeparateClassMethod.instance_method
|
test
|
def instance_method(self, imeth: typing.Optional[typing.Callable[..., typing.Any]]) -> "SeparateClassMethod":
"""Descriptor to change instance method.
|
python
|
{
"resource": ""
}
|
q275187
|
SeparateClassMethod.class_method
|
test
|
def class_method(self, cmeth: typing.Optional[typing.Callable[..., typing.Any]]) -> "SeparateClassMethod":
"""Descriptor to change class method.
|
python
|
{
"resource": ""
}
|
q275188
|
LogOnAccess.__traceback
|
test
|
def __traceback(self) -> str:
"""Get outer traceback text for logging."""
if not self.log_traceback:
return ""
exc_info = sys.exc_info()
stack = traceback.extract_stack()
exc_tb = traceback.extract_tb(exc_info[2])
|
python
|
{
"resource": ""
}
|
q275189
|
LogOnAccess.__get_obj_source
|
test
|
def __get_obj_source(self, instance: typing.Any, owner: typing.Optional[type] = None) -> str:
"""Get object repr block."""
|
python
|
{
"resource": ""
}
|
q275190
|
LogOnAccess._get_logger_for_instance
|
test
|
def _get_logger_for_instance(self, instance: typing.Any) -> logging.Logger:
"""Get logger for log calls.
:param instance: Owner class instance. Filled only if instance created, else None.
:type instance: typing.Optional[owner]
:return: logger instance
:rtype: logging.Logger
"""
if self.logger is not None: # pylint: disable=no-else-return
|
python
|
{
"resource": ""
}
|
q275191
|
LogOnAccess.logger
|
test
|
def logger(self, logger: typing.Union[logging.Logger, str, None]) -> None:
"""Logger instance to use as override."""
if logger is None or isinstance(logger, logging.Logger):
|
python
|
{
"resource": ""
}
|
q275192
|
SlackAPI._call_api
|
test
|
def _call_api(self, method, params=None):
"""
Low-level method to call the Slack API.
Args:
method: {str} method name to call
params: {dict} GET parameters
The token will always be added
"""
url = self.url.format(method=method)
if not params:
params = {'token': self.token}
else:
params['token'] = self.token
logger.debug('Send request to %s', url)
response
|
python
|
{
"resource": ""
}
|
q275193
|
SlackAPI.channels
|
test
|
def channels(self):
"""
List of channels of this slack team
"""
if not self._channels:
|
python
|
{
"resource": ""
}
|
q275194
|
SlackAPI.users
|
test
|
def users(self):
"""
List of users of this slack team
"""
if not self._users:
|
python
|
{
"resource": ""
}
|
q275195
|
SlackClientProtocol.make_message
|
test
|
def make_message(self, text, channel):
"""
High-level function for creating messages. Return packed bytes.
Args:
text: {str}
channel: {str} Either name or ID
"""
try:
channel_id = self.slack.channel_from_name(channel)['id']
|
python
|
{
"resource": ""
}
|
q275196
|
SlackClientProtocol.translate
|
test
|
def translate(self, message):
"""
Translate machine identifiers into human-readable
"""
# translate user
try:
user_id = message.pop('user')
user = self.slack.user_from_id(user_id)
message[u'user'] = user['name']
except (KeyError, IndexError, ValueError):
pass
# translate channel
try:
if type(message['channel']) == str:
channel_id = message.pop('channel')
|
python
|
{
"resource": ""
}
|
q275197
|
SlackClientProtocol.sendSlack
|
test
|
def sendSlack(self, message):
"""
Send message to Slack
"""
channel = message.get('channel', 'general')
|
python
|
{
"resource": ""
}
|
q275198
|
SlackClientFactory.read_channel
|
test
|
def read_channel(self):
"""
Get available messages and send through to the protocol
"""
channel, message = self.protocol.channel_layer.receive_many([u'slack.send'], block=False)
delay = 0.1
|
python
|
{
"resource": ""
}
|
q275199
|
Client.run
|
test
|
def run(self):
"""
Main interface. Instantiate the SlackAPI, connect to RTM
and start the client.
"""
slack = SlackAPI(token=self.token)
rtm = slack.rtm_start()
factory = SlackClientFactory(rtm['url'])
# Attach attributes
factory.protocol = SlackClientProtocol
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.