output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def profiler(self):
"""Creates a dictionary from the profile scheme(s)"""
logging.info('Loading profiles')
# Initialise variables
profiledata = defaultdict(make_dict)
reverse_profiledata = dict()
profileset = set()
# Find all the unique profiles to use with a set
... | Can you implement a function in Python 3 that
creates a dictionary of the profile scheme and the total number of genes in the typing scheme | As a Python code analyst, you investigate and solve complex coding mysteries |
Determines the sequence type of each strain based on comparisons to sequence type profiles | Can you generate a brief explanation for the following Python 3 code
def sequencetyper(self):
logging.info('Performing sequence typing')
for sample in self.runmetadata.samples:
if sample.general.bestassemblyfile != 'NA':
if type(sample[self.analysistype].allelenames) == list:... | As a Python code composer, you craft elegant and concise scripts. |
def mlstreporter(self):
""" Parse the results into a report"""
logging.info('Writing reports')
# Initialise variables
header_row = str()
combinedrow = str()
combined_header_row = str()
reportdirset = set()
mlst_dict = dict()
# Populate a set of all... | Write a Python 3 function for
parsing the results into a report | As a python code expert, you are capable of creating scripts from specifications. |
Parse the report and return the dictionary of results. | Can you generate a brief explanation for the following Python 3 code
def report_parse(self):
# Initialise lists
report_strains = list()
genus_list = list()
if self.analysistype == 'mlst':
for sample in self.runmetadata.samples:
try:
genus_l... | You are a Python code analyst, evaluating scripts for potential improvements. |
Utility function to call classes based on filename extension. | Given the following Python 3 function, write the documentation
def guess_type(filename, **kwargs):
extension = os.path.splitext(filename)[1]
case = {'.xls': Xls,
'.xlsx': Xlsx,
'.csv': Csv}
if extension and case.get(extension.lower()):
low_extension = extension.lower()
... | As a Python code composer, you craft elegant and concise scripts. |
This function takes the database path and a gene name as inputs and
returns the gene sequence contained in the file given by the gene name | How would you explain what the following Python 3 function does
def get_gene_seqs(database_path, gene):
gene_path = database_path + "/" + gene + ".fsa"
gene_seq = ""
# Open fasta file
with open(gene_path) as gene_file:
header = gene_file.readline()
for line in gene_file:
seq ... | You are a Python code analyst, evaluating scripts for potential improvements. |
This function opens the file resistens - overview. txt and reads the content of the file into a dict of dicts. The keys are the gene ID and the values are the list of known mutations in the database. | Explain what the following Python 3 code does
def get_db_mutations(mut_db_path, gene_list, res_stop_codons):
# Open resistens-overview.txt
try:
drugfile = open(mut_db_path, "r")
except:
sys.exit("Wrong path: %s"%(mut_db_path))
# Initiate variables
known_mutations = dict()
d... | As a Python code analyst, you investigate and solve complex coding mysteries |
This function finds the best sequence for a given gene from a list of hits found. | Can you generate a brief explanation for the following Python 3 code
def find_best_sequence(hits_found, specie_path, gene, silent_N_flag):
# Get information from the fisrt hit found
all_start = hits_found[0][0]
current_end = hits_found[0][1]
final_sbjct = hits_found[0][2]
final_qry = hits_found[0]... | As a Python code translator, you convert algorithms and pseudocode into Python. |
This function finds mis matches between two sequences. | Explain what the following Python 3 code does
def find_mismatches(gene, sbjct_start, sbjct_seq, qry_seq, alternative_overlaps = []):
# Initiate the mis_matches list that will store all found mis matcehs
mis_matches = []
# Find mis matches in RNA genes
if gene in RNA_gene_list:
mis_matches += f... | As a Python code composer, you craft elegant and concise scripts. |
This function finds mis matches in a sequence of nucleotides in a subject and query. | Can you generate a brief explanation for the following Python 3 code
def find_nucleotid_mismatches(sbjct_start, sbjct_seq, qry_seq, promoter = False):
# Initiate the mis_matches list that will store all found mis matcehs
mis_matches = []
sbjct_start = abs(sbjct_start)
seq_pos = sbjct_start
# ... | You are a Python code architect, reviewing and designing scalable and efficient code |
This function converts a codon to an amino acid. | How would you explain what the following Python 3 function does
def aa(codon):
codon = codon.upper()
aa = {"ATT": "I", "ATC": "I", "ATA": "I",
"CTT": "L", "CTC": "L", "CTA": "L", "CTG": "L", "TTA": "L", "TTG": "L",
"GTT": "V", "GTC": "V", "GTA": "V", "GTG": "V",
"TTT": "F", "... | As a Python code composer, you craft elegant and concise scripts. |
This function takes a sequence and returns the inframe gap of the sequence. | Here you have a function in Python 3, explain what it does
def get_inframe_gap(seq, nucs_needed = 3):
nuc_count = 0
gap_indel = ""
nucs = ""
for i in range(len(seq)):
# Check if the character is not a gap
if seq[i] != "-":
# Check if the indel is a 'clean'
# i... | As a Python code composer, you craft elegant and concise scripts. |
This function uses regex to find insert and delete indels in sequences
given as arguments. A list of these indels are returned. | Here you have a function in Python 3, explain what it does
def get_indels(sbjct_seq, qry_seq, start_pos):
seqs = [sbjct_seq, qry_seq]
indels = []
gap_obj = re.compile(r"-+")
for i in range(len(seqs)):
for match in gap_obj.finditer(seqs[i]):
pos = int(match.start())
gap =... | As a Python code analyst, you investigate and solve complex coding mysteries |
This function finds mismatches in a sequence in a given subject and query. | Make a summary of the following Python 3 code
def find_codon_mismatches(sbjct_start, sbjct_seq, qry_seq):
mis_matches = []
# Find start pos of first codon in frame, i_start
codon_offset = (sbjct_start-1) % 3
i_start = 0
if codon_offset != 0:
i_start = 3 - codon_offset
sbjct_start = ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
This function takes a gene name a list of mis matches found betreewn subject and query of a gene and returns a list of strings that can be written to the user. | Can you generate a brief explanation for the following Python 3 code
def write_output(gene, gene_name, mis_matches, known_mutations, known_stop_codon, unknown_flag, GENES):
RNA = False
known_header = "Mutation\tNucleotide change\tAmino acid change\tResistance\tPMID\n"
unknown_header = "Mutation\tNucleotide ... | As a python code expert, you are capable of creating scripts from specifications. |
def merge(self):
"""Try merging all the bravado_core models across all loaded APIs. If
duplicates occur, use the same bravado-core model to represent each, so
bravado-core won't treat them as different models when passing them
from one PyMacaron client stub to an other or when returning ... | Can you implement a function in Python 3 that
tries to merge all the bravado_core models across all loaded APIs and return them as a new set of bravado_core models. | As a Python code composer, you craft elegant and concise scripts. |
def _cmp_models(self, m1, m2):
"""Compare two models from different swagger APIs and tell if they are
equal (return 0), or not (return != 0)"""
# Don't alter m1/m2 by mistake
m1 = copy.deepcopy(m1)
m2 = copy.deepcopy(m2)
# Remove keys added by bravado-core
def _... | Can you create a Python 3 function that
compares two models and return True if they are equal False otherwise. | You are a Python code analyst, evaluating scripts for potential improvements. |
Creates a new object of the specified type. | Given the following Python 3 function, write the documentation
def create(
self,
name,
command_to_run,
description="",
environment_variables=None,
required_arguments=None,
required_arguments_default_values=None,
extra_data_to_post=None,
):
"""C... | As a Python code composer, you craft elegant and concise scripts. |
def put(
self,
id,
name,
description,
command_to_run,
environment_variables,
required_arguments,
required_arguments_default_values,
extra_data_to_put=None,
):
"""Updates a task type on the saltant server.
Args:
id (... | How would you implement a function in Python 3 that
updates the object type with the given parameters. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def response_data_to_model_instance(self, response_data):
"""Convert response data to a task type model.
Args:
response_data (dict): The data from the request's response.
Returns:
:class:`saltant.models.base_task_type.BaseTaskType`:
A model instance repr... | Write a Python 3 script to
convert the response data to a task type model. | You are a Python code architect, reviewing and designing scalable and efficient code |
def regression():
"""
Run regression testing - lint and then run all tests.
"""
# HACK: Start using hitchbuildpy to get around this.
Command("touch", DIR.project.joinpath("pathquery", "__init__.py").abspath()).run()
storybook = _storybook({}).only_uninherited()
#storybook.with_params(**{"pyt... | Write a Python 3 script to
run regression testing - lint and then run all tests. | You are a Python code generator, capable of creating scripts from specifications. |
def deploy(version):
"""
Deploy to pypi as specified version.
"""
NAME = "pathquery"
git = Command("git").in_dir(DIR.project)
version_file = DIR.project.joinpath("VERSION")
old_version = version_file.bytes().decode('utf8')
if version_file.bytes().decode("utf8") != version:
DIR.pr... | Create a Python 3 function to
deploy to pypi as specified version. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def hvenvup(package, directory):
"""
Install a new version of a package in the hitch venv.
"""
pip = Command(DIR.gen.joinpath("hvenv", "bin", "pip"))
pip("uninstall", package, "-y").run()
pip("install", DIR.project.joinpath(directory).abspath()).run() | Write a Python 3 script to
install a new version of a package in the hitch venv. | As a Python code composer, you craft elegant and concise scripts. |
def set_up(self):
"""Set up your applications and the test environment."""
self.path.state = self.path.gen.joinpath("state")
if self.path.state.exists():
self.path.state.rmtree(ignore_errors=True)
self.path.state.mkdir()
if self.path.gen.joinpath("q").exists():
... | Write a Python 3 script to
set up the application and test environment. | You are a Python code analyst, evaluating scripts for potential improvements. |
Validates single instance. Returns boolean value and store errors in self. errors
| Explain what the following Python 3 code does
def is_valid(self):
self.errors = []
for field in self.get_all_field_names_declared_by_user():
getattr(type(self), field).is_valid(self, type(self), field)
field_errors = getattr(type(self), field).errors(self)
self.error... | As a Python code analyst, you investigate and solve complex coding mysteries |
Run the analyses and create the object objects and report objects for each sample. | Given the following Python 3 function, write the documentation
def main(self):
logging.info('Starting {} analysis pipeline'.format(self.analysistype))
self.createobjects()
# Run the genesipping analyses
self.methods()
# Determine if the analyses are complete
self.complete... | You are a Python code architect, reviewing and designing scalable and efficient code |
Run the typing methods | Here you have a function in Python 3, explain what it does
def methods(self):
self.contamination_detection()
ReportImage(self, 'confindr')
self.run_genesippr()
ReportImage(self, 'genesippr')
self.run_sixteens()
self.run_mash()
self.run_gdcs()
ReportImage(s... | You are a Python code architect, reviewing and designing scalable and efficient code |
def contamination_detection(self):
"""
Calculate the levels of contamination in the reads
"""
self.qualityobject = quality.Quality(self)
self.qualityobject.contamination_finder(input_path=self.sequencepath,
report_path=self.reportpa... | Can you write a function in Python 3 where it
calculates the levels of contamination in the reads | As a Python code analyst, you investigate and solve complex coding mysteries |
Run the genesippr analyses | Can you tell what is the following Python 3 function doing
def run_genesippr(self):
GeneSippr(args=self,
pipelinecommit=self.commit,
startingtime=self.starttime,
scriptpath=self.homepath,
analysistype='genesippr',
cutoff=0... | As a Python code analyst, you investigate and solve complex coding mysteries |
Run the 16S analyses using the filtered database | Explain what the following Python 3 code does
def run_sixteens(self):
SixteensFull(args=self,
pipelinecommit=self.commit,
startingtime=self.starttime,
scriptpath=self.homepath,
analysistype='sixteens_full',
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Run MASH to determine the closest refseq genomes | How would you explain what the following Python 3 function does
def run_mash(self):
self.pipeline = True
mash.Mash(inputobject=self,
analysistype='mash') | As a Python code composer, you craft elegant and concise scripts. |
def complete(self):
"""
Determine if the analyses of the strains are complete e.g. there are no missing GDCS genes, and the
sample.general.bestassemblyfile != 'NA'
"""
# Boolean to store the completeness of the analyses
allcomplete = True
# Clear the list of samp... | Write a Python 3 function that can
determine if the analyses of the strains are complete e. g. there are no missing GDCS genes and there are no missing GDCS genes. | As a Python code analyst, you investigate and solve complex coding mysteries |
Decorator to prevent an operation from being executed when the related uri resource is still in use. | How would you explain what the following Python 3 function does
def protected_operation(fn):
@functools.wraps(fn)
def advice(parent_object, *args, **kw):
response = _advice(parent_object.request)
if response is not None:
return response
else:
return fn(parent_obje... | As a Python code analyst, you investigate and solve complex coding mysteries |
Decorator to prevent an operation from being executed when the related uri resource is still in use. | Make a summary of the following Python 3 code
def protected_operation_with_request(fn):
@functools.wraps(fn)
def wrapped(request, *args, **kwargs):
response = _advice(request)
if response is not None:
return response
else:
return fn(request, *args, **kwargs)
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def protected_view(view, info):
"""allows adding `protected=True` to a view_config`"""
if info.options.get('protected'):
def wrapper_view(context, request):
response = _advice(request)
if response is not None:
return response
else:
ret... | Write a Python 3 script to
allow adding protected = True to a view_config | As a Python code analyst, you investigate and solve complex coding mysteries |
Create tables if they don t exist | Can you generate a brief explanation for the following Python 3 code
def syncdb(pool=None):
from flask_philo_sqlalchemy.schema import Base # noqa
from flask_philo_sqlalchemy.orm import BaseModel # noqa
from flask_philo_sqlalchemy.connection import create_pool
if pool is None:
pool = create_po... | As a python code expert, you are capable of creating scripts from specifications. |
checks if a given package is installed on pip | Given the following Python 3 function, write the documentation
def checkInstalledPip(package, speak=True, speakSimilar=True):
packages = sorted([i.key for i in pip.get_installed_distributions()])
installed = package in packages
similar = None
if not installed:
similar = [pkg for pkg in packages... | You are a Python code architect, reviewing and designing scalable and efficient code |
def checkInstalledBrew(package, similar=True, speak=True, speakSimilar=True):
"""checks if a given package is installed on homebrew"""
packages = subprocess.check_output(['brew', 'list']).split()
installed = package in packages
similar = []
if not installed:
similar = [pkg for pkg in packag... | Write a Python 3 script to
check if a given package is installed on homebrew | You are a Python code analyst, evaluating scripts for potential improvements. |
def init_module(remote_credences=None,local_path=None):
"""Connnexion informations : remote_credences for remote acces OR local_path for local access"""
if remote_credences is not None:
RemoteConnexion.HOST = remote_credences["DB"]["host"]
RemoteConnexion.USER = remote_credences["DB"]["user"]
... | Create a Python 3 function to
initialize the SQL module with the given credences. | As a Python code composer, you craft elegant and concise scripts. |
def cree_local_DB(scheme):
"""Create emmpt DB according to the given scheme : dict { table : [ (column_name, column_type), .. ]}
Usefull at installation of application (and for developement)
"""
conn = LocalConnexion()
req = ""
for table, fields in scheme.items():
req += f"DROP TABLE IF ... | Create a Python 3 function to
create emmpt DB according to the given scheme. | As a Python code composer, you craft elegant and concise scripts. |
Execute one or many requests
requete_SQL may be a tuple or a list of such tuples Return the result or a list of results
| Make a summary of the following Python 3 code
def execute(self, requete_SQL):
try:
cursor = self.cursor()
if isinstance(requete_SQL,tuple):
res = self._execute_one(cursor,*requete_SQL)
else:
res = []
for r in requete_SQL:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Renvoie un dictionnaire dont les champs dont compatibles avec SQL
Utilise Json. Attention à None et non - null et non - null | Given the following Python 3 function, write the documentation
def jsonise(dic):
d = {}
for k, v in dic.items():
if type(v) in abstractRequetesSQL.TYPES_PERMIS:
d[k] = v
else:
try:
d[k] = json.dumps(v, ensure_ascii=False, cls=fo... | You are a Python code analyst, evaluating scripts for potential improvements. |
Insert row from datas. | Explain what the following Python 3 code does
def insert(table, datas, avoid_conflict=False):
if avoid_conflict:
debut = """INSERT INTO {table} {ENTETE_INSERT} VALUES {BIND_INSERT} ON CONFLICT DO NOTHING"""
else:
debut = """INSERT INTO {table} {ENTETE_INSERT} VALUES {BIND_INSERT}... | As a Python code analyst, you investigate and solve complex coding mysteries |
Update row with Id from table. Set fields given by dic. | How would you explain what the following Python 3 function does
def update(cls,table, dic, Id):
if dic:
req = "UPDATE {table} SET {SET} WHERE id = " + cls.named_style.format('__id') + " RETURNING * "
r = abstractRequetesSQL.formate(req, SET=dic, table=table, args=dict(dic, __id=Id))
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Create ONE row from dic and returns the entry created | Can you generate a brief explanation for the following Python 3 code
def cree(table, dic, avoid_conflict=False):
if avoid_conflict:
req = """ INSERT INTO {table} {ENTETE_INSERT} VALUES {BIND_INSERT} ON CONFLICT DO NOTHING RETURNING *"""
else:
req = """ INSERT INTO {table} {ENTETE... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Remove entries matchin given condition
| Can you generate a brief explanation for the following Python 3 code
def supprime(cls,table, **kwargs):
assert len(kwargs) == 1
field, value = kwargs.popitem()
req = f"""DELETE FROM {table} WHERE {field} = """ + cls.mark_style
args = (value,)
return MonoExecutant((req, args)) | You are a Python code generator, capable of creating scripts from specifications. |
def trace(self, context, obj):
"""Enumerate the children of the given object, as would be visible and utilized by dispatch."""
root = obj
if isroutine(obj):
yield Crumb(self, root, endpoint=True, handler=obj, options=opts(obj))
return
for name, attr in getmembers(obj if isclass(obj) else obj.__cl... | Create a Python 3 function to
enumerate the children of the given object as would be visible and utilized by dispatch. | As a python code expert, you are capable of creating scripts from specifications. |
Main entry - point for calling layouts directly as a program. | Here you have a function in Python 3, explain what it does
def main(argv=None):
'''
Main entry-point for calling layouts directly as a program.
'''
# Prep argparse
ap = argparse.ArgumentParser(
description='Basic query options for Python HID-IO Layouts repository',
)
ap.add_argument(... | You are a Python code generator, capable of creating scripts from specifications. |
def retrieve_github_cache(self, github_path, version, cache_dir, token):
'''
Retrieves a cache of the layouts git repo from GitHub
@param github_path: Location of the git repo on GitHub (e.g. hid-io/layouts)
@param version: git reference for the version to download (e.g. master)
... | Can you create a Python 3 function that
retrieves a cache of the layouts git repo from GitHub and store it in cache_dir. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the layout with the given name | Explain what the following Python 3 code does
def get_layout(self, name):
'''
Returns the layout with the given name
'''
layout_chain = []
# Retrieve initial layout file
try:
json_data = self.json_files[self.layout_names[name]]
except KeyError:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Squash a list of layouts into one Layout with the same data. | Can you generate the documentation for the following Python 3 function
def squash_layouts(self, layouts):
'''
Returns a squashed layout
The first element takes precedence (i.e. left to right).
Dictionaries are recursively merged, overwrites only occur on non-dictionary entries.
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def dict(self, name, key_caps=False, value_caps=False):
'''
Returns a JSON dict
@key_caps: Converts all dictionary keys to uppercase
@value_caps: Converts all dictionary values to uppercase
@return: JSON item (may be a variable, list or dictionary)
'''
# Invalid... | How would you code a function in Python 3 to
return a JSON dictionary of the specified key and value. | You are a Python code generator, capable of creating scripts from specifications. |
Do a lookup for the locale code that is set for this layout. | Can you generate the documentation for the following Python 3 function
def locale(self):
'''
Do a lookup for the locale code that is set for this layout.
NOTE: USB HID specifies only 35 different locales. If your layout does not fit, it should be set to Undefined/0
@return: Tuple (<USB... | As a python code expert, you are capable of creating scripts from specifications. |
def compose(self, text, minimal_clears=False, no_clears=False):
'''
Returns the sequence of combinations necessary to compose given text.
If the text expression is not possible with the given layout an ComposeException is thrown.
Iterate over the string, converting each character into ... | Write a Python 3 function for
generating a sequence of combinations needed to compose given text. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Run the analyses in the correct order. | Can you tell what is the following Python 3 function doing
def main(self):
logging.info('Starting {at} analysis pipeline'.format(at=self.analysistype))
# Create the objects to be used in the analyses
objects = Objectprep(self)
objects.objectprep()
self.runmetadata = objects.sampl... | As a Python code composer, you craft elegant and concise scripts. |
def genus_specific(self):
"""
For genus-specific targets, MLST and serotyping, determine if the closest refseq genus is known - i.e. if 16S
analyses have been performed. Perform the analyses if required
"""
# Initialise a variable to store whether the necessary analyses have alre... | Can you create a Python 3 function that
determines if the closest refseq genus is known - i. e. if the MASH analyses are performed and if required is True then perform the analyses if required is False then perform the analyses if required is True. | As a Python code composer, you craft elegant and concise scripts. |
def pause():
"""Tell iTunes to pause"""
if not settings.platformCompatible():
return False
(output, error) = subprocess.Popen(["osascript", "-e", PAUSE], stdout=subprocess.PIPE).communicate() | How would you code a function in Python 3 to
tell iTunes to pause | As a python code expert, you are capable of creating scripts from specifications. |
Tell iTunes to resume | Can you generate the documentation for the following Python 3 function
def resume():
if not settings.platformCompatible():
return False
(output, error) = subprocess.Popen(["osascript", "-e", RESUME], stdout=subprocess.PIPE).communicate() | As a Python code analyst, you investigate and solve complex coding mysteries |
def skip():
"""Tell iTunes to skip a song"""
if not settings.platformCompatible():
return False
(output, error) = subprocess.Popen(["osascript", "-e", SKIP], stdout=subprocess.PIPE).communicate() | Write a Python 3 script to
tell iTunes to skip a song | You are a Python code generator, capable of creating scripts from specifications. |
def play(song, artist=None, album=None):
"""Tells iTunes to play a given song/artist/album - MACOSX ONLY"""
if not settings.platformCompatible():
return False
if song and not artist and not album:
(output, error) = subprocess.Popen(["osascript", "-e", DEFAULT_ITUNES_PLAY % (song, song, song)], stdout=subproces... | How would you implement a function in Python 3 that
tells iTunes to play a given song artist or album. | You are a Python code architect, reviewing and designing scalable and efficient code |
This is a class decorator that declares a class to provide a set of services. | Can you generate a brief explanation for the following Python 3 code
def service_provider(*services):
def real_decorator(clazz):
instance = clazz()
for service in services:
global_lookup.add(service, instance)
return clazz
return real_decorator | As a Python code analyst, you investigate and solve complex coding mysteries |
def syllabify(word):
'''Syllabify the given word, whether simplex or complex.'''
compound = bool(re.search(r'(-| |=)', word))
syllabify = _syllabify_compound if compound else _syllabify_simplex
syllabifications = list(syllabify(word))
for word, rules in rank(syllabifications):
# post-proces... | Create a Python 3 function for
syllabifying the given word whether simplex or complex. | As a Python code analyst, you investigate and solve complex coding mysteries |
This function applies T6 to a word. | How would you explain what the following Python 3 function does
def apply_T6(word):
'''If a VVV-sequence contains a long vowel, there is a syllable boundary
between it and the third vowel, e.g. [kor.ke.aa], [yh.ti.öön], [ruu.an],
[mää.yt.te].'''
WORD = word
offset = 0
for vvv in vvv_sequences(W... | As a Python code composer, you craft elegant and concise scripts. |
A function to apply T7 to a VVV - sequence. | Can you generate the documentation for the following Python 3 function
def apply_T7(word):
'''If a VVV-sequence does not contain a potential /i/-final diphthong,
there is a syllable boundary between the second and third vowels, e.g.
[kau.an], [leu.an], [kiu.as].'''
WORD = word
offset = 0
for vv... | As a Python code analyst, you investigate and solve complex coding mysteries |
def apply_T8(word):
'''Split /ie/, /uo/, or /yö/ sequences in syllables that do not take
primary stress.'''
WORD = word
offset = 0
for vv in tail_diphthongs(WORD):
i = vv.start(1) + 1 + offset
WORD = WORD[:i] + '.' + WORD[i:]
offset += 1
RULE = ' T8' if word != WORD els... | Can you write a function in Python 3 where it
splits the syllables that do not take primary stress. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return the number of unstressed heavy syllables. | Can you generate the documentation for the following Python 3 function
def wsp(word):
'''Return the number of unstressed heavy syllables.'''
HEAVY = r'[ieaAoO]{1}[\.]*(u|y)[^ieaAoO]+(\.|$)'
# # if the word is not monosyllabic, lop off the final syllable, which is
# # extrametrical
# if '.' in word:... | As a Python code composer, you craft elegant and concise scripts. |
Return the number of stressed light syllables. | Can you tell what is the following Python 3 function doing
def pk_prom(word):
'''Return the number of stressed light syllables.'''
LIGHT = r'[ieaAoO]{1}[\.]*(u|y)(\.|$)'
# # if the word is not monosyllabic, lop off the final syllable, which is
# # extrametrical
# if '.' in word:
# word = wo... | You are a Python code analyst, evaluating scripts for potential improvements. |
Match files with an extension - e. g. js txt | Explain what the following Python 3 code does
def ext(self, extension):
new_pathq = copy(self)
new_pathq._pattern.ext = extension
return new_pathq | As a Python code analyst, you investigate and solve complex coding mysteries |
Split / ie sequences in syllables that do not take primary stress. | Given the following Python 3 function, write the documentation
def apply_T8(word):
'''Split /ie/ sequences in syllables that do not take primary stress.'''
WORD = word
offset = 0
for ie in ie_sequences(WORD):
i = ie.start(1) + 1 + offset
WORD = WORD[:i] + '.' + WORD[i:]
offset +... | As a python code expert, you are capable of creating scripts from specifications. |
Split / iu sequences that do not appear in the first second or final
syllables. | Make a summary of the following Python 3 code
def apply_T9(word):
'''Split /iu/ sequences that do not appear in the first, second, or final
syllables.'''
WORD = word
index = 0
offset = 0
for iu in iu_sequences(WORD):
if iu.start(1) != index:
i = iu.start(1) + 1 + offset
... | You are a Python code generator, capable of creating scripts from specifications. |
def import_class(import_str):
"""Returns a class from a string including module and class."""
mod_str, _sep, class_str = import_str.rpartition('.')
try:
__import__(mod_str)
return getattr(sys.modules[mod_str], class_str)
except (ValueError, AttributeError):
raise ImportError('Cla... | Write a Python 3 function that can
return a class from a string including module and class. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def import_object_ns(name_space, import_str, *args, **kwargs):
"""Tries to import object from default namespace.
Imports a class and return an instance of it, first by trying
to find the class in a default namespace, then failing back to
a full path if not found in the default namespace.
"""
im... | Create a Python 3 function to
try to import an object from the default namespace and returns an instance of it | As a Python code translator, you convert algorithms and pseudocode into Python. |
installs the virtualbox if the distribution is ubuntu | Here you have a function in Python 3, explain what it does
def install_virtualbox(distribution, force_setup=False):
if 'ubuntu' in distribution:
with hide('running', 'stdout'):
sudo('DEBIAN_FRONTEND=noninteractive apt-get update')
sudo("sudo DEBIAN_FRONTEND=noninteractive apt-get -y... | You are a Python code architect, reviewing and designing scalable and efficient code |
Run the necessary methods in the correct order for the mashsippr analysis pipeline | Can you generate a brief explanation for the following Python 3 code
def runner(self):
printtime('Starting mashsippr analysis pipeline', self.starttime)
if not self.pipeline:
# Create the objects to be used in the analyses
objects = Objectprep(self)
objects.objectprep... | You are a Python code architect, reviewing and designing scalable and efficient code |
Create widgets and store them in self. widgets | Explain what the following Python 3 code does
def cree_widgets(self):
for t in self.FIELDS:
if type(t) is str:
attr, kwargs = t, {}
else:
attr, kwargs = t[0], t[1].copy()
self.champs.append(attr)
is_editable = kwargs.pop("is_editabl... | As a Python code composer, you craft elegant and concise scripts. |
Function for splitting a string into a list of characters preserving surrogates. | Here you have a function in Python 3, explain what it does
def preservesurrogates(s):
if not isinstance(s, six.text_type):
raise TypeError(u"String to split must be of type 'unicode'!")
surrogates_regex_str = u"[{0}-{1}][{2}-{3}]".format(HIGH_SURROGATE_START,
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Helper function for taking a Unicode scalar value and returning a Unicode character. | Can you tell what is the following Python 3 function doing
def _unichr(i):
if not isinstance(i, int):
raise TypeError
try:
return six.unichr(i)
except ValueError:
# Workaround the error "ValueError: unichr() arg not in range(0x10000) (narrow Python build)"
return struct.pack(... | As a python code expert, you are capable of creating scripts from specifications. |
This function transforms a string into a UAX44 - LM2 string. | Can you generate a brief explanation for the following Python 3 code
def _uax44lm2transform(s):
result = s
# For the regex, we are using lookaround assertions to verify that there is a word character immediately before (the
# lookbehind assertion (?<=\w)) and immediately after (the lookahead assertion (?=\... | As a python code expert, you are capable of creating scripts from specifications. |
Helper function to convert a Unicode scalar value from a string to a Unicode scalar value. | Can you generate the documentation for the following Python 3 function
def _to_unicode_scalar_value(s):
if len(s) == 1:
return ord(s)
elif len(s) == 2:
return (ord(s[0]) - 0xD800) * 0x0400 + (ord(s[1]) - 0xDC00) + 0x10000
else:
raise ValueError | You are a Python code architect, reviewing and designing scalable and efficient code |
Helper function for looking up the derived name prefix associated with a Unicode scalar value. | Given the following Python 3 function, write the documentation
def _get_nr_prefix(i):
for lookup_range, prefix_string in _nr_prefix_strings.items():
if i in lookup_range:
return prefix_string
raise ValueError("No prefix string associated with {0}!".format(i)) | You are a Python code analyst, evaluating scripts for potential improvements. |
This function will perform a case folding on the input string s. | Here you have a function in Python 3, explain what it does
def casefold(s, fullcasefold=True, useturkicmapping=False):
if not isinstance(s, six.text_type):
raise TypeError(u"String to casefold must be of type 'unicode'!")
lookup_order = "CF"
if not fullcasefold:
lookup_order = "CS"
if us... | As a python code expert, you are capable of creating scripts from specifications. |
Function for parsing the Unicode Character Database and generating a lookup table. | Can you generate the documentation for the following Python 3 function
def _build_unicode_character_database(self):
filename = "UnicodeData.txt"
current_dir = os.path.abspath(os.path.dirname(__file__))
tag = re.compile(r"<\w+?>")
with codecs.open(os.path.join(current_dir, filename), mode... | You are a Python code analyst, evaluating scripts for potential improvements. |
def lookup_by_name(self, name):
"""
Function for retrieving the UnicodeCharacter associated with a name. The name lookup uses the loose matching
rule UAX44-LM2 for loose matching. See the following for more info:
https://www.unicode.org/reports/tr44/#UAX44-LM2
For example:
... | Write a Python 3 function for
functioning for retrieving the UnicodeCharacter associated with a name. | You are a Python code analyst, evaluating scripts for potential improvements. |
This method returns a generator that yields UnicodeCharacter instances for the given partial name. | How would you explain what the following Python 3 function does
def lookup_by_partial_name(self, partial_name):
for k, v in self._name_database.items():
if _uax44lm2transform(partial_name) in k:
yield v | As a Python code translator, you convert algorithms and pseudocode into Python. |
Function for parsing Unicode character set info from the Unicode CharacterSet Database and generating a lookup table. | Make a summary of the following Python 3 code
def _load_unicode_block_info(self):
filename = "Blocks.txt"
current_dir = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(current_dir, filename), mode="r", encoding="utf-8") as fp:
for line in fp:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Function for parsing the Unicode Character
database and generating a lookup table. | How would you explain what the following Python 3 function does
def _build_casefold_map(self):
self._casefold_map = defaultdict(dict)
filename = "CaseFolding.txt"
current_dir = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(current_dir, filename), mode="r", enco... | As a Python code analyst, you investigate and solve complex coding mysteries |
def lookup(self, c, lookup_order="CF"):
"""
Function to lookup a character in the casefold map.
The casefold map has four sub-tables, the 'C' or common table, the 'F' or
full table, the 'S' or simple table and the 'T' or the Turkic special
case table. These tables correspond to... | Can you write a function in Python 3 where it
functions to lookup a character in the casefold map. | You are a Python code generator, capable of creating scripts from specifications. |
Load a RegistryResponse from a dictionary or a string. | Explain what the following Python 3 code does
def load_from_json(data):
if isinstance(data, str):
data = json.loads(data)
applications = [
ApplicationResponse.load_from_json(a) for a in data['applications']
] if data['applications'] is not None else []
return Regi... | You are a Python code analyst, evaluating scripts for potential improvements. |
Load a : class : ApplicationResponse from a dictionary or string. | Make a summary of the following Python 3 code
def load_from_json(data):
if isinstance(data, str):
data = json.loads(data)
items = [Item.load_from_json(a) for a in data['items']] if data['items'] is not None else []
return ApplicationResponse(
data['title'], data['uri'], d... | You are a Python code generator, capable of creating scripts from specifications. |
def load_from_json(data):
"""
Load a :class:`Item` from a dictionary ot string (that will be parsed
as json)
"""
if isinstance(data, str):
data = json.loads(data)
return Item(data['title'], data['uri']) | Can you write a function in Python 3 where it
loads a : class : Item from a dictionary ot string | You are a Python code analyst, evaluating scripts for potential improvements. |
Apply T11 to a word. | Given the following Python 3 function, write the documentation
def apply_T11(word):
'''If a VVV sequence contains a /u, y/-final diphthong and the third vowel
is /i/, there is a syllable boundary between the diphthong and /i/.'''
WORD = word
offset = 0
for vvv in t11_vvv_sequences(WORD):
# ... | You are a Python code generator, capable of creating scripts from specifications. |
Syllabify the given word. | Can you tell what is the following Python 3 function doing
def _syllabify_simplex(word):
'''Syllabify the given word.'''
word, rules = apply_T1(word)
if re.search(r'[^ieAyOauo]*([ieAyOauo]{2})[^ieAyOauo]*', word):
word, T2 = apply_T2(word)
word, T8 = apply_T8(word)
word, T9 = apply_... | You are a Python code architect, reviewing and designing scalable and efficient code |
T1 - > T1. | Can you tell what is the following Python 3 function doing
def T1(word):
'''Insert a syllable boundary in front of every CV sequence.'''
# split consonants and vowels: 'balloon' -> ['b', 'a', 'll', 'oo', 'n']
WORD = [i for i in re.split(r'([ieaouäöy]+)', word, flags=FLAGS) if i]
# keep track of which s... | You are a Python code architect, reviewing and designing scalable and efficient code |
def T2(word, rules):
'''Split any VV sequence that is not a genuine diphthong or long vowel.
E.g., [ta.e], [ko.et.taa]. This rule can apply within VVV+ sequences.'''
WORD = word
offset = 0
for vv in vv_sequences(WORD):
seq = vv.group(1)
if not phon.is_diphthong(seq) and not phon.is... | Write a Python 3 function that can
split any VV sequence that is not a genuine diphthong or long vowel. Eg., [ ta. e ko. et. taa ]. This rule can apply within VVV + sequences. | You are a Python code generator, capable of creating scripts from specifications. |
Join IE UO or Yö or Yö sequences in syllables that take primary
stress. | Make a summary of the following Python 3 code
def T8(word, rules):
'''Join /ie/, /uo/, or /yö/ sequences in syllables that take primary
stress.'''
WORD = word
try:
vv = tail_diphthongs(WORD)
i = vv.start(1) + 1
WORD = WORD[:i] + word[i + 1:]
except AttributeError:
p... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def pk_prom(word):
'''Return the number of stressed light syllables.'''
violations = 0
stressed = []
for w in extract_words(word):
stressed += w.split('.')[2:-1:2] # odd syllables, excl. word-initial
# (CVV = light)
for syll in stressed:
if phon.is_vowel(syll[-1]):
... | Can you create a Python 3 function that
returns the number of stressed light syllables. | You are a Python code analyst, evaluating scripts for potential improvements. |
Return an iterator over the ANSI escape sequences that can be used to render the image. | Can you generate a brief explanation for the following Python 3 code
def ansi_format_iter( self, x_start=0, y_start=0, width=None, height=None, frame=0, columns=1, downsample=1 ):
image = self.get_image()
frames = []
frame_count = 1 if not hasattr( image, 'n_frames' ) else image.n_frames
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Return an iterator over the ANSI escape sequences that can be used to render the image. | Can you generate the documentation for the following Python 3 function
def ansi_format_iter( self, x_start=0, y_start=0, width=None, height=None, frame=0, columns=1, downsample=1, frame_index=None, frame_flip_v=0, frame_flip_h=0 ):
assert x_start in range( 0, self.width )
assert y_start in range( 0, se... | As a Python code analyst, you investigate and solve complex coding mysteries |
Purges a single fastly url from fastly. | Given the following Python 3 function, write the documentation
def main():
parser = OptionParser(description=
"Purge a single url from fastly.")
parser.add_option("-k", "--key", dest="apikey",
default="", help="fastly api key")
parser.add_option("-H", "--host", dest="host... | As a python code expert, you are capable of creating scripts from specifications. |
def set_callbacks(self, **dic_functions):
"""Register callbacks needed by the interface object"""
for action in self.interface.CALLBACKS:
try:
f = dic_functions[action]
except KeyError:
pass
else:
setattr(self.interface.... | Write a Python 3 script for
registering callbacks needed by the interface object. | You are a Python code generator, 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.