output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def get_builder_toplevel(self, builder):
"""Get the toplevel widget from a Gtk.Builder file.
The main view implementation first searches for the widget named as
self.toplevel_name (which defaults to "main". If this is missing, or not
a Gtk.Window, the first toplevel window found in the ... | Implement a function in Python 3 to
get the toplevel widget from a Gtk. Builder file. | As a python code expert, you are capable of creating scripts from specifications. |
Round the number to the specified number of significant figures | Explain what the following Python 3 code does
def round_sig(x, sig):
return round(x, sig - int(floor(log10(abs(x)))) - 1) | You are a Python code architect, reviewing and designing scalable and efficient code |
Open the file with gzipping it if it ends with. gz. | Can you generate a brief explanation for the following Python 3 code
def open_file(filename, as_text=False):
if filename.lower().endswith('.gz'):
if as_text:
return gzip.open(filename, 'rt')
else:
return gzip.open(filename, 'rb')
else:
if as_text:
retu... | As a python code expert, you are capable of creating scripts from specifications. |
Create a simple writer suitable for writing flat data
e. g. as BasicObject or TSV. | Can you generate the documentation for the following Python 3 function
def create_simple_writer(outputDef, defaultOutput, outputFormat, fieldNames,
compress=True, valueClassMappings=None,
datasetMetaProps=None, fieldMetaProps=None):
"""Create a simple writer suitabl... | As a Python code composer, you craft elegant and concise scripts. |
This function writes the minimal metadata that Squonk needs. | Make a summary of the following Python 3 code
def write_squonk_datasetmetadata(outputBase, thinOutput, valueClassMappings, datasetMetaProps, fieldMetaProps):
meta = {}
props = {}
# TODO add created property - how to handle date formats?
if datasetMetaProps:
props.update(datasetMetaProps)
if... | You are a Python code generator, capable of creating scripts from specifications. |
def write_metrics(baseName, values):
"""Write the metrics data
:param baseName: The base name of the output files.
e.g. extensions will be appended to this base name
:param values dictionary of values to write
"""
m = open(baseName + '_metrics.txt', 'w')
for key in values:... | Create a Python 3 function to
write the metrics to the file | You are a Python code generator, capable of creating scripts from specifications. |
def generate_molecule_object_dict(source, format, values):
"""Generate a dictionary that represents a Squonk MoleculeObject when
written as JSON
:param source: Molecules in molfile or smiles format
:param format: The format of the molecule. Either 'mol' or 'smiles'
:param values: Optional dict of v... | Implement a Python 3 function for
generating a dictionary that represents a Squonk MoleculeObject when written as JSON | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns the module name of the caller s calling module. | Here you have a function in Python 3, explain what it does
def get_undecorated_calling_module():
frame = inspect.stack()[2]
module = inspect.getmodule(frame[0])
# Return the module's file and its path
# and omit the extension...
# so /a/c.py becomes /a/c
return module.__file__.rsplit('.', 1)[0] | As a python code expert, you are capable of creating scripts from specifications. |
def query_nexus(query_url, timeout_sec, basic_auth=None):
"""Queries Nexus for an artifact
:param query_url: (str) Query URL
:param timeout_sec: (int) query timeout
:param basic_auth (HTTPBasicAuth) object or none
:return: requests.Response object
:raises: RuntimeError
"""
log = logging... | Implement a function in Python 3 to
query Nexus for an artifact and returns the response object. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_artifact(suppress_status=False, nexus_url=sample_nexus_url, timeout_sec=600, overwrite=True,
username=None, password=None, **kwargs):
"""Retrieves an artifact from Nexus
:param suppress_status: (bool) Set to True to suppress printing download status
:param nexus_url: (str) URL of t... | Implement a Python 3 function for
retrieving an artifact from Nexus server and returns it. | You are a Python code architect, reviewing and designing scalable and efficient code |
Retrieves an artifact from Nexus 3 ReST API. | Can you generate the documentation for the following Python 3 function
def get_artifact_nexus3(suppress_status=False, nexus_base_url=sample_nexus_base_url, repository=None,
timeout_sec=600, overwrite=True, username=None, password=None, **kwargs):
"""Retrieves an artifact from the Nexus 3 ReS... | You are a Python code generator, capable of creating scripts from specifications. |
This module handles calling this module as a script
| Here you have a function in Python 3, explain what it does
def main():
log = logging.getLogger(mod_logger + '.main')
parser = argparse.ArgumentParser(description='This Python module retrieves artifacts from Nexus.')
parser.add_argument('-u', '--url', help='Nexus Server URL', required=False)
parser.add_a... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_doc(additional_doc=False,
field_prefix='$',
field_suffix=':',
indent=4):
"""Return a formated string containing documentation about the audio
fields.
"""
if additional_doc:
f = fields.copy()
f.update(additional_doc)
else:
f = fields... | Implement a Python 3 function for
returning a formated string containing documentation about the audio Formula fields. | You are a Python code architect, reviewing and designing scalable and efficient code |
def list_images(self):
# type: () -> List[str]
""" List images stored in the registry.
Returns:
list[str]: List of image names.
"""
r = self.get(self.registry_url + '/v2/_catalog', auth=self.auth)
return r.json()['repositories'] | Write a Python 3 function for
listing images stored in the registry. | As a Python code composer, you craft elegant and concise scripts. |
List all tags for the given image in the registry. | Given the following Python 3 function, write the documentation
def list_tags(self, image_name):
# type: (str) -> Iterator[str]
""" List all tags for the given image stored in the registry.
Args:
image_name (str):
The name of the image to query. The image must be pres... | As a Python code analyst, you investigate and solve complex coding mysteries |
def validate_asset_structure(asset_dir_path):
"""Checks asset structure validity
:param asset_dir_path: (str) path to the directory containing the asset
:return: (str) Asset name
:raises: Cons3rtAssetStructureError
"""
log = logging.getLogger(mod_logger + '.validate_asset_structure')
log.i... | Create a Python 3 function for
checking the validity of the asset structure | As a Python code analyst, you investigate and solve complex coding mysteries |
def make_asset_zip(asset_dir_path, destination_directory=None):
"""Given an asset directory path, creates an asset zip file in the provided
destination directory
:param asset_dir_path: (str) path to the directory containing the asset
:param destination_directory: (str) path to the destination directory... | Write a Python 3 script to
give an asset directory path creates an asset zip file in the provided directory containing the asset. | You are a Python code generator, capable of creating scripts from specifications. |
def validate(asset_dir):
"""Command line call to validate an asset structure
:param asset_dir: (full path to the asset dir)
:return: (int)
"""
try:
asset_name = validate_asset_structure(asset_dir_path=asset_dir)
except Cons3rtAssetStructureError:
_, ex, trace = sys.exc_info()
... | Can you create a Python 3 function that
commands line call to validate an asset structure | You are a Python code generator, capable of creating scripts from specifications. |
Command line call to create an asset zip file | Given the following Python 3 function, write the documentation
def create(asset_dir, dest_dir):
val = validate(asset_dir=asset_dir)
if val != 0:
return 1
try:
asset_zip = make_asset_zip(asset_dir_path=asset_dir, destination_directory=dest_dir)
except AssetZipCreationError:
_, ex,... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_object_or_none(cls, **kwargs):
"""
Returns model instance or None if not found.
:param cls: Class or queryset
:param kwargs: Filters for get() call
:return: Object or None
"""
from django.shortcuts import _get_queryset
qs = _get_queryset(cls)
try:
return qs.get(**kwar... | Write a Python 3 function that can
return model instance or None if not found. | As a python code expert, you are capable of creating scripts from specifications. |
Returns model field label and value. | How would you explain what the following Python 3 function does
def get_model_field_label_and_value(instance, field_name) -> (str, str):
label = field_name
value = str(getattr(instance, field_name))
for f in instance._meta.fields:
if f.attname == field_name:
label = f.verbose_name
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Clones the model instance to new object. | Explain what the following Python 3 code does
def clone_model(instance, cls, commit: bool=True, exclude_fields: tuple=('id',), base_class_suffix: str='_ptr', **kw):
keys = [f.name for f in cls._meta.fields if f.name not in exclude_fields and not f.name.endswith(base_class_suffix)]
new_instance = cls()
for k... | You are a Python code generator, capable of creating scripts from specifications. |
This method returns a list of all the identities that are in the database for the specified query parameters. | Can you generate the documentation for the following Python 3 function
def get_queryset(self):
query_params = list(self.request.query_params.keys())
# variable that stores criteria to filter identities by
filter_criteria = {}
# variable that stores a list of addresses that should be act... | You are a Python code analyst, evaluating scripts for potential improvements. |
def check_internet_connection(self, remote_server: str = "api.isogeo.com") -> bool:
"""Test if an internet connection is operational.
Src: http://stackoverflow.com/a/20913928/2556577.
:param str remote_server: remote server used to check
"""
try:
# see if we can reso... | How would you code a function in Python 3 to
test if an internet connection is operational. | As a python code expert, you are capable of creating scripts from specifications. |
Check the validity of the given token. | How would you explain what the following Python 3 function does
def check_bearer_validity(self, token: dict, connect_mtd) -> dict:
warnings.warn(
"Method is now executed as a decorator within the main SDK class. Will be removed in future versions.",
DeprecationWarning,
)
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Check API response and raise exceptions if needed. | Can you generate a brief explanation for the following Python 3 code
def check_api_response(self, response):
# check response
if response.status_code == 200:
return True
elif response.status_code >= 400:
logging.error(
"{}: {} - {} - URL: {}".format(
... | As a python code expert, you are capable of creating scripts from specifications. |
Check the parameters passed to avoid errors and help debug. | Can you generate a brief explanation for the following Python 3 code
def check_request_parameters(self, parameters: dict = dict):
# -- SEMANTIC QUERY ---------------------------------------------------
li_args = parameters.get("q").split()
logging.debug(li_args)
# Unicity
li_fil... | You are a Python code generator, capable of creating scripts from specifications. |
Check if the given string is an Isogeo UUID handling specific form. | Given the following Python 3 function, write the documentation
def check_is_uuid(self, uuid_str: str):
# check uuid type
if not isinstance(uuid_str, str):
raise TypeError("'uuid_str' expected a str value.")
else:
pass
# handle Isogeo specific UUID in XML exports
... | As a python code expert, you are capable of creating scripts from specifications. |
Check if asked tab is part of Isogeo web form and reliable
with metadata type. | Given the following Python 3 function, write the documentation
def check_edit_tab(self, tab: str, md_type: str):
# check parameters types
if not isinstance(tab, str):
raise TypeError("'tab' expected a str value.")
else:
pass
if not isinstance(md_type, str):
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _check_filter_specific_md(self, specific_md: list):
"""Check if specific_md parameter is valid.
:param list specific_md: list of specific metadata UUID to check
"""
if isinstance(specific_md, list):
if len(specific_md) > 0:
# checking UUIDs and poping bad... | How would you code a function in Python 3 to
check if specific metadata UUID is correct. | You are a Python code analyst, evaluating scripts for potential improvements. |
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... | Can you implement a function in Python 3 that
checks if specific_tag parameter is valid. | You are a Python code architect, reviewing and designing scalable and efficient code |
Check if specific_resources parameter is valid. | Can you tell what is the following Python 3 function doing
def _check_filter_includes(self, includes: list, resource: str = "metadata"):
# check resource parameter
if resource == "metadata":
ref_subresources = _SUBRESOURCES_MD
elif resource == "keyword":
ref_subresources ... | You are a Python code architect, reviewing and designing scalable and efficient code |
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,
)
... | Create a Python 3 function to
check if specific_resources parameter is valid. | You are a Python code generator, capable of creating scripts from specifications. |
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
... | Write a Python 3 function that can
convert metadata types to Isogeo API format | You are a Python code generator, capable of creating scripts from specifications. |
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... | Can you write a function in Python 3 where it
shows 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 u... | You are a Python code analyst, evaluating scripts for potential improvements. |
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... | Create a Python 3 function to
bump current project version without committing anything. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a name for a log file that is meant to be used in a call to the
EffectiveLogFile method. | Can you generate a brief explanation for the following Python 3 code
def get_logfile_name(tag):
if not os.path.exists(p.LOG_DIR):
os.mkdir(p.LOG_DIR)
filename = "log_" + p.HOST + "_" + tag + ".txt"
filename = os.path.join(p.LOG_DIR, filename)
return filename | You are a Python code analyst, evaluating scripts for potential improvements. |
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)
... | Write a Python 3 script to
fetch a record by the record s ID or upstream_identifier. | As a Python code analyst, you investigate and solve complex coding mysteries |
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... | Write a Python 3 function for
replacing a foreign key reference using a name with an ID. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Adds the model name to the payload. | How would you explain what the following Python 3 function does
def add_model_name_to_payload(cls, payload):
if not cls.MODEL_NAME in payload:
payload = {cls.MODEL_NAME: payload}
return payload | You are a Python code generator, capable of creating scripts from specifications. |
Searches the model in question by AND joining the query parameters. | Can you generate a brief explanation for the following Python 3 code
def find_by(cls, payload, require=False):
if not isinstance(payload, dict):
raise ValueError("The 'payload' parameter must be provided a dictionary object.")
url = os.path.join(cls.URL, "find_by")
payload = {"find_b... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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... | Write a Python 3 function for
searching the model in question by OR joining the query parameters. | As a python code expert, you are capable of creating scripts from specifications. |
Fetches all records.
Returns:
`dict`. The JSON formatted response.
Raises:
`requests.exceptions.HTTPError`: The status code is not ok. | Can you generate a brief explanation for the following Python 3 code
def index(cls):
res = requests.get(cls.URL, headers=HEADERS, verify=False)
res.raise_for_status()
return res.json() | As a Python code composer, you craft elegant and concise scripts. |
Patches the current record and udpates the current instance s attrs attribute to reflect the new changes. | Make a summary of the following Python 3 code
def patch(self, payload, append_to_arrays=True):
if not isinstance(payload, dict):
raise ValueError("The 'payload' parameter must be provided a dictionary object.")
payload = self.__class__.set_id_in_fkeys(payload)
if append_to_arrays:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Sets the ID of the record that is referenced by the foreign key fields in the payload. | Given the following Python 3 function, write the documentation
def set_id_in_fkeys(cls, payload):
for key in payload:
val = payload[key]
if not val:
continue
if key.endswith("_id"):
model = getattr(THIS_MODULE, cls.FKEY_MAP[key])
... | As a python code expert, you are capable of creating scripts from specifications. |
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... | Can you write a function in Python 3 where it
posts the data to the specified record. | As a Python code composer, you craft elegant and concise scripts. |
Logs the provided error message to both the error logger and the debug logger logging
instances. | Here you have a function in Python 3, explain what it does
def log_error(cls, msg):
cls.error_logger.error(msg)
cls.debug_logger.debug(msg) | You are a Python code analyst, evaluating scripts for potential improvements. |
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.
... | How would you code a function in Python 3 to
write the response to a file. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns an array of parent Biosample IDs. | Given the following Python 3 function, write the documentation
def parent_ids(self):
action = os.path.join(self.record_url, "parent_ids")
res = requests.get(url=action, headers=HEADERS, verify=False)
res.raise_for_status()
return res.json()["biosamples"] | As a Python code composer, you craft elegant and concise scripts. |
Recursively searches the part_of_id_of_wt_parent method and returns the first WT parent that is not a parent of the Biosample. | Can you generate a brief explanation for the following Python 3 code
def find_first_wt_parent(self, with_ip=False):
parent_id = self.part_of_id
if not parent_id:
return False
parent = Biosample(parent_id)
if parent.wild_type:
if with_ip and parent.immunoblot_ids:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Uploads a new entry to the database. | How would you explain what the following Python 3 function does
def upload(cls, path, document_type, is_protocol, description=""):
file_name = os.path.basename(path)
mime_type = mimetypes.guess_type(file_name)[0]
data = base64.b64encode(open(path, 'rb').read())
temp_uri = str(data, "utf-... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a hash of all Libraries and barcode_sequence for all Libraries on the SequencingRequest. | Can you generate a brief explanation for the following Python 3 code
def get_library_barcode_sequence_hash(self, inverse=False):
action = os.path.join(self.record_url, "get_library_barcode_sequence_hash")
res = requests.get(url=action, headers=HEADERS, verify=False)
res.raise_for_status()
... | As a Python code composer, you craft elegant and concise scripts. |
Generates a dictionary where each key is a Library ID and each value is a SequencingResult. Each key is a SequencingRequest and each value is a SequencingResult. Each value is a SequencingResult. | Given the following Python 3 function, write the documentation
def library_sequencing_results(self):
sres_ids = self.sequencing_result_ids
res = {}
for i in sres_ids:
sres = SequencingResult(i)
res[sres.library_id] = sres
return res | As a Python code analyst, you investigate and solve complex coding mysteries |
Unarchives the user with the specified user ID. | Can you generate the documentation for the following Python 3 function
def unarchive_user(self, user_id):
url = self.record_url + "/unarchive"
res = requests.patch(url=url, json={"user_id": user_id}, headers=HEADERS, verify=False)
self.write_response_html_to_file(res,"bob.html")
res.rais... | As a python code expert, you are capable of creating scripts from specifications. |
Removes the user s existing API key if present and sets the current instance s api_key attribute to the empty string. | Can you generate a brief explanation for the following Python 3 code
def remove_api_key(self):
url = self.record_url + "/remove_api_key"
res = requests.patch(url=url, headers=HEADERS, verify=False)
res.raise_for_status()
self.api_key = "" | As a Python code composer, you craft elegant and concise scripts. |
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]),... | Write a Python 3 function that can
generate the synth observation for the given bases wavelength flux and sigma. | As a Python code composer, you craft elegant and concise scripts. |
Processes the current transaction and returns the status of the current object | Here you have a function in Python 3, explain what it does
def _process(self, resource=None, data={}):
# use object's data if no data is passed
_data = data or self._data
rsc_url = self.get_rsc_endpoint(resource)
if _data:
req = requests.post(rsc_url, data=json.dumps(_data),
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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)
) | How would you code a function in Python 3 to
add a custom HTTP header to the client s request headers | You are a Python code analyst, evaluating scripts for potential improvements. |
Generate changelog from commit messages. | Can you tell what is the following Python 3 function doing
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()) | You are a Python code generator, capable of creating scripts from specifications. |
Convert the Argument object to a tuple use in the argument parser. add_argument call on the parser | Can you generate the documentation for the following Python 3 function
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", "defau... | As a Python code composer, you craft elegant and concise scripts. |
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 ... | Write a Python 3 script for
returning the default generated name for the option. | As a Python code analyst, you investigate and solve complex coding mysteries |
Construct the filename based on the attributes. | Here you have a function in Python 3, explain what it does
def get_filename(self, base_dir=None, modality=None):
filename = 'sub-' + self.subject
if self.session is not None:
filename += '_ses-' + self.session
if self.task is not None:
filename += '_task-' + self.task
... | As a Python code analyst, you investigate and solve complex coding mysteries |
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
... | Can you implement a function in Python 3 that
selects elements of the TSV using python filter and map. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Authenticate application and get token bearer. | Can you generate a brief explanation for the following Python 3 code
def connect(self, client_id: str = None, client_secret: str = None) -> dict:
# instanciated or direct call
if not client_id and not client_secret:
client_id = self.client_id
client_secret = self.client_secret
... | You are a Python code architect, reviewing and designing scalable and efficient code |
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... | Create a Python 3 function for
checking 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 :param... | You are a Python code generator, capable of creating scripts from specifications. |
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... | How would you implement a function in Python 3 that
searches within the resources shared to the application. | You are a Python code analyst, evaluating scripts for potential improvements. |
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... | How would you code a function in Python 3 to
get complete or partial metadata about one specific resource. | You are a Python code architect, reviewing and designing scalable and efficient code |
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... | Can you create a Python 3 function that
gets information about the application s shares. | You are a Python code architect, reviewing and designing scalable and efficient code |
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 ... | Create a Python 3 function to
get information about a specific share and its applications. | As a python code expert, you are capable of creating scripts from specifications. |
Get information about licenses owned by a specific workgroup. | Can you tell what is the following Python 3 function doing
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 UU... | As a python code expert, you are capable of creating scripts from specifications. |
Get details about a specific license. | Can you generate the documentation for the following Python 3 function
def license(self, license_id: str, token: dict = None, prot: str = "https") -> dict:
# handling request parameters
payload = {"lid": license_id}
# search request
license_url = "{}://v1.{}.isogeo.com/licenses/{}".form... | As a python code expert, you are capable of creating scripts from specifications. |
Get list of available thesauri. | Can you generate a brief explanation for the following Python 3 code
def thesauri(self, token: dict = None, prot: str = "https") -> dict:
# passing auth parameter
thez_url = "{}://v1.{}.isogeo.com/thesauri".format(prot, self.api_url)
thez_req = self.get(
thez_url, headers=self.header... | You are a Python code analyst, evaluating scripts for potential improvements. |
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... | Can you create a Python 3 function that
gets 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). | You are a Python code architect, reviewing and designing scalable and efficient code |
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 = ... | Can you create a Python 3 function that
searches for keywords within a specific thesaurus. | As a Python code translator, you convert algorithms and pseudocode into Python. |
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 ... | Implement a function in Python 3 to
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 (use it only f... | You are a Python code architect, reviewing and designing scalable and efficient code |
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... | Implement a function in Python 3 to
get resource exported into XML ISO 19139. | As a Python code analyst, you investigate and solve complex coding mysteries |
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 ... | Write a Python 3 function for
adding shares list to the tags dictionary in search results. | As a python code expert, you are capable of creating scripts from specifications. |
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... | Can you write a function in Python 3 where it
gets information about the application declared on Isogeo. | As a Python code translator, you convert algorithms and pseudocode into Python. |
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... | Write a Python 3 script for
getting environment directives which represent INSPIRE limitations. | You are a Python code analyst, evaluating scripts for potential improvements. |
Get available coordinate systems in Isogeo API. | Here you have a function in Python 3, explain what it does
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 sp... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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... | Create a Python 3 function for
getting the formats for a specific language. | As a Python code composer, you craft elegant and concise scripts. |
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... | Create a Python 3 function for
parsing a boolean value from the input string and returns the corresponding value. | You are a Python code architect, reviewing and designing scalable and efficient code |
Parses a datetime from a string into a datetime object. | Can you generate the documentation for the following Python 3 function
def parse_datetime(v, default=None, tz=None, exceptions: bool=True) -> datetime:
try:
t = dateutil_parse(v, default=datetime(2000, 1, 1))
if tz is None:
tz = pytz.utc
return t if t.tzinfo else tz.localize(t)
... | As a python code expert, you are capable of creating scripts from specifications. |
Converts a string to a boolean. | Given the following Python 3 function, write the documentation
def convert_boolean(string_value):
lean_string_value = string_value.strip().lower()
if lean_string_value in ['yes', 'true', 'on', '1']:
return True
elif lean_string_value in ['no', 'false', 'off', '0']:
return False
# Not r... | As a Python code composer, you craft elegant and concise scripts. |
Handles the header line. | Explain what the following Python 3 code does
def _handle_hdr(self, hdr):
column_number = 1
for cell in hdr:
cell_parts = cell.split(self._type_sep)
if len(cell_parts) not in [1, 2]:
raise ContentError(column_number, self._c_reader.line_num,
... | As a Python code analyst, you investigate and solve complex coding mysteries |
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."""
... | Write a Python 3 script for
searching datasets within uData portal. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get different filters values as dicts. | Here you have a function in Python 3, explain what it does
def get_filters_values(self):
# 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 i... | You are a Python code generator, capable of creating scripts from specifications. |
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... | Can you write a function in Python 3 where it
deploys the app to AppEngine. | As a Python code analyst, you investigate and solve complex coding mysteries |
Run devserver on startup. | Given the following Python 3 function, write the documentation
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 s... | As a python code expert, you are capable of creating scripts from specifications. |
Setup AppEngine SDK on CircleCI | Can you generate a brief explanation for the following Python 3 code
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 = ... | As a Python code composer, you craft elegant and concise scripts. |
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... | Implement a function in Python 3 to
mark function as experimental. | As a Python code analyst, you investigate and solve complex coding mysteries |
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)
... | Write a Python 3 function for
marking a function as deprecated. | As a Python code translator, you convert algorithms and pseudocode into Python. |
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 ... | Create a Python 3 function to
split the given iterable into batches of size batch_size. | As a Python code composer, you craft elegant and concise scripts. |
Dump data to a YAML string or file - like object. | Make a summary of the following Python 3 code
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. I... | You are a Python code architect, reviewing and designing scalable and efficient code |
Clears the result cache on the given function. | Explain what the following Python 3 code does
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 ... | As a Python code composer, you craft elegant and concise scripts. |
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 ... | Write a Python 3 script to
start working on a new feature by branching off develop. | You are a Python code architect, reviewing and designing scalable and efficient code |
Update the feature with updates committed to develop. | Can you generate a brief explanation for the following Python 3 code
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_br... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Merge current feature branch into develop. | Explain what the following Python 3 code does
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 are a Python code generator, capable of creating scripts from specifications. |
Cleanup a remotely merged task. | Explain what the following Python 3 code does
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_... | As a Python code composer, you craft elegant and concise scripts. |
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 ... | Write a Python 3 script for
calling a Mutagen function with appropriate error handling. | As a python code expert, you are capable of creating scripts from specifications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.