sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def extract_objects(self, fname, type_filter=None):
'''Extract objects from a source file
Args:
fname(str): Name of file to read from
type_filter (class, optional): Object class to filter results
Returns:
List of objects extracted from the file.
'''
objects = []
if fname in se... | Extract objects from a source file
Args:
fname(str): Name of file to read from
type_filter (class, optional): Object class to filter results
Returns:
List of objects extracted from the file. | entailment |
def extract_objects_from_source(self, text, type_filter=None):
'''Extract object declarations from a text buffer
Args:
text (str): Source code to parse
type_filter (class, optional): Object class to filter results
Returns:
List of parsed objects.
'''
objects = parse_verilog(text)
... | Extract object declarations from a text buffer
Args:
text (str): Source code to parse
type_filter (class, optional): Object class to filter results
Returns:
List of parsed objects. | entailment |
def load_json_from_file(file_path):
"""Load schema from a JSON file"""
try:
with open(file_path) as f:
json_data = json.load(f)
except ValueError as e:
raise ValueError('Given file {} is not a valid JSON file: {}'.format(file_path, e))
else:
return json_data | Load schema from a JSON file | entailment |
def load_json_from_string(string):
"""Load schema from JSON string"""
try:
json_data = json.loads(string)
except ValueError as e:
raise ValueError('Given string is not valid JSON: {}'.format(e))
else:
return json_data | Load schema from JSON string | entailment |
def _generate_one_fake(self, schema):
"""
Recursively traverse schema dictionary and for each "leaf node", evaluate the fake
value
Implementation:
For each key-value pair:
1) If value is not an iterable (i.e. dict or list), evaluate the fake data (base case)
2) I... | Recursively traverse schema dictionary and for each "leaf node", evaluate the fake
value
Implementation:
For each key-value pair:
1) If value is not an iterable (i.e. dict or list), evaluate the fake data (base case)
2) If value is a dictionary, recurse
3) If value is a ... | entailment |
def fetch(method, uri, params_prefix=None, **params):
"""Fetch the given uri and return the contents of the response."""
params = urlencode(_prepare_params(params, params_prefix))
binary_params = params.encode('ASCII')
# build the HTTP request
url = "https://%s/%s.xml" % (CHALLONGE_API_URL, uri)
... | Fetch the given uri and return the contents of the response. | entailment |
def fetch_and_parse(method, uri, params_prefix=None, **params):
"""Fetch the given uri and return the root Element of the response."""
doc = ElementTree.parse(fetch(method, uri, params_prefix, **params))
return _parse(doc.getroot()) | Fetch the given uri and return the root Element of the response. | entailment |
def _parse(root):
"""Recursively convert an Element into python data types"""
if root.tag == "nil-classes":
return []
elif root.get("type") == "array":
return [_parse(child) for child in root]
d = {}
for child in root:
type = child.get("type") or "string"
if child.g... | Recursively convert an Element into python data types | entailment |
def _prepare_params(dirty_params, prefix=None):
"""Prepares parameters to be sent to challonge.com.
The `prefix` can be used to convert parameters with keys that
look like ("name", "url", "tournament_type") into something like
("tournament[name]", "tournament[url]", "tournament[tournament_type]"),
... | Prepares parameters to be sent to challonge.com.
The `prefix` can be used to convert parameters with keys that
look like ("name", "url", "tournament_type") into something like
("tournament[name]", "tournament[url]", "tournament[tournament_type]"),
which is how challonge.com expects parameters describin... | entailment |
def expandDescendants(self, branches):
"""
Expand descendants from list of branches
:param list branches: list of immediate children as TreeOfContents objs
:return: list of all descendants
"""
return sum([b.descendants() for b in branches], []) + \
[b.source ... | Expand descendants from list of branches
:param list branches: list of immediate children as TreeOfContents objs
:return: list of all descendants | entailment |
def parseBranches(self, descendants):
"""
Parse top level of markdown
:param list elements: list of source objects
:return: list of filtered TreeOfContents objects
"""
parsed, parent, cond = [], False, lambda b: (b.string or '').strip()
for branch in filter(cond,... | Parse top level of markdown
:param list elements: list of source objects
:return: list of filtered TreeOfContents objects | entailment |
def fromMarkdown(md, *args, **kwargs):
"""
Creates abstraction using path to file
:param str path: path to markdown file
:return: TreeOfContents object
"""
return TOC.fromHTML(markdown(md, *args, **kwargs)) | Creates abstraction using path to file
:param str path: path to markdown file
:return: TreeOfContents object | entailment |
def fromHTML(html, *args, **kwargs):
"""
Creates abstraction using HTML
:param str html: HTML
:return: TreeOfContents object
"""
source = BeautifulSoup(html, 'html.parser', *args, **kwargs)
return TOC('[document]',
source=source,
descendan... | Creates abstraction using HTML
:param str html: HTML
:return: TreeOfContents object | entailment |
def from_data(cls, type, **data):
"""Create an attachment from data.
:param str type: attachment type
:param kwargs data: additional attachment data
:return: an attachment subclass object
:rtype: `~groupy.api.attachments.Attachment`
"""
try:
return cl... | Create an attachment from data.
:param str type: attachment type
:param kwargs data: additional attachment data
:return: an attachment subclass object
:rtype: `~groupy.api.attachments.Attachment` | entailment |
def from_file(self, fp):
"""Create a new image attachment from an image file.
:param file fp: a file object containing binary image data
:return: an image attachment
:rtype: :class:`~groupy.api.attachments.Image`
"""
image_urls = self.upload(fp)
return Image(imag... | Create a new image attachment from an image file.
:param file fp: a file object containing binary image data
:return: an image attachment
:rtype: :class:`~groupy.api.attachments.Image` | entailment |
def upload(self, fp):
"""Upload image data to the image service.
Call this, rather than :func:`from_file`, you don't want to
create an attachment of the image.
:param file fp: a file object containing binary image data
:return: the URLs for the image uploaded
:rtype: di... | Upload image data to the image service.
Call this, rather than :func:`from_file`, you don't want to
create an attachment of the image.
:param file fp: a file object containing binary image data
:return: the URLs for the image uploaded
:rtype: dict | entailment |
def download(self, image, url_field='url', suffix=None):
"""Download the binary data of an image attachment.
:param image: an image attachment
:type image: :class:`~groupy.api.attachments.Image`
:param str url_field: the field of the image with the right URL
:param str suffix: a... | Download the binary data of an image attachment.
:param image: an image attachment
:type image: :class:`~groupy.api.attachments.Image`
:param str url_field: the field of the image with the right URL
:param str suffix: an optional URL suffix
:return: binary image data
:rt... | entailment |
def download_preview(self, image, url_field='url'):
"""Downlaod the binary data of an image attachment at preview size.
:param str url_field: the field of the image with the right URL
:return: binary image data
:rtype: bytes
"""
return self.download(image, url_field=url... | Downlaod the binary data of an image attachment at preview size.
:param str url_field: the field of the image with the right URL
:return: binary image data
:rtype: bytes | entailment |
def download_large(self, image, url_field='url'):
"""Downlaod the binary data of an image attachment at large size.
:param str url_field: the field of the image with the right URL
:return: binary image data
:rtype: bytes
"""
return self.download(image, url_field=url_fie... | Downlaod the binary data of an image attachment at large size.
:param str url_field: the field of the image with the right URL
:return: binary image data
:rtype: bytes | entailment |
def download_avatar(self, image, url_field='url'):
"""Downlaod the binary data of an image attachment at avatar size.
:param str url_field: the field of the image with the right URL
:return: binary image data
:rtype: bytes
"""
return self.download(image, url_field=url_f... | Downlaod the binary data of an image attachment at avatar size.
:param str url_field: the field of the image with the right URL
:return: binary image data
:rtype: bytes | entailment |
def autopage(self):
"""Iterate through results from all pages.
:return: all results
:rtype: generator
"""
while self.items:
yield from self.items
self.items = self.fetch_next() | Iterate through results from all pages.
:return: all results
:rtype: generator | entailment |
def detect_mode(cls, **params):
"""Detect which listing mode of the given params.
:params kwargs params: the params
:return: one of the available modes
:rtype: str
:raises ValueError: if multiple modes are detected
"""
modes = []
for mode in cls.modes:
... | Detect which listing mode of the given params.
:params kwargs params: the params
:return: one of the available modes
:rtype: str
:raises ValueError: if multiple modes are detected | entailment |
def set_next_page_params(self):
"""Set the params so that the next page is fetched."""
if self.items:
index = self.get_last_item_index()
self.params[self.mode] = self.get_next_page_param(self.items[index]) | Set the params so that the next page is fetched. | entailment |
def list(self):
"""List the users you have blocked.
:return: a list of :class:`~groupy.api.blocks.Block`'s
:rtype: :class:`list`
"""
params = {'user': self.user_id}
response = self.session.get(self.url, params=params)
blocks = response.data['blocks']
retu... | List the users you have blocked.
:return: a list of :class:`~groupy.api.blocks.Block`'s
:rtype: :class:`list` | entailment |
def between(self, other_user_id):
"""Check if there is a block between you and the given user.
:return: ``True`` if the given user has been blocked
:rtype: bool
"""
params = {'user': self.user_id, 'otherUser': other_user_id}
response = self.session.get(self.url, params=p... | Check if there is a block between you and the given user.
:return: ``True`` if the given user has been blocked
:rtype: bool | entailment |
def block(self, other_user_id):
"""Block the given user.
:param str other_user_id: the ID of the user to block
:return: the block created
:rtype: :class:`~groupy.api.blocks.Block`
"""
params = {'user': self.user_id, 'otherUser': other_user_id}
response = self.ses... | Block the given user.
:param str other_user_id: the ID of the user to block
:return: the block created
:rtype: :class:`~groupy.api.blocks.Block` | entailment |
def unblock(self, other_user_id):
"""Unblock the given user.
:param str other_user_id: the ID of the user to unblock
:return: ``True`` if successful
:rtype: bool
"""
params = {'user': self.user_id, 'otherUser': other_user_id}
response = self.session.delete(self.u... | Unblock the given user.
:param str other_user_id: the ID of the user to unblock
:return: ``True`` if successful
:rtype: bool | entailment |
def list(self, page=1, per_page=10):
"""List a page of chats.
:param int page: which page
:param int per_page: how many chats per page
:return: chats with other users
:rtype: :class:`~groupy.pagers.ChatList`
"""
return pagers.ChatList(self, self._raw_list, per_pa... | List a page of chats.
:param int page: which page
:param int per_page: how many chats per page
:return: chats with other users
:rtype: :class:`~groupy.pagers.ChatList` | entailment |
def list(self, before_id=None, since_id=None, after_id=None, limit=20):
"""Return a page of group messages.
The messages come in reversed order (newest first). Note you can only
provide _one_ of ``before_id``, ``since_id``, or ``after_id``.
:param str before_id: message ID for paging b... | Return a page of group messages.
The messages come in reversed order (newest first). Note you can only
provide _one_ of ``before_id``, ``since_id``, or ``after_id``.
:param str before_id: message ID for paging backwards
:param str after_id: message ID for paging forwards
:param... | entailment |
def list_since(self, message_id, limit=None):
"""Return a page of group messages created since a message.
This is used to fetch the most recent messages after another. There
may exist messages between the one given and the ones returned. Use
:func:`list_after` to retrieve newer messages... | Return a page of group messages created since a message.
This is used to fetch the most recent messages after another. There
may exist messages between the one given and the ones returned. Use
:func:`list_after` to retrieve newer messages without skipping any.
:param str message_id: th... | entailment |
def list_after(self, message_id, limit=None):
"""Return a page of group messages created after a message.
This is used to page forwards through messages.
:param str message_id: the ID of a message
:param int limit: maximum number of messages per page
:return: group messages
... | Return a page of group messages created after a message.
This is used to page forwards through messages.
:param str message_id: the ID of a message
:param int limit: maximum number of messages per page
:return: group messages
:rtype: :class:`~groupy.pagers.MessageList` | entailment |
def list_all_before(self, message_id, limit=None):
"""Return all group messages created before a message.
:param str message_id: the ID of a message
:param int limit: maximum number of messages per page
:return: group messages
:rtype: generator
"""
return self.li... | Return all group messages created before a message.
:param str message_id: the ID of a message
:param int limit: maximum number of messages per page
:return: group messages
:rtype: generator | entailment |
def list_all_after(self, message_id, limit=None):
"""Return all group messages created after a message.
:param str message_id: the ID of a message
:param int limit: maximum number of messages per page
:return: group messages
:rtype: generator
"""
return self.list... | Return all group messages created after a message.
:param str message_id: the ID of a message
:param int limit: maximum number of messages per page
:return: group messages
:rtype: generator | entailment |
def create(self, text=None, attachments=None, source_guid=None):
"""Create a new message in the group.
:param str text: the text of the message
:param attachments: a list of attachments
:type attachments: :class:`list`
:param str source_guid: a unique identifier for the message
... | Create a new message in the group.
:param str text: the text of the message
:param attachments: a list of attachments
:type attachments: :class:`list`
:param str source_guid: a unique identifier for the message
:return: the created message
:rtype: :class:`~groupy.api.mes... | entailment |
def list(self, before_id=None, since_id=None, **kwargs):
"""Return a page of direct messages.
The messages come in reversed order (newest first). Note you can only
provide _one_ of ``before_id``, ``since_id``.
:param str before_id: message ID for paging backwards
:param str sin... | Return a page of direct messages.
The messages come in reversed order (newest first). Note you can only
provide _one_ of ``before_id``, ``since_id``.
:param str before_id: message ID for paging backwards
:param str since_id: message ID for most recent messages since
:return: di... | entailment |
def list_all(self, before_id=None, since_id=None, **kwargs):
"""Return all direct messages.
The messages come in reversed order (newest first). Note you can only
provide _one_ of ``before_id``, ``since_id``.
:param str before_id: message ID for paging backwards
:param str since... | Return all direct messages.
The messages come in reversed order (newest first). Note you can only
provide _one_ of ``before_id``, ``since_id``.
:param str before_id: message ID for paging backwards
:param str since_id: message ID for most recent messages since
:return: direct m... | entailment |
def add(self, nickname, email=None, phone_number=None, user_id=None):
"""Add a user to the group.
You must provide either the email, phone number, or user_id that
uniquely identifies a user.
:param str nickname: new name for the user in the group
:param str email: email address... | Add a user to the group.
You must provide either the email, phone number, or user_id that
uniquely identifies a user.
:param str nickname: new name for the user in the group
:param str email: email address of the user
:param str phone_number: phone number of the user
:p... | entailment |
def add_multiple(self, *users):
"""Add multiple users to the group at once.
Each given user must be a dictionary containing a nickname and either
an email, phone number, or user_id.
:param args users: the users to add
:return: a membership request
:rtype: :class:`Member... | Add multiple users to the group at once.
Each given user must be a dictionary containing a nickname and either
an email, phone number, or user_id.
:param args users: the users to add
:return: a membership request
:rtype: :class:`MembershipRequest` | entailment |
def check(self, results_id):
"""Check for results of a membership request.
:param str results_id: the ID of a membership request
:return: successfully created memberships
:rtype: :class:`list`
:raises groupy.exceptions.ResultsNotReady: if the results are not ready
:raise... | Check for results of a membership request.
:param str results_id: the ID of a membership request
:return: successfully created memberships
:rtype: :class:`list`
:raises groupy.exceptions.ResultsNotReady: if the results are not ready
:raises groupy.exceptions.ResultsExpired: if t... | entailment |
def update(self, nickname=None, **kwargs):
"""Update your own membership.
Note that this fails on former groups.
:param str nickname: new nickname
:return: updated membership
:rtype: :class:`~groupy.api.memberships.Member`
"""
url = self.url + 'hips/update'
... | Update your own membership.
Note that this fails on former groups.
:param str nickname: new nickname
:return: updated membership
:rtype: :class:`~groupy.api.memberships.Member` | entailment |
def remove(self, membership_id):
"""Remove a member from the group.
:param str membership_id: the ID of a member in this group
:return: ``True`` if the member was successfully removed
:rtype: bool
"""
path = '{}/remove'.format(membership_id)
url = utils.urljoin(s... | Remove a member from the group.
:param str membership_id: the ID of a member in this group
:return: ``True`` if the member was successfully removed
:rtype: bool | entailment |
def post(self, text=None, attachments=None, source_guid=None):
"""Post a direct message to the user.
:param str text: the message content
:param attachments: message attachments
:param str source_guid: a client-side unique ID for the message
:return: the message sent
:rt... | Post a direct message to the user.
:param str text: the message content
:param attachments: message attachments
:param str source_guid: a client-side unique ID for the message
:return: the message sent
:rtype: :class:`~groupy.api.messages.DirectMessage` | entailment |
def add_to_group(self, group_id, nickname=None):
"""Add the member to another group.
If a nickname is not provided the member's current nickname is used.
:param str group_id: the group_id of a group
:param str nickname: a new nickname
:return: a membership request
:rtyp... | Add the member to another group.
If a nickname is not provided the member's current nickname is used.
:param str group_id: the group_id of a group
:param str nickname: a new nickname
:return: a membership request
:rtype: :class:`MembershipRequest` | entailment |
def check_if_ready(self):
"""Check for and fetch the results if ready."""
try:
results = self.manager.check(self.results_id)
except exceptions.ResultsNotReady as e:
self._is_ready = False
self._not_ready_exception = e
except exceptions.ResultsExpired a... | Check for and fetch the results if ready. | entailment |
def get_failed_requests(self, results):
"""Return the requests that failed.
:param results: the results of a membership request check
:type results: :class:`list`
:return: the failed requests
:rtype: generator
"""
data = {member['guid']: member for member in resu... | Return the requests that failed.
:param results: the results of a membership request check
:type results: :class:`list`
:return: the failed requests
:rtype: generator | entailment |
def get_new_members(self, results):
"""Return the newly added members.
:param results: the results of a membership request check
:type results: :class:`list`
:return: the successful requests, as :class:`~groupy.api.memberships.Members`
:rtype: generator
"""
for m... | Return the newly added members.
:param results: the results of a membership request check
:type results: :class:`list`
:return: the successful requests, as :class:`~groupy.api.memberships.Members`
:rtype: generator | entailment |
def is_ready(self, check=True):
"""Return ``True`` if the results are ready.
If you pass ``check=False``, no attempt is made to check again for
results.
:param bool check: whether to query for the results
:return: ``True`` if the results are ready
:rtype: bool
"... | Return ``True`` if the results are ready.
If you pass ``check=False``, no attempt is made to check again for
results.
:param bool check: whether to query for the results
:return: ``True`` if the results are ready
:rtype: bool | entailment |
def poll(self, timeout=30, interval=2):
"""Return the results when they become ready.
:param int timeout: the maximum time to wait for the results
:param float interval: the number of seconds between checks
:return: the membership request result
:rtype: :class:`~groupy.api.membe... | Return the results when they become ready.
:param int timeout: the maximum time to wait for the results
:param float interval: the number of seconds between checks
:return: the membership request result
:rtype: :class:`~groupy.api.memberships.MembershipResult.Results` | entailment |
def get(self):
"""Return the results now.
:return: the membership request results
:rtype: :class:`~groupy.api.memberships.MembershipResult.Results`
:raises groupy.exceptions.ResultsNotReady: if the results are not ready
:raises groupy.exceptions.ResultsExpired: if the results ha... | Return the results now.
:return: the membership request results
:rtype: :class:`~groupy.api.memberships.MembershipResult.Results`
:raises groupy.exceptions.ResultsNotReady: if the results are not ready
:raises groupy.exceptions.ResultsExpired: if the results have expired | entailment |
def list(self, page=1, per_page=10, omit=None):
"""List groups by page.
The API allows certain fields to be excluded from the results so that
very large groups can be fetched without exceeding the maximum
response size. At the time of this writing, only 'memberships' is
supporte... | List groups by page.
The API allows certain fields to be excluded from the results so that
very large groups can be fetched without exceeding the maximum
response size. At the time of this writing, only 'memberships' is
supported.
:param int page: page number
:param int... | entailment |
def list_all(self, per_page=10, omit=None):
"""List all groups.
Since the order of groups is determined by recent activity, this is the
recommended way to obtain a list of all groups. See
:func:`~groupy.api.groups.Groups.list` for details about ``omit``.
:param int per_page: nu... | List all groups.
Since the order of groups is determined by recent activity, this is the
recommended way to obtain a list of all groups. See
:func:`~groupy.api.groups.Groups.list` for details about ``omit``.
:param int per_page: number of groups per page
:param int omit: a comm... | entailment |
def list_former(self):
"""List all former groups.
:return: a list of groups
:rtype: :class:`list`
"""
url = utils.urljoin(self.url, 'former')
response = self.session.get(url)
return [Group(self, **group) for group in response.data] | List all former groups.
:return: a list of groups
:rtype: :class:`list` | entailment |
def get(self, id):
"""Get a single group by ID.
:param str id: a group ID
:return: a group
:rtype: :class:`~groupy.api.groups.Group`
"""
url = utils.urljoin(self.url, id)
response = self.session.get(url)
return Group(self, **response.data) | Get a single group by ID.
:param str id: a group ID
:return: a group
:rtype: :class:`~groupy.api.groups.Group` | entailment |
def create(self, name, description=None, image_url=None, share=None, **kwargs):
"""Create a new group.
Note that, although possible, there may be issues when not using an
image URL from GroupMe's image service.
:param str name: group name (140 characters maximum)
:param str des... | Create a new group.
Note that, although possible, there may be issues when not using an
image URL from GroupMe's image service.
:param str name: group name (140 characters maximum)
:param str description: short description (255 characters maximum)
:param str image_url: GroupMe ... | entailment |
def update(self, id, name=None, description=None, image_url=None,
office_mode=None, share=None, **kwargs):
"""Update the details of a group.
.. note::
There are significant bugs in this endpoint!
1. not providing ``name`` produces 400: "Topic can't be blank"
... | Update the details of a group.
.. note::
There are significant bugs in this endpoint!
1. not providing ``name`` produces 400: "Topic can't be blank"
2. not providing ``office_mode`` produces 500: "sql: Scan error on
column index 14: sql/driver: couldn't convert ... | entailment |
def destroy(self, id):
"""Destroy a group.
:param str id: a group ID
:return: ``True`` if successful
:rtype: bool
"""
path = '{}/destroy'.format(id)
url = utils.urljoin(self.url, path)
response = self.session.post(url)
return response.ok | Destroy a group.
:param str id: a group ID
:return: ``True`` if successful
:rtype: bool | entailment |
def join(self, group_id, share_token):
"""Join a group using a share token.
:param str group_id: the group_id of a group
:param str share_token: the share token
:return: the group
:rtype: :class:`~groupy.api.groups.Group`
"""
path = '{}/join/{}'.format(group_id, ... | Join a group using a share token.
:param str group_id: the group_id of a group
:param str share_token: the share token
:return: the group
:rtype: :class:`~groupy.api.groups.Group` | entailment |
def rejoin(self, group_id):
"""Rejoin a former group.
:param str group_id: the group_id of a group
:return: the group
:rtype: :class:`~groupy.api.groups.Group`
"""
url = utils.urljoin(self.url, 'join')
payload = {'group_id': group_id}
response = self.sess... | Rejoin a former group.
:param str group_id: the group_id of a group
:return: the group
:rtype: :class:`~groupy.api.groups.Group` | entailment |
def change_owners(self, group_id, owner_id):
"""Change the owner of a group.
.. note:: you must be the owner to change owners
:param str group_id: the group_id of a group
:param str owner_id: the ID of the new owner
:return: the result
:rtype: :class:`~groupy.api.groups... | Change the owner of a group.
.. note:: you must be the owner to change owners
:param str group_id: the group_id of a group
:param str owner_id: the ID of the new owner
:return: the result
:rtype: :class:`~groupy.api.groups.ChangeOwnersResult` | entailment |
def update(self, name=None, description=None, image_url=None,
office_mode=None, share=None, **kwargs):
"""Update the details of the group.
:param str name: group name (140 characters maximum)
:param str description: short description (255 characters maximum)
:param str im... | Update the details of the group.
:param str name: group name (140 characters maximum)
:param str description: short description (255 characters maximum)
:param str image_url: GroupMe image service URL
:param bool office_mode: (undocumented)
:param bool share: whether to generate... | entailment |
def refresh_from_server(self):
"""Refresh the group from the server in place."""
group = self.manager.get(id=self.id)
self.__init__(self.manager, **group.data) | Refresh the group from the server in place. | entailment |
def create_bot(self, name, avatar_url=None, callback_url=None, dm_notification=None,
**kwargs):
"""Create a new bot in a particular group.
:param str name: bot name
:param str avatar_url: the URL of an image to use as an avatar
:param str callback_url: a POST-back URL... | Create a new bot in a particular group.
:param str name: bot name
:param str avatar_url: the URL of an image to use as an avatar
:param str callback_url: a POST-back URL for each new message
:param bool dm_notification: whether to POST-back for direct messages?
:return: the new ... | entailment |
def get_membership(self):
"""Get your membership.
Note that your membership may not exist. For example, you do not have
a membership in a former group. Also, the group returned by the API
when rejoining a former group does not contain your membership. You
must call :func:`refres... | Get your membership.
Note that your membership may not exist. For example, you do not have
a membership in a former group. Also, the group returned by the API
when rejoining a former group does not contain your membership. You
must call :func:`refresh_from_server` to update the list of ... | entailment |
def update_membership(self, nickname=None, **kwargs):
"""Update your own membership.
Note that this fails on former groups.
:param str nickname: new nickname
:return: updated membership
:rtype: :class:`~groupy.api.members.Member`
"""
return self.memberships.upda... | Update your own membership.
Note that this fails on former groups.
:param str nickname: new nickname
:return: updated membership
:rtype: :class:`~groupy.api.members.Member` | entailment |
def urljoin(base, path=None):
"""Join a base url with a relative path."""
# /foo/bar + baz makes /foo/bar/baz instead of /foo/baz
if path is None:
url = base
else:
if not base.endswith('/'):
base += '/'
url = urllib.parse.urljoin(base, str(path))
return url | Join a base url with a relative path. | entailment |
def parse_share_url(share_url):
"""Return the group_id and share_token in a group's share url.
:param str share_url: the share url of a group
"""
*__, group_id, share_token = share_url.rstrip('/').split('/')
return group_id, share_token | Return the group_id and share_token in a group's share url.
:param str share_url: the share url of a group | entailment |
def get_rfc3339(when):
"""Return an RFC 3339 timestamp.
:param datetime.datetime when: a datetime in UTC
:return: RFC 3339 timestamp
:rtype: str
"""
microseconds = format(when.microsecond, '04d')[:4]
rfc3339 = '%Y-%m-%dT%H:%M:%S.{}Z'
return when.strftime(rfc3339.format(microseconds)) | Return an RFC 3339 timestamp.
:param datetime.datetime when: a datetime in UTC
:return: RFC 3339 timestamp
:rtype: str | entailment |
def make_filter(**tests):
"""Create a filter from keyword arguments."""
tests = [AttrTest(k, v) for k, v in tests.items()]
return Filter(tests) | Create a filter from keyword arguments. | entailment |
def find(self, objects):
"""Find exactly one match in the list of objects.
:param objects: objects to filter
:type objects: :class:`list`
:return: the one matching object
:raises groupy.exceptions.NoMatchesError: if no objects match
:raises groupy.exceptions.MultipleMatc... | Find exactly one match in the list of objects.
:param objects: objects to filter
:type objects: :class:`list`
:return: the one matching object
:raises groupy.exceptions.NoMatchesError: if no objects match
:raises groupy.exceptions.MultipleMatchesError: if multiple objects match | entailment |
def list(self):
"""Return a list of bots.
:return: all of your bots
:rtype: :class:`list`
"""
response = self.session.get(self.url)
return [Bot(self, **bot) for bot in response.data] | Return a list of bots.
:return: all of your bots
:rtype: :class:`list` | entailment |
def create(self, name, group_id, avatar_url=None, callback_url=None,
dm_notification=None, **kwargs):
"""Create a new bot in a particular group.
:param str name: bot name
:param str group_id: the group_id of a group
:param str avatar_url: the URL of an image to use as an ... | Create a new bot in a particular group.
:param str name: bot name
:param str group_id: the group_id of a group
:param str avatar_url: the URL of an image to use as an avatar
:param str callback_url: a POST-back URL for each new message
:param bool dm_notification: whether to POS... | entailment |
def post(self, bot_id, text, attachments=None):
"""Post a new message as a bot to its room.
:param str bot_id: the ID of the bot
:param str text: the text of the message
:param attachments: a list of attachments
:type attachments: :class:`list`
:return: ``True`` if succe... | Post a new message as a bot to its room.
:param str bot_id: the ID of the bot
:param str text: the text of the message
:param attachments: a list of attachments
:type attachments: :class:`list`
:return: ``True`` if successful
:rtype: bool | entailment |
def destroy(self, bot_id):
"""Destroy a bot.
:param str bot_id: the ID of the bot to destroy
:return: ``True`` if successful
:rtype: bool
"""
url = utils.urljoin(self.url, 'destroy')
payload = {'bot_id': bot_id}
response = self.session.post(url, json=payl... | Destroy a bot.
:param str bot_id: the ID of the bot to destroy
:return: ``True`` if successful
:rtype: bool | entailment |
def post(self, text, attachments=None):
"""Post a message as the bot.
:param str text: the text of the message
:param attachments: a list of attachments
:type attachments: :class:`list`
:return: ``True`` if successful
:rtype: bool
"""
return self.manager.... | Post a message as the bot.
:param str text: the text of the message
:param attachments: a list of attachments
:type attachments: :class:`list`
:return: ``True`` if successful
:rtype: bool | entailment |
def flatten_until(is_leaf, xs):
"""
Flatten a nested sequence. A sequence could be a nested list of lists
or tuples or a combination of both
:param is_leaf: Predicate. Predicate to determine whether an item
in the iterable `xs` is a leaf node or not.
:param xs: Iterable. Neste... | Flatten a nested sequence. A sequence could be a nested list of lists
or tuples or a combination of both
:param is_leaf: Predicate. Predicate to determine whether an item
in the iterable `xs` is a leaf node or not.
:param xs: Iterable. Nested lists or tuples
:return: list. | entailment |
def flip(f):
"""
Calls the function f by flipping the first two positional
arguments
"""
def wrapped(*args, **kwargs):
return f(*flip_first_two(args), **kwargs)
f_spec = make_func_curry_spec(f)
return curry_by_spec(f_spec, wrapped) | Calls the function f by flipping the first two positional
arguments | entailment |
def cachier(stale_after=None, next_time=False, pickle_reload=True,
mongetter=None):
"""A persistent, stale-free memoization decorator.
The positional and keyword arguments to the wrapped function must be
hashable (i.e. Python's immutable built-in objects, not mutable
containers). Also, noti... | A persistent, stale-free memoization decorator.
The positional and keyword arguments to the wrapped function must be
hashable (i.e. Python's immutable built-in objects, not mutable
containers). Also, notice that since objects which are instances of
user-defined classes are hashable but all compare uneq... | entailment |
def defineID(defid):
"""Search for UD's definition ID and return list of UrbanDefinition objects.
Keyword arguments:
defid -- definition ID to search for (int or str)
"""
json = _get_urban_json(UD_DEFID_URL + urlquote(str(defid)))
return _parse_urban_json(json) | Search for UD's definition ID and return list of UrbanDefinition objects.
Keyword arguments:
defid -- definition ID to search for (int or str) | entailment |
def has_external_dependency(name):
'Check that a non-Python dependency is installed.'
for directory in os.environ['PATH'].split(':'):
if os.path.exists(os.path.join(directory, name)):
return True
return False | Check that a non-Python dependency is installed. | entailment |
def with_vtk(plot=True):
""" Tests VTK interface and mesh repair of Stanford Bunny Mesh """
mesh = vtki.PolyData(bunny_scan)
meshfix = pymeshfix.MeshFix(mesh)
if plot:
print('Plotting input mesh')
meshfix.plot()
meshfix.repair()
if plot:
print('Plotting repaired mesh')
... | Tests VTK interface and mesh repair of Stanford Bunny Mesh | entailment |
def load_arrays(self, v, f):
"""Loads triangular mesh from vertex and face numpy arrays.
Both vertex and face arrays should be 2D arrays with each
vertex containing XYZ data and each face containing three
points.
Parameters
----------
v : np.ndarray
... | Loads triangular mesh from vertex and face numpy arrays.
Both vertex and face arrays should be 2D arrays with each
vertex containing XYZ data and each face containing three
points.
Parameters
----------
v : np.ndarray
n x 3 vertex array.
f : np.ndar... | entailment |
def mesh(self):
"""Return the surface mesh"""
triangles = np.empty((self.f.shape[0], 4))
triangles[:, -3:] = self.f
triangles[:, 0] = 3
return vtki.PolyData(self.v, triangles, deep=False) | Return the surface mesh | entailment |
def plot(self, show_holes=True):
"""
Plot the mesh.
Parameters
----------
show_holes : bool, optional
Shows boundaries. Default True
"""
if show_holes:
edges = self.mesh.extract_edges(boundary_edges=True,
... | Plot the mesh.
Parameters
----------
show_holes : bool, optional
Shows boundaries. Default True | entailment |
def repair(self, verbose=False, joincomp=False,
remove_smallest_components=True):
"""Performs mesh repair using MeshFix's default repair
process.
Parameters
----------
verbose : bool, optional
Enables or disables debug printing. Disabled by default.
... | Performs mesh repair using MeshFix's default repair
process.
Parameters
----------
verbose : bool, optional
Enables or disables debug printing. Disabled by default.
joincomp : bool, optional
Attempts to join nearby open components.
remove_small... | entailment |
def write(self, filename, binary=True):
"""Writes a surface mesh to disk.
Written file may be an ASCII or binary ply, stl, or vtk mesh
file.
Parameters
----------
filename : str
Filename of mesh to be written. Filetype is inferred from
the exten... | Writes a surface mesh to disk.
Written file may be an ASCII or binary ply, stl, or vtk mesh
file.
Parameters
----------
filename : str
Filename of mesh to be written. Filetype is inferred from
the extension of the filename unless overridden with
... | entailment |
def scrape(url, params=None, user_agent=None):
'''
Scrape a URL optionally with parameters.
This is effectively a wrapper around urllib2.urlopen.
'''
headers = {}
if user_agent:
headers['User-Agent'] = user_agent
data = params and six.moves.urllib.parse.urlencode(params) or None
... | Scrape a URL optionally with parameters.
This is effectively a wrapper around urllib2.urlopen. | entailment |
def pdftoxml(pdfdata, options=""):
"""converts pdf file to xml file"""
pdffout = tempfile.NamedTemporaryFile(suffix='.pdf')
pdffout.write(pdfdata)
pdffout.flush()
xmlin = tempfile.NamedTemporaryFile(mode='r', suffix='.xml')
tmpxml = xmlin.name # "temph.xml"
cmd = 'pdftohtml -xml -nodrm -zo... | converts pdf file to xml file | entailment |
def execute(query, data=None):
"""
Execute an arbitrary SQL query given by query, returning any
results as a list of OrderedDicts. A list of values can be supplied as an,
additional argument, which will be substituted into question marks in the
query.
"""
connection = _State.connection()
... | Execute an arbitrary SQL query given by query, returning any
results as a list of OrderedDicts. A list of values can be supplied as an,
additional argument, which will be substituted into question marks in the
query. | entailment |
def select(query, data=None):
"""
Perform a sql select statement with the given query (without 'select') and
return any results as a list of OrderedDicts.
"""
connection = _State.connection()
_State.new_transaction()
if data is None:
data = []
result = connection.execute('select... | Perform a sql select statement with the given query (without 'select') and
return any results as a list of OrderedDicts. | entailment |
def save(unique_keys, data, table_name='swdata'):
"""
Save the given data to the table specified by `table_name`
(which defaults to 'swdata'). The data must be a mapping
or an iterable of mappings. Unique keys is a list of keys that exist
for all rows and for which a unique index will be created.
... | Save the given data to the table specified by `table_name`
(which defaults to 'swdata'). The data must be a mapping
or an iterable of mappings. Unique keys is a list of keys that exist
for all rows and for which a unique index will be created. | entailment |
def _set_table(table_name):
"""
Specify the table to work on.
"""
_State.connection()
_State.reflect_metadata()
_State.table = sqlalchemy.Table(table_name, _State.metadata,
extend_existing=True)
if list(_State.table.columns.keys()) == []:
_State.t... | Specify the table to work on. | entailment |
def show_tables():
"""
Return the names of the tables currently in the database.
"""
_State.connection()
_State.reflect_metadata()
metadata = _State.metadata
response = select('name, sql from sqlite_master where type="table"')
return {row['name']: row['sql'] for row in response} | Return the names of the tables currently in the database. | entailment |
def save_var(name, value):
"""
Save a variable to the table specified by _State.vars_table_name. Key is
the name of the variable, and value is the value.
"""
connection = _State.connection()
_State.reflect_metadata()
vars_table = sqlalchemy.Table(
_State.vars_table_name, _State.meta... | Save a variable to the table specified by _State.vars_table_name. Key is
the name of the variable, and value is the value. | entailment |
def get_var(name, default=None):
"""
Returns the variable with the provided key from the
table specified by _State.vars_table_name.
"""
alchemytypes = {"text": lambda x: x.decode('utf-8'),
"big_integer": lambda x: int(x),
"date": lambda x: x.decode('utf-8'),
... | Returns the variable with the provided key from the
table specified by _State.vars_table_name. | entailment |
def create_index(column_names, unique=False):
"""
Create a new index of the columns in column_names, where column_names is
a list of strings. If unique is True, it will be a
unique index.
"""
connection = _State.connection()
_State.reflect_metadata()
table_name = _State.table.name
t... | Create a new index of the columns in column_names, where column_names is
a list of strings. If unique is True, it will be a
unique index. | entailment |
def fit_row(connection, row, unique_keys):
"""
Takes a row and checks to make sure it fits in the columns of the
current table. If it does not fit, adds the required columns.
"""
new_columns = []
for column_name, column_value in list(row.items()):
new_column = sqlalchemy.Column(column_na... | Takes a row and checks to make sure it fits in the columns of the
current table. If it does not fit, adds the required columns. | entailment |
def create_table(unique_keys):
"""
Save the table currently waiting to be created.
"""
_State.new_transaction()
_State.table.create(bind=_State.engine, checkfirst=True)
if unique_keys != []:
create_index(unique_keys, unique=True)
_State.table_pending = False
_State.reflect_metada... | Save the table currently waiting to be created. | entailment |
def add_column(connection, column):
"""
Add a column to the current table.
"""
stmt = alembic.ddl.base.AddColumn(_State.table.name, column)
connection.execute(stmt)
_State.reflect_metadata() | Add a column to the current table. | entailment |
def drop():
"""
Drop the current table if it exists
"""
# Ensure the connection is up
_State.connection()
_State.table.drop(checkfirst=True)
_State.metadata.remove(_State.table)
_State.table = None
_State.new_transaction() | Drop the current table if it exists | entailment |
def attach_attrs_table(key, value, fmt, meta):
"""Extracts attributes and attaches them to element."""
# We can't use attach_attrs_factory() because Table is a block-level element
if key in ['Table']:
assert len(value) == 5
caption = value[0] # caption, align, x, head, body
# Set ... | Extracts attributes and attaches them to element. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.