text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _notify_change(self, model, attr, old, new, hint=None, setter=None, callback_invoker=None):
''' Called by Model when it changes
'''
# if name changes, update by-name index
if attr == 'name':
if old is not None:
self._all_models_by_name.remove_value(old, m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _remove_session_callback(self, callback_obj, originator):
''' Remove a callback added earlier with ``add_periodic_callback``,
``add_timeout_callback``, or ``add_next_tick_callback``.
Returns:
None
Raises:
KeyError, if the callback was never added
''... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _check_callback(callback, fargs, what="Callback functions"):
'''Bokeh-internal function to check callback signature'''
sig = signature(callback)
formatted_args = format_signature(sig)
error_msg = what + " must have signature func(%s), got func%s"
all_names, default_values = get_param_info(sig)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def remove_on_change(self, attr, *callbacks):
''' Remove a callback from this object '''
if len(callbacks) == 0:
raise ValueError("remove_on_change takes an attribute name and one or more callbacks, got only one parameter")
_callbacks = self._callbacks.setdefault(attr, [])
fo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def trigger(self, attr, old, new, hint=None, setter=None):
''' Trigger callbacks for ``attr`` on this object.
Args:
attr (str) :
old (object) :
new (object) :
Returns:
None
'''
def invoke():
callbacks = self._callback... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def download(progress=True):
''' Download larger data sets for various Bokeh examples.
'''
data_dir = external_data_dir(create=True)
print("Using data directory: %s" % data_dir)
s3 = 'https://bokeh-sampledata.s3.amazonaws.com'
files = [
(s3, 'CGM.csv'),
(s3, 'US_Counties.zip'),... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def main(argv):
''' Execute the Bokeh command.
Args:
argv (seq[str]) : a list of command line arguments to process
Returns:
None
The first item in ``argv`` is typically "bokeh", and the second should
be the name of one of the available subcommands:
* :ref:`html <bokeh.command... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def show(obj, browser=None, new="tab", notebook_handle=False, notebook_url="localhost:8888", **kw):
''' Immediately display a Bokeh object or application.
:func:`show` may be called multiple times in a single Jupyter notebook
cell to display multiple objects. The objects are displayed in order.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def html_page_for_render_items(bundle, docs_json, render_items, title, template=None, template_variables={}):
''' Render an HTML page from a template and Bokeh render items.
Args:
bundle (tuple):
a tuple containing (bokehjs, bokehcss)
docs_json (JSON-like):
Serialized B... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_hosted_zip(data_url, save_dir, exclude_term=None):
"""Downloads, then extracts a zip file.""" |
zip_name = os.path.join(save_dir, 'temp.zip')
# get the zip file
try:
print('Downloading %r to %r' % (data_url, zip_name))
zip_name, hdrs = urllib.request.urlretrieve(url=data_url, filename=zip_name)
print('Download successfully completed')
except IOError as e:
print("... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_zip(zip_name, exclude_term=None):
"""Extracts a zip file to its containing directory.""" |
zip_dir = os.path.dirname(os.path.abspath(zip_name))
try:
with zipfile.ZipFile(zip_name) as z:
# write each zipped file out if it isn't a directory
files = [zip_file for zip_file in z.namelist() if not zip_file.endswith('/')]
print('Extracting %i files from %r.' ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def value_as_datetime(self):
''' Convenience property to retrieve the value tuple as a tuple of
datetime objects.
'''
if self.value is None:
return None
v1, v2 = self.value
if isinstance(v1, numbers.Number):
d1 = datetime.utcfromtimestamp(v1 / 100... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def value_as_date(self):
''' Convenience property to retrieve the value tuple as a tuple of
date objects.
Added in version 1.1
'''
if self.value is None:
return None
v1, v2 = self.value
if isinstance(v1, numbers.Number):
dt = datetime.utcf... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def modify_document(self, doc):
''' Execute the configured ``main.py`` or ``main.ipynb`` to modify the
document.
This method will also search the app directory for any theme or
template files, and automatically configure the document with them
if they are found.
'''
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def scatter(self, *args, **kwargs):
''' Creates a scatter plot of the given x and y items.
Args:
x (str or seq[float]) : values or field names of center x coordinates
y (str or seq[float]) : values or field names of center y coordinates
size (str or list[float]) : ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def hexbin(self, x, y, size, orientation="pointytop", palette="Viridis256", line_color=None, fill_color=None, aspect_scale=1, **kwargs):
''' Perform a simple equal-weight hexagonal binning.
A :class:`~bokeh.models._glyphs.HexTile` glyph will be added to display
the binning. The :class:`~bokeh.m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def harea_stack(self, stackers, **kw):
''' Generate multiple ``HArea`` renderers for levels stacked left
to right.
Args:
stackers (seq[str]) : a list of data source field names to stack
successively for ``x1`` and ``x2`` harea coordinates.
Additional... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def hbar_stack(self, stackers, **kw):
''' Generate multiple ``HBar`` renderers for levels stacked left to right.
Args:
stackers (seq[str]) : a list of data source field names to stack
successively for ``left`` and ``right`` bar coordinates.
Additionally, the... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def line_stack(self, x, y, **kw):
''' Generate multiple ``Line`` renderers for lines stacked vertically
or horizontally.
Args:
x (seq[str]) :
y (seq[str]) :
Additionally, the ``name`` of the renderer will be set to
the value of each successive stacker (... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def varea_stack(self, stackers, **kw):
''' Generate multiple ``VArea`` renderers for levels stacked bottom
to top.
Args:
stackers (seq[str]) : a list of data source field names to stack
successively for ``y1`` and ``y1`` varea coordinates.
Additional... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def vbar_stack(self, stackers, **kw):
''' Generate multiple ``VBar`` renderers for levels stacked bottom
to top.
Args:
stackers (seq[str]) : a list of data source field names to stack
successively for ``left`` and ``right`` bar coordinates.
Additiona... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def graph(self, node_source, edge_source, layout_provider, **kwargs):
''' Creates a network graph using the given node, edge and layout provider.
Args:
node_source (:class:`~bokeh.models.sources.ColumnDataSource`) : a user-supplied data source
for the graph nodes. An attempt... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def without_property_validation(input_function):
''' Turn off property validation during update callbacks
Example:
.. code-block:: python
@without_property_validation
def update(attr, old, new):
# do things without validation
See Also:
:class:`~boke... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_env():
''' Get the correct Jinja2 Environment, also for frozen scripts.
'''
if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
# PyInstaller uses _MEIPASS and only works with jinja2.FileSystemLoader
templates_path = join(sys._MEIPASS, 'bokeh', 'core', '_templates')
el... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def handle(self, message, connection):
''' Delegate a received message to the appropriate handler.
Args:
message (Message) :
The message that was receive that needs to be handled
connection (ServerConnection) :
The connection that received this m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _needs_document_lock(func):
'''Decorator that adds the necessary locking and post-processing
to manipulate the session's document. Expects to decorate a
method on ServerSession and transforms it into a coroutine
if it wasn't already.
'''
@gen.coroutine
def _needs_document_lock_w... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unsubscribe(self, connection):
"""This should only be called by ``ServerConnection.unsubscribe_session`` or our book-keeping will be broken""" |
self._subscribed_connections.discard(connection)
self._last_unsubscribe_time = current_time() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_cwd(self, dirname):
"""Set shell current working directory.""" |
# Replace single for double backslashes on Windows
if os.name == 'nt':
dirname = dirname.replace(u"\\", u"\\\\")
if not self.external_kernel:
code = u"get_ipython().kernel.set_cwd(u'''{}''')".format(dirname)
if self._reading:
self.kernel_clie... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_bracket_matcher_color_scheme(self, color_scheme):
"""Set color scheme for matched parentheses.""" |
bsh = sh.BaseSH(parent=self, color_scheme=color_scheme)
mpcolor = bsh.get_matched_p_color()
self._bracket_matcher.format.setBackground(mpcolor) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_color_scheme(self, color_scheme, reset=True):
"""Set color scheme of the shell.""" |
self.set_bracket_matcher_color_scheme(color_scheme)
self.style_sheet, dark_color = create_qss_style(color_scheme)
self.syntax_style = color_scheme
self._style_sheet_changed()
self._syntax_style_changed()
if reset:
self.reset(clear=True)
if not dark_co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def long_banner(self):
"""Banner for IPython widgets with pylab message""" |
# Default banner
try:
from IPython.core.usage import quick_guide
except Exception:
quick_guide = ''
banner_parts = [
'Python %s\n' % self.interpreter_versions['python_version'],
'Type "copyright", "credits" or "license" for more informatio... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reset_namespace(self, warning=False, message=False):
"""Reset the namespace by removing all names defined by the user.""" |
reset_str = _("Remove all variables")
warn_str = _("All user-defined variables will be removed. "
"Are you sure you want to proceed?")
kernel_env = self.kernel_manager._kernel_spec.env
if warning:
box = MessageCheckBox(icon=QMessageBox.Warning, parent=s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_shortcuts(self):
"""Create shortcuts for ipyconsole.""" |
inspect = config_shortcut(self._control.inspect_current_object,
context='Console',
name='Inspect current object', parent=self)
clear_console = config_shortcut(self.clear_console, context='Console',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def silent_execute(self, code):
"""Execute code in the kernel without increasing the prompt""" |
try:
self.kernel_client.execute(to_text_string(code), silent=True)
except AttributeError:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def silent_exec_method(self, code):
"""Silently execute a kernel method and save its reply The methods passed here **don't** involve getting the value of a varia... |
# Generate uuid, which would be used as an indication of whether or
# not the unique request originated from here
local_uuid = to_text_string(uuid.uuid1())
code = to_text_string(code)
if self.kernel_client is None:
return
msg_id = self.kernel_client.execute(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_exec_method(self, msg):
""" Handle data returned by silent executions of kernel methods This is based on the _handle_exec_callback of RichJupyterWidge... |
user_exp = msg['content'].get('user_expressions')
if not user_exp:
return
for expression in user_exp:
if expression in self._kernel_methods:
# Process kernel reply
method = self._kernel_methods[expression]
reply = user_exp[... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_backend_for_mayavi(self, command):
""" Mayavi plots require the Qt backend, so we try to detect if one is generated to change backends """ |
calling_mayavi = False
lines = command.splitlines()
for l in lines:
if not l.startswith('#'):
if 'import mayavi' in l or 'from mayavi' in l:
calling_mayavi = True
break
if calling_mayavi:
message = _("Changi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def change_mpl_backend(self, command):
""" If the user is trying to change Matplotlib backends with %matplotlib, send the same command again to the kernel to cor... |
if command.startswith('%matplotlib') and \
len(command.splitlines()) == 1:
if not 'inline' in command:
self.silent_execute(command) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _context_menu_make(self, pos):
"""Reimplement the IPython context menu""" |
menu = super(ShellWidget, self)._context_menu_make(pos)
return self.ipyclient.add_actions_to_context_menu(menu) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _banner_default(self):
""" Reimplement banner creation to let the user decide if he wants a banner or not """ |
# Don't change banner for external kernels
if self.external_kernel:
return ''
show_banner_o = self.additional_options['show_banner']
if show_banner_o:
return self.long_banner()
else:
return self.short_banner() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _syntax_style_changed(self):
"""Refresh the highlighting with the current syntax style by class.""" |
if self._highlighter is None:
# ignore premature calls
return
if self.syntax_style:
self._highlighter._style = create_style_class(self.syntax_style)
self._highlighter._clear_caches()
else:
self._highlighter.set_style_sheet(self.style_s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _prompt_started_hook(self):
"""Emit a signal when the prompt is ready.""" |
if not self._reading:
self._highlighter.highlighting_on = True
self.sig_prompt_ready.emit() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear(self):
"""Removes all panel from the CodeEditor.""" |
for i in range(4):
while len(self._panels[i]):
key = sorted(list(self._panels[i].keys()))[0]
panel = self.remove(key)
panel.setParent(None)
panel.deleteLater() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resize(self):
"""Resizes panels.""" |
crect = self.editor.contentsRect()
view_crect = self.editor.viewport().contentsRect()
s_bottom, s_left, s_right, s_top = self._compute_zones_sizes()
tw = s_left + s_right
th = s_bottom + s_top
w_offset = crect.width() - (view_crect.width() + tw)
h_offset = crect.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_floating_panels(self):
"""Update foating panels.""" |
crect = self.editor.contentsRect()
panels = self.panels_for_zone(Panel.Position.FLOATING)
for panel in panels:
if not panel.isVisible():
continue
panel.set_geometry(crect) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _update_viewport_margins(self):
"""Update viewport margins.""" |
top = 0
left = 0
right = 0
bottom = 0
for panel in self.panels_for_zone(Panel.Position.LEFT):
if panel.isVisible():
width = panel.sizeHint().width()
left += width
for panel in self.panels_for_zone(Panel.Position.RIGHT):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _compute_zones_sizes(self):
"""Compute panel zone sizes.""" |
# Left panels
left = 0
for panel in self.panels_for_zone(Panel.Position.LEFT):
if not panel.isVisible():
continue
size_hint = panel.sizeHint()
left += size_hint.width()
# Right panels
right = 0
for panel in self.panels_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_definition_with_regex(source, token, start_line=-1):
"""
Find the definition of an object within a source closest to a given line
""" |
if not token:
return None
if DEBUG_EDITOR:
t0 = time.time()
patterns = [ # python / cython keyword definitions
r'^c?import.*\W{0}{1}',
r'from.*\W{0}\W.*c?import ',
r'from .* c?import.*\W{0}{1}',
r'class\s*{0}{1}',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def python_like_exts():
"""Return a list of all python-like extensions""" |
exts = []
for lang in languages.PYTHON_LIKE_LANGUAGES:
exts.extend(list(languages.ALL_LANGUAGES[lang]))
return ['.' + ext for ext in exts] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all_editable_exts():
"""Return a list of all editable extensions""" |
exts = []
for (language, extensions) in languages.ALL_LANGUAGES.items():
exts.extend(list(extensions))
return ['.' + ext for ext in exts] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_info(self, info):
"""Get a formatted calltip and docstring from Fallback""" |
if info['docstring']:
if info['filename']:
filename = os.path.basename(info['filename'])
filename = os.path.splitext(filename)[0]
else:
filename = '<module>'
resp = dict(docstring=info['docstring'],
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_item_children(item):
"""Return a sorted list of all the children items of 'item'.""" |
children = [item.child(index) for index in range(item.childCount())]
for child in children[:]:
others = get_item_children(child)
if others is not None:
children += others
return sorted(children, key=lambda child: child.line) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def item_at_line(root_item, line):
"""
Find and return the item of the outline explorer under which is located
the specified 'line' of the editor.
""" |
previous_item = root_item
item = root_item
for item in get_item_children(root_item):
if item.line > line:
return previous_item
previous_item = item
else:
return item |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_current_editor(self, editor, update):
"""Bind editor instance""" |
editor_id = editor.get_id()
if editor_id in list(self.editor_ids.values()):
item = self.editor_items[editor_id]
if not self.freeze:
self.scrollToItem(item)
self.root_item_selected(item)
self.__hide_or_show_root_items(item)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def file_renamed(self, editor, new_filename):
"""File was renamed, updating outline explorer tree""" |
if editor is None:
# This is needed when we can't find an editor to attach
# the outline explorer to.
# Fix issue 8813
return
editor_id = editor.get_id()
if editor_id in list(self.editor_ids.values()):
root_item = self.editor_i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_editor_ids_order(self, ordered_editor_ids):
"""
Order the root file items in the Outline Explorer following the
provided list of editor ids.
""" |
if self.ordered_editor_ids != ordered_editor_ids:
self.ordered_editor_ids = ordered_editor_ids
if self.sort_files_alphabetically is False:
self.__sort_toplevel_items() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __sort_toplevel_items(self):
"""
Sort the root file items in alphabetical order if
'sort_files_alphabetically' is True, else order the items as
specified... |
if self.show_all_files is False:
return
current_ordered_items = [self.topLevelItem(index) for index in
range(self.topLevelItemCount())]
if self.sort_files_alphabetically:
new_ordered_items = sorted(
current_ordere... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_root_item(self, item):
"""Return the root item of the specified item.""" |
root_item = item
while isinstance(root_item.parent(), QTreeWidgetItem):
root_item = root_item.parent()
return root_item |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_visible_items(self):
"""Return a list of all visible items in the treewidget.""" |
items = []
iterator = QTreeWidgetItemIterator(self)
while iterator.value():
item = iterator.value()
if not item.isHidden():
if item.parent():
if item.parent().isExpanded():
items.append(item)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup_buttons(self):
"""Setup the buttons of the outline explorer widget toolbar.""" |
self.fromcursor_btn = create_toolbutton(
self, icon=ima.icon('fromcursor'), tip=_('Go to cursor position'),
triggered=self.treewidget.go_to_cursor_position)
buttons = [self.fromcursor_btn]
for action in [self.treewidget.collapse_all_action,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_options(self):
"""
Return outline explorer options
""" |
return dict(
show_fullpath=self.treewidget.show_fullpath,
show_all_files=self.treewidget.show_all_files,
group_cells=self.treewidget.group_cells,
show_comments=self.treewidget.show_comments,
sort_files_alphabetically=(
self.tree... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_uninstall(self):
"""Uninstalls the editor extension from the editor.""" |
self._on_close = True
self.enabled = False
self._editor = None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_versions(reporev=True):
"""Get version information for components used by Spyder""" |
import sys
import platform
import qtpy
import qtpy.QtCore
revision = None
if reporev:
from spyder.utils import vcs
revision, branch = vcs.get_git_revision(os.path.dirname(__dir__))
if not sys.platform == 'darwin': # To avoid a crash with our Mac app
system = plat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_number(dtype):
"""Return True is datatype dtype is a number kind""" |
return is_float(dtype) or ('int' in dtype.name) or ('long' in dtype.name) \
or ('short' in dtype.name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_idx_rect(index_list):
"""Extract the boundaries from a list of indexes""" |
rows, cols = list(zip(*[(i.row(), i.column()) for i in index_list]))
return ( min(rows), max(rows), min(cols), max(cols) ) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def columnCount(self, qindex=QModelIndex()):
"""Array column number""" |
if self.total_cols <= self.cols_loaded:
return self.total_cols
else:
return self.cols_loaded |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def createEditor(self, parent, option, index):
"""Create editor widget""" |
model = index.model()
value = model.get_value(index)
if model._data.dtype.name == "bool":
value = not value
model.setData(index, to_qvariant(value))
return
elif value is not np.ma.masked:
editor = QLineEdit(parent)
edi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def commitAndCloseEditor(self):
"""Commit and close editor""" |
editor = self.sender()
# Avoid a segfault with PyQt5. Variable value won't be changed
# but at least Spyder won't crash. It seems generated by a bug in sip.
try:
self.commitData.emit(editor)
except AttributeError:
pass
self.closeEditor.emi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setEditorData(self, editor, index):
"""Set editor widget's data""" |
text = from_qvariant(index.model().data(index, Qt.DisplayRole), str)
editor.setText(text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resize_to_contents(self):
"""Resize cells to contents""" |
QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
self.resizeColumnsToContents()
self.model().fetch_more(columns=True)
self.resizeColumnsToContents()
QApplication.restoreOverrideCursor() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _sel_to_text(self, cell_range):
"""Copy an array portion to a unicode string""" |
if not cell_range:
return
row_min, row_max, col_min, col_max = get_idx_rect(cell_range)
if col_min == 0 and col_max == (self.model().cols_loaded-1):
# we've selected a whole column. It isn't possible to
# select only the first part of a column without l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def change_format(self):
"""Change display format""" |
format, valid = QInputDialog.getText(self, _( 'Format'),
_( "Float formatting"),
QLineEdit.Normal, self.model.get_format())
if valid:
format = str(format)
try:
format % 1.1
exce... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def change_active_widget(self, index):
"""
This is implemented for handling negative values in index for
3d arrays, to give the same behavior as slicing
""" |
string_index = [':']*3
string_index[self.last_dim] = '<font color=red>%i</font>'
self.slicing_label.setText((r"Slicing: [" + ", ".join(string_index) +
"]") % index)
if index < 0:
data_index = self.data.shape[self.last_dim] + index
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def current_dim_changed(self, index):
"""
This change the active axis the array editor is plotting over
in 3D
""" |
self.last_dim = index
string_size = ['%i']*3
string_size[index] = '<font color=red>%i</font>'
self.shape_label.setText(('Shape: (' + ', '.join(string_size) +
') ') % self.data.shape)
if self.index_spin.value() != 0:
self.ind... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def error(self, message):
"""An error occured, closing the dialog box""" |
QMessageBox.critical(self, _("Array editor"), message)
self.setAttribute(Qt.WA_DeleteOnClose)
self.reject() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_lexer_for_filename(filename):
"""Get a Pygments Lexer given a filename. """ |
filename = filename or ''
root, ext = os.path.splitext(filename)
if ext in custom_extension_lexer_mapping:
lexer = get_lexer_by_name(custom_extension_lexer_mapping[ext])
else:
try:
lexer = get_lexer_for_filename(filename)
except Exception:
return TextLexe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_keywords(lexer):
"""Get the keywords for a given lexer. """ |
if not hasattr(lexer, 'tokens'):
return []
if 'keywords' in lexer.tokens:
try:
return lexer.tokens['keywords'][0][0].words
except:
pass
keywords = []
for vals in lexer.tokens.values():
for val in vals:
try:
if isinstanc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_words(file_path=None, content=None, extension=None):
""" Extract all words from a source code file to be used in code completion. Extract the list of wor... |
if (file_path is None and (content is None or extension is None) or
file_path and content and extension):
error_msg = ('Must provide `file_path` or `content` and `extension`')
raise Exception(error_msg)
if file_path and content is None and extension is None:
extensi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_parent_until(path):
""" Given a file path, determine the full module path. e.g. '/usr/lib/python2.7/dist-packages/numpy/core/__init__.pyc' yields 'numpy.... |
dirname = osp.dirname(path)
try:
mod = osp.basename(path)
mod = osp.splitext(mod)[0]
imp.find_module(mod, [dirname])
except ImportError:
return
items = [mod]
while 1:
items.append(osp.basename(dirname))
try:
dirname = osp.dirname(dirname)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_connection_settings(self):
"""Load the user's previously-saved kernel connection settings.""" |
existing_kernel = CONF.get("existing-kernel", "settings", {})
connection_file_path = existing_kernel.get("json_file_path", "")
is_remote = existing_kernel.get("is_remote", False)
username = existing_kernel.get("username", "")
hostname = existing_kernel.get("hostname", "")
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_connection_settings(self):
"""Save user's kernel connection settings.""" |
if not self.save_layout.isChecked():
return
is_ssh_key = bool(self.kf_radio.isChecked())
connection_settings = {
"json_file_path": self.cf.text(),
"is_remote": self.rm_group.isChecked(),
"username": self.un.text(),
"hostname": self.h... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_color(value, alpha):
"""Return color depending on value type""" |
color = QColor()
for typ in COLORS:
if isinstance(value, typ):
color = QColor(COLORS[typ])
color.setAlphaF(alpha)
return color |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_col_sep(self):
"""Return the column separator""" |
if self.tab_btn.isChecked():
return u"\t"
elif self.ws_btn.isChecked():
return None
return to_text_string(self.line_edt.text()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_row_sep(self):
"""Return the row separator""" |
if self.eol_btn.isChecked():
return u"\n"
return to_text_string(self.line_edt_row.text()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_as_data(self, as_data):
"""Set if data type conversion""" |
self._as_data = as_data
self.asDataChanged.emit(as_data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _display_data(self, index):
"""Return a data element""" |
return to_qvariant(self._data[index.row()][index.column()]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def data(self, index, role=Qt.DisplayRole):
"""Return a model data element""" |
if not index.isValid():
return to_qvariant()
if role == Qt.DisplayRole:
return self._display_data(index)
elif role == Qt.BackgroundColorRole:
return to_qvariant(get_color(self._data[index.row()][index.column()], .2))
elif role == Qt.TextAlignme... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_data_type(self, index, **kwargs):
"""Parse a type to an other type""" |
if not index.isValid():
return False
try:
if kwargs['atype'] == "date":
self._data[index.row()][index.column()] = \
datestr_to_datetime(self._data[index.row()][index.column()],
kwargs['dayfirst']).dat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _shape_text(self, text, colsep=u"\t", rowsep=u"\n",
transpose=False, skiprows=0, comments='#'):
"""Decode the shape of the given text""" |
assert colsep != rowsep
out = []
text_rows = text.split(rowsep)[skiprows:]
for row in text_rows:
stripped = to_text_string(row).strip()
if len(stripped) == 0 or stripped.startswith(comments):
continue
line = to_text_string(row)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_data(self, text, colsep=u"\t", rowsep=u"\n",
transpose=False, skiprows=0, comments='#'):
"""Put data into table model""" |
data = self._shape_text(text, colsep, rowsep, transpose, skiprows,
comments)
self._model = PreviewTableModel(data)
self.setModel(self._model) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_to_type(self,**kwargs):
"""Parse to a given type""" |
indexes = self.selectedIndexes()
if not indexes: return
for index in indexes:
self.model().parse_data_type(index, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open_data(self, text, colsep=u"\t", rowsep=u"\n",
transpose=False, skiprows=0, comments='#'):
"""Open clipboard text as table""" |
if pd:
self.pd_text = text
self.pd_info = dict(sep=colsep, lineterminator=rowsep,
skiprows=skiprows, comment=comments)
if colsep is None:
self.pd_info = dict(lineterminator=rowsep, skiprows=skiprows,
comment=comments... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _focus_tab(self, tab_idx):
"""Change tab focus""" |
for i in range(self.tab_widget.count()):
self.tab_widget.setTabEnabled(i, False)
self.tab_widget.setTabEnabled(tab_idx, True)
self.tab_widget.setCurrentIndex(tab_idx) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set_step(self, step):
"""Proceed to a given step""" |
new_tab = self.tab_widget.currentIndex() + step
assert new_tab < self.tab_widget.count() and new_tab >= 0
if new_tab == self.tab_widget.count()-1:
try:
self.table_widget.open_data(self._get_plain_text(),
self.text_widget.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _simplify_shape(self, alist, rec=0):
"""Reduce the alist dimension if needed""" |
if rec != 0:
if len(alist) == 1:
return alist[-1]
return alist
if len(alist) == 1:
return self._simplify_shape(alist[-1], 1)
return [self._simplify_shape(al, 1) for al in alist] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_table_data(self):
"""Return clipboard processed as data""" |
data = self._simplify_shape(
self.table_widget.get_data())
if self.table_widget.array_btn.isChecked():
return array(data)
elif pd and self.table_widget.df_btn.isChecked():
info = self.table_widget.pd_info
buf = io.StringIO(self.table_wi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process(self):
"""Process the data from clipboard""" |
var_name = self.name_edt.text()
try:
self.var_name = str(var_name)
except UnicodeEncodeError:
self.var_name = to_text_string(var_name)
if self.text_widget.get_as_data():
self.clip_data = self._get_table_data()
elif self.text_widget.get... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_spyder_breakpoints(self, force=False):
"""Set Spyder breakpoints into a debugging session""" |
if self._reading or force:
breakpoints_dict = CONF.get('run', 'breakpoints', {})
# We need to enclose pickled values in a list to be able to
# send them to the kernel in Python 2
serialiazed_breakpoints = [pickle.dumps(breakpoints_dict,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dbg_exec_magic(self, magic, args=''):
"""Run an IPython magic while debugging.""" |
code = "!get_ipython().kernel.shell.run_line_magic('{}', '{}')".format(
magic, args)
self.kernel_client.input(code) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def refresh_from_pdb(self, pdb_state):
""" Refresh Variable Explorer and Editor from a Pdb session, after running any pdb command. See publish_pdb_state and noti... |
if 'step' in pdb_state and 'fname' in pdb_state['step']:
fname = pdb_state['step']['fname']
lineno = pdb_state['step']['lineno']
self.sig_pdb_step.emit(fname, lineno)
if 'namespace_view' in pdb_state:
self.sig_namespace_view.emit(ast.literal_eval(
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.