output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def save(self, **kwargs):
"""Override save method to catch handled errors and repackage them as 400 errors."""
try:
return super().save(**kwargs)
except SlugError as error:
raise ParseError(error) | Create a Python 3 function for
overriding save method to catch handled errors and repackage them as 400 errors. | You are a Python code generator, capable of creating scripts from specifications. |
Read the Node document from a node and return an int containing the latest D1 APIVersion supported by the node. | Can you tell what is the following Python 3 function doing
def get_api_major_by_base_url(base_url, *client_arg_list, **client_arg_dict):
api_major = 0
client = d1_client.mnclient.MemberNodeClient(
base_url, *client_arg_list, **client_arg_dict
)
node_pyxb = client.getCapabilities()
for servic... | You are a Python code generator, capable of creating scripts from specifications. |
def delete_unused_subjects():
"""Delete any unused subjects from the database.
This is not strictly required as any unused subjects will automatically be reused if
needed in the future.
"""
# This causes Django to create a single join (check with query.query)
query = d1_gmn.app.models.Subject.... | Create a Python 3 function to
delete any unused subjects from the database. | As a Python code composer, you craft elegant and concise scripts. |
Serialize a DN to a DataONE subject string. | Can you tell what is the following Python 3 function doing
def extract_subject_from_dn(cert_obj):
return ",".join(
"{}={}".format(
OID_TO_SHORT_NAME_DICT.get(v.oid.dotted_string, v.oid.dotted_string),
rdn_escape(v.value),
)
for v in reversed(list(cert_obj.subject))
... | As a Python code composer, you craft elegant and concise scripts. |
Create the DN Subject for a DataONE environment. | Given the following Python 3 function, write the documentation
def create_d1_dn_subject(common_name_str):
return cryptography.x509.Name(
[
cryptography.x509.NameAttribute(
cryptography.x509.oid.NameOID.COUNTRY_NAME, "US"
),
cryptography.x509.NameAttribute(... | As a Python code composer, you craft elegant and concise scripts. |
def generate_csr(private_key_bytes, subject_name, fqdn_list):
"""Generate a Certificate Signing Request (CSR).
Args:
private_key_bytes: bytes
Private key with which the CSR will be signed.
subject_name: str
Certificate Subject Name
fqdn_list:
List o... | Create a Python 3 function to
generate a Certificate Signing Request (CSR). Args: private_key_bytes: bytes Private key with which the CSR will be signed. subject_name: str Certificate Subject Name fqdn_list: List of Fully Qualified Domain Names (FQDN) and/or IP addresses for which this certificate will provide authenti... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Serialize a cryptography. Certificate object to PEM. | Given the following Python 3 function, write the documentation
def serialize_cert_to_pem(cert_obj):
return cert_obj.public_bytes(
encoding=cryptography.hazmat.primitives.serialization.Encoding.PEM
) | You are a Python code analyst, evaluating scripts for potential improvements. |
def extract_subject_info_extension(cert_obj):
"""Extract DataONE SubjectInfo XML doc from certificate.
Certificates issued by DataONE may include an embedded XML doc containing
additional information about the subject specified in the certificate DN. If
present, the doc is stored as an extension with a... | Can you write a function in Python 3 where it
extracts the SubjectInfo XML doc from a certificate. | As a Python code composer, you craft elegant and concise scripts. |
def download_as_der(
base_url=d1_common.const.URL_DATAONE_ROOT,
timeout_sec=d1_common.const.DEFAULT_HTTP_TIMEOUT,
):
"""Download public certificate from a TLS/SSL web server as DER encoded ``bytes``.
If the certificate is being downloaded in order to troubleshoot validation issues,
the download its... | Write a Python 3 function that can
download a public certificate from a DataONE server as DER encoded bytes. | As a Python code analyst, you investigate and solve complex coding mysteries |
Download a public certificate from a TLS or SSL web server as PEM encoded string. | Can you generate a brief explanation for the following Python 3 code
def download_as_pem(
base_url=d1_common.const.URL_DATAONE_ROOT,
timeout_sec=d1_common.const.DEFAULT_HTTP_TIMEOUT,
):
"""Download public certificate from a TLS/SSL web server as PEM encoded string.
Also see download_as_der().
Args... | As a Python code analyst, you investigate and solve complex coding mysteries |
def download_as_obj(
base_url=d1_common.const.URL_DATAONE_ROOT,
timeout_sec=d1_common.const.DEFAULT_HTTP_TIMEOUT,
):
"""Download public certificate from a TLS/SSL web server as Certificate object.
Also see download_as_der().
Args:
base_url : str
A full URL to a DataONE service en... | Write a Python 3 function that can
download a public certificate from a TLS or SSL web server as Certificate object. | You are a Python code architect, reviewing and designing scalable and efficient code |
def decode_der(cert_der):
"""Decode cert DER string to Certificate object.
Args:
cert_der : Certificate as a DER encoded string
Returns:
cryptography.Certificate()
"""
return cryptography.x509.load_der_x509_certificate(
data=cert_der, backend=cryptography.hazmat.backends.defau... | Can you create a Python 3 function that
decodes a DER encoded certificate into a cryptography. Certificate object. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Extract issuer CA certificate URL from certificate. | Can you generate the documentation for the following Python 3 function
def extract_issuer_ca_cert_url(cert_obj):
for extension in cert_obj.extensions:
if extension.oid.dotted_string == AUTHORITY_INFO_ACCESS_OID:
authority_info_access = extension.value
for access_description in author... | As a Python code composer, you craft elegant and concise scripts. |
def serialize_private_key_to_pem(private_key, passphrase_bytes=None):
"""Serialize private key to PEM.
Args:
private_key:
passphrase_bytes:
Returns:
bytes: PEM encoded private key
"""
return private_key.private_bytes(
encoding=cryptography.hazmat.primitives.serialization... | Write a Python 3 script for
serializing a private key to PEM. | You are a Python code analyst, evaluating scripts for potential improvements. |
def generate_private_key(key_size=2048):
"""Generate a private key"""
return cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key(
public_exponent=65537,
key_size=key_size,
backend=cryptography.hazmat.backends.default_backend(),
) | How would you code a function in Python 3 to
generate a private key for a single resource. | As a python code expert, you are capable of creating scripts from specifications. |
def get_public_key_pem(cert_obj):
"""Extract public key from certificate as PEM encoded PKCS#1.
Args:
cert_obj: cryptography.Certificate
Returns:
bytes: PEM encoded PKCS#1 public key.
"""
return cert_obj.public_key().public_bytes(
encoding=cryptography.hazmat.primitives.serial... | Can you create a Python 3 function that
extracts public key from certificate as PEM encoded PKCS#1 public key. | You are a Python code architect, reviewing and designing scalable and efficient code |
def load_csr(pem_path):
"""Load CSR from PEM encoded file"""
with open(pem_path, "rb") as f:
return cryptography.x509.load_pem_x509_csr(
data=f.read(), backend=cryptography.hazmat.backends.default_backend()
) | Write a Python 3 function for
loading CSR from PEM encoded file | As a Python code composer, you craft elegant and concise scripts. |
Load a private key from PEM encoded file. | Can you generate a brief explanation for the following Python 3 code
def load_private_key(pem_path, passphrase_bytes=None):
with open(pem_path, "rb") as f:
return cryptography.hazmat.primitives.serialization.load_pem_private_key(
data=f.read(),
password=passphrase_bytes,
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def serialize_cert_to_der(cert_obj):
"""Serialize certificate to DER.
Args:
cert_obj: cryptography.Certificate
Returns:
bytes: DER encoded certificate
"""
return cert_obj.public_bytes(
cryptography.hazmat.primitives.serialization.Encoding.DER
) | Write a Python 3 script for
serializing certificate to DER. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def log_cert_info(logger, msg_str, cert_obj):
"""Dump basic certificate values to the log.
Args:
logger: Logger
Logger to which to write the certificate values.
msg_str: str
A message to write to the log before the certificate values.
cert_obj: cryptography.Certificate
... | Write a Python 3 script to
dump basic certificate values to the log. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_extension_by_name(cert_obj, extension_name):
"""Get a standard certificate extension by attribute name.
Args:
cert_obj: cryptography.Certificate
Certificate containing a standard extension.
extension_name : str
Extension name. E.g., 'SUBJECT_DIRECTORY_ATTRIBUTES'.
Retu... | How would you implement a function in Python 3 that
gets a standard certificate extension by its name. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _get_val_list(obj, path_list, reverse=False):
"""Extract values from nested objects by attribute names.
Objects contain attributes which are named references to objects. This will descend
down a tree of nested objects, starting at the given object, following the given
path.
Args:
obj: ob... | Create a Python 3 function to
return a list of values from nested objects by attribute names. | You are a Python code architect, reviewing and designing scalable and efficient code |
Extract values from nested objects by attribute names and concatenate their
string representations. | Can you tell what is the following Python 3 function doing
def _get_val_str(obj, path_list=None, reverse=False):
val_list = _get_val_list(obj, path_list or [], reverse)
return "<not found>" if obj is None else " / ".join(map(str, val_list)) | You are a Python code architect, reviewing and designing scalable and efficient code |
From Bern to JMS basis for $\ Delta F = 2$ operators. | Given the following Python 3 function, write the documentation
def _Bern_to_JMS_I(C, qq):
if qq in ['sb', 'db', 'ds']:
dd = 'dd'
ij = '{}{}'.format(dflav[qq[0]] + 1, dflav[qq[1]] + 1)
elif qq == 'cu':
dd = 'uu'
ij = '{}{}'.format(uflav[qq[0]] + 1, uflav[qq[1]] + 1)
else:
... | As a Python code composer, you craft elegant and concise scripts. |
From BernI to FormFlavorI basis for $\ Delta F = 2$ operators. | Explain what the following Python 3 code does
def _BernI_to_FormFlavor_I(C, qq):
qqf = qq[::-1] # FormFlavour uses "bs" instead of "sb" etc.
if qq in ['sb', 'db', 'ds']:
return {
'CVLL_' + 2*qqf: C["1" + 2*qq],
'CSLL_' + 2*qqf: C["2" + 2*qq] + 1 / 2 * C["3" + 2*qq],
'... | You are a Python code analyst, evaluating scripts for potential improvements. |
From Bern to 4 - quark Fierz basis for Classes III and IV and V. | How would you explain what the following Python 3 function does
def _Bern_to_Fierz_III_IV_V(C, qqqq):
# 2nd != 4th, color-octet redundant
if qqqq in ['sbss', 'dbdd', 'dbds', 'sbsd', 'bsbd', 'dsdd']:
return {
'F' + qqqq + '1': C['1' + qqqq] + 16 * C['3' + qqqq],
'F' + qqqq... | You are a Python code architect, reviewing and designing scalable and efficient code |
From Fierz to JMS basis for Class V. ddll should be of the form sbl_enu_tau dbl_munu_e etc. | Make a summary of the following Python 3 code
def Fierz_to_JMS_lep(C, ddll):
if ddll[:2] == 'uc':
s = str(uflav[ddll[0]] + 1)
b = str(uflav[ddll[1]] + 1)
q = 'u'
else:
s = str(dflav[ddll[0]] + 1)
b = str(dflav[ddll[1]] + 1)
q = 'd'
l = str(lflav[ddll[4:ddll.fi... | As a Python code analyst, you investigate and solve complex coding mysteries |
From semileptonic Fierz basis to Bern semileptonic basis for Class V and ddll should be of the form sbl_enu_tau dbl_munu_e | Can you generate a brief explanation for the following Python 3 code
def Fierz_to_Bern_nunu(C, ddll):
ind = ddll.replace('l_','').replace('nu_','')
dic = {
'nu1' + ind : C['F' + ind + 'nu'],
'nu1p' + ind : C['F' + ind + 'nup']
}
return dic | You are a Python code analyst, evaluating scripts for potential improvements. |
From semileptonic Bern basis to Fierz basis for Class V. ddll should be of the form sbl_enu_tau dbl_munu_e | Can you tell what is the following Python 3 function doing
def Bern_to_Fierz_nunu(C,ddll):
ind = ddll.replace('l_','').replace('nu_','')
return {
'F' + ind + 'nu': C['nu1' + ind],
'F' + ind + 'nup': C['nu1p' + ind],
} | As a python code expert, you are capable of creating scripts from specifications. |
From semileptonic Fierz basis to Flavio semileptonic basis for Class V ddll should be of the form sb_enu_tau dbl_munu_e etc. | How would you explain what the following Python 3 function does
def Fierz_to_Flavio_lep(C, ddll, parameters, norm_gf=True):
p = parameters
V = ckmutil.ckm.ckm_tree(p["Vus"], p["Vub"], p["Vcb"], p["delta"])
if ddll[:2] == 'sb':
xi = V[2, 2] * V[2, 1].conj()
elif ddll[:2] == 'db':
xi = V[2... | As a Python code composer, you craft elegant and concise scripts. |
From Flavio semileptonic basis to leptonic Fierz basis for Class V. ddll should be of the form sb_enu_tau dbl_munu_e etc. | Can you tell what is the following Python 3 function doing
def Flavio_to_Fierz_nunu(C, ddll, parameters, norm_gf=True):
p = parameters
V = ckmutil.ckm.ckm_tree(p["Vus"], p["Vub"], p["Vcb"], p["delta"])
if ddll[:2] == 'sb':
xi = V[2, 2] * V[2, 1].conj()
elif ddll[:2] == 'db':
xi = V[2, 2]... | As a Python code translator, you convert algorithms and pseudocode into Python. |
From semileptonic Fierz basis to EOS semileptonic basis for Class V ddll should be of the form sbl_enu_tau dbl_munu_e etc. | Can you tell what is the following Python 3 function doing
def Fierz_to_EOS_lep(C, ddll, parameters):
p = parameters
V = ckmutil.ckm.ckm_tree(p["Vus"], p["Vub"], p["Vcb"], p["delta"])
Vtb = V[2,2]
Vts = V[2,1]
ind = ddll.replace('l_','').replace('nu_','')
ind2 = ddll.replace('l_','').replace('nu... | As a Python code translator, you convert algorithms and pseudocode into Python. |
From chromomagnetic Fierz to JMS basis for Class V. | Can you tell what is the following Python 3 function doing
def Fierz_to_JMS_chrom(C, qq):
if qq[0] in dflav:
s = dflav[qq[0]] + 1
b = dflav[qq[1]] + 1
return {'dgamma_{}{}'.format(s, b): C['F7gamma' + qq],
'dG_{}{}'.format(s, b): C['F8g' + qq],
'dgamma_{}{}'.f... | You are a Python code analyst, evaluating scripts for potential improvements. |
From Flavio to chromomagnetic Fierz basis for Class V. qq should be of the form sb db etc. | Here you have a function in Python 3, explain what it does
def Flavio_to_Fierz_chrom(C, qq, parameters):
p = parameters
V = ckmutil.ckm.ckm_tree(p["Vus"], p["Vub"], p["Vcb"], p["delta"])
if qq == 'sb':
xi = V[2, 2] * V[2, 1].conj()
elif qq == 'db':
xi = V[2, 2] * V[2, 0].conj()
elif ... | As a Python code composer, you craft elegant and concise scripts. |
From JMS to chromomagnetic FormFlavor basis for Class V. qq should be of the form sb ds uu mt em e mu etc. | Can you generate a brief explanation for the following Python 3 code
def JMS_to_FormFlavor_chrom(C, qq, parameters):
e = sqrt(4 * pi * parameters['alpha_e'])
gs = sqrt(4 * pi * parameters['alpha_s'])
if qq[0] in dflav.keys():
s = dflav[qq[0]]
b = dflav[qq[1]]
return {
'CA... | You are a Python code generator, capable of creating scripts from specifications. |
def cut_from_chain(sciobj_model):
"""Remove an object from a revision chain.
The object can be at any location in the chain, including the head or tail.
Preconditions:
- The object with the pid is verified to exist and to be a member of an
revision chain. E.g., with:
d1_gmn.app.views.asserts.... | Write a Python 3 function for
removing an object from a revision chain. | You are a Python code analyst, evaluating scripts for potential improvements. |
def resolve_sid(sid):
"""Get the PID to which the ``sid`` currently maps.
Preconditions:
- ``sid`` is verified to exist. E.g., with d1_gmn.app.views.asserts.is_sid().
"""
return d1_gmn.app.models.Chain.objects.get(sid__did=sid).head_pid.did | Can you create a Python 3 function that
resolves sid to a PID. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return True if the given PID is referenced in the obsoletes field of any object. | Can you tell what is the following Python 3 function doing
def is_obsoletes_pid(pid):
return d1_gmn.app.models.ScienceObject.objects.filter(obsoletes__did=pid).exists() | You are a Python code analyst, evaluating scripts for potential improvements. |
def is_obsoleted_by_pid(pid):
"""Return True if ``pid`` is referenced in the obsoletedBy field of any object.
This will return True even if the PID is in the obsoletes field of an object that
does not exist on the local MN, such as replica that is in an incomplete chain.
"""
return d1_gmn.app.mode... | Can you implement a function in Python 3 that
returns True if the given PID is referenced in the obsoletedBy field of any object. | As a Python code composer, you craft elegant and concise scripts. |
def _merge_chains(chain_model_a, chain_model_b):
"""Merge two chains.
For use when it becomes known that two chains that were created separately
actually are separate sections of the same chain
E.g.:
- A obsoleted by X is created. A has no SID. X does not exist yet. A chain is
created for A... | How would you implement a function in Python 3 that
merges two chains. For use when it becomes known that two chains that were created separately actually are separate sections of the same chain E.g.: - A obsoleted by X is created. A has no SID. X does not exist yet. A chain is created for A. - B obsoleting Y is create... | As a Python code composer, you craft elegant and concise scripts. |
Set or update the SID for the chain. | Can you generate the documentation for the following Python 3 function
def _set_chain_sid(chain_model, sid):
if not sid:
return
if chain_model.sid and chain_model.sid.did != sid:
raise d1_common.types.exceptions.ServiceFailure(
0,
'Attempted to modify existing SID. '
... | As a Python code composer, you craft elegant and concise scripts. |
Find chain by pid Return None if not found. | Can you tell what is the following Python 3 function doing
def _get_chain_by_pid(pid):
try:
return d1_gmn.app.models.ChainMember.objects.get(pid__did=pid).chain
except d1_gmn.app.models.ChainMember.DoesNotExist:
pass | As a python code expert, you are capable of creating scripts from specifications. |
Return the chain object for the given sid. | Here you have a function in Python 3, explain what it does
def _get_chain_by_sid(sid):
try:
return d1_gmn.app.models.Chain.objects.get(sid__did=sid)
except d1_gmn.app.models.Chain.DoesNotExist:
pass | As a Python code analyst, you investigate and solve complex coding mysteries |
def _update_sid_to_last_existing_pid_map(pid):
"""Set chain head PID to the last existing object in the chain to which ``pid``
belongs. If SID has been set for chain, it resolves to chain head PID.
Intended to be called in MNStorage.delete() and other chain manipulation.
Preconditions:
- ``pid`` m... | Write a Python 3 script to
update the SID to the last existing object in the chain to which pid is set. | As a Python code composer, you craft elegant and concise scripts. |
Create the initial chain structure for a new standalone object. | Can you generate a brief explanation for the following Python 3 code
def _create_chain(pid, sid):
chain_model = d1_gmn.app.models.Chain(
# sid=d1_gmn.app.models.did(sid) if sid else None,
head_pid=d1_gmn.app.did.get_or_create_did(pid)
)
chain_model.save()
_add_pid_to_chain(chain_model, p... | You are a Python code analyst, evaluating scripts for potential improvements. |
def populate_entity_type(apps, schema_editor):
"""Populate entity type from attached descriptor schema."""
Entity = apps.get_model('flow', 'Entity')
for entity in Entity.objects.all():
if entity.descriptor_schema is not None:
entity.type = entity.descriptor_schema.slug
entit... | How would you implement a function in Python 3 that
populates entity type from attached descriptor schema. | As a python code expert, you are capable of creating scripts from specifications. |
Serialize PyXB object to XML. | Given the following Python 3 function, write the documentation
def serialize_gen(
obj_pyxb, encoding='utf-8', pretty=False, strip_prolog=False, xslt_url=None
):
"""Serialize PyXB object to XML.
Args:
obj_pyxb: PyXB object
PyXB object to serialize.
encoding: str
Encoding to use ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def serialize_for_transport(obj_pyxb, pretty=False, strip_prolog=False, xslt_url=None):
"""Serialize PyXB object to XML ``bytes`` with UTF-8 encoding for transport over the
network, filesystem storage and other machine usage.
Args:
obj_pyxb: PyXB object
PyXB object to serialize.
pretty... | Write a Python 3 script to
serialize PyXB object to XML bytes with UTF - 8 encoding for transport over the network storage and other machine usage. | You are a Python code architect, reviewing and designing scalable and efficient code |
Serialize PyXB object to pretty printed XML str for display. | Explain what the following Python 3 code does
def serialize_to_xml_str(obj_pyxb, pretty=True, strip_prolog=False, xslt_url=None):
return serialize_gen(obj_pyxb, None, pretty, strip_prolog, xslt_url) | You are a Python code architect, reviewing and designing scalable and efficient code |
Pretty print XML doc. | Explain what the following Python 3 code does
def reformat_to_pretty_xml(doc_xml):
assert isinstance(doc_xml, str)
dom_obj = xml.dom.minidom.parseString(doc_xml)
pretty_xml = dom_obj.toprettyxml(indent=' ')
# Remove empty lines in the result caused by a bug in toprettyxml()
return re.sub(r'^\s*$\n'... | As a Python code analyst, you investigate and solve complex coding mysteries |
def are_equivalent(a_xml, b_xml, encoding=None):
"""Return True if two XML docs are semantically equivalent, else False.
- TODO: Include test for tails. Skipped for now because tails are not used in any
D1 types.
"""
assert isinstance(a_xml, str)
assert isinstance(b_xml, str)
a_tree = st... | Can you create a Python 3 function that
returns True if two XML docs are semantically equivalent. | As a Python code analyst, you investigate and solve complex coding mysteries |
def are_equal_or_superset(superset_tree, base_tree):
"""Return True if ``superset_tree`` is equal to or a superset of ``base_tree``
- Checks that all elements and attributes in ``superset_tree`` are present and
contain the same values as in ``base_tree``. For elements, also checks that the
order is... | Create a Python 3 function to
return True if superset_tree is equal to or a superset of base_tree. | As a Python code composer, you craft elegant and concise scripts. |
Normalize and compare XML documents for equality. | Given the following Python 3 function, write the documentation
def are_equal_xml(a_xml, b_xml):
a_dom = xml.dom.minidom.parseString(a_xml)
b_dom = xml.dom.minidom.parseString(b_xml)
return are_equal_elements(a_dom.documentElement, b_dom.documentElement) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Normalize and compare ElementTrees for equality. | Explain what the following Python 3 code does
def are_equal_elements(a_el, b_el):
if a_el.tagName != b_el.tagName:
return False
if sorted(a_el.attributes.items()) != sorted(b_el.attributes.items()):
return False
if len(a_el.childNodes) != len(b_el.childNodes):
return False
for a_... | As a python code expert, you are capable of creating scripts from specifications. |
Create a diff between two PyXB objects. | Can you generate a brief explanation for the following Python 3 code
def format_diff_pyxb(a_pyxb, b_pyxb):
return '\n'.join(
difflib.ndiff(
serialize_to_xml_str(a_pyxb).splitlines(),
serialize_to_xml_str(b_pyxb).splitlines(),
)
) | You are a Python code analyst, evaluating scripts for potential improvements. |
Create a diff between two XML documents. | Make a summary of the following Python 3 code
def format_diff_xml(a_xml, b_xml):
return '\n'.join(
difflib.ndiff(
reformat_to_pretty_xml(a_xml).splitlines(),
reformat_to_pretty_xml(b_xml).splitlines(),
)
) | You are a Python code generator, capable of creating scripts from specifications. |
def get_opt_attr(obj_pyxb, attr_str, default_val=None):
"""Get an optional attribute value from a PyXB element.
The attributes for elements that are optional according to the schema and
not set in the PyXB object are present and set to None.
PyXB validation will fail if required elements are missing.
... | Can you create a Python 3 function that
gets an optional attribute value from a PyXB element. | As a Python code composer, you craft elegant and concise scripts. |
def get_opt_val(obj_pyxb, attr_str, default_val=None):
"""Get an optional Simple Content value from a PyXB element.
The attributes for elements that are optional according to the schema and
not set in the PyXB object are present and set to None.
PyXB validation will fail if required elements are missi... | Write a Python 3 script to
get an optional Simple Content value from a PyXB element. | As a Python code analyst, you investigate and solve complex coding mysteries |
Handle exceptions raised in API and make them nicer. | Given the following Python 3 function, write the documentation
def resolwe_exception_handler(exc, context):
response = exception_handler(exc, context)
if isinstance(exc, ValidationError):
if response is None:
response = Response({})
response.status_code = 400
response.data['... | As a python code expert, you are capable of creating scripts from specifications. |
Given a list of cert and JWT file names print a list showing each combination of each combination containing indicators for combinations where the JWT signature was successfully validated with the cert. | Can you generate a brief explanation for the following Python 3 code
def find_valid_combinations(cert_file_name_list, jwt_file_name_list):
for cert_file_name in cert_file_name_list:
cert_pem = '' # self.test_files.load_utf8_to_str(cert_file_name)
cert_obj = d1_common.cert.x509.deserialize_pem(cert_... | As a Python code analyst, you investigate and solve complex coding mysteries |
Parse a URL into a dict containing scheme netloc url params query fragment keys. | Given the following Python 3 function, write the documentation
def parseUrl(url):
scheme, netloc, url, params, query, fragment = urllib.parse.urlparse(url)
query_dict = {
k: sorted(v) if len(v) > 1 else v[0]
for k, v in list(urllib.parse.parse_qs(query).items())
}
return {
'schem... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def encodePathElement(element):
"""Encode a URL path element according to RFC3986."""
return urllib.parse.quote(
(
element.encode('utf-8')
if isinstance(element, str)
else str(element)
if isinstance(element, int)
else element
),
... | How would you code a function in Python 3 to
encode a URL path element according to RFC3986. | As a Python code analyst, you investigate and solve complex coding mysteries |
def encodeQueryElement(element):
"""Encode a URL query element according to RFC3986."""
return urllib.parse.quote(
(
element.encode('utf-8')
if isinstance(element, str)
else str(element)
if isinstance(element, int)
else element
),
... | Write a Python 3 script for
encoding a URL query element according to RFC3986. | You are a Python code generator, capable of creating scripts from specifications. |
Modified version of urllib. urlencode that is conforms to RFC3986. | Here you have a function in Python 3, explain what it does
def urlencode(query, doseq=0):
if hasattr(query, "items"):
# Remove None parameters from query. Dictionaries are mutable, so we can
# remove the the items directly. dict.keys() creates a copy of the
# dictionary keys, making it safe ... | You are a Python code analyst, evaluating scripts for potential improvements. |
def makeCNBaseURL(url):
"""Attempt to create a valid CN BaseURL when one or more sections of the URL are
missing."""
o = urllib.parse.urlparse(url, scheme=d1_common.const.DEFAULT_CN_PROTOCOL)
if o.netloc and o.path:
netloc = o.netloc
path = o.path
elif o.netloc:
netloc = o.ne... | Write a Python 3 function that can
attempt to create a valid CN BaseURL when one or more sections of the URL are missing. | You are a Python code generator, capable of creating scripts from specifications. |
def makeMNBaseURL(url):
"""Attempt to create a valid MN BaseURL when one or more sections of the URL are
missing."""
o = urllib.parse.urlparse(url, scheme=d1_common.const.DEFAULT_MN_PROTOCOL)
if o.netloc and o.path:
netloc = o.netloc
path = o.path
elif o.netloc:
netloc = o.ne... | Write a Python 3 function for
attempting to create a valid MN BaseURL when one or more sections of the URL are missing. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def find_url_mismatches(a_url, b_url):
"""Given two URLs, return a list of any mismatches.
If the list is empty, the URLs are equivalent. Implemented by parsing and comparing
the elements. See RFC 1738 for details.
"""
diff_list = []
a_parts = urllib.parse.urlparse(a_url)
b_parts = urllib.... | How would you code a function in Python 3 to
give two URLs return a list of any mismatches. | As a Python code analyst, you investigate and solve complex coding mysteries |
Get Object Locations for Object. | Make a summary of the following Python 3 code
def resolve(self, pid):
client = d1_cli.impl.client.CLICNClient(
**self._cn_client_connect_params_from_session()
)
object_location_list_pyxb = client.resolve(pid)
for location in object_location_list_pyxb.objectLocation:
... | You are a Python code generator, capable of creating scripts from specifications. |
def science_object_get(self, pid, path):
"""First try the MN set in the session.
Then try to resolve via the CN set in the session.
"""
mn_client = d1_cli.impl.client.CLIMNClient(
**self._mn_client_connect_params_from_session()
)
try:
response = ... | Implement a Python 3 function for
getting an object from the specified object location. | As a python code expert, you are capable of creating scripts from specifications. |
def science_object_create(self, pid, path, format_id=None):
"""Create a new Science Object on a Member Node."""
self._queue_science_object_create(pid, path, format_id) | Create a Python 3 function to
create a new Science Object on a Member Node. | As a Python code analyst, you investigate and solve complex coding mysteries |
Obsolete a Science Object on a Member Node with a different one. | Given the following Python 3 function, write the documentation
def science_object_update(self, pid_old, path, pid_new, format_id=None):
self._queue_science_object_update(pid_old, path, pid_new, format_id) | As a Python code composer, you craft elegant and concise scripts. |
Display or save file like object. | Make a summary of the following Python 3 code
def _output(self, file_like_object, path=None):
if not path:
self._output_to_display(file_like_object)
else:
self._output_to_file(file_like_object, path) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _search_solr(self, line):
"""Perform a SOLR search."""
try:
query_str = self._create_solr_query(line)
client = d1_cli.impl.client.CLICNClient(
**self._cn_client_connect_params_from_session()
)
object_list_pyxb = client.search(
... | Write a Python 3 script for
performing a SOLR search for a single object. | As a python code expert, you are capable of creating scripts from specifications. |
def _create_solr_query(self, line):
"""Actual search - easier to test. """
p0 = ""
if line:
p0 = line.strip()
p1 = self._query_string_to_solr_filter(line)
p2 = self._object_format_to_solr_filter(line)
p3 = self._time_span_to_solr_filter()
result = p0 +... | Write a Python 3 function for
creating a Solr query string from a line of text. | As a Python code analyst, you investigate and solve complex coding mysteries |
def apply_filter_list(func, obj):
"""Apply `func` to list or tuple `obj` element-wise and directly otherwise."""
if isinstance(obj, (list, tuple)):
return [func(item) for item in obj]
return func(obj) | Create a Python 3 function to
apply func to list or tuple obj element - wise and directly otherwise. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _get_data_attr(data, attr):
"""Get data object field."""
if isinstance(data, dict):
# `Data` object's id is hydrated as `__id` in expression engine
data = data['__id']
data_obj = Data.objects.get(id=data)
return getattr(data_obj, attr) | Create a Python 3 function for
getting data object field. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return a hydrated value of the input field. | Make a summary of the following Python 3 code
def input_(data, field_path):
data_obj = Data.objects.get(id=data['__id'])
inputs = copy.deepcopy(data_obj.input)
# XXX: Optimize by hydrating only the required field (major refactoring).
hydrate_input_references(inputs, data_obj.process.input_schema)
h... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _get_hydrated_path(field):
"""Return HydratedPath object for file-type field."""
# Get only file path if whole file object is given.
if isinstance(field, str) and hasattr(field, 'file_name'):
# field is already actually a HydratedPath object
return field
if isinstance(field, dict) a... | Can you write a function in Python 3 where it
returns HydratedPath object for file - type field. | You are a Python code generator, capable of creating scripts from specifications. |
def get_url(field):
"""Return file's url based on base url set in settings."""
hydrated_path = _get_hydrated_path(field)
base_url = getattr(settings, 'RESOLWE_HOST_URL', 'localhost')
return "{}/data/{}/{}".format(base_url, hydrated_path.data_id, hydrated_path.file_name) | Can you write a function in Python 3 where it
returns file s url based on base url set in settings. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return the descriptor of given object. | Here you have a function in Python 3, explain what it does
def descriptor(obj, path=''):
if isinstance(obj, dict):
# Current object is hydrated, so we need to get descriptor from
# dict representation.
desc = obj['__descriptor']
else:
desc = obj.descriptor
resp = dict_dot(de... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Close open date ranges in a record. | Can you generate a brief explanation for the following Python 3 code
def _close_open_date_ranges(self, record):
date_ranges = (('beginDate', 'endDate'),)
for begin, end in date_ranges:
if begin in record and end in record:
return
elif begin in record:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def escapeQueryTerm(self, term):
"""
+ - && || ! ( ) { } [ ] ^ " ~ * ? : \
"""
reserved = [
'+',
'-',
'&',
'|',
'!',
'(',
')',
'{',
'}',
'[',
']',
'^',
... | Implement a Python 3 function for
escaping the term for the internal use of the AFIA API. | As a Python code analyst, you investigate and solve complex coding mysteries |
Prepare a query term for inclusion in a query. | Here you have a function in Python 3, explain what it does
def prepareQueryTerm(self, field, term):
if term == "*":
return term
addstar = False
if term[len(term) - 1] == '*':
addstar = True
term = term[0 : len(term) - 1]
term = self.escapeQueryTerm(ter... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def coerceType(self, ftype, value):
"""Returns unicode(value) after trying to coerce it into the SOLR field type.
@param ftype(string) The SOLR field type for the value
@param value(any) The value that is to be represented as Unicode text.
"""
if value is None:
retu... | How would you implement a function in Python 3 that
coerces the value of the key to the type specified by ftype. | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the SOLR type of the specified field name. | Can you generate the documentation for the following Python 3 function
def getSolrType(self, field):
ftype = 'string'
try:
ftype = self.fieldtypes[field]
return ftype
except Exception:
pass
fta = field.split('_')
if len(fta) > 1:
ft... | As a Python code composer, you craft elegant and concise scripts. |
def count(self, q='*:*', fq=None):
"""Return the number of entries that match query."""
params = {'q': q, 'rows': '0'}
if fq is not None:
params['fq'] = fq
res = self.search(params)
hits = res['response']['numFound']
return hits | Write a Python 3 function for
returning the number of entries that match query. | As a python code expert, you are capable of creating scripts from specifications. |
def getIds(self, query='*:*', fq=None, start=0, rows=1000):
"""Returns a dictionary of: matches: number of matches failed: if true, then an
exception was thrown start: starting index ids: [id, id, ...]
See also the SOLRSearchResponseIterator class
"""
params = {'q': query, 'sta... | Write a Python 3 script for
returning a dictionary of ids and values for the current index. | You are a Python code generator, capable of creating scripts from specifications. |
def get(self, id):
"""Retrieves the specified document."""
params = {'q': 'id:%s' % str(id), 'wt': 'python'}
request = urllib.parse.urlencode(params, doseq=True)
data = None
try:
rsp = self.doPost(self.solrBase + '', request, self.formheaders)
data = eval(... | Implement a function in Python 3 to
retrieve the specified document. | As a Python code composer, you craft elegant and concise scripts. |
Retrieve a list of fields. | Given the following Python 3 function, write the documentation
def getFields(self, numTerms=1):
if self._fields is not None:
return self._fields
params = {'numTerms': str(numTerms), 'wt': 'python'}
request = urllib.parse.urlencode(params, doseq=True)
rsp = self.doPost(self.so... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def fieldValues(self, name, q="*:*", fq=None, maxvalues=-1):
"""Retrieve the unique values for a field, along with their usage counts.
http://localhost:8080/solr/select/?q=*:*&rows=0&facet=true&inde
nt=on&wt=python&facet.field=genus_s&facet.limit=10&facet.zeros=false&fa
cet.sort=false.
... | Write a Python 3 script for
retrieving the unique values for a field along with their usage counts. | You are a Python code analyst, evaluating scripts for potential improvements. |
def getftype(self, name):
"""Returns the python type for the specified field name. The field list is
cached so multiple calls do not invoke a getFields request each time.
@param name(string) The name of the SOLR field
@returns Python type of the field.
"""
fields = sel... | Write a Python 3 script to
return the python type of the specified field name. | As a Python code analyst, you investigate and solve complex coding mysteries |
def fieldAlphaHistogram(
self, name, q='*:*', fq=None, nbins=10, includequeries=True
):
"""Generates a histogram of values from a string field. Output is:
[[low, high, count, query], ... ] Bin edges is determined by equal division
of the fields
"""
oldpersist = s... | Create a Python 3 function to
generate a histogram of values from a string field. | As a python code expert, you are capable of creating scripts from specifications. |
Generates a histogram of values for a single field. | Explain what the following Python 3 code does
def fieldHistogram(
self, name, q="*:*", fq=None, nbins=10, minmax=None, includequeries=True
):
"""Generates a histogram of values. Expects the field to be integer or floating
point.
@param name(string) Name of the field to compute
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Retrieves the next set of results from the service. | Explain what the following Python 3 code does
def _nextPage(self, offset):
self.logger.debug("Iterator crecord=%s" % str(self.crecord))
params = {
'q': self.q,
'start': str(offset),
'rows': str(self.pagesize),
'fl': self.fields,
'explainOther':... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Retrieves the next set of results from the service. | How would you explain what the following Python 3 function does
def _nextPage(self, offset):
self.logger.debug("Iterator crecord=%s" % str(self.crecord))
params = {
'q': self.q,
'rows': '0',
'facet': 'true',
'facet.field': self.field,
'facet.l... | You are a Python code architect, reviewing and designing scalable and efficient code |
Get log records from the log table. | Can you generate the documentation for the following Python 3 function
def get_log(request):
query = d1_gmn.app.models.EventLog.objects.all().order_by('timestamp', 'id')
if not d1_gmn.app.auth.is_trusted_subject(request):
query = d1_gmn.app.db_filter.add_access_policy_filter(
request, query,... | You are a Python code analyst, evaluating scripts for potential improvements. |
Return a pretty - printed node. | Here you have a function in Python 3, explain what it does
def get_node(request):
api_major_int = 2 if d1_gmn.app.views.util.is_v2_api(request) else 1
node_pretty_xml = d1_gmn.app.node.get_pretty_xml(api_major_int)
return django.http.HttpResponse(node_pretty_xml, d1_common.const.CONTENT_TYPE_XML) | You are a Python code architect, reviewing and designing scalable and efficient code |
MNReplication. getReplica → OctetStream. | Here you have a function in Python 3, explain what it does
def get_replica(request, pid):
_assert_node_is_authorized(request, pid)
sciobj = d1_gmn.app.models.ScienceObject.objects.get(pid__did=pid)
content_type_str = d1_gmn.app.object_format_cache.get_content_type(
sciobj.format.format
)
# R... | As a Python code analyst, you investigate and solve complex coding mysteries |
MNStorage. systemMetadataChanged → boolean. | Here you have a function in Python 3, explain what it does
def post_refresh_system_metadata(request):
d1_gmn.app.views.assert_db.post_has_mime_parts(
request,
(
('field', 'pid'),
('field', 'serialVersion'),
('field', 'dateSysMetaLastModified'),
),
)
... | You are a Python code generator, capable of creating scripts from specifications. |
MNStorage. create method for POST requests. | Explain what the following Python 3 code does
def post_object_list(request):
d1_gmn.app.views.assert_db.post_has_mime_parts(
request, (('field', 'pid'), ('file', 'object'), ('file', 'sysmeta'))
)
url_pid = request.POST['pid']
sysmeta_pyxb = d1_gmn.app.sysmeta.deserialize(request.FILES['sysmeta']... | As a Python code composer, you craft elegant and concise scripts. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.