sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def _check_filter_specific_tag(self, specific_tag: list):
"""Check if specific_tag parameter is valid.
:param list specific_tag: list of specific tag to check
"""
if isinstance(specific_tag, list):
if len(specific_tag) > 0:
specific_tag = ",".join(specific_ta... | Check if specific_tag parameter is valid.
:param list specific_tag: list of specific tag to check | entailment |
def _check_filter_includes(self, includes: list, resource: str = "metadata"):
"""Check if specific_resources parameter is valid.
:param list includes: sub resources to check
:param str resource: resource type to check sub resources.
Must be one of: metadata | keyword.
"""
... | Check if specific_resources parameter is valid.
:param list includes: sub resources to check
:param str resource: resource type to check sub resources.
Must be one of: metadata | keyword. | entailment |
def _check_subresource(self, subresource: str):
"""Check if specific_resources parameter is valid.
:param str resource: subresource to check.
"""
warnings.warn(
"subresource in URL is deprecated." " Use _include mecanism instead.",
DeprecationWarning,
)
... | Check if specific_resources parameter is valid.
:param str resource: subresource to check. | entailment |
def _convert_md_type(self, type_to_convert: str):
"""Metadata types are not consistent in Isogeo API. A vector dataset is
defined as vector-dataset in query filter but as vectorDataset in
resource (metadata) details.
see: https://github.com/isogeo/isogeo-api-py-minsdk/issues/29
... | Metadata types are not consistent in Isogeo API. A vector dataset is
defined as vector-dataset in query filter but as vectorDataset in
resource (metadata) details.
see: https://github.com/isogeo/isogeo-api-py-minsdk/issues/29 | entailment |
def version_cli(ctx, porcelain):
# type: (click.Context, bool) -> None
""" Show project version. Has sub commands.
For this command to work you must specify where the project version is
stored. You can do that with version_file conf variable. peltak supports
multiple ways to store the project versi... | Show project version. Has sub commands.
For this command to work you must specify where the project version is
stored. You can do that with version_file conf variable. peltak supports
multiple ways to store the project version. Right now you can store it in a
python file using built-in __version__ vari... | entailment |
def bump_version(component='patch', exact=None):
# type: (str, str) -> None
""" Bump current project version without committing anything.
No tags are created either.
Examples:
\b
$ peltak version bump patch # Bump patch version component
$ peltak version bump minor... | Bump current project version without committing anything.
No tags are created either.
Examples:
\b
$ peltak version bump patch # Bump patch version component
$ peltak version bump minor # Bump minor version component
$ peltak version bump major ... | entailment |
def get_logfile_name(tag):
"""
Creates a name for a log file that is meant to be used in a call to
``logging.FileHandler``. The log file name will incldue the path to the log directory given
by the `p.LOG_DIR` constant. The format of the file name is: 'log_$HOST_$TAG.txt', where
... | Creates a name for a log file that is meant to be used in a call to
``logging.FileHandler``. The log file name will incldue the path to the log directory given
by the `p.LOG_DIR` constant. The format of the file name is: 'log_$HOST_$TAG.txt', where
$HOST is the hostname part of the URL given by... | entailment |
def _get(self, rec_id=None, upstream=None):
"""
Fetches a record by the record's ID or upstream_identifier.
Raises:
`pulsarpy.models.RecordNotFound`: A record could not be found.
"""
if rec_id:
self.record_url = self.__class__.get_record_url(rec_id)
... | Fetches a record by the record's ID or upstream_identifier.
Raises:
`pulsarpy.models.RecordNotFound`: A record could not be found. | entailment |
def replace_name_with_id(cls, name):
"""
Used to replace a foreign key reference using a name with an ID. Works by searching the
record in Pulsar and expects to find exactly one hit. First, will check if the foreign key
reference is an integer value and if so, returns that as it is presu... | Used to replace a foreign key reference using a name with an ID. Works by searching the
record in Pulsar and expects to find exactly one hit. First, will check if the foreign key
reference is an integer value and if so, returns that as it is presumed to be the foreign key.
Raises:
`... | entailment |
def add_model_name_to_payload(cls, payload):
"""
Checks whether the model name in question is in the payload. If not, the entire payload
is set as a value of a key by the name of the model. This method is useful when some
server-side Rails API calls expect the parameters to include the ... | Checks whether the model name in question is in the payload. If not, the entire payload
is set as a value of a key by the name of the model. This method is useful when some
server-side Rails API calls expect the parameters to include the parameterized model name.
For example, server-side endpoi... | entailment |
def delete(self):
"""Deletes the record.
"""
res = requests.delete(url=self.record_url, headers=HEADERS, verify=False)
#self.write_response_html_to_file(res,"bob_delete.html")
if res.status_code == 204:
#No content. Can't render json:
return {}
ret... | Deletes the record. | entailment |
def find_by(cls, payload, require=False):
"""
Searches the model in question by AND joining the query parameters.
Implements a Railsy way of looking for a record using a method by the same name and passing
in the query as a dict. as well. Only the first hit is returned, and there is no ... | Searches the model in question by AND joining the query parameters.
Implements a Railsy way of looking for a record using a method by the same name and passing
in the query as a dict. as well. Only the first hit is returned, and there is no particular
ordering specified in the server-side API m... | entailment |
def find_by_or(cls, payload):
"""
Searches the model in question by OR joining the query parameters.
Implements a Railsy way of looking for a record using a method by the same name and passing
in the query as a string (for the OR operator joining to be specified).
Only the firs... | Searches the model in question by OR joining the query parameters.
Implements a Railsy way of looking for a record using a method by the same name and passing
in the query as a string (for the OR operator joining to be specified).
Only the first hit is returned, and there is not particular ord... | entailment |
def index(cls):
"""Fetches all records.
Returns:
`dict`. The JSON formatted response.
Raises:
`requests.exceptions.HTTPError`: The status code is not ok.
"""
res = requests.get(cls.URL, headers=HEADERS, verify=False)
res.raise_for_status()
... | Fetches all records.
Returns:
`dict`. The JSON formatted response.
Raises:
`requests.exceptions.HTTPError`: The status code is not ok. | entailment |
def patch(self, payload, append_to_arrays=True):
"""
Patches current record and udpates the current instance's 'attrs'
attribute to reflect the new changes.
Args:
payload - hash. This will be JSON-formatted prior to sending the request.
Returns:
`dict`. ... | Patches current record and udpates the current instance's 'attrs'
attribute to reflect the new changes.
Args:
payload - hash. This will be JSON-formatted prior to sending the request.
Returns:
`dict`. The JSON formatted response.
Raises:
`requests.e... | entailment |
def set_id_in_fkeys(cls, payload):
"""
Looks for any keys in the payload that end with either _id or _ids, signaling a foreign
key field. For each foreign key field, checks whether the value is using the name of the
record or the actual primary ID of the record (which may include the mod... | Looks for any keys in the payload that end with either _id or _ids, signaling a foreign
key field. For each foreign key field, checks whether the value is using the name of the
record or the actual primary ID of the record (which may include the model abbreviation, i.e.
B-1). If the former case,... | entailment |
def post(cls, payload):
"""Posts the data to the specified record.
Args:
payload: `dict`. This will be JSON-formatted prior to sending the request.
Returns:
`dict`. The JSON formatted response.
Raises:
`Requests.exceptions.HTTPError`: The status cod... | Posts the data to the specified record.
Args:
payload: `dict`. This will be JSON-formatted prior to sending the request.
Returns:
`dict`. The JSON formatted response.
Raises:
`Requests.exceptions.HTTPError`: The status code is not ok.
`RecordNot... | entailment |
def log_error(cls, msg):
"""
Logs the provided error message to both the error logger and the debug logger logging
instances.
Args:
msg: `str`. The error message to log.
"""
cls.error_logger.error(msg)
cls.debug_logger.debug(msg) | Logs the provided error message to both the error logger and the debug logger logging
instances.
Args:
msg: `str`. The error message to log. | entailment |
def write_response_html_to_file(response,filename):
"""
An aid in troubleshooting internal application errors, i.e. <Response [500]>, to be mainly
beneficial when developing the server-side API. This method will write the response HTML
for viewing the error details in the browesr.
... | An aid in troubleshooting internal application errors, i.e. <Response [500]>, to be mainly
beneficial when developing the server-side API. This method will write the response HTML
for viewing the error details in the browesr.
Args:
response: `requests.models.Response` instance.
... | entailment |
def parent_ids(self):
"""
Returns an array of parent Biosample IDs. If the current Biosample has a part_of relationship,
the Biosampled referenced there will be returned. Otherwise, if the current Biosample was
generated from a pool of Biosamples (pooled_from_biosample_ids), then those w... | Returns an array of parent Biosample IDs. If the current Biosample has a part_of relationship,
the Biosampled referenced there will be returned. Otherwise, if the current Biosample was
generated from a pool of Biosamples (pooled_from_biosample_ids), then those will be returned.
Otherwise, the re... | entailment |
def find_first_wt_parent(self, with_ip=False):
"""
Recursively looks at the part_of parent ancestry line (ignoring pooled_from parents) and returns
a parent Biosample ID if its wild_type attribute is True.
Args:
with_ip: `bool`. True means to restrict the search to the firs... | Recursively looks at the part_of parent ancestry line (ignoring pooled_from parents) and returns
a parent Biosample ID if its wild_type attribute is True.
Args:
with_ip: `bool`. True means to restrict the search to the first parental Wild Type that
also has an Immunoblot l... | entailment |
def upload(cls, path, document_type, is_protocol, description=""):
"""
Args:
path: `str`. The path to the document to upload.
document_type: `str`. DocumentType identified by the value of its name attribute.
is_protocol: `bool`.
description: `str`.
... | Args:
path: `str`. The path to the document to upload.
document_type: `str`. DocumentType identified by the value of its name attribute.
is_protocol: `bool`.
description: `str`. | entailment |
def post(cls, payload):
"""
A wrapper over Model.post() that handles the case where a Library has a PairedBarcode
and the user may have supplied the PairedBarcode in the form of index1-index2, i.e.
GATTTCCA-GGCGTCGA. This isn't the PairedBarcode's record name or a record ID, thus
... | A wrapper over Model.post() that handles the case where a Library has a PairedBarcode
and the user may have supplied the PairedBarcode in the form of index1-index2, i.e.
GATTTCCA-GGCGTCGA. This isn't the PairedBarcode's record name or a record ID, thus
Model.post() won't be able to figure out ... | entailment |
def get_library_barcode_sequence_hash(self, inverse=False):
"""
Calls the SequencingRequest's get_library_barcode_sequence_hash server-side endpoint to
create a hash of the form {LibraryID -> barcode_sequence} for all Libraries on the
SequencingRequest.
Args:
inver... | Calls the SequencingRequest's get_library_barcode_sequence_hash server-side endpoint to
create a hash of the form {LibraryID -> barcode_sequence} for all Libraries on the
SequencingRequest.
Args:
inverse: `bool`. True means to inverse the key and value pairs such that the barcode
... | entailment |
def library_sequencing_results(self):
"""
Generates a dict. where each key is a Library ID on the SequencingRequest and each value
is the associated SequencingResult. Libraries that aren't yet with a SequencingResult are
not inlcuded in the dict.
"""
sres_ids = self.seque... | Generates a dict. where each key is a Library ID on the SequencingRequest and each value
is the associated SequencingResult. Libraries that aren't yet with a SequencingResult are
not inlcuded in the dict. | entailment |
def unarchive_user(self, user_id):
"""Unarchives the user with the specified user ID.
Args:
user_id: `int`. The ID of the user to unarchive.
Returns:
`NoneType`: None.
"""
url = self.record_url + "/unarchive"
res = requests.patch(url=url, json={"... | Unarchives the user with the specified user ID.
Args:
user_id: `int`. The ID of the user to unarchive.
Returns:
`NoneType`: None. | entailment |
def remove_api_key(self):
"""
Removes the user's existing API key, if present, and sets the current instance's 'api_key'
attribute to the empty string.
Returns:
`NoneType`: None.
"""
url = self.record_url + "/remove_api_key"
res = requests.patch(url=u... | Removes the user's existing API key, if present, and sets the current instance's 'api_key'
attribute to the empty string.
Returns:
`NoneType`: None. | entailment |
def generate_synthObs(self, bases_wave, bases_flux, basesCoeff, Av_star, z_star, sigma_star, resample_range = None, resample_int = 1):
'''basesWave: Bases wavelength must be at rest'''
nbases = basesCoeff.shape[0]
bases_wave_resam = arange(int(resample_range[0]),... | basesWave: Bases wavelength must be at rest | entailment |
def _process(self, resource=None, data={}):
"""Processes the current transaction
Sends an HTTP request to the PAYDUNYA API server
"""
# use object's data if no data is passed
_data = data or self._data
rsc_url = self.get_rsc_endpoint(resource)
if _data:
... | Processes the current transaction
Sends an HTTP request to the PAYDUNYA API server | entailment |
def add_header(self, header):
"""Add a custom HTTP header to the client's request headers"""
if type(header) is dict:
self._headers.update(header)
else:
raise ValueError(
"Dictionary expected, got '%s' instead" % type(header)
) | Add a custom HTTP header to the client's request headers | entailment |
def changelog_cli(ctx):
# type: () -> None
""" Generate changelog from commit messages. """
if ctx.invoked_subcommand:
return
from peltak.core import shell
from . import logic
shell.cprint(logic.changelog()) | Generate changelog from commit messages. | entailment |
def convert_to_argument(self):
'''
Convert the Argument object to a tuple use in :meth:`~argparse.ArgumentParser.add_argument` calls on the parser
'''
field_list = [
"action", "nargs", "const", "default", "type",
"choices", "required", "help", "metavar", "des... | Convert the Argument object to a tuple use in :meth:`~argparse.ArgumentParser.add_argument` calls on the parser | entailment |
def get_default_name(self):
'''
Return the default generated name to store value on the parser for this option.
eg. An option *['-s', '--use-ssl']* will generate the *use_ssl* name
Returns:
str: the default name of the option
'''
long_names = [name for name ... | Return the default generated name to store value on the parser for this option.
eg. An option *['-s', '--use-ssl']* will generate the *use_ssl* name
Returns:
str: the default name of the option | entailment |
def get_filename(self, base_dir=None, modality=None):
"""Construct filename based on the attributes.
Parameters
----------
base_dir : Path
path of the root directory. If specified, the return value is a Path,
with base_dir / sub-XXX / (ses-XXX /) modality / filen... | Construct filename based on the attributes.
Parameters
----------
base_dir : Path
path of the root directory. If specified, the return value is a Path,
with base_dir / sub-XXX / (ses-XXX /) modality / filename
otherwise the return value is a string.
m... | entailment |
def get(self, filter_lambda=None, map_lambda=None):
"""Select elements of the TSV, using python filter and map.
Parameters
----------
filter_lambda : function
function to filter the tsv rows (the function needs to return True/False)
map_lambda : function
... | Select elements of the TSV, using python filter and map.
Parameters
----------
filter_lambda : function
function to filter the tsv rows (the function needs to return True/False)
map_lambda : function
function to select the tsv columns
Returns
---... | entailment |
def connect(self, client_id: str = None, client_secret: str = None) -> dict:
"""Authenticate application and get token bearer.
Isogeo API uses oAuth 2.0 protocol (https://tools.ietf.org/html/rfc6749)
see: http://help.isogeo.com/api/fr/authentication/groupsapps.html
:param str client_id... | Authenticate application and get token bearer.
Isogeo API uses oAuth 2.0 protocol (https://tools.ietf.org/html/rfc6749)
see: http://help.isogeo.com/api/fr/authentication/groupsapps.html
:param str client_id: application oAuth2 identifier
:param str client_secret: application oAuth2 sec... | entailment |
def _check_bearer_validity(decorated_func):
"""Check API Bearer token validity.
Isogeo ID delivers authentication bearers which are valid during
a certain time. So this decorator checks the validity of the token
comparing with actual datetime (UTC) and renews it if necessary.
Se... | Check API Bearer token validity.
Isogeo ID delivers authentication bearers which are valid during
a certain time. So this decorator checks the validity of the token
comparing with actual datetime (UTC) and renews it if necessary.
See: http://tools.ietf.org/html/rfc6750#section-2
... | entailment |
def search(
self,
token: dict = None,
query: str = "",
bbox: list = None,
poly: str = None,
georel: str = None,
order_by: str = "_created",
order_dir: str = "desc",
page_size: int = 100,
offset: int = 0,
share: str = None,
s... | Search within the resources shared to the application.
It's the main method to use.
:param str token: API auth token - DEPRECATED: token is now automatically included
:param str query: search terms and semantic filters. Equivalent of
**q** parameter in Isogeo API. It could be a simple... | entailment |
def resource(
self,
token: dict = None,
id_resource: str = None,
subresource=None,
include: list = [],
prot: str = "https",
) -> dict:
"""Get complete or partial metadata about one specific resource.
:param str token: API auth token
:param str... | Get complete or partial metadata about one specific resource.
:param str token: API auth token
:param str id_resource: metadata UUID to get
:param list include: subresources that should be included.
Must be a list of strings. Available values: 'isogeo.SUBRESOURCES'
:param str p... | entailment |
def shares(self, token: dict = None, prot: str = "https") -> dict:
"""Get information about shares which feed the application.
:param str token: API auth token
:param str prot: https [DEFAULT] or http
(use it only for dev and tracking needs).
"""
# passing auth paramete... | Get information about shares which feed the application.
:param str token: API auth token
:param str prot: https [DEFAULT] or http
(use it only for dev and tracking needs). | entailment |
def share(
self,
share_id: str,
token: dict = None,
augment: bool = False,
prot: str = "https",
) -> dict:
"""Get information about a specific share and its applications.
:param str token: API auth token
:param str share_id: share UUID
:param ... | Get information about a specific share and its applications.
:param str token: API auth token
:param str share_id: share UUID
:param bool augment: option to improve API response by adding
some tags on the fly.
:param str prot: https [DEFAULT] or http
(use it only for d... | entailment |
def licenses(
self, token: dict = None, owner_id: str = None, prot: str = "https"
) -> dict:
"""Get information about licenses owned by a specific workgroup.
:param str token: API auth token
:param str owner_id: workgroup UUID
:param str prot: https [DEFAULT] or http
... | Get information about licenses owned by a specific workgroup.
:param str token: API auth token
:param str owner_id: workgroup UUID
:param str prot: https [DEFAULT] or http
(use it only for dev and tracking needs). | entailment |
def license(self, license_id: str, token: dict = None, prot: str = "https") -> dict:
"""Get details about a specific license.
:param str token: API auth token
:param str license_id: license UUID
:param str prot: https [DEFAULT] or http
(use it only for dev and tracking needs).
... | Get details about a specific license.
:param str token: API auth token
:param str license_id: license UUID
:param str prot: https [DEFAULT] or http
(use it only for dev and tracking needs). | entailment |
def thesauri(self, token: dict = None, prot: str = "https") -> dict:
"""Get list of available thesauri.
:param str token: API auth token
:param str prot: https [DEFAULT] or http
(use it only for dev and tracking needs).
"""
# passing auth parameter
thez_url = "{... | Get list of available thesauri.
:param str token: API auth token
:param str prot: https [DEFAULT] or http
(use it only for dev and tracking needs). | entailment |
def thesaurus(
self,
token: dict = None,
thez_id: str = "1616597fbc4348c8b11ef9d59cf594c8",
prot: str = "https",
) -> dict:
"""Get a thesaurus.
:param str token: API auth token
:param str thez_id: thesaurus UUID
:param str prot: https [DEFAULT] or htt... | Get a thesaurus.
:param str token: API auth token
:param str thez_id: thesaurus UUID
:param str prot: https [DEFAULT] or http
(use it only for dev and tracking needs). | entailment |
def keywords(
self,
token: dict = None,
thez_id: str = "1616597fbc4348c8b11ef9d59cf594c8",
query: str = "",
offset: int = 0,
order_by: str = "text",
order_dir: str = "desc",
page_size: int = 20,
specific_md: list = [],
specific_tag: list = ... | Search for keywords within a specific thesaurus.
:param str token: API auth token
:param str thez_id: thesaurus UUID
:param str query: search terms
:param int offset: pagination start
:param str order_by: sort criteria. Available values :
- count.group,
... | entailment |
def dl_hosted(
self,
token: dict = None,
resource_link: dict = None,
encode_clean: bool = 1,
proxy_url: str = None,
prot: str = "https",
) -> tuple:
"""Download hosted resource.
:param str token: API auth token
:param dict resource_link: link ... | Download hosted resource.
:param str token: API auth token
:param dict resource_link: link dictionary
:param bool encode_clean: option to ensure a clean filename and avoid OS errors
:param str proxy_url: proxy to use to download
:param str prot: https [DEFAULT] or http
... | entailment |
def xml19139(
self,
token: dict = None,
id_resource: str = None,
proxy_url=None,
prot: str = "https",
):
"""Get resource exported into XML ISO 19139.
:param str token: API auth token
:param str id_resource: metadata UUID to export
:param str p... | Get resource exported into XML ISO 19139.
:param str token: API auth token
:param str id_resource: metadata UUID to export
:param str proxy_url: proxy to use to download
:param str prot: https [DEFAULT] or http
(use it only for dev and tracking needs). | entailment |
def add_tags_shares(self, tags: dict = dict()):
"""Add shares list to the tags attributes in search results.
:param dict tags: tags dictionary from a search request
"""
# check if shares_id have already been retrieved or not
if not hasattr(self, "shares_id"):
shares ... | Add shares list to the tags attributes in search results.
:param dict tags: tags dictionary from a search request | entailment |
def get_app_properties(self, token: dict = None, prot: str = "https"):
"""Get information about the application declared on Isogeo.
:param str token: API auth token
:param str prot: https [DEFAULT] or http
(use it only for dev and tracking needs).
"""
# check if app pro... | Get information about the application declared on Isogeo.
:param str token: API auth token
:param str prot: https [DEFAULT] or http
(use it only for dev and tracking needs). | entailment |
def get_directives(self, token: dict = None, prot: str = "https") -> dict:
"""Get environment directives which represent INSPIRE limitations.
:param str token: API auth token
:param str prot: https [DEFAULT] or http
(use it only for dev and tracking needs).
"""
# search... | Get environment directives which represent INSPIRE limitations.
:param str token: API auth token
:param str prot: https [DEFAULT] or http
(use it only for dev and tracking needs). | entailment |
def get_coordinate_systems(
self, token: dict = None, srs_code: str = None, prot: str = "https"
) -> dict:
"""Get available coordinate systems in Isogeo API.
:param str token: API auth token
:param str srs_code: code of a specific coordinate system
:param str prot: https [DE... | Get available coordinate systems in Isogeo API.
:param str token: API auth token
:param str srs_code: code of a specific coordinate system
:param str prot: https [DEFAULT] or http
(use it only for dev and tracking needs). | entailment |
def get_formats(
self, token: dict = None, format_code: str = None, prot: str = "https"
) -> dict:
"""Get formats.
:param str token: API auth token
:param str format_code: code of a specific format
:param str prot: https [DEFAULT] or http
(use it only for dev and tr... | Get formats.
:param str token: API auth token
:param str format_code: code of a specific format
:param str prot: https [DEFAULT] or http
(use it only for dev and tracking needs). | entailment |
def parse_bool(v, default=None, exceptions: bool=True) -> bool:
"""
Parses boolean value
:param v: Input string
:param default: Default value if exceptions=False
:param exceptions: Raise exception on error or not
:return: bool
"""
if isinstance(v, bool):
return v
s = str(v).l... | Parses boolean value
:param v: Input string
:param default: Default value if exceptions=False
:param exceptions: Raise exception on error or not
:return: bool | entailment |
def parse_datetime(v, default=None, tz=None, exceptions: bool=True) -> datetime:
"""
Parses datetime
:param v: Input string
:param default: Default value if exceptions=False
:param tz: Default pytz timezone or None if utc
:param exceptions: Raise exception on error or not
:return: datetime
... | Parses datetime
:param v: Input string
:param default: Default value if exceptions=False
:param tz: Default pytz timezone or None if utc
:param exceptions: Raise exception on error or not
:return: datetime | entailment |
def convert_boolean(string_value):
"""Converts a string to a boolean (see CONVERTERS).
There is a converter function for each column type.
Boolean strings are independent of case. Values interpreted as True
are: "yes", "true", "on", "1". values interpreted as False are
"no", "false", "off", "0". An... | Converts a string to a boolean (see CONVERTERS).
There is a converter function for each column type.
Boolean strings are independent of case. Values interpreted as True
are: "yes", "true", "on", "1". values interpreted as False are
"no", "false", "off", "0". Any other value will result in a ValueError.... | entailment |
def _handle_hdr(self, hdr):
"""Given the file header line (or one provided when the object
is instantiated) this method populates the ``self._converters`` array,
a list of type converters indexed by the column name.
:param hdr: The header line.
:raises: ContentError for any for... | Given the file header line (or one provided when the object
is instantiated) this method populates the ``self._converters`` array,
a list of type converters indexed by the column name.
:param hdr: The header line.
:raises: ContentError for any formatting problems
:raises: Unkno... | entailment |
def search_datasets(
self,
license=None,
format=None,
query=None,
featured=None,
owner=None,
organization=None,
badge=None,
reuses=None,
page_size=20,
x_fields=None,
):
"""Search datasets within uData portal."""
... | Search datasets within uData portal. | entailment |
def get_filters_values(self):
"""Get different filters values as dicts."""
# DATASETS --
# badges
self._DST_BADGES = requests.get(self.base_url + "datasets/badges/").json()
# licences
self._DST_LICENSES = {
l.get("id"): l.get("title")
for l in requ... | Get different filters values as dicts. | entailment |
def deploy(app_id, version, promote, quiet):
# type: (str, str, bool, bool) -> None
""" Deploy the app to AppEngine.
Args:
app_id (str):
AppEngine App ID. Overrides config value app_id if given.
version (str):
AppEngine project version. Overrides config values if giv... | Deploy the app to AppEngine.
Args:
app_id (str):
AppEngine App ID. Overrides config value app_id if given.
version (str):
AppEngine project version. Overrides config values if given.
promote (bool):
If set to **True** promote the current remote app versio... | entailment |
def devserver(port, admin_port, clear):
# type: (int, int, bool) -> None
""" Run devserver.
Args:
port (int):
Port on which the app will be served.
admin_port (int):
Port on which the admin interface is served.
clear (bool):
If set to **True**, cl... | Run devserver.
Args:
port (int):
Port on which the app will be served.
admin_port (int):
Port on which the admin interface is served.
clear (bool):
If set to **True**, clear the datastore on startup. | entailment |
def setup_ci():
# type: () -> None
""" Setup AppEngine SDK on CircleCI """
gcloud_path = shell.run('which gcloud', capture=True).stdout.strip()
sdk_path = normpath(join(gcloud_path, '../../platform/google_appengine'))
gcloud_cmd = gcloud_path + ' --quiet'
if not exists(sdk_path):
log.in... | Setup AppEngine SDK on CircleCI | entailment |
def mark_experimental(fn):
# type: (FunctionType) -> FunctionType
""" Mark function as experimental.
Args:
fn (FunctionType):
The command function to decorate.
"""
@wraps(fn)
def wrapper(*args, **kw): # pylint: disable=missing-docstring
from peltak.core import shel... | Mark function as experimental.
Args:
fn (FunctionType):
The command function to decorate. | entailment |
def mark_deprecated(replaced_by):
# type: (Text) -> FunctionType
""" Mark command as deprecated.
Args:
replaced_by (str):
The command that deprecated this command and should be used instead.
"""
def decorator(fn): # pylint: disable=missing-docstring
@wraps(fn)
... | Mark command as deprecated.
Args:
replaced_by (str):
The command that deprecated this command and should be used instead. | entailment |
def in_batches(iterable, batch_size):
# type: (Iterable[Any]) -> Generator[List[Any]]
""" Split the given iterable into batches.
Args:
iterable (Iterable[Any]):
The iterable you want to split into batches.
batch_size (int):
The size of each bach. The last batch will ... | Split the given iterable into batches.
Args:
iterable (Iterable[Any]):
The iterable you want to split into batches.
batch_size (int):
The size of each bach. The last batch will be probably smaller (if
the number of elements cannot be equally divided.
Returns... | entailment |
def yaml_dump(data, stream=None):
# type: (YamlData, Optional[TextIO]) -> Text
""" Dump data to a YAML string/file.
Args:
data (YamlData):
The data to serialize as YAML.
stream (TextIO):
The file-like object to save to. If given, this function will write
... | Dump data to a YAML string/file.
Args:
data (YamlData):
The data to serialize as YAML.
stream (TextIO):
The file-like object to save to. If given, this function will write
the resulting YAML to that stream.
Returns:
str: The YAML string. | entailment |
def clear(cls, fn):
# type: (FunctionType) -> None
""" Clear result cache on the given function.
If the function has no cached result, this call will do nothing.
Args:
fn (FunctionType):
The function whose cache should be cleared.
"""
if hasa... | Clear result cache on the given function.
If the function has no cached result, this call will do nothing.
Args:
fn (FunctionType):
The function whose cache should be cleared. | entailment |
def start(name):
# type: (str) -> None
""" Start working on a new feature by branching off develop.
This will create a new branch off develop called feature/<name>.
Args:
name (str):
The name of the new feature.
"""
branch = git.current_branch(refresh=True)
task_branch ... | Start working on a new feature by branching off develop.
This will create a new branch off develop called feature/<name>.
Args:
name (str):
The name of the new feature. | entailment |
def update():
# type: () -> None
""" Update the feature with updates committed to develop.
This will merge current develop into the current branch.
"""
branch = git.current_branch(refresh=True)
base_branch = common.get_base_branch()
common.assert_branch_type('task')
common.git_checkout... | Update the feature with updates committed to develop.
This will merge current develop into the current branch. | entailment |
def finish():
# type: () -> None
""" Merge current feature branch into develop. """
pretend = context.get('pretend', False)
if not pretend and (git.staged() or git.unstaged()):
log.err(
"You have uncommitted changes in your repo!\n"
"You need to stash them before you mer... | Merge current feature branch into develop. | entailment |
def merged():
# type: () -> None
""" Cleanup a remotely merged branch. """
base_branch = common.get_base_branch()
branch = git.current_branch(refresh=True)
common.assert_branch_type('task')
# Pull feature branch with the merged task
common.git_checkout(base_branch)
common.git_pull(base... | Cleanup a remotely merged branch. | entailment |
def mutagen_call(action, path, func, *args, **kwargs):
"""Call a Mutagen function with appropriate error handling.
`action` is a string describing what the function is trying to do,
and `path` is the relevant filename. The rest of the arguments
describe the callable to invoke.
We require at least ... | Call a Mutagen function with appropriate error handling.
`action` is a string describing what the function is trying to do,
and `path` is the relevant filename. The rest of the arguments
describe the callable to invoke.
We require at least Mutagen 1.33, where `IOError` is *never* used,
neither for... | entailment |
def _safe_cast(out_type, val):
"""Try to covert val to out_type but never raise an exception. If
the value can't be converted, then a sensible default value is
returned. out_type should be bool, int, or unicode; otherwise, the
value is just passed through.
"""
if val is None:
return None... | Try to covert val to out_type but never raise an exception. If
the value can't be converted, then a sensible default value is
returned. out_type should be bool, int, or unicode; otherwise, the
value is just passed through. | entailment |
def _unpack_asf_image(data):
"""Unpack image data from a WM/Picture tag. Return a tuple
containing the MIME type, the raw image data, a type indicator, and
the image's description.
This function is treated as "untrusted" and could throw all manner
of exceptions (out-of-bounds, etc.). We should clea... | Unpack image data from a WM/Picture tag. Return a tuple
containing the MIME type, the raw image data, a type indicator, and
the image's description.
This function is treated as "untrusted" and could throw all manner
of exceptions (out-of-bounds, etc.). We should clean this up
sometime so that the f... | entailment |
def _pack_asf_image(mime, data, type=3, description=""):
"""Pack image data for a WM/Picture tag.
"""
tag_data = struct.pack('<bi', type, len(data))
tag_data += mime.encode("utf-16-le") + b'\x00\x00'
tag_data += description.encode("utf-16-le") + b'\x00\x00'
tag_data += data
return tag_data | Pack image data for a WM/Picture tag. | entailment |
def _sc_decode(soundcheck):
"""Convert a Sound Check bytestring value to a (gain, peak) tuple as
used by ReplayGain.
"""
# We decode binary data. If one of the formats gives us a text
# string, interpret it as UTF-8.
if isinstance(soundcheck, six.text_type):
soundcheck = soundcheck.encod... | Convert a Sound Check bytestring value to a (gain, peak) tuple as
used by ReplayGain. | entailment |
def _sc_encode(gain, peak):
"""Encode ReplayGain gain/peak values as a Sound Check string.
"""
# SoundCheck stores the peak value as the actual value of the
# sample, rather than the percentage of full scale that RG uses, so
# we do a simple conversion assuming 16 bit samples.
peak *= 32768.0
... | Encode ReplayGain gain/peak values as a Sound Check string. | entailment |
def image_mime_type(data):
"""Return the MIME type of the image data (a bytestring).
"""
# This checks for a jpeg file with only the magic bytes (unrecognized by
# imghdr.what). imghdr.what returns none for that type of file, so
# _wider_test_jpeg is run in that case. It still returns None if it did... | Return the MIME type of the image data (a bytestring). | entailment |
def deserialize(self, mutagen_value):
"""Given a raw value stored on a Mutagen object, decode and
return the represented value.
"""
if self.suffix and isinstance(mutagen_value, six.text_type) \
and mutagen_value.endswith(self.suffix):
return mutagen_value[:-len(sel... | Given a raw value stored on a Mutagen object, decode and
return the represented value. | entailment |
def set(self, mutagen_file, value):
"""Assign the value for the field using this style.
"""
self.store(mutagen_file, self.serialize(value)) | Assign the value for the field using this style. | entailment |
def serialize(self, value):
"""Convert the external Python value to a type that is suitable for
storing in a Mutagen file object.
"""
if isinstance(value, float) and self.as_type is six.text_type:
value = u'{0:.{1}f}'.format(value, self.float_places)
value = self.... | Convert the external Python value to a type that is suitable for
storing in a Mutagen file object. | entailment |
def get_list(self, mutagen_file):
"""Get a list of all values for the field using this style.
"""
return [self.deserialize(item) for item in self.fetch(mutagen_file)] | Get a list of all values for the field using this style. | entailment |
def set_list(self, mutagen_file, values):
"""Set all values for the field using this style. `values`
should be an iterable.
"""
self.store(mutagen_file, [self.serialize(value) for value in values]) | Set all values for the field using this style. `values`
should be an iterable. | entailment |
def deserialize(self, apic_frame):
"""Convert APIC frame into Image."""
return Image(data=apic_frame.data, desc=apic_frame.desc,
type=apic_frame.type) | Convert APIC frame into Image. | entailment |
def serialize(self, image):
"""Return an APIC frame populated with data from ``image``.
"""
assert isinstance(image, Image)
frame = mutagen.id3.Frames[self.key]()
frame.data = image.data
frame.mime = image.mime_type
frame.desc = image.desc or u''
# For co... | Return an APIC frame populated with data from ``image``. | entailment |
def serialize(self, image):
"""Turn a Image into a base64 encoded FLAC picture block.
"""
pic = mutagen.flac.Picture()
pic.data = image.data
pic.type = image.type_index
pic.mime = image.mime_type
pic.desc = image.desc or u''
# Encoding with base64 returns... | Turn a Image into a base64 encoded FLAC picture block. | entailment |
def store(self, mutagen_file, pictures):
"""``pictures`` is a list of mutagen.flac.Picture instances.
"""
mutagen_file.clear_pictures()
for pic in pictures:
mutagen_file.add_picture(pic) | ``pictures`` is a list of mutagen.flac.Picture instances. | entailment |
def serialize(self, image):
"""Turn a Image into a mutagen.flac.Picture.
"""
pic = mutagen.flac.Picture()
pic.data = image.data
pic.type = image.type_index
pic.mime = image.mime_type
pic.desc = image.desc or u''
return pic | Turn a Image into a mutagen.flac.Picture. | entailment |
def delete(self, mutagen_file):
"""Remove all images from the file.
"""
for cover_tag in self.TAG_NAMES.values():
try:
del mutagen_file[cover_tag]
except KeyError:
pass | Remove all images from the file. | entailment |
def styles(self, mutagen_file):
"""Yields the list of storage styles of this field that can
handle the MediaFile's format.
"""
for style in self._styles:
if mutagen_file.__class__.__name__ in style.formats:
yield style | Yields the list of storage styles of this field that can
handle the MediaFile's format. | entailment |
def _none_value(self):
"""Get an appropriate "null" value for this field's type. This
is used internally when setting the field to None.
"""
if self.out_type == int:
return 0
elif self.out_type == float:
return 0.0
elif self.out_type == bool:
... | Get an appropriate "null" value for this field's type. This
is used internally when setting the field to None. | entailment |
def _get_date_tuple(self, mediafile):
"""Get a 3-item sequence representing the date consisting of a
year, month, and day number. Each number is either an integer or
None.
"""
# Get the underlying data and split on hyphens and slashes.
datestring = super(DateField, self).... | Get a 3-item sequence representing the date consisting of a
year, month, and day number. Each number is either an integer or
None. | entailment |
def _set_date_tuple(self, mediafile, year, month=None, day=None):
"""Set the value of the field given a year, month, and day
number. Each number can be an integer or None to indicate an
unset component.
"""
if year is None:
self.__delete__(mediafile)
retur... | Set the value of the field given a year, month, and day
number. Each number can be an integer or None to indicate an
unset component. | entailment |
def save(self):
"""Write the object's tags back to the file. May
throw `UnreadableFileError`.
"""
# Possibly save the tags to ID3v2.3.
kwargs = {}
if self.id3v23:
id3 = self.mgfile
if hasattr(id3, 'tags'):
# In case this is an MP3 o... | Write the object's tags back to the file. May
throw `UnreadableFileError`. | entailment |
def fields(cls):
"""Get the names of all writable properties that reflect
metadata tags (i.e., those that are instances of
:class:`MediaField`).
"""
for property, descriptor in cls.__dict__.items():
if isinstance(descriptor, MediaField):
if isinstance(... | Get the names of all writable properties that reflect
metadata tags (i.e., those that are instances of
:class:`MediaField`). | entailment |
def _field_sort_name(cls, name):
"""Get a sort key for a field name that determines the order
fields should be written in.
Fields names are kept unchanged, unless they are instances of
:class:`DateItemField`, in which case `year`, `month`, and `day`
are replaced by `date0`, `dat... | Get a sort key for a field name that determines the order
fields should be written in.
Fields names are kept unchanged, unless they are instances of
:class:`DateItemField`, in which case `year`, `month`, and `day`
are replaced by `date0`, `date1`, and `date2`, respectively, to
m... | entailment |
def sorted_fields(cls):
"""Get the names of all writable metadata fields, sorted in the
order that they should be written.
This is a lexicographic order, except for instances of
:class:`DateItemField`, which are sorted in year-month-day
order.
"""
for property in... | Get the names of all writable metadata fields, sorted in the
order that they should be written.
This is a lexicographic order, except for instances of
:class:`DateItemField`, which are sorted in year-month-day
order. | entailment |
def add_field(cls, name, descriptor):
"""Add a field to store custom tags.
:param name: the name of the property the field is accessed
through. It must not already exist on this class.
:param descriptor: an instance of :class:`MediaField`.
"""
if not isinst... | Add a field to store custom tags.
:param name: the name of the property the field is accessed
through. It must not already exist on this class.
:param descriptor: an instance of :class:`MediaField`. | entailment |
def update(self, dict):
"""Set all field values from a dictionary.
For any key in `dict` that is also a field to store tags the
method retrieves the corresponding value from `dict` and updates
the `MediaFile`. If a key has the value `None`, the
corresponding property is deleted ... | Set all field values from a dictionary.
For any key in `dict` that is also a field to store tags the
method retrieves the corresponding value from `dict` and updates
the `MediaFile`. If a key has the value `None`, the
corresponding property is deleted from the `MediaFile`. | entailment |
def samplerate(self):
"""The audio's sample rate (an int)."""
if hasattr(self.mgfile.info, 'sample_rate'):
return self.mgfile.info.sample_rate
elif self.type == 'opus':
# Opus is always 48kHz internally.
return 48000
return 0 | The audio's sample rate (an int). | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.