sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
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 ...
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.
entailment
def attr_names(cls) -> List[str]: """ Returns annotated attribute names :return: List[str] """ return [k for k, v in cls.attr_types().items()]
Returns annotated attribute names :return: List[str]
entailment
def elliptic_fourier_descriptors(contour, order=10, normalize=False): """Calculate elliptical Fourier descriptors for a contour. :param numpy.ndarray contour: A contour array of size ``[M x 2]``. :param int order: The order of Fourier coefficients to calculate. :param bool normalize: If the coefficient...
Calculate elliptical Fourier descriptors for a contour. :param numpy.ndarray contour: A contour array of size ``[M x 2]``. :param int order: The order of Fourier coefficients to calculate. :param bool normalize: If the coefficients should be normalized; see references for details. :return: A ``...
entailment
def normalize_efd(coeffs, size_invariant=True): """Normalizes an array of Fourier coefficients. See [#a]_ and [#b]_ for details. :param numpy.ndarray coeffs: A ``[n x 4]`` Fourier coefficient array. :param bool size_invariant: If size invariance normalizing should be done as well. Default is `...
Normalizes an array of Fourier coefficients. See [#a]_ and [#b]_ for details. :param numpy.ndarray coeffs: A ``[n x 4]`` Fourier coefficient array. :param bool size_invariant: If size invariance normalizing should be done as well. Default is ``True``. :return: The normalized ``[n x 4]`` Fourie...
entailment
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...
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
entailment
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...
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 numpy.ndarray locus: The :math:`A_0` and :math:`C_0` elliptic locus i...
entailment
def _errcheck(result, func, arguments): """ Error checker for functions returning an integer indicating success (0) / failure (1). Raises a XdoException in case of error, otherwise just returns ``None`` (returning the original code, 0, would be useless anyways..) """ if result != 0: ...
Error checker for functions returning an integer indicating success (0) / failure (1). Raises a XdoException in case of error, otherwise just returns ``None`` (returning the original code, 0, would be useless anyways..)
entailment
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), ...
Generate input mask from bytemask
entailment
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...
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.
entailment
def move_mouse_relative_to_window(self, window, x, y): """ Move the mouse to a specific location relative to the top-left corner of a window. :param x: the target X coordinate on the screen in pixels. :param y: the target Y coordinate on the screen in pixels. """ ...
Move the mouse to a specific location relative to the top-left corner of a window. :param x: the target X coordinate on the screen in pixels. :param y: the target Y coordinate on the screen in pixels.
entailment
def move_mouse_relative(self, x, y): """ Move the mouse relative to it's current position. :param x: the distance in pixels to move on the X axis. :param y: the distance in pixels to move on the Y axis. """ _libxdo.xdo_move_mouse_relative(self._xdo, x, y)
Move the mouse relative to it's current position. :param x: the distance in pixels to move on the X axis. :param y: the distance in pixels to move on the Y axis.
entailment
def mouse_down(self, window, button): """ Send a mouse press (aka mouse down) 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,...
Send a mouse press (aka mouse down) 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 is middle, 3 is right, 4 is wheel up, 5 is ...
entailment
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...
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 is middle, 3 is right, 4 is wheel up, 5 is ...
entailment
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...
Get the current mouse location (coordinates and screen number). :return: a namedtuple with ``x``, ``y`` and ``screen_num`` fields
entailment
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
Get the window the mouse is currently over
entailment
def get_mouse_location2(self): """ Get all mouse location-related data. :return: a namedtuple with ``x``, ``y``, ``screen_num`` and ``window`` fields """ x = ctypes.c_int(0) y = ctypes.c_int(0) screen_num_ret = ctypes.c_ulong(0) window_ret = c...
Get all mouse location-related data. :return: a namedtuple with ``x``, ``y``, ``screen_num`` and ``window`` fields
entailment
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 ...
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 the mouse to move from
entailment
def wait_for_mouse_move_to(self, dest_x, dest_y): """ Wait for the mouse to move to a location. This function will block until the condition has been satisified. :param dest_x: the X position you expect the mouse to move to :param dest_y: the Y position you expect the mouse to m...
Wait for the mouse to move to a location. This function will block until the condition has been satisified. :param dest_x: the X position you expect the mouse to move to :param dest_y: the Y position you expect the mouse to move to
entailment
def click_window(self, window, button): """ Send a click 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 mouse button. Generally, 1 is left, 2 is middle, 3 is ...
Send a click 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 mouse button. Generally, 1 is left, 2 is middle, 3 is right, 4 is wheel up, 5 is wheel down.
entailment
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...
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 mouse button. Generally, 1 is left, 2 is middle, 3 is right, 4 is wheel up, 5 is w...
entailment
def enter_text_window(self, window, string, delay=12000): """ Type a string to the specified window. If you want to send a specific key or key sequence, such as "alt+l", you want instead ``send_keysequence_window(...)``. :param window: The window you want to send ke...
Type a string to the specified window. If you want to send a specific key or key sequence, such as "alt+l", you want instead ``send_keysequence_window(...)``. :param window: The window you want to send keystrokes to or CURRENTWINDOW :param string: The string to ...
entailment
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. ...
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. Examples: "l" "semicolon" "alt+Return" "Alt_L+Tab...
entailment
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))
Send key release (up) events for the given key sequence
entailment
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))
Send key press (down) events for the given key sequence
entailment
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 array of charcodemap_t entities to send. :param pressed: 1...
Send a series of keystrokes. :param window: The window to send events to or CURRENTWINDOW :param keys: The array of charcodemap_t entities to send. :param pressed: 1 for key press, 0 for key release. :param modifier: Pointer to integer to record the modifiers act...
entailment
def get_active_keys_to_keycode_list(self): """Get a list of active keys. Uses XQueryKeymap""" try: _libxdo.xdo_get_active_keys_to_keycode_list except AttributeError: # Apparently, this was implemented in a later version.. raise NotImplementedError() ...
Get a list of active keys. Uses XQueryKeymap
entailment
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) ...
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) IsUnviewable - window is mapped but a parent window is unmapped. ...
entailment
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. """...
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.
entailment
def translate_window_with_sizehint(self, window, width, height): """ Apply a window's sizing hints (if any) to a given width and height. This function wraps XGetWMNormalHints() and applies any resize increment and base size to your given width and height values. :param window: ...
Apply a window's sizing hints (if any) to a given width and height. This function wraps XGetWMNormalHints() and applies any resize increment and base size to your given width and height values. :param window: the window to use :param width: the unit width you want to translate ...
entailment
def set_window_size(self, window, w, h, flags=0): """ Change the window size. :param wid: the window to resize :param w: the new desired width :param h: the new desired height :param flags: if 0, use pixels for units. If SIZE_USEHINTS, then the units will be ...
Change the window size. :param wid: the window to resize :param w: the new desired width :param h: the new desired height :param flags: if 0, use pixels for units. If SIZE_USEHINTS, then the units will be relative to the window size hints.
entailment
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...
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 value of the property.
entailment
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...
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.
entailment
def set_window_urgency(self, window, urgency): """Sets the urgency hint for a window""" _libxdo.xdo_set_window_urgency(self._xdo, window, urgency)
Sets the urgency hint for a window
entailment
def set_window_override_redirect(self, window, override_redirect): """ Set the override_redirect value for a window. This generally means whether or not a window manager will manage this window. If you set it to 1, the window manager will usually not draw borders on the window, ...
Set the override_redirect value for a window. This generally means whether or not a window manager will manage this window. If you set it to 1, the window manager will usually not draw borders on the window, etc. If you set it to 0, the window manager will see it like a normal applicat...
entailment
def get_focused_window(self): """ Get the window currently having focus. :param window_ret: Pointer to a window where the currently-focused window will be stored. """ window_ret = window_t(0) _libxdo.xdo_get_focused_window(self._xdo, ctypes.byref(window_r...
Get the window currently having focus. :param window_ret: Pointer to a window where the currently-focused window will be stored.
entailment
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...
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.
entailment
def get_focused_window_sane(self): """ Like xdo_get_focused_window, but return the first ancestor-or-self window * having a property of WM_CLASS. This allows you to get the "real" or top-level-ish window having focus rather than something you may not expect to be the window havin...
Like xdo_get_focused_window, but return the first ancestor-or-self window * having a property of WM_CLASS. This allows you to get the "real" or top-level-ish window having focus rather than something you may not expect to be the window having focused. :param window_ret: Poin...
entailment
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 ...
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 0, wait for inactive.
entailment
def reparent_window(self, window_source, window_target): """ Reparents a window :param wid_source: the window to reparent :param wid_target: the new parent window """ _libxdo.xdo_reparent_window(self._xdo, window_source, window_target)
Reparents a window :param wid_source: the window to reparent :param wid_target: the new parent window
entailment
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...
Get a window's location.
entailment
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....
Get a window's size.
entailment
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)) ...
Get the currently-active window. Requires your window manager to support this. Uses ``_NET_ACTIVE_WINDOW`` from the EWMH spec.
entailment
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
Get a window ID by clicking on it. This function blocks until a selection is made.
entailment
def get_number_of_desktops(self): """ Get the current number of desktops. Uses ``_NET_NUMBER_OF_DESKTOPS`` of the EWMH spec. :param ndesktops: pointer to long where the current number of desktops is stored """ ndesktops = ctypes.c_long(0) _libxdo.xdo_...
Get the current number of desktops. Uses ``_NET_NUMBER_OF_DESKTOPS`` of the EWMH spec. :param ndesktops: pointer to long where the current number of desktops is stored
entailment
def get_current_desktop(self): """ Get the current desktop. Uses ``_NET_CURRENT_DESKTOP`` of the EWMH spec. """ desktop = ctypes.c_long(0) _libxdo.xdo_get_current_desktop(self._xdo, ctypes.byref(desktop)) return desktop.value
Get the current desktop. Uses ``_NET_CURRENT_DESKTOP`` of the EWMH spec.
entailment
def set_desktop_for_window(self, window, desktop): """ Move a window to another desktop Uses _NET_WM_DESKTOP of the EWMH spec. :param wid: the window to move :param desktop: the desktop destination for the window """ _libxdo.xdo_set_desktop_for_window(self._xdo, ...
Move a window to another desktop Uses _NET_WM_DESKTOP of the EWMH spec. :param wid: the window to move :param desktop: the desktop destination for the window
entailment
def get_desktop_for_window(self, window): """ Get the desktop a window is on. Uses _NET_WM_DESKTOP of the EWMH spec. If your desktop does not support ``_NET_WM_DESKTOP``, then '*desktop' remains unmodified. :param wid: the window to query """ desktop = c...
Get the desktop a window is on. Uses _NET_WM_DESKTOP of the EWMH spec. If your desktop does not support ``_NET_WM_DESKTOP``, then '*desktop' remains unmodified. :param wid: the window to query
entailment
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 for windows. :param winname: Regexp to be matched ag...
Search for windows. :param winname: Regexp to be matched against window name :param winclass: Regexp to be matched against window class :param winclassname: Regexp to be matched against window class name :param pid: Only return windows fro...
entailment
def get_symbol_map(self): """ If you need the symbol map, use this method. The symbol map is an array of string pairs mapping common tokens to X Keysym strings, such as "alt" to "Alt_L" :return: array of strings. """ # todo: make sure we return a list of strings...
If you need the symbol map, use this method. The symbol map is an array of string pairs mapping common tokens to X Keysym strings, such as "alt" to "Alt_L" :return: array of strings.
entailment
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...
Get a list of active keys. Uses XQueryKeymap. :return: list of charcodemap_t instances
entailment
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...
Get a window's name, if any.
entailment
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(...
Import all the given modules
entailment
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...
Load JSON metadata from opened stream.
entailment
def strip_punctuation_space(value): "Strip excess whitespace prior to punctuation." def strip_punctuation(string): replacement_list = ( (' .', '.'), (' :', ':'), ('( ', '('), (' )', ')'), ) for match, replacement in replacement_list: ...
Strip excess whitespace prior to punctuation.
entailment
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...
concatenate two sentences together with punctuation glue
entailment
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
Attempts to cast given value to an integer, return the original value if failed or the default if one provided.
entailment
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
Decorator. If empty list, returns None, else list.
entailment
def strippen(function): "Decorator. Strip excess whitespace from return value." def wrapper(*args, **kwargs): return strip_strings(function(*args, **kwargs)) return wrapper
Decorator. Strip excess whitespace from return value.
entailment
def inten(function): "Decorator. Attempts to convert return value to int" def wrapper(*args, **kwargs): return coerce_to_int(function(*args, **kwargs)) return wrapper
Decorator. Attempts to convert return value to int
entailment
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...
Given year, month and day numeric values and a timezone convert to structured date object
entailment
def date_struct_nn(year, month, day, tz="UTC"): """ Assemble a date object but if day or month is none set them to 1 to make it easier to deal with partial dates """ if not day: day = 1 if not month: month = 1 return date_struct(year, month, day, tz)
Assemble a date object but if day or month is none set them to 1 to make it easier to deal with partial dates
entailment
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...
Strip the uri schema from the start of DOI URL strings
entailment
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
Given a list of tags, only return those whose text doesn't start with 'DOI:
entailment
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
Strip the uri schema from the start of ORCID URL strings
entailment
def component_acting_parent_tag(parent_tag, tag): """ Only intended for use in getting components, look for tag name of fig-group and if so, find the first fig tag inside it as the acting parent tag """ if parent_tag.name == "fig-group": if (len(tag.find_previous_siblings("fig")) > 0): ...
Only intended for use in getting components, look for tag name of fig-group and if so, find the first fig tag inside it as the acting parent tag
entailment
def extract_nodes(soup, nodename, attr = None, value = None): """ Returns a list of tags (nodes) from the given soup matching the given nodename. If an optional attribute and value are given, these are used to filter the results further.""" tags = soup.find_all(nodename) if attr != None and valu...
Returns a list of tags (nodes) from the given soup matching the given nodename. If an optional attribute and value are given, these are used to filter the results further.
entailment
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...
Return the contents of a tag, including it's children, as a string. Does not include the root/parent of the tag.
entailment
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...
Given a beautiful soup tag, look at its parents and return the first tag name that matches nodename or the list nodename
entailment
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: ...
Meant for finding the position of fig tags with respect to whether they are for a main figure or a child figure
entailment
def tag_limit_sibling_ordinal(tag, stop_tag_name): """ Count previous tags of the same name until it reaches a tag name of type stop_tag, then stop counting """ tag_count = 1 for prev_tag in tag.previous_elements: if prev_tag.name == tag.name: tag_count += 1 if prev_t...
Count previous tags of the same name until it reaches a tag name of type stop_tag, then stop counting
entailment
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...
Count sibling ordinal differently depending on if the mimetype is video or not
entailment
def tag_supplementary_material_sibling_ordinal(tag): """ Strategy is to count the previous supplementary-material tags having the same asset value to get its sibling ordinal. The result is its position inside any parent tag that are the same asset type """ if hasattr(tag, 'name') and tag.nam...
Strategy is to count the previous supplementary-material tags having the same asset value to get its sibling ordinal. The result is its position inside any parent tag that are the same asset type
entailment
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...
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
entailment
def text_to_title(value): """when a title is required, generate one from the 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) i...
when a title is required, generate one from the value
entailment
def escape_unmatched_angle_brackets(string, allowed_tag_fragments=()): """ In order to make an XML string less malformed, escape unmatched less than tags that are not part of an allowed tag Note: Very, very basic, and do not try regex \1 style replacements on unicode ever again! Instead this uses ...
In order to make an XML string less malformed, escape unmatched less than tags that are not part of an allowed tag Note: Very, very basic, and do not try regex \1 style replacements on unicode ever again! Instead this uses string replace allowed_tag_fragments is a tuple of tag name matches for use wit...
entailment
def escape_ampersand(string): """ Quick convert unicode ampersand characters not associated with a numbered entity or not starting with allowed characters to a plain &amp; """ if not string: return string start_with_match = r"(\#x(....);|lt;|gt;|amp;)" # The pattern below is match & ...
Quick convert unicode ampersand characters not associated with a numbered entity or not starting with allowed characters to a plain &amp;
entailment
def parse(filename, return_doctype_dict=False): """ to extract the doctype details from the file when parsed and return the data for later use, set return_doctype_dict to True """ doctype_dict = {} # check for python version, doctype in ElementTree is deprecated 3.2 and above if sys.version_...
to extract the doctype details from the file when parsed and return the data for later use, set return_doctype_dict to True
entailment
def add_tag_before(tag_name, tag_text, parent_tag, before_tag_name): """ Helper function to refactor the adding of new tags especially for when converting text to role tags """ new_tag = Element(tag_name) new_tag.text = tag_text if get_first_element_index(parent_tag, before_tag_name): ...
Helper function to refactor the adding of new tags especially for when converting text to role tags
entailment
def get_first_element_index(root, tag_name): """ In order to use Element.insert() in a convenient way, this function will find the first child tag with tag_name and return its index position The index can then be used to insert an element before or after the found tag using Element.insert() ...
In order to use Element.insert() in a convenient way, this function will find the first child tag with tag_name and return its index position The index can then be used to insert an element before or after the found tag using Element.insert()
entailment
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 = 'subj-group-type' # the parent tag where it should be found...
add or rewrite subject tags inside subj-group tags
entailment
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...
Instantiate an ElifeDocumentType, a subclass of minidom.DocumentType, with some properties so it is more testable
entailment
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...
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 attributes: a list of attribute names to copy
entailment
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...
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
entailment
def rewrite_elife_references_json(json_content, doi): """ this does the work of rewriting elife references json """ references_rewrite_json = elife_references_rewrite_json() if doi in references_rewrite_json: json_content = rewrite_references_json(json_content, references_rewrite_json[doi]) # E...
this does the work of rewriting elife references json
entailment
def rewrite_references_json(json_content, rewrite_json): """ general purpose references json rewriting by matching the id value """ 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[k...
general purpose references json rewriting by matching the id value
entailment
def elife_references_rewrite_json(): """ Here is the DOI and references json replacements data for elife """ references_rewrite_json = {} references_rewrite_json["10.7554/eLife.00051"] = {"bib25": {"date": "2012"}} references_rewrite_json["10.7554/eLife.00278"] = {"bib11": {"date": "2013"}} referen...
Here is the DOI and references json replacements data for elife
entailment
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...
rewrite elife body json
entailment
def rewrite_elife_funding_awards(json_content, doi): """ rewrite elife funding awards """ # 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_content[i] # add fundin...
rewrite elife funding awards
entailment
def rewrite_elife_authors_json(json_content, doi): """ this does the work of rewriting elife authors json """ # 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": fo...
this does the work of rewriting elife authors json
entailment
def rewrite_elife_datasets_json(json_content, doi): """ this does the work of rewriting elife datasets json """ # 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", "d...
this does the work of rewriting elife datasets json
entailment
def rewrite_elife_editors_json(json_content, doi): """ this does the work of rewriting elife editors json """ # 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 ...
this does the work of rewriting elife editors json
entailment
def person_same_name_map(json_content, role_from): "to merge multiple editors into one record, filter by role values and group by name" matched_editors = [(i, person) for i, person in enumerate(json_content) if person.get('role') in role_from] same_name_map = {} for i, editor in m...
to merge multiple editors into one record, filter by role values and group by name
entailment
def rewrite_elife_title_prefix_json(json_content, doi): """ this does the work of rewriting elife title prefix json values""" 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"...
this does the work of rewriting elife title prefix json values
entailment
def metadata_lint(old, new, locations): """Run the linter over the new metadata, comparing to the old.""" # ensure we don't modify the metadata old = old.copy() new = new.copy() # remove version info old.pop('$version', None) new.pop('$version', None) for old_group_name in old: ...
Run the linter over the new metadata, comparing to the old.
entailment
def lint_api(api_name, old, new, locations): """Lint an acceptable api metadata.""" is_new_api = not old api_location = locations['api'] changelog = new.get('changelog', {}) changelog_location = api_location if locations['changelog']: changelog_location = list(locations['changelog'].val...
Lint an acceptable api metadata.
entailment
def bind(self, flask_app, service, group=None): """Bind the service API urls to a flask app.""" if group not in self.services[service]: raise RuntimeError( 'API group {} does not exist in service {}'.format( group, service) ) for name, ...
Bind the service API urls to a flask app.
entailment
def serialize(self): """Serialize into JSONable dict, and associated locations data.""" api_metadata = OrderedDict() # $ char makes this come first in sort ordering api_metadata['$version'] = self.current_version locations = {} for svc_name, group in self.groups(): ...
Serialize into JSONable dict, and associated locations data.
entailment
def api(self, url, name, introduced_at=None, undocumented=False, deprecated_at=None, title=None, **options): """Add an API to the service. :param url: This is the url that the API should be registered at. :param...
Add an API to the service. :param url: This is the url that the API should be registered at. :param name: This is the name of the api, and will be registered with flask apps under. Other keyword arguments may be used, and they will be passed to the flask application when in...
entailment
def django_api( self, name, introduced_at, undocumented=False, deprecated_at=None, title=None, **options): """Add a django API handler to the service. :param name: This is the name of the django url to use. The...
Add a django API handler to the service. :param name: This is the name of the django url to use. The 'methods' paramater can be supplied as normal, you can also user the @api.handler decorator to link this API to its handler.
entailment
def bind(self, flask_app): """Bind the service API urls to a flask app.""" self.metadata.bind(flask_app, self.name, self.group)
Bind the service API urls to a flask app.
entailment