output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Delete multiple objects from collection. | Make a summary of the following Python 3 code
def delete_many(self, **kwargs):
db_objects = self.get_dbcollection_with_es(**kwargs)
return self.Model._delete_many(db_objects, self.request) | As a Python code composer, you craft elegant and concise scripts. |
Update multiple objects from collection. | Can you generate the documentation for the following Python 3 function
def update_many(self, **kwargs):
db_objects = self.get_dbcollection_with_es(**kwargs)
return self.Model._update_many(
db_objects, self._json_params, self.request) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get value of self. _resource. parent. id_name from kwargs. | Can you tell what is the following Python 3 function doing
def _get_context_key(self, **kwargs):
return str(kwargs.get(self._resource.parent.id_name)) | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_item(self, **kwargs):
""" Reload context on each access. """
self.reload_context(es_based=False, **kwargs)
return super(ItemSubresourceBaseView, self).get_item(**kwargs) | Write a Python 3 script to
reload context on each access. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Setup the Sphinx extension. | Given the following Python 3 function, write the documentation
def setup(app):
import sphinxcontrib_django.docstrings
import sphinxcontrib_django.roles
# Setup both modules at once. They can also be separately imported to
# use only fragments of this package.
sphinxcontrib_django.docstrings.setup(a... | You are a Python code generator, capable of creating scripts from specifications. |
def patch_django_for_autodoc():
"""Fix the appearance of some classes in autodoc.
This avoids query evaluation.
"""
# Fix Django's manager appearance
ManagerDescriptor.__get__ = lambda self, *args, **kwargs: self.manager
# Stop Django from executing DB queries
models.QuerySet.__repr__ = la... | Write a Python 3 script for
fixing Django s manager appearance of some classes in autodoc. This avoids query evaluation. | You are a Python code architect, reviewing and designing scalable and efficient code |
def setup(app):
"""Allow this package to be used as Sphinx extension.
This is also called from the top-level ``__init__.py``.
:type app: sphinx.application.Sphinx
"""
from .patches import patch_django_for_autodoc
# When running, make sure Django doesn't execute querysets
patch_django_for_a... | How would you code a function in Python 3 to
allow this package to be used as Sphinx extension. This is also called from the top-level ``__init__.py``. :type app: sphinx.application.Sphinx | You are a Python code analyst, evaluating scripts for potential improvements. |
Hook that tells autodoc to skip certain fields. | Can you generate the documentation for the following Python 3 function
def autodoc_skip(app, what, name, obj, skip, options):
if name in config.EXCLUDE_MEMBERS:
return True
if name in config.INCLUDE_MEMBERS:
return False
return skip | As a Python code translator, you convert algorithms and pseudocode into Python. |
def improve_model_docstring(app, what, name, obj, options, lines):
"""Hook that improves the autodoc docstrings for Django models.
:type app: sphinx.application.Sphinx
:param what: The parent type, ``class`` or ``module``
:type what: str
:param name: The dotted path to the child method/attribute.
... | Write a Python 3 script for
hooking that improves the autodoc docstrings for Django models. | As a python code expert, you are capable of creating scripts from specifications. |
def _improve_class_docs(app, cls, lines):
"""Improve the documentation of a class."""
if issubclass(cls, models.Model):
_add_model_fields_as_params(app, cls, lines)
elif issubclass(cls, forms.Form):
_add_form_fields(cls, lines) | Can you implement a function in Python 3 that
improves the documentation of a class. | You are a Python code analyst, evaluating scripts for potential improvements. |
Improve the documentation of a Django model subclass. | Can you generate a brief explanation for the following Python 3 code
def _add_model_fields_as_params(app, obj, lines):
for field in obj._meta.get_fields():
try:
help_text = strip_tags(force_text(field.help_text))
verbose_name = force_text(field.verbose_name).capitalize()
exce... | As a Python code composer, you craft elegant and concise scripts. |
def _add_form_fields(obj, lines):
"""Improve the documentation of a Django Form class.
This highlights the available fields in the form.
"""
lines.append("**Form fields:**")
lines.append("")
for name, field in obj.base_fields.items():
field_type = "{}.{}".format(field.__class__.__module... | How would you implement a function in Python 3 that
improves the documentation of a Django Form class. | As a python code expert, you are capable of creating scripts from specifications. |
def _improve_attribute_docs(obj, name, lines):
"""Improve the documentation of various attributes.
This improves the navigation between related objects.
:param obj: the instance of the object to document.
:param name: full dotted path to the object.
:param lines: expected documentation lines.
"... | Create a Python 3 function for
improving the documentation of various attributes. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _improve_method_docs(obj, name, lines):
"""Improve the documentation of various methods.
:param obj: the instance of the method to document.
:param name: full dotted path to the object.
:param lines: expected documentation lines.
"""
if not lines:
# Not doing obj.__module__ lookups ... | Create a Python 3 function for
improving the documentation of various methods. | You are a Python code generator, capable of creating scripts from specifications. |
def attr_names(cls) -> List[str]:
"""
Returns annotated attribute names
:return: List[str]
"""
return [k for k, v in cls.attr_types().items()] | Can you implement a function in Python 3 that
returns annotated attribute names | As a Python code analyst, you investigate and solve complex coding mysteries |
Calculate the elliptical Fourier coefficients for a contour array. | Make a summary of the following Python 3 code
def elliptic_fourier_descriptors(contour, order=10, normalize=False):
dxy = np.diff(contour, axis=0)
dt = np.sqrt((dxy ** 2).sum(axis=1))
t = np.concatenate([([0., ]), np.cumsum(dt)])
T = t[-1]
phi = (2 * np.pi * t) / T
coeffs = np.zeros((order, 4)... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Normalizes an array of Fourier coefficients. | Given the following Python 3 function, write the documentation
def normalize_efd(coeffs, size_invariant=True):
# Make the coefficients have a zero phase shift from
# the first major axis. Theta_1 is that shift angle.
theta_1 = 0.5 * np.arctan2(
2 * ((coeffs[0, 0] * coeffs[0, 1]) + (coeffs[0, 2] * co... | As a Python code analyst, you investigate and solve complex coding mysteries |
def calculate_dc_coefficients(contour):
"""Calculate the :math:`A_0` and :math:`C_0` coefficients of the elliptic Fourier series.
:param numpy.ndarray contour: A contour array of size ``[M x 2]``.
:return: The :math:`A_0` and :math:`C_0` coefficients.
:rtype: tuple
"""
dxy = np.diff(contour, a... | How would you implement a function in Python 3 that
calculates the A_0 and C_0 coefficients of the elliptic Fourier series. | You are a Python code generator, capable of creating scripts from specifications. |
def plot_efd(coeffs, locus=(0., 0.), image=None, contour=None, n=300):
"""Plot a ``[2 x (N / 2)]`` grid of successive truncations of the series.
.. note::
Requires `matplotlib <http://matplotlib.org/>`_!
:param numpy.ndarray coeffs: ``[N x 4]`` Fourier coefficient array.
:param list, tuple or... | Implement a Python 3 function for
plotting a grid of successive truncations of the Fourier coefficients. | You are a Python code generator, capable of creating scripts from specifications. |
Error checker for functions returning an integer indicating that the function returned an error code. | How would you explain what the following Python 3 function does
def _errcheck(result, func, arguments):
if result != 0:
raise XdoException(
'Function {0} returned error code {1}'
.format(func.__name__, result))
return None | You are a Python code architect, reviewing and designing scalable and efficient code |
def _gen_input_mask(mask):
"""Generate input mask from bytemask"""
return input_mask(
shift=bool(mask & MOD_Shift),
lock=bool(mask & MOD_Lock),
control=bool(mask & MOD_Control),
mod1=bool(mask & MOD_Mod1),
mod2=bool(mask & MOD_Mod2),
mod3=bool(mask & MOD_Mod3),
... | How would you code a function in Python 3 to
generate input mask from bytemask | As a Python code translator, you convert algorithms and pseudocode into Python. |
def move_mouse(self, x, y, screen=0):
"""
Move the mouse to a specific location.
:param x: the target X coordinate on the screen in pixels.
:param y: the target Y coordinate on the screen in pixels.
:param screen: the screen (number) you want to move on.
"""
# to... | Write a Python 3 script to
move the mouse to a specific location. | You are a Python code analyst, evaluating scripts for potential improvements. |
Move the mouse to a specific location relative to the top - left corner of a window. | Can you tell what is the following Python 3 function doing
def move_mouse_relative_to_window(self, window, x, y):
_libxdo.xdo_move_mouse_relative_to_window(
self._xdo, ctypes.c_ulong(window), x, y) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Move the mouse relative to the current position. | Can you generate a brief explanation for the following Python 3 code
def move_mouse_relative(self, x, y):
_libxdo.xdo_move_mouse_relative(self._xdo, x, y) | As a Python code analyst, you investigate and solve complex coding mysteries |
Send a mouse down event for a given button. | How would you explain what the following Python 3 function does
def mouse_down(self, window, button):
_libxdo.xdo_mouse_down(
self._xdo, ctypes.c_ulong(window), ctypes.c_int(button)) | You are a Python code analyst, evaluating scripts for potential improvements. |
def mouse_up(self, window, button):
"""
Send a mouse release (aka mouse up) for a given button at
the current mouse location.
:param window:
The window you want to send the event to or CURRENTWINDOW
:param button:
The mouse button. Generally, 1 is left, 2... | Implement a function in Python 3 to
send a mouse release for a given button. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_mouse_location(self):
"""
Get the current mouse location (coordinates and screen number).
:return: a namedtuple with ``x``, ``y`` and ``screen_num`` fields
"""
x = ctypes.c_int(0)
y = ctypes.c_int(0)
screen_num = ctypes.c_int(0)
_libxdo.xdo_get_mo... | Can you create a Python 3 function that
gets the current mouse location. | You are a Python code generator, capable of creating scripts from specifications. |
def get_window_at_mouse(self):
"""
Get the window the mouse is currently over
"""
window_ret = ctypes.c_ulong(0)
_libxdo.xdo_get_window_at_mouse(self._xdo, ctypes.byref(window_ret))
return window_ret.value | Write a Python 3 function that can
get the window the mouse is currently over. | You are a Python code analyst, evaluating scripts for potential improvements. |
Get all mouse location - related data. | Can you generate the documentation for the following Python 3 function
def get_mouse_location2(self):
x = ctypes.c_int(0)
y = ctypes.c_int(0)
screen_num_ret = ctypes.c_ulong(0)
window_ret = ctypes.c_ulong(0)
_libxdo.xdo_get_mouse_location2(
self._xdo, ctypes.byref(x),... | You are a Python code analyst, evaluating scripts for potential improvements. |
def wait_for_mouse_move_from(self, origin_x, origin_y):
"""
Wait for the mouse to move from a location. This function will block
until the condition has been satisified.
:param origin_x: the X position you expect the mouse to move from
:param origin_y: the Y position you expect ... | Implement a Python 3 function for
waiting for the mouse to move from a location. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Wait for the mouse to move to a location. | Can you tell what is the following Python 3 function doing
def wait_for_mouse_move_to(self, dest_x, dest_y):
_libxdo.xdo_wait_for_mouse_move_from(self._xdo, dest_x, dest_y) | As a Python code analyst, you investigate and solve complex coding mysteries |
Send a click for a specific mouse button at the current mouse location. | Here you have a function in Python 3, explain what it does
def click_window(self, window, button):
_libxdo.xdo_click_window(self._xdo, window, button) | You are a Python code generator, capable of creating scripts from specifications. |
def click_window_multiple(self, window, button, repeat=2, delay=100000):
"""
Send a one or more clicks for a specific mouse button at the
current mouse location.
:param window:
The window you want to send the event to or CURRENTWINDOW
:param button:
The m... | Can you create a Python 3 function that
sends a one or more clicks for a specific mouse button at the current mouse location. | You are a Python code generator, capable of creating scripts from specifications. |
Enter a string to the specified window. | How would you explain what the following Python 3 function does
def enter_text_window(self, window, string, delay=12000):
return _libxdo.xdo_enter_text_window(self._xdo, window, string, delay) | You are a Python code generator, capable of creating scripts from specifications. |
def send_keysequence_window(self, window, keysequence, delay=12000):
"""
Send a keysequence to the specified window.
This allows you to send keysequences by symbol name. Any combination
of X11 KeySym names separated by '+' are valid. Single KeySym names
are valid, too.
... | How would you implement a function in Python 3 that
sends a keysequence to the specified window. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def send_keysequence_window_up(self, window, keysequence, delay=12000):
"""Send key release (up) events for the given key sequence"""
_libxdo.xdo_send_keysequence_window_up(
self._xdo, window, keysequence, ctypes.c_ulong(delay)) | Implement a Python 3 function for
sending key release up events for the given key sequence. | You are a Python code generator, capable of creating scripts from specifications. |
def send_keysequence_window_down(self, window, keysequence, delay=12000):
"""Send key press (down) events for the given key sequence"""
_libxdo.xdo_send_keysequence_window_down(
self._xdo, window, keysequence, ctypes.c_ulong(delay)) | How would you implement a function in Python 3 that
sends key press ( down ) events for the given key sequence. | You are a Python code architect, reviewing and designing scalable and efficient code |
Send a series of keystrokes to a specific window. | How would you explain what the following Python 3 function does
def send_keysequence_window_list_do(
self, window, keys, pressed=1, modifier=None, delay=120000):
"""
Send a series of keystrokes.
:param window: The window to send events to or CURRENTWINDOW
:param keys: The ar... | As a Python code analyst, you investigate and solve complex coding mysteries |
Get a list of active keys. Uses XQueryKeymap | How would you explain what the following Python 3 function does
def get_active_keys_to_keycode_list(self):
try:
_libxdo.xdo_get_active_keys_to_keycode_list
except AttributeError:
# Apparently, this was implemented in a later version..
raise NotImplementedError()
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def wait_for_window_map_state(self, window, state):
"""
Wait for a window to have a specific map state.
State possibilities:
IsUnmapped - window is not displayed.
IsViewable - window is mapped and shown (though may be
clipped by windows on top of it)
... | Write a Python 3 function that can
wait for a window to have a specific map state. | You are a Python code analyst, evaluating scripts for potential improvements. |
def move_window(self, window, x, y):
"""
Move a window to a specific location.
The top left corner of the window will be moved to the x,y coordinate.
:param wid: the window to move
:param x: the X coordinate to move to.
:param y: the Y coordinate to move to.
"""... | Write a Python 3 function for
moving a window to a specific location. | As a Python code composer, you craft elegant and concise scripts. |
This function will apply a window sizing hints to a given width and height. | Explain what the following Python 3 code does
def translate_window_with_sizehint(self, window, width, height):
width_ret = ctypes.c_uint(0)
height_ret = ctypes.c_uint(0)
_libxdo.xdo_translate_window_with_sizehint(
self._xdo, window, width, height,
ctypes.byref(width_ret),... | You are a Python code architect, reviewing and designing scalable and efficient code |
Change the size of a window. | Explain what the following Python 3 code does
def set_window_size(self, window, w, h, flags=0):
_libxdo.xdo_set_window_size(self._xdo, window, w, h, flags) | As a Python code analyst, you investigate and solve complex coding mysteries |
def set_window_property(self, window, name, value):
"""
Change a window property.
Example properties you can change are WM_NAME, WM_ICON_NAME, etc.
:param wid: The window to change a property of.
:param name: the string name of the property.
:param value: the string val... | Implement a function in Python 3 to
change a window property. | You are a Python code generator, capable of creating scripts from specifications. |
def set_window_class(self, window, name, class_):
"""
Change the window's classname and or class.
:param name: The new class name. If ``None``, no change.
:param class_: The new class. If ``None``, no change.
"""
_libxdo.xdo_set_window_class(self._xdo, window, name, clas... | Create a Python 3 function for
changing the classname and or class. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Sets the urgency hint for a window. | Here you have a function in Python 3, explain what it does
def set_window_urgency(self, window, urgency):
_libxdo.xdo_set_window_urgency(self._xdo, window, urgency) | You are a Python code analyst, evaluating scripts for potential improvements. |
Set the override_redirect value for a window. | How would you explain what the following Python 3 function does
def set_window_override_redirect(self, window, override_redirect):
_libxdo.xdo_set_window_override_redirect(
self._xdo, window, override_redirect) | You are a Python code analyst, evaluating scripts for potential improvements. |
Get the currently - focused window. | Here you have a function in Python 3, explain what it does
def get_focused_window(self):
window_ret = window_t(0)
_libxdo.xdo_get_focused_window(self._xdo, ctypes.byref(window_ret))
return window_ret.value | As a Python code translator, you convert algorithms and pseudocode into Python. |
def wait_for_window_focus(self, window, want_focus):
"""
Wait for a window to have or lose focus.
:param window: The window to wait on
:param want_focus: If 1, wait for focus. If 0, wait for loss of focus.
"""
_libxdo.xdo_wait_for_window_focus(self._xdo, window, want_foc... | How would you code a function in Python 3 to
wait for a window to have or lose focus. | You are a Python code generator, capable of creating scripts from specifications. |
Like xdo_get_focused_window but return the first ancestor - or - self
. | Make a summary of the following Python 3 code
def get_focused_window_sane(self):
window_ret = window_t(0)
_libxdo.xdo_get_focused_window_sane(
self._xdo, ctypes.byref(window_ret))
return window_ret.value | As a python code expert, you are capable of creating scripts from specifications. |
def wait_for_window_active(self, window, active=1):
"""
Wait for a window to be active or not active.
Requires your window manager to support this.
Uses _NET_ACTIVE_WINDOW from the EWMH spec.
:param window: the window to wait on
:param active: If 1, wait for active. If ... | Write a Python 3 script for
waiting for a window to be active or not active. | You are a Python code generator, capable of creating scripts from specifications. |
def get_window_location(self, window):
"""
Get a window's location.
"""
screen_ret = Screen()
x_ret = ctypes.c_int(0)
y_ret = ctypes.c_int(0)
_libxdo.xdo_get_window_location(
self._xdo, window, ctypes.byref(x_ret), ctypes.byref(y_ret),
ctyp... | Write a Python 3 script for
getting a window s location. | As a python code expert, you are capable of creating scripts from specifications. |
def get_window_size(self, window):
"""
Get a window's size.
"""
w_ret = ctypes.c_uint(0)
h_ret = ctypes.c_uint(0)
_libxdo.xdo_get_window_size(self._xdo, window, ctypes.byref(w_ret),
ctypes.byref(h_ret))
return window_size(w_ret.... | Can you create a Python 3 function that
gets a window s size. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_active_window(self):
"""
Get the currently-active window.
Requires your window manager to support this.
Uses ``_NET_ACTIVE_WINDOW`` from the EWMH spec.
"""
window_ret = window_t(0)
_libxdo.xdo_get_active_window(self._xdo, ctypes.byref(window_ret))
... | Write a Python 3 script to
get the currently - active window. | You are a Python code generator, capable of creating scripts from specifications. |
def select_window_with_click(self):
"""
Get a window ID by clicking on it.
This function blocks until a selection is made.
"""
window_ret = window_t(0)
_libxdo.xdo_select_window_with_click(
self._xdo, ctypes.byref(window_ret))
return window_ret.value | Write a Python 3 script for
selecting a window ID by clicking on it. | You are a Python code generator, capable of creating scripts from specifications. |
Get the current number of desktops. | Given the following Python 3 function, write the documentation
def get_number_of_desktops(self):
ndesktops = ctypes.c_long(0)
_libxdo.xdo_get_number_of_desktops(self._xdo, ctypes.byref(ndesktops))
return ndesktops.value | You are a Python code generator, capable of creating scripts from specifications. |
Get the current desktop. | Can you tell what is the following Python 3 function doing
def get_current_desktop(self):
desktop = ctypes.c_long(0)
_libxdo.xdo_get_current_desktop(self._xdo, ctypes.byref(desktop))
return desktop.value | As a Python code analyst, you investigate and solve complex coding mysteries |
Move a window to another desktop | Here you have a function in Python 3, explain what it does
def set_desktop_for_window(self, window, desktop):
_libxdo.xdo_set_desktop_for_window(self._xdo, window, desktop) | As a Python code composer, you craft elegant and concise scripts. |
Get the desktop a window is on. | Make a summary of the following Python 3 code
def get_desktop_for_window(self, window):
desktop = ctypes.c_long(0)
_libxdo.xdo_get_desktop_for_window(
self._xdo, window, ctypes.byref(desktop))
return desktop.value | As a python code expert, you are capable of creating scripts from specifications. |
Search for windows in the current process. | Can you generate the documentation for the following Python 3 function
def search_windows(
self, winname=None, winclass=None, winclassname=None,
pid=None, only_visible=False, screen=None, require=False,
searchmask=0, desktop=None, limit=0, max_depth=-1):
"""
Search fo... | You are a Python code architect, reviewing and designing scalable and efficient code |
Get the symbol map for the current set of tokens. | Explain what the following Python 3 code does
def get_symbol_map(self):
# todo: make sure we return a list of strings!
sm = _libxdo.xdo_get_symbol_map()
# Return value is like:
# ['alt', 'Alt_L', ..., None, None, None, ...]
# We want to return only values up to the first None.
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_active_modifiers(self):
"""
Get a list of active keys. Uses XQueryKeymap.
:return: list of charcodemap_t instances
"""
keys = ctypes.pointer(charcodemap_t())
nkeys = ctypes.c_int(0)
_libxdo.xdo_get_active_modifiers(
self._xdo, ctypes.byref(ke... | Write a Python 3 script to
get a list of active keys. Uses XQueryKeymap. | As a python code expert, you are capable of creating scripts from specifications. |
def get_window_name(self, win_id):
"""
Get a window's name, if any.
"""
window = window_t(win_id)
name_ptr = ctypes.c_char_p()
name_len = ctypes.c_int(0)
name_type = ctypes.c_int(0)
_libxdo.xdo_get_window_name(
self._xdo, window, ctypes.byref(n... | Can you create a Python 3 function that
gets a window s name if any. | As a Python code composer, you craft elegant and concise scripts. |
def import_metadata(module_paths):
"""Import all the given modules"""
cwd = os.getcwd()
if cwd not in sys.path:
sys.path.insert(0, cwd)
modules = []
try:
for path in module_paths:
modules.append(import_module(path))
except ImportError as e:
err = RuntimeError(... | Write a Python 3 script for
importing all the given modules | As a Python code analyst, you investigate and solve complex coding mysteries |
def load_metadata(stream):
"""Load JSON metadata from opened stream."""
try:
metadata = json.load(
stream, encoding='utf8', object_pairs_hook=OrderedDict)
except json.JSONDecodeError as e:
err = RuntimeError('Error parsing {}: {}'.format(stream.name, e))
raise_from(err, e... | Create a Python 3 function for
loading JSON metadata from opened stream. | You are a Python code architect, reviewing and designing scalable and efficient code |
Strip excess whitespace prior to punctuation. | Can you tell what is the following Python 3 function doing
def strip_punctuation_space(value):
"Strip excess whitespace prior to punctuation."
def strip_punctuation(string):
replacement_list = (
(' .', '.'),
(' :', ':'),
('( ', '('),
(' )', ')'),
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def join_sentences(string1, string2, glue='.'):
"concatenate two sentences together with punctuation glue"
if not string1 or string1 == '':
return string2
if not string2 or string2 == '':
return string1
# both are strings, continue joining them together with the glue and whitespace
n... | Create a Python 3 function to
concatenate two sentences together with punctuation glue | As a Python code translator, you convert algorithms and pseudocode into Python. |
def coerce_to_int(val, default=0xDEADBEEF):
"""Attempts to cast given value to an integer, return the original value if failed or the default if one provided."""
try:
return int(val)
except (TypeError, ValueError):
if default != 0xDEADBEEF:
return default
return val | Can you create a Python 3 function that
attempts to cast given value to an integer if failed return the original value if failed. | As a Python code composer, you craft elegant and concise scripts. |
Decorator. If empty list returns None else list. | Explain what the following Python 3 code does
def nullify(function):
"Decorator. If empty list, returns None, else list."
def wrapper(*args, **kwargs):
value = function(*args, **kwargs)
if(type(value) == list and len(value) == 0):
return None
return value
return wrapper | As a Python code translator, you convert algorithms and pseudocode into Python. |
Decorator. Attempts to convert return value to int | Can you tell what is the following Python 3 function doing
def inten(function):
"Decorator. Attempts to convert return value to int"
def wrapper(*args, **kwargs):
return coerce_to_int(function(*args, **kwargs))
return wrapper | You are a Python code analyst, evaluating scripts for potential improvements. |
def date_struct(year, month, day, tz = "UTC"):
"""
Given year, month and day numeric values and a timezone
convert to structured date object
"""
ymdtz = (year, month, day, tz)
if None in ymdtz:
#logger.debug("a year, month, day or tz value was empty: %s" % str(ymdtz))
return None... | Write a Python 3 script to
give a year month and day numeric values and a timezone returns a structured date object. | You are a Python code generator, capable of creating scripts from specifications. |
Assemble a date object but set it to 1 if none is set it to 1 if none is set it to 1 if none is set it to 1 if none is set it to 1 if none is set it to 1 if none is set it to 1 if none is set it to 1 if none is set it to 1 if none is set | Can you generate the documentation for the following Python 3 function
def date_struct_nn(year, month, day, tz="UTC"):
if not day:
day = 1
if not month:
month = 1
return date_struct(year, month, day, tz) | As a Python code analyst, you investigate and solve complex coding mysteries |
def doi_uri_to_doi(value):
"Strip the uri schema from the start of DOI URL strings"
if value is None:
return value
replace_values = ['http://dx.doi.org/', 'https://dx.doi.org/',
'http://doi.org/', 'https://doi.org/']
for replace_value in replace_values:
value = valu... | Can you write a function in Python 3 where it
strips the uri schema from the start of DOI URL strings | As a Python code composer, you craft elegant and concise scripts. |
def remove_doi_paragraph(tags):
"Given a list of tags, only return those whose text doesn't start with 'DOI:'"
p_tags = list(filter(lambda tag: not starts_with_doi(tag), tags))
p_tags = list(filter(lambda tag: not paragraph_is_only_doi(tag), p_tags))
return p_tags | How would you implement a function in Python 3 that
gives a list of tags only return those whose text doesn t start with DOI : | You are a Python code generator, capable of creating scripts from specifications. |
def orcid_uri_to_orcid(value):
"Strip the uri schema from the start of ORCID URL strings"
if value is None:
return value
replace_values = ['http://orcid.org/', 'https://orcid.org/']
for replace_value in replace_values:
value = value.replace(replace_value, '')
return value | Can you implement a function in Python 3 that
strips the uri schema from the start of ORCID URL strings | You are a Python code generator, capable of creating scripts from specifications. |
Return the parent tag of the given tag. | Here you have a function in Python 3, explain what it does
def component_acting_parent_tag(parent_tag, tag):
if parent_tag.name == "fig-group":
if (len(tag.find_previous_siblings("fig")) > 0):
acting_parent_tag = first(extract_nodes(parent_tag, "fig"))
else:
# Do not return t... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a list of tags from the given soup matching the given nodename. | Can you generate a brief explanation for the following Python 3 code
def extract_nodes(soup, nodename, attr = None, value = None):
tags = soup.find_all(nodename)
if attr != None and value != None:
return list(filter(lambda tag: tag.get(attr) == value, tags))
return list(tags) | As a python code expert, you are capable of creating scripts from specifications. |
def node_contents_str(tag):
"""
Return the contents of a tag, including it's children, as a string.
Does not include the root/parent of the tag.
"""
if not tag:
return None
tag_string = ''
for child_tag in tag.children:
if isinstance(child_tag, Comment):
# Beautif... | Write a Python 3 function that can
return the contents of a tag including it s children as a string. | You are a Python code architect, reviewing and designing scalable and efficient code |
def first_parent(tag, nodename):
"""
Given a beautiful soup tag, look at its parents and return the first
tag name that matches nodename or the list nodename
"""
if nodename is not None and type(nodename) == str:
nodename = [nodename]
return first(list(filter(lambda tag: tag.name in node... | Write a Python 3 function that can
give a beautiful soup tag look at its parents and return the first parent tag that matches nodename or the list nodename | You are a Python code architect, reviewing and designing scalable and efficient code |
def tag_fig_ordinal(tag):
"""
Meant for finding the position of fig tags with respect to whether
they are for a main figure or a child figure
"""
tag_count = 0
if 'specific-use' not in tag.attrs:
# Look for tags with no "specific-use" attribute
return len(list(filter(lambda tag: ... | Write a Python 3 function for
returning the ordinal of the figure in which the given tag is for a main figure or a child figure. | As a Python code analyst, you investigate and solve complex coding mysteries |
def tag_media_sibling_ordinal(tag):
"""
Count sibling ordinal differently depending on if the
mimetype is video or not
"""
if hasattr(tag, 'name') and tag.name != 'media':
return None
nodenames = ['fig','supplementary-material','sub-article']
first_parent_tag = first_parent(tag, nod... | How would you code a function in Python 3 to
count the number of media tags that are sibling of the given tag. | You are a Python code analyst, evaluating scripts for potential improvements. |
Return the ordinal of the supplementary - material tag that is the position inside any parent tag that has the same asset value to get its sibling ordinal. | Can you tell what is the following Python 3 function doing
def tag_supplementary_material_sibling_ordinal(tag):
if hasattr(tag, 'name') and tag.name != 'supplementary-material':
return None
nodenames = ['fig','media','sub-article']
first_parent_tag = first_parent(tag, nodenames)
sibling_ordina... | As a python code expert, you are capable of creating scripts from specifications. |
def supp_asset(tag):
"""
Given a supplementary-material tag, the asset value depends on
its label text. This also informs in what order (its ordinal) it
has depending on how many of each type is present
"""
# Default
asset = 'supp'
if first(extract_nodes(tag, "label")):
label_tex... | Write a Python 3 function that can
give a supplementary - material tag returns the asset value | As a Python code analyst, you investigate and solve complex coding mysteries |
when a title is required generate one from the value | Can you generate a brief explanation for the following Python 3 code
def text_to_title(value):
title = None
if not value:
return title
words = value.split(" ")
keep_words = []
for word in words:
if word.endswith(".") or word.endswith(":"):
keep_words.append(word)
... | You are a Python code generator, capable of creating scripts from specifications. |
This function is used to escape unmatched angle brackets in an XML string. | Make a summary of the following Python 3 code
def escape_unmatched_angle_brackets(string, allowed_tag_fragments=()):
if not string:
return string
# Split string on tags
tags = re.split('(<.*?>)', string)
#print tags
for i, val in enumerate(tags):
# Use angle bracket character count... | As a Python code composer, you craft elegant and concise scripts. |
Quick convert unicode ampersand characters not associated with a numbered entity to a plain & ; | Can you generate the documentation for the following Python 3 function
def escape_ampersand(string):
if not string:
return string
start_with_match = r"(\#x(....);|lt;|gt;|amp;)"
# The pattern below is match & that is not immediately followed by #
string = re.sub(r"&(?!" + start_with_match + ")",... | You are a Python code architect, reviewing and designing scalable and efficient code |
Parse the file and return the root and doctype dict | Here you have a function in Python 3, explain what it does
def parse(filename, return_doctype_dict=False):
doctype_dict = {}
# check for python version, doctype in ElementTree is deprecated 3.2 and above
if sys.version_info < (3,2):
parser = CustomXMLParser(html=0, target=None, encoding='utf-8')
... | You are a Python code analyst, evaluating scripts for potential improvements. |
This function returns the index of the first child tag with tag_name in the tree root. | Can you generate a brief explanation for the following Python 3 code
def get_first_element_index(root, tag_name):
tag_index = 1
for tag in root:
if tag.tag == tag_name:
# Return the first one found if there is a match
return tag_index
tag_index = tag_index + 1
# Defau... | You are a Python code analyst, evaluating scripts for potential improvements. |
add or rewrite subject tags inside subj - group tags | Can you tell what is the following Python 3 function doing
def rewrite_subject_group(root, subjects, subject_group_type, overwrite=True):
"add or rewrite subject tags inside subj-group tags"
parent_tag_name = 'subj-group'
tag_name = 'subject'
wrap_tag_name = 'article-categories'
tag_attribute = 'sub... | You are a Python code analyst, evaluating scripts for potential improvements. |
def build_doctype(qualifiedName, publicId=None, systemId=None, internalSubset=None):
"""
Instantiate an ElifeDocumentType, a subclass of minidom.DocumentType, with
some properties so it is more testable
"""
doctype = ElifeDocumentType(qualifiedName)
doctype._identified_mixin_init(publicId, syste... | How would you code a function in Python 3 to
build a doctype object. | You are a Python code analyst, evaluating scripts for potential improvements. |
def append_minidom_xml_to_elementtree_xml(parent, xml, recursive=False, attributes=None):
"""
Recursively,
Given an ElementTree.Element as parent, and a minidom instance as xml,
append the tags and content from xml to parent
Used primarily for adding a snippet of XML with <italic> tags
attribute... | Create a Python 3 function to
append a minidom XML element to a parent ElementTree. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def rewrite_json(rewrite_type, soup, json_content):
"""
Due to XML content that will not conform with the strict JSON schema validation rules,
for elife articles only, rewrite the JSON to make it valid
"""
if not soup:
return json_content
if not elifetools.rawJATS.doi(soup) or not elifet... | Write a Python 3 script to
rewrite the JSON content to make it valid according to the rewrite_type. | As a Python code composer, you craft elegant and concise scripts. |
general purpose references json rewriting by matching the id value | How would you explain what the following Python 3 function does
def rewrite_references_json(json_content, rewrite_json):
for ref in json_content:
if ref.get("id") and ref.get("id") in rewrite_json:
for key, value in iteritems(rewrite_json.get(ref.get("id"))):
ref[key] = value
... | As a Python code composer, you craft elegant and concise scripts. |
This function returns the DOI and references json replacements data for the Ife References Rewriting. | How would you explain what the following Python 3 function does
def elife_references_rewrite_json():
references_rewrite_json = {}
references_rewrite_json["10.7554/eLife.00051"] = {"bib25": {"date": "2012"}}
references_rewrite_json["10.7554/eLife.00278"] = {"bib11": {"date": "2013"}}
references_rewrite_... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def rewrite_elife_body_json(json_content, doi):
""" rewrite elife body json """
# Edge case add an id to a section
if doi == "10.7554/eLife.00013":
if (json_content and len(json_content) > 0):
if (json_content[0].get("type") and json_content[0].get("type") == "section"
a... | Write a Python 3 function that can
rewrite elife body json | You are a Python code analyst, evaluating scripts for potential improvements. |
rewrite ife funding awards | How would you explain what the following Python 3 function does
def rewrite_elife_funding_awards(json_content, doi):
# remove a funding award
if doi == "10.7554/eLife.00801":
for i, award in enumerate(json_content):
if "id" in award and award["id"] == "par-2":
del json_conte... | You are a Python code architect, reviewing and designing scalable and efficient code |
This function rewrites the elife authors json to include the correct doi. | Can you generate a brief explanation for the following Python 3 code
def rewrite_elife_authors_json(json_content, doi):
# Convert doi from testing doi if applicable
article_doi = elifetools.utils.convert_testing_doi(doi)
# Edge case fix an affiliation name
if article_doi == "10.7554/eLife.06956":
... | You are a Python code analyst, evaluating scripts for potential improvements. |
This function rewrites the elife datasets json in the current article to include the same doi as the original. | Here you have a function in Python 3, explain what it does
def rewrite_elife_datasets_json(json_content, doi):
# Add dates in bulk
elife_dataset_dates = []
elife_dataset_dates.append(("10.7554/eLife.00348", "used", "dataro17", u"2010"))
elife_dataset_dates.append(("10.7554/eLife.01179", "used", "dataro... | As a python code expert, you are capable of creating scripts from specifications. |
This function rewrites the elife editors json to include the doi and the content of the new content. | How would you explain what the following Python 3 function does
def rewrite_elife_editors_json(json_content, doi):
# Remove affiliations with no name value
for i, ref in enumerate(json_content):
if ref.get("affiliations"):
for aff in ref.get("affiliations"):
if "name" not in... | As a python code expert, you are capable of creating scripts from specifications. |
this function rewrites the elife title prefix json values in the article DOI to match the original article DOI. | Can you tell what is the following Python 3 function doing
def rewrite_elife_title_prefix_json(json_content, doi):
if not json_content:
return json_content
# title prefix rewrites by article DOI
title_prefix_values = {}
title_prefix_values["10.7554/eLife.00452"] = "Point of View"
title_pref... | You are a Python code analyst, evaluating scripts for potential improvements. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.