sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def release(self, id):
"""Get a single release.
:param int id: (required), id of release
:returns: :class:`Release <github3.repos.release.Release>`
"""
json = None
if int(id) > 0:
url = self._build_url('releases', str(id), base_url=self._api)
json... | Get a single release.
:param int id: (required), id of release
:returns: :class:`Release <github3.repos.release.Release>` | entailment |
def remove_collaborator(self, login):
"""Remove collaborator ``login`` from the repository.
:param str login: (required), login name of the collaborator
:returns: bool
"""
resp = False
if login:
url = self._build_url('collaborators', login, base_url=self._api... | Remove collaborator ``login`` from the repository.
:param str login: (required), login name of the collaborator
:returns: bool | entailment |
def tag(self, sha):
"""Get an annotated tag.
http://learn.github.com/p/tagging.html
:param str sha: (required), sha of the object for this tag
:returns: :class:`Tag <github3.git.Tag>`
"""
json = None
if sha:
url = self._build_url('git', 'tags', sha, ... | Get an annotated tag.
http://learn.github.com/p/tagging.html
:param str sha: (required), sha of the object for this tag
:returns: :class:`Tag <github3.git.Tag>` | entailment |
def tree(self, sha):
"""Get a tree.
:param str sha: (required), sha of the object for this tree
:returns: :class:`Tree <github3.git.Tree>`
"""
json = None
if sha:
url = self._build_url('git', 'trees', sha, base_url=self._api)
json = self._json(sel... | Get a tree.
:param str sha: (required), sha of the object for this tree
:returns: :class:`Tree <github3.git.Tree>` | entailment |
def update_label(self, name, color, new_name=''):
"""Update the label ``name``.
:param str name: (required), name of the label
:param str color: (required), color code
:param str new_name: (optional), new name of the label
:returns: bool
"""
label = self.label(na... | Update the label ``name``.
:param str name: (required), name of the label
:param str color: (required), color code
:param str new_name: (optional), new name of the label
:returns: bool | entailment |
def weekly_commit_count(self):
"""Returns the total commit counts.
The dictionary returned has two entries: ``all`` and ``owner``. Each
has a fifty-two element long list of commit counts. (Note: ``all``
includes the owner.) ``d['all'][0]`` will be the oldest week,
``d['all'][51]... | Returns the total commit counts.
The dictionary returned has two entries: ``all`` and ``owner``. Each
has a fifty-two element long list of commit counts. (Note: ``all``
includes the owner.) ``d['all'][0]`` will be the oldest week,
``d['all'][51]`` will be the most recent.
:retu... | entailment |
def rename(args):
"""Supply two names: Existing instance name or ID, and new name to assign to the instance."""
old_name, new_name = args.names
add_tags(resources.ec2.Instance(resolve_instance_id(old_name)), Name=new_name, dry_run=args.dry_run) | Supply two names: Existing instance name or ID, and new name to assign to the instance. | entailment |
def create_status(self, state, target_url='', description=''):
"""Create a new deployment status for this deployment.
:param str state: (required), The state of the status. Can be one of
``pending``, ``success``, ``error``, or ``failure``.
:param str target_url: The target URL to as... | Create a new deployment status for this deployment.
:param str state: (required), The state of the status. Can be one of
``pending``, ``success``, ``error``, or ``failure``.
:param str target_url: The target URL to associate with this status.
This URL should contain output to ke... | entailment |
def iter_statuses(self, number=-1, etag=None):
"""Iterate over the deployment statuses for this deployment.
:param int number: (optional), the number of statuses to return.
Default: -1, returns all statuses.
:param str etag: (optional), the ETag header value from the last time
... | Iterate over the deployment statuses for this deployment.
:param int number: (optional), the number of statuses to return.
Default: -1, returns all statuses.
:param str etag: (optional), the ETag header value from the last time
you iterated over the statuses.
:returns: g... | entailment |
def get_gist(self):
"""Retrieve the gist at this version.
:returns: :class:`Gist <github3.gists.gist.Gist>`
"""
from .gist import Gist
json = self._json(self._get(self._api), 200)
return Gist(json, self) | Retrieve the gist at this version.
:returns: :class:`Gist <github3.gists.gist.Gist>` | entailment |
def update(self, sha, force=False):
"""Update this reference.
:param str sha: (required), sha of the reference
:param bool force: (optional), force the update or not
:returns: bool
"""
data = {'sha': sha, 'force': force}
json = self._json(self._patch(self._api, ... | Update this reference.
:param str sha: (required), sha of the reference
:param bool force: (optional), force the update or not
:returns: bool | entailment |
def recurse(self):
"""Recurse into the tree.
:returns: :class:`Tree <Tree>`
"""
json = self._json(self._get(self._api, params={'recursive': '1'}),
200)
return Tree(json, self._session) if json else None | Recurse into the tree.
:returns: :class:`Tree <Tree>` | entailment |
def format_table(table, column_names=None, column_specs=None, max_col_width=32, auto_col_width=False):
"""
Table pretty printer. Expects tables to be given as arrays of arrays::
print(format_table([[1, "2"], [3, "456"]], column_names=['A', 'B']))
"""
orig_col_args = dict(column_names=column_nam... | Table pretty printer. Expects tables to be given as arrays of arrays::
print(format_table([[1, "2"], [3, "456"]], column_names=['A', 'B'])) | entailment |
def get(args):
"""Get an Aegea configuration parameter by name"""
from . import config
for key in args.key.split("."):
config = getattr(config, key)
print(json.dumps(config)) | Get an Aegea configuration parameter by name | entailment |
def set(args):
"""Set an Aegea configuration parameter to a given value"""
from . import config, tweak
class ConfigSaver(tweak.Config):
@property
def config_files(self):
return [config.config_files[2]]
config_saver = ConfigSaver(use_yaml=True, save_on_exit=False)
c = co... | Set an Aegea configuration parameter to a given value | entailment |
def authorize(login, password, scopes, note='', note_url='', client_id='',
client_secret='', two_factor_callback=None):
"""Obtain an authorization token for the GitHub API.
:param str login: (required)
:param str password: (required)
:param list scopes: (required), areas you want this tok... | Obtain an authorization token for the GitHub API.
:param str login: (required)
:param str password: (required)
:param list scopes: (required), areas you want this token to apply to,
i.e., 'gist', 'user'
:param str note: (optional), note about the authorization
:param str note_url: (optional... | entailment |
def login(username=None, password=None, token=None, url=None,
two_factor_callback=None):
"""Construct and return an authenticated GitHub session.
This will return a GitHubEnterprise session if a url is provided.
:param str username: login name
:param str password: password for the login
... | Construct and return an authenticated GitHub session.
This will return a GitHubEnterprise session if a url is provided.
:param str username: login name
:param str password: password for the login
:param str token: OAuth token
:param str url: (optional), URL of a GitHub Enterprise instance
:par... | entailment |
def iter_followers(username, number=-1, etag=None):
"""List the followers of ``username``.
:param str username: (required), login of the person to list the followers
of
:param int number: (optional), number of followers to return, Default: -1,
return all of them
:param str etag: (option... | List the followers of ``username``.
:param str username: (required), login of the person to list the followers
of
:param int number: (optional), number of followers to return, Default: -1,
return all of them
:param str etag: (optional), ETag from a previous request to the same
endpo... | entailment |
def iter_following(username, number=-1, etag=None):
"""List the people ``username`` follows.
:param str username: (required), login of the user
:param int number: (optional), number of users being followed by username
to return. Default: -1, return all of them
:param str etag: (optional), ETag ... | List the people ``username`` follows.
:param str username: (required), login of the user
:param int number: (optional), number of users being followed by username
to return. Default: -1, return all of them
:param str etag: (optional), ETag from a previous request to the same
endpoint
:r... | entailment |
def iter_repo_issues(owner, repository, milestone=None, state=None,
assignee=None, mentioned=None, labels=None, sort=None,
direction=None, since=None, number=-1, etag=None):
"""List issues on owner/repository. Only owner and repository are
required.
.. versionchang... | List issues on owner/repository. Only owner and repository are
required.
.. versionchanged:: 0.9.0
- The ``state`` parameter now accepts 'all' in addition to 'open'
and 'closed'.
:param str owner: login of the owner of the repository
:param str repository: name of the repository
... | entailment |
def iter_orgs(username, number=-1, etag=None):
"""List the organizations associated with ``username``.
:param str username: (required), login of the user
:param int number: (optional), number of orgs to return. Default: -1,
return all of the issues
:param str etag: (optional), ETag from a previ... | List the organizations associated with ``username``.
:param str username: (required), login of the user
:param int number: (optional), number of orgs to return. Default: -1,
return all of the issues
:param str etag: (optional), ETag from a previous request to the same
endpoint
:returns:... | entailment |
def iter_user_repos(login, type=None, sort=None, direction=None, number=-1,
etag=None):
"""List public repositories for the specified ``login``.
.. versionadded:: 0.6
.. note:: This replaces github3.iter_repos
:param str login: (required)
:param str type: (optional), accepted ... | List public repositories for the specified ``login``.
.. versionadded:: 0.6
.. note:: This replaces github3.iter_repos
:param str login: (required)
:param str type: (optional), accepted values:
('all', 'owner', 'member')
API default: 'all'
:param str sort: (optional), accepted val... | entailment |
def markdown(text, mode='', context='', raw=False):
"""Render an arbitrary markdown document.
:param str text: (required), the text of the document to render
:param str mode: (optional), 'markdown' or 'gfm'
:param str context: (optional), only important when using mode 'gfm',
this is the reposi... | Render an arbitrary markdown document.
:param str text: (required), the text of the document to render
:param str mode: (optional), 'markdown' or 'gfm'
:param str context: (optional), only important when using mode 'gfm',
this is the repository to use as the context for the rendering
:param boo... | entailment |
def search_repositories(query, sort=None, order=None, per_page=None,
text_match=False, number=-1, etag=None):
"""Find repositories via various criteria.
.. warning::
You will only be able to make 5 calls with this or other search
functions. To raise the rate-limit on th... | Find repositories via various criteria.
.. warning::
You will only be able to make 5 calls with this or other search
functions. To raise the rate-limit on this set of endpoints, create an
authenticated :class:`GitHub <github3.github.GitHub>` Session with
``login``.
The query c... | entailment |
def limits(args):
"""
Describe limits in effect on your AWS account. See also https://console.aws.amazon.com/ec2/v2/home#Limits:
"""
# https://aws.amazon.com/about-aws/whats-new/2014/06/19/amazon-ec2-service-limits-report-now-available/
# Console-only APIs: getInstanceLimits, getAccountLimits, getAu... | Describe limits in effect on your AWS account. See also https://console.aws.amazon.com/ec2/v2/home#Limits: | entailment |
def add_labels(self, *args):
"""Add labels to this issue.
:param str args: (required), names of the labels you wish to add
:returns: list of :class:`Label`\ s
"""
url = self._build_url('labels', base_url=self._api)
json = self._json(self._post(url, data=args), 200)
... | Add labels to this issue.
:param str args: (required), names of the labels you wish to add
:returns: list of :class:`Label`\ s | entailment |
def assign(self, login):
"""Assigns user ``login`` to this issue. This is a short cut for
``issue.edit``.
:param str login: username of the person to assign this issue to
:returns: bool
"""
if not login:
return False
number = self.milestone.number if ... | Assigns user ``login`` to this issue. This is a short cut for
``issue.edit``.
:param str login: username of the person to assign this issue to
:returns: bool | entailment |
def comment(self, id_num):
"""Get a single comment by its id.
The catch here is that id is NOT a simple number to obtain. If
you were to look at the comments on issue #15 in
sigmavirus24/Todo.txt-python, the first comment's id is 4150787.
:param int id_num: (required), comment ... | Get a single comment by its id.
The catch here is that id is NOT a simple number to obtain. If
you were to look at the comments on issue #15 in
sigmavirus24/Todo.txt-python, the first comment's id is 4150787.
:param int id_num: (required), comment id, see example above
:returns... | entailment |
def create_comment(self, body):
"""Create a comment on this issue.
:param str body: (required), comment body
:returns: :class:`IssueComment <github3.issues.comment.IssueComment>`
"""
json = None
if body:
url = self._build_url('comments', base_url=self._api)
... | Create a comment on this issue.
:param str body: (required), comment body
:returns: :class:`IssueComment <github3.issues.comment.IssueComment>` | entailment |
def edit(self, title=None, body=None, assignee=None, state=None,
milestone=None, labels=None):
"""Edit this issue.
:param str title: Title of the issue
:param str body: markdown formatted body (description) of the issue
:param str assignee: login name of user the issue shou... | Edit this issue.
:param str title: Title of the issue
:param str body: markdown formatted body (description) of the issue
:param str assignee: login name of user the issue should be assigned
to
:param str state: accepted values: ('open', 'closed')
:param int mileston... | entailment |
def iter_comments(self, number=-1):
"""Iterate over the comments on this issue.
:param int number: (optional), number of comments to iterate over
:returns: iterator of
:class:`IssueComment <github3.issues.comment.IssueComment>`\ s
"""
url = self._build_url('comments'... | Iterate over the comments on this issue.
:param int number: (optional), number of comments to iterate over
:returns: iterator of
:class:`IssueComment <github3.issues.comment.IssueComment>`\ s | entailment |
def iter_events(self, number=-1):
"""Iterate over events associated with this issue only.
:param int number: (optional), number of events to return. Default: -1
returns all events available.
:returns: generator of
:class:`IssueEvent <github3.issues.event.IssueEvent>`\ s
... | Iterate over events associated with this issue only.
:param int number: (optional), number of events to return. Default: -1
returns all events available.
:returns: generator of
:class:`IssueEvent <github3.issues.event.IssueEvent>`\ s | entailment |
def remove_label(self, name):
"""Removes label ``name`` from this issue.
:param str name: (required), name of the label to remove
:returns: bool
"""
url = self._build_url('labels', name, base_url=self._api)
# Docs say it should be a list of strings returned, practice say... | Removes label ``name`` from this issue.
:param str name: (required), name of the label to remove
:returns: bool | entailment |
def replace_labels(self, labels):
"""Replace all labels on this issue with ``labels``.
:param list labels: label names
:returns: bool
"""
url = self._build_url('labels', base_url=self._api)
json = self._json(self._put(url, data=dumps(labels)), 200)
return [Label(... | Replace all labels on this issue with ``labels``.
:param list labels: label names
:returns: bool | entailment |
def reopen(self):
"""Re-open a closed issue.
:returns: bool
"""
assignee = self.assignee.login if self.assignee else ''
number = self.milestone.number if self.milestone else None
labels = [str(l) for l in self.labels]
return self.edit(self.title, self.body, assig... | Re-open a closed issue.
:returns: bool | entailment |
def _strptime(self, time_str):
"""Convert an ISO 8601 formatted string in UTC into a
timezone-aware datetime object."""
if time_str:
# Parse UTC string into naive datetime, then add timezone
dt = datetime.strptime(time_str, __timeformat__)
return dt.replace(tz... | Convert an ISO 8601 formatted string in UTC into a
timezone-aware datetime object. | entailment |
def _iter(self, count, url, cls, params=None, etag=None):
"""Generic iterator for this project.
:param int count: How many items to return.
:param int url: First URL to start with
:param class cls: cls to return an object of
:param params dict: (optional) Parameters for the requ... | Generic iterator for this project.
:param int count: How many items to return.
:param int url: First URL to start with
:param class cls: cls to return an object of
:param params dict: (optional) Parameters for the request
:param str etag: (optional), ETag from the last call | entailment |
def ratelimit_remaining(self):
"""Number of requests before GitHub imposes a ratelimit.
:returns: int
"""
json = self._json(self._get(self._github_url + '/rate_limit'), 200)
core = json.get('resources', {}).get('core', {})
self._remaining = core.get('remaining', 0)
... | Number of requests before GitHub imposes a ratelimit.
:returns: int | entailment |
def refresh(self, conditional=False):
"""Re-retrieve the information for this object and returns the
refreshed instance.
:param bool conditional: If True, then we will search for a stored
header ('Last-Modified', or 'ETag') on the object and send that
as described in the... | Re-retrieve the information for this object and returns the
refreshed instance.
:param bool conditional: If True, then we will search for a stored
header ('Last-Modified', or 'ETag') on the object and send that
as described in the `Conditional Requests`_ section of the docs
... | entailment |
def edit(self, body):
"""Edit this comment.
:param str body: (required), new body of the comment, Markdown
formatted
:returns: bool
"""
if body:
json = self._json(self._patch(self._api,
data=dumps({'body': body})), 200)
... | Edit this comment.
:param str body: (required), new body of the comment, Markdown
formatted
:returns: bool | entailment |
def toplot(ts,
filename=None,
grid=True,
legend=True,
pargs=(),
**kwargs):
'''To plot formatter'''
fig = plt.figure()
ax = fig.add_subplot(111)
dates = list(ts.dates())
ax.plot(dates, ts.values(), *pargs)
ax.grid(grid)
# ro... | To plot formatter | entailment |
def check_table(table):
"""
Ensure the table is valid for converting to grid table.
* The table must a list of lists
* Each row must contain the same number of columns
* The table must not be empty
Parameters
----------
table : list of lists of str
The list of rows of strings t... | Ensure the table is valid for converting to grid table.
* The table must a list of lists
* Each row must contain the same number of columns
* The table must not be empty
Parameters
----------
table : list of lists of str
The list of rows of strings to convert to a grid table
Retur... | entailment |
def get_span(spans, row, column):
"""
Gets the span containing the [row, column] pair
Parameters
----------
spans : list of lists of lists
A list containing spans, which are lists of [row, column] pairs
that define where a span is inside a table.
Returns
-------
span : ... | Gets the span containing the [row, column] pair
Parameters
----------
spans : list of lists of lists
A list containing spans, which are lists of [row, column] pairs
that define where a span is inside a table.
Returns
-------
span : list of lists
A span containing the [r... | entailment |
def find_unassigned_table_cell(table):
"""
Search through a table and return the first [row, column] pair
who's value is None.
Parameters
----------
table : list of lists of str
Returns
-------
list of int
The row column pair of the None type cell
"""
for row in ran... | Search through a table and return the first [row, column] pair
who's value is None.
Parameters
----------
table : list of lists of str
Returns
-------
list of int
The row column pair of the None type cell | entailment |
def insert(self, dte, values):
'''insert *values* at date *dte*.'''
if len(values):
dte = self.dateconvert(dte)
if not self:
self._date = np.array([dte])
self._data = np.array([values])
else:
# search for the date
... | insert *values* at date *dte*. | entailment |
def _translate_nodes(root, *nodes):
"""
Convert node names into node instances...
"""
#name2node = {[n, None] for n in nodes if type(n) is str}
name2node = dict([[n, None] for n in nodes if type(n) is str])
for n in root.traverse():
if n.name in name2node:
if name2node[n.name... | Convert node names into node instances... | entailment |
def add_feature(self, pr_name, pr_value):
""" Add or update a node's feature. """
setattr(self, pr_name, pr_value)
self.features.add(pr_name) | Add or update a node's feature. | entailment |
def add_features(self, **features):
""" Add or update several features. """
for fname, fvalue in six.iteritems(features):
setattr(self, fname, fvalue)
self.features.add(fname) | Add or update several features. | entailment |
def del_feature(self, pr_name):
""" Permanently deletes a node's feature."""
if hasattr(self, pr_name):
delattr(self, pr_name)
self.features.remove(pr_name) | Permanently deletes a node's feature. | entailment |
def add_child(self, child=None, name=None, dist=None, support=None):
"""
Adds a new child to this node. If child node is not suplied
as an argument, a new node instance will be created.
Parameters
----------
child:
the node instance to be added as a... | Adds a new child to this node. If child node is not suplied
as an argument, a new node instance will be created.
Parameters
----------
child:
the node instance to be added as a child.
name:
the name that will be given to the child.
dist... | entailment |
def remove_child(self, child):
"""
Removes a child from this node (parent and child
nodes still exit but are no longer connected).
"""
try:
self.children.remove(child)
except ValueError as e:
raise TreeError("child not found")
else:
... | Removes a child from this node (parent and child
nodes still exit but are no longer connected). | entailment |
def add_sister(self, sister=None, name=None, dist=None):
"""
Adds a sister to this node. If sister node is not supplied
as an argument, a new TreeNode instance will be created and
returned.
"""
if self.up == None:
raise TreeError("A parent node is required to ... | Adds a sister to this node. If sister node is not supplied
as an argument, a new TreeNode instance will be created and
returned. | entailment |
def remove_sister(self, sister=None):
"""
Removes a sister node. It has the same effect as
**`TreeNode.up.remove_child(sister)`**
If a sister node is not supplied, the first sister will be deleted
and returned.
:argument sister: A node instance
:return: The nod... | Removes a sister node. It has the same effect as
**`TreeNode.up.remove_child(sister)`**
If a sister node is not supplied, the first sister will be deleted
and returned.
:argument sister: A node instance
:return: The node removed | entailment |
def delete(self, prevent_nondicotomic=True, preserve_branch_length=False):
"""
Deletes node from the tree structure. Notice that this method
makes 'disappear' the node from the tree structure. This means
that children from the deleted node are transferred to the
next available pa... | Deletes node from the tree structure. Notice that this method
makes 'disappear' the node from the tree structure. This means
that children from the deleted node are transferred to the
next available parent.
Parameters:
-----------
prevent_nondicotomic:
When ... | entailment |
def detach(self):
"""
Detachs this node (and all its descendants) from its parent
and returns the referent to itself.
Detached node conserves all its structure of descendants, and can
be attached to another node through the 'add_child' function. This
mechanism can be see... | Detachs this node (and all its descendants) from its parent
and returns the referent to itself.
Detached node conserves all its structure of descendants, and can
be attached to another node through the 'add_child' function. This
mechanism can be seen as a cut and paste. | entailment |
def prune(self, nodes, preserve_branch_length=False):
"""
Prunes the topology of a node to conserve only a selected list of leaf
internal nodes. The minimum number of nodes that conserve the
topological relationships among the requested nodes will be
retained. Root node is always... | Prunes the topology of a node to conserve only a selected list of leaf
internal nodes. The minimum number of nodes that conserve the
topological relationships among the requested nodes will be
retained. Root node is always conserved.
Parameters:
-----------
nodes:
... | entailment |
def get_sisters(self):
""" Returns an indepent list of sister nodes."""
if self.up != None:
return [ch for ch in self.up.children if ch != self]
else:
return [] | Returns an indepent list of sister nodes. | entailment |
def iter_leaves(self, is_leaf_fn=None):
""" Returns an iterator over the leaves under this node."""
for n in self.traverse(strategy="preorder", is_leaf_fn=is_leaf_fn):
if not is_leaf_fn:
if n.is_leaf():
yield n
else:
if is_leaf_... | Returns an iterator over the leaves under this node. | entailment |
def iter_leaf_names(self, is_leaf_fn=None):
"""Returns an iterator over the leaf names under this node."""
for n in self.iter_leaves(is_leaf_fn=is_leaf_fn):
yield n.name | Returns an iterator over the leaf names under this node. | entailment |
def iter_descendants(self, strategy="levelorder", is_leaf_fn=None):
""" Returns an iterator over all descendant nodes."""
for n in self.traverse(strategy=strategy, is_leaf_fn=is_leaf_fn):
if n is not self:
yield n | Returns an iterator over all descendant nodes. | entailment |
def get_descendants(self, strategy="levelorder", is_leaf_fn=None):
""" Returns a list of all (leaves and internal) descendant nodes."""
return [n for n in self.iter_descendants(
strategy=strategy, is_leaf_fn=is_leaf_fn)] | Returns a list of all (leaves and internal) descendant nodes. | entailment |
def traverse(self, strategy="levelorder", is_leaf_fn=None):
""" Returns an iterator to traverse tree under this node.
Parameters:
-----------
strategy:
set the way in which tree will be traversed. Possible
values are: "preorder" (first parent and then c... | Returns an iterator to traverse tree under this node.
Parameters:
-----------
strategy:
set the way in which tree will be traversed. Possible
values are: "preorder" (first parent and then children)
'postorder' (first children and the parent) and
... | entailment |
def iter_prepostorder(self, is_leaf_fn=None):
"""
Iterate over all nodes in a tree yielding every node in both
pre and post order. Each iteration returns a postorder flag
(True if node is being visited in postorder) and a node
instance.
"""
to_visit = [self]
... | Iterate over all nodes in a tree yielding every node in both
pre and post order. Each iteration returns a postorder flag
(True if node is being visited in postorder) and a node
instance. | entailment |
def _iter_descendants_levelorder(self, is_leaf_fn=None):
""" Iterate over all desdecendant nodes."""
tovisit = deque([self])
while len(tovisit) > 0:
node = tovisit.popleft()
yield node
if not is_leaf_fn or not is_leaf_fn(node):
tovisit.extend(n... | Iterate over all desdecendant nodes. | entailment |
def _iter_descendants_preorder(self, is_leaf_fn=None):
""" Iterator over all descendant nodes. """
to_visit = deque()
node = self
while node is not None:
yield node
if not is_leaf_fn or not is_leaf_fn(node):
to_visit.extendleft(reversed(node.childr... | Iterator over all descendant nodes. | entailment |
def iter_ancestors(self):
"""
Iterates over the list of all ancestor nodes from
current node to the current tree root.
"""
node = self
while node.up is not None:
yield node.up
node = node.up | Iterates over the list of all ancestor nodes from
current node to the current tree root. | entailment |
def write(self,
features=None,
outfile=None,
format=0,
is_leaf_fn=None,
format_root_node=False,
dist_formatter=None,
support_formatter=None,
name_formatter=None):
"""
Returns the newick representation of current node. Several
... | Returns the newick representation of current node. Several
arguments control the way in which extra data is shown for
every node:
Parameters:
-----------
features:
a list of feature names to be exported using the Extended Newick
Format (i.e. features=["... | entailment |
def get_tree_root(self):
""" Returns the absolute root node of current tree structure."""
root = self
while root.up is not None:
root = root.up
return root | Returns the absolute root node of current tree structure. | entailment |
def get_common_ancestor(self, *target_nodes, **kargs):
"""
Returns the first common ancestor between this node and a given
list of 'target_nodes'.
**Examples:**
t = tree.Tree("(((A:0.1, B:0.01):0.001, C:0.0001):1.0[&&NHX:name=common], (D:0.00001):0.000001):2.0[&&NHX:name=root]... | Returns the first common ancestor between this node and a given
list of 'target_nodes'.
**Examples:**
t = tree.Tree("(((A:0.1, B:0.01):0.001, C:0.0001):1.0[&&NHX:name=common], (D:0.00001):0.000001):2.0[&&NHX:name=root];")
A = t.get_descendants_by_name("A")[0]
C = t.get_des... | entailment |
def iter_search_nodes(self, **conditions):
"""
Search nodes in an interative way. Matches are being yield as
they are being found. This avoids to scan the full tree
topology before returning the first matches. Useful when
dealing with huge trees.
"""
for n in self... | Search nodes in an interative way. Matches are being yield as
they are being found. This avoids to scan the full tree
topology before returning the first matches. Useful when
dealing with huge trees. | entailment |
def search_nodes(self, **conditions):
"""
Returns the list of nodes matching a given set of conditions.
**Example:**
tree.search_nodes(dist=0.0, name="human")
"""
matching_nodes = []
for n in self.iter_search_nodes(**conditions):
matching_nodes.append(... | Returns the list of nodes matching a given set of conditions.
**Example:**
tree.search_nodes(dist=0.0, name="human") | entailment |
def get_distance(self, target, target2=None, topology_only=False):
"""
Returns the distance between two nodes. If only one target is
specified, it returns the distance bewtween the target and the
current node.
Parameters:
-----------
target:
a no... | Returns the distance between two nodes. If only one target is
specified, it returns the distance bewtween the target and the
current node.
Parameters:
-----------
target:
a node within the same tree structure.
target2:
a node within the sam... | entailment |
def get_farthest_node(self, topology_only=False):
"""
Returns the node's farthest descendant or ancestor node, and the
distance to it.
:argument False topology_only: If set to True, distance
between nodes will be referred to the number of nodes
between them. In other... | Returns the node's farthest descendant or ancestor node, and the
distance to it.
:argument False topology_only: If set to True, distance
between nodes will be referred to the number of nodes
between them. In other words, topological distance will be
used instead of branch ... | entailment |
def get_farthest_leaf(self, topology_only=False, is_leaf_fn=None):
"""
Returns node's farthest descendant node (which is always a leaf), and the
distance to it.
:argument False topology_only: If set to True, distance
between nodes will be referred to the number of nodes
... | Returns node's farthest descendant node (which is always a leaf), and the
distance to it.
:argument False topology_only: If set to True, distance
between nodes will be referred to the number of nodes
between them. In other words, topological distance will be
used instead o... | entailment |
def get_midpoint_outgroup(self):
"""
Returns the node that divides the current tree into two
distance-balanced partitions.
"""
# Gets the farthest node to the current root
root = self.get_tree_root()
nA, r2A_dist = root.get_farthest_leaf()
nB, A2B_dist = ... | Returns the node that divides the current tree into two
distance-balanced partitions. | entailment |
def populate(self,
size,
names_library=None,
reuse_names=False,
random_branches=False,
branch_range=(0, 1),
support_range=(0, 1)):
"""
Generates a random topology by populating current node.
:argument None names_library: If provided, names lib... | Generates a random topology by populating current node.
:argument None names_library: If provided, names library
(list, set, dict, etc.) will be used to name nodes.
:argument False reuse_names: If True, node names will not be
necessarily unique, which makes the process a bit more
... | entailment |
def set_outgroup(self, outgroup):
"""
Sets a descendant node as the outgroup of a tree. This function
can be used to root a tree or even an internal node.
Parameters:
-----------
outgroup:
a node instance within the same tree structure that will be
... | Sets a descendant node as the outgroup of a tree. This function
can be used to root a tree or even an internal node.
Parameters:
-----------
outgroup:
a node instance within the same tree structure that will be
used as a basal node. | entailment |
def unroot(self):
"""
Unroots current node. This function is expected to be used on
the absolute tree root node, but it can be also be applied to
any other internal node. It will convert a split into a
multifurcation.
"""
if len(self.children)==2:
if n... | Unroots current node. This function is expected to be used on
the absolute tree root node, but it can be also be applied to
any other internal node. It will convert a split into a
multifurcation. | entailment |
def _asciiArt(self, char1='-', show_internal=True, compact=False, attributes=None):
"""
Returns the ASCII representation of the tree.
Code based on the PyCogent GPL project.
"""
if not attributes:
attributes = ["name"]
# toytree edit:
# remove... | Returns the ASCII representation of the tree.
Code based on the PyCogent GPL project. | entailment |
def get_ascii(self, show_internal=True, compact=False, attributes=None):
"""
Returns a string containing an ascii drawing of the tree.
Parameters:
-----------
show_internal:
include internal edge names.
compact:
use exactly one line per ... | Returns a string containing an ascii drawing of the tree.
Parameters:
-----------
show_internal:
include internal edge names.
compact:
use exactly one line per tip.
attributes:
A list of node attributes to shown in the ASCII represe... | entailment |
def ladderize(self, direction=0):
"""
Sort the branches of a given tree (swapping children nodes)
according to the size of each partition.
"""
if not self.is_leaf():
n2s = {}
for n in self.get_children():
s = n.ladderize(direction=direction... | Sort the branches of a given tree (swapping children nodes)
according to the size of each partition. | entailment |
def sort_descendants(self, attr="name"):
"""
This function sort the branches of a given tree by
considerening node names. After the tree is sorted, nodes are
labeled using ascendent numbers. This can be used to ensure
that nodes in a tree with the same node names are always
... | This function sort the branches of a given tree by
considerening node names. After the tree is sorted, nodes are
labeled using ascendent numbers. This can be used to ensure
that nodes in a tree with the same node names are always
labeled in the same way. Note that if duplicated names ar... | entailment |
def get_cached_content(self, store_attr=None, container_type=set, _store=None):
"""
Returns a dictionary pointing to the preloaded content of each
internal node under this tree. Such a dictionary is intended
to work as a cache for operations that require many traversal
operations... | Returns a dictionary pointing to the preloaded content of each
internal node under this tree. Such a dictionary is intended
to work as a cache for operations that require many traversal
operations.
Parameters:
-----------
store_attr:
Specifies the no... | entailment |
def robinson_foulds(self,
t2,
attr_t1="name",
attr_t2="name",
unrooted_trees=False,
expand_polytomies=False,
polytomy_size_limit=5,
skip_large_polytomies=False,
correct_by_polytomy_size=False,
min_support_t1=0.0,
min_support_t2=0.0):
... | Returns the Robinson-Foulds symmetric distance between current
tree and a different tree instance.
Parameters:
-----------
t2:
reference tree
attr_t1:
Compare trees using a custom node attribute as a node name.
attr_t2:
Compare tree... | entailment |
def iter_edges(self, cached_content=None):
"""
Iterate over the list of edges of a tree. Each egde is represented as a
tuple of two elements, each containing the list of nodes separated by
the edge.
"""
if not cached_content:
cached_content = self.get_cached_c... | Iterate over the list of edges of a tree. Each egde is represented as a
tuple of two elements, each containing the list of nodes separated by
the edge. | entailment |
def get_topology_id(self, attr="name"):
"""
Returns the unique ID representing the topology of the current tree.
Two trees with the same topology will produce the same id. If trees are
unrooted, make sure that the root node is not binary or use the
tree.unroot() function before ... | Returns the unique ID representing the topology of the current tree.
Two trees with the same topology will produce the same id. If trees are
unrooted, make sure that the root node is not binary or use the
tree.unroot() function before generating the topology id.
This is useful to detec... | entailment |
def check_monophyly(self,
values,
target_attr,
ignore_missing=False,
unrooted=False):
"""
Returns True if a given target attribute is monophyletic under
this node for the provided set of values.
If not all values are represented in the current tree
... | Returns True if a given target attribute is monophyletic under
this node for the provided set of values.
If not all values are represented in the current tree
structure, a ValueError exception will be raised to warn that
strict monophyly could never be reached (this behaviour can be
... | entailment |
def get_monophyletic(self, values, target_attr):
"""
Returns a list of nodes matching the provided monophyly
criteria. For a node to be considered a match, all
`target_attr` values within and node, and exclusively them,
should be grouped.
:param values: a set of values f... | Returns a list of nodes matching the provided monophyly
criteria. For a node to be considered a match, all
`target_attr` values within and node, and exclusively them,
should be grouped.
:param values: a set of values for which monophyly is
expected.
:param target_at... | entailment |
def expand_polytomies(self,
map_attr="name",
polytomy_size_limit=5,
skip_large_polytomies=False):
"""
Given a tree with one or more polytomies, this functions returns the
list of all trees (in newick format) resulting from the combination of
all possible solutio... | Given a tree with one or more polytomies, this functions returns the
list of all trees (in newick format) resulting from the combination of
all possible solutions of the multifurcated nodes.
.. warning:
Please note that the number of of possible binary trees grows
exponen... | entailment |
def resolve_polytomy(self,
default_dist=0.0,
default_support=0.0,
recursive=True):
"""
Resolve all polytomies under current node by creating an
arbitrary dicotomic structure among the affected nodes. This
function randomly modifies current tree topology and shou... | Resolve all polytomies under current node by creating an
arbitrary dicotomic structure among the affected nodes. This
function randomly modifies current tree topology and should
only be used for compatibility reasons (i.e. programs
rejecting multifurcated node in the newick representatio... | entailment |
def truncate_empty_lines(lines):
"""
Removes all empty lines from above and below the text.
We can't just use text.strip() because that would remove the leading
space for the table.
Parameters
----------
lines : list of str
Returns
-------
lines : list of str
The text ... | Removes all empty lines from above and below the text.
We can't just use text.strip() because that would remove the leading
space for the table.
Parameters
----------
lines : list of str
Returns
-------
lines : list of str
The text lines without empty lines above or below | entailment |
def jstimestamp_slow(dte):
'''Convert a date or datetime object into a javsacript timestamp'''
year, month, day, hour, minute, second = dte.timetuple()[:6]
days = date(year, month, 1).toordinal() - _EPOCH_ORD + day - 1
hours = days*24 + hour
minutes = hours*60 + minute
seconds = minutes*60... | Convert a date or datetime object into a javsacript timestamp | entailment |
def jstimestamp(dte):
'''Convert a date or datetime object into a javsacript timestamp.'''
days = date(dte.year, dte.month, 1).toordinal() - _EPOCH_ORD + dte.day - 1
hours = days*24
if isinstance(dte,datetime):
hours += dte.hour
minutes = hours*60 + dte.minute
second... | Convert a date or datetime object into a javsacript timestamp. | entailment |
def html2rst(html_string, force_headers=False, center_cells=False,
center_headers=False):
"""
Convert a string or html file to an rst table string.
Parameters
----------
html_string : str
Either the html string, or the filepath to the html
force_headers : bool
Make ... | Convert a string or html file to an rst table string.
Parameters
----------
html_string : str
Either the html string, or the filepath to the html
force_headers : bool
Make the first row become headers, whether or not they are
headers in the html file.
center_cells : bool
... | entailment |
def make_span(row, column, extra_rows, extra_columns):
"""
Create a list of rows and columns that will make up a span
Parameters
----------
row : int
The row of the first cell in the span
column : int
The column of the first cell in the span
extra_rows : int
The numb... | Create a list of rows and columns that will make up a span
Parameters
----------
row : int
The row of the first cell in the span
column : int
The column of the first cell in the span
extra_rows : int
The number of rows that make up the span
extra_columns : int
Th... | entailment |
def make_cell(table, span, widths, heights, use_headers):
"""
Convert the contents of a span of the table to a grid table cell
Parameters
----------
table : list of lists of str
The table of rows containg strings to convert to a grid table
span : list of lists of int
list of [ro... | Convert the contents of a span of the table to a grid table cell
Parameters
----------
table : list of lists of str
The table of rows containg strings to convert to a grid table
span : list of lists of int
list of [row, column] pairs that make up a span in the table
widths : list of... | entailment |
def init_app(self, app, **kwargs):
"""Initialize application object."""
self.init_db(app, **kwargs)
app.config.setdefault('ALEMBIC', {
'script_location': pkg_resources.resource_filename(
'invenio_db', 'alembic'
),
'version_locations': [
... | Initialize application object. | entailment |
def init_db(self, app, entry_point_group='invenio_db.models', **kwargs):
"""Initialize Flask-SQLAlchemy extension."""
# Setup SQLAlchemy
app.config.setdefault(
'SQLALCHEMY_DATABASE_URI',
'sqlite:///' + os.path.join(app.instance_path, app.name + '.db')
)
ap... | Initialize Flask-SQLAlchemy extension. | entailment |
def init_versioning(self, app, database, versioning_manager=None):
"""Initialize the versioning support using SQLAlchemy-Continuum."""
try:
pkg_resources.get_distribution('sqlalchemy_continuum')
except pkg_resources.DistributionNotFound: # pragma: no cover
default_versio... | Initialize the versioning support using SQLAlchemy-Continuum. | entailment |
def extract_table(html_string, row_count, column_count):
"""
Convert an html string to data table
Parameters
----------
html_string : str
row_count : int
column_count : int
Returns
-------
data_table : list of lists of str
"""
try:
from bs4 import BeautifulSoup
... | Convert an html string to data table
Parameters
----------
html_string : str
row_count : int
column_count : int
Returns
-------
data_table : list of lists of str | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.