output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def get_reference_templates(self, ref_types):
"""Return the reference templates for the types as an ordered dictionary."""
return OrderedDict([(x, self.get_reference_template(x)) for x in ref_types]) | Can you implement a function in Python 3 that
returns the reference templates for the types as an ordered dictionary. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_reference_template(self, ref_type):
"""Return the reference template for the type as an ordered dictionary.
Zotero.item_template() caches data after the first API call.
"""
template = self._zotero_lib.item_template(ref_type)
return OrderedDict(sorted(template.items(), ke... | How would you code a function in Python 3 to
return the reference template for the type as an ordered dictionary. | As a Python code composer, you craft elegant and concise scripts. |
def reference_extra_field(self, field, index):
"""Return the value of the field in 'extra', otherwise ''."""
ref_data = self.reference_data(index)
extra_fields = ref_data["extra"].split("\n")
field_id = field + ":"
matched = next((x for x in extra_fields if x.startswith(field_id)... | Write a Python 3 script to
return the value of the field in extra otherwise empty. | As a Python code analyst, you investigate and solve complex coding mysteries |
def reference_id(self, index):
"""Return the reference ID (locally defined)."""
# TODO Include ISBN and ISSN?
doi = self.reference_doi(index)
if doi:
return doi
else:
pmid = self.reference_pmid(index)
if pmid:
return "PMID_" + p... | Write a Python 3 function that can
return the reference ID for the specified index. | You are a Python code analyst, evaluating scripts for potential improvements. |
def reference_doi(self, index):
"""Return the reference DOI."""
return self.reference_data(index).get("DOI", self.reference_extra_field("DOI", index)) | Can you implement a function in Python 3 that
returns the reference DOI. | You are a Python code architect, reviewing and designing scalable and efficient code |
def reference_creator_surnames(self, index):
"""Return as a list the surnames of the reference creators (locally defined)."""
# TODO Not true, ex: ISBN 978-1-4398-3778-8. Return all creator types?
# Academic books published as a collection of chapters contributed by
# different authors h... | How would you code a function in Python 3 to
return as a list the surnames of the reference creators ( locally defined. | You are a Python code analyst, evaluating scripts for potential improvements. |
def reference_year(self, index):
"""Return the reference publication year."""
# TODO Use meta:parsedDate field instead?
ref_date = self.reference_date(index)
try:
# NB: datetime.year returns an int.
return parse(ref_date).year
except ValueError:
... | Can you create a Python 3 function that
returns the reference publication year. | As a python code expert, you are capable of creating scripts from specifications. |
Return the reference journal name. | Given the following Python 3 function, write the documentation
def reference_journal(self, index):
# TODO Change the column name 'Journal' to an other?
ref_type = self.reference_type(index)
if ref_type == "journalArticle":
return self.reference_data(index)["publicationTitle"]
... | As a Python code composer, you craft elegant and concise scripts. |
Return the first reference with this ID. | Can you generate a brief explanation for the following Python 3 code
def reference_index(self, ref_id):
try:
indexes = range(self.reference_count())
return next(i for i in indexes if self.reference_id(i) == ref_id)
except StopIteration as e:
raise ReferenceNotFoundErr... | You are a Python code generator, capable of creating scripts from specifications. |
def reference_creators_citation(self, ref_id):
"""Return for citation the creator surnames (locally defined) and the publication year."""
# FIXME Delayed refactoring. Use an index instead of an ID.
index = self.reference_index(ref_id)
creators = self.reference_creator_surnames(index)
... | Write a Python 3 function for
returning for citation the creator surnames and the publication year. | As a Python code analyst, you investigate and solve complex coding mysteries |
def computePDFSimilarity(paperId, userPDF):
if not isPDFInDb(paperId):
return None
userPDF.save("temp.pdf")
# check_call is blocking
check_call(['pdftotext', '-enc', 'UTF-8', "temp.pdf", "temp.txt"])
os.remove("temp.pdf")
a = open("temp.txt", 'r').read()
b = open(join(dbPath, ... | Can you implement a function in Python 3 that
computes the similarity between two PDFs. | As a python code expert, you are capable of creating scripts from specifications. |
Get the list of children of a given root_id. | Explain what the following Python 3 code does
def getChildren(root_id, maxDepth=100, relationshipType="subClassOf",
alwaysFetch=False):
"""
Accessing web-based ontology service is too long, so we cache the
information in a pickle file and query the services only if the info
has not... | As a python code expert, you are capable of creating scripts from specifications. |
Automatically installs plugins into the app. | Here you have a function in Python 3, explain what it does
def install_plugins(plugins, app, install_type, config):
try:
disable_plugins = config.disable_plugins
if not disable_plugins:
disable_plugins = []
except AttributeError:
disable_plugins = []
for plugin_name in pl... | As a python code expert, you are capable of creating scripts from specifications. |
def addElement(self,etype='hex8',corners=[-1.0,-1.0,-1.0,1.,-1.0,-1.0,1.0,1.0,-1.0,-1.0,1.0,-1.0,-1.0,-1.0,1.0,1.0,-1.0,1.0,1.0,1.0,1.0,-1.0,1.0,1.0],name='new_elem'):
'''
corners - list of nodal coordinates properly ordered for element type (counter clockwise)
'''
lastelm = self.element... | Implement a Python 3 function for
adding a new element to the set. | As a python code expert, you are capable of creating scripts from specifications. |
Get the nodes connected by an edge type from the graph. | Can you generate the documentation for the following Python 3 function
def getEdges(self, type, entail='true', limit=100, skip=0, callback=None, output='application/json'):
kwargs = {'type':type, 'entail':entail, 'limit':limit, 'skip':skip, 'callback':callback}
kwargs = {k:dumps(v) if type(v) is dict e... | As a python code expert, you are capable of creating scripts from specifications. |
def getNeighbors(self, id, depth=1, blankNodes='false', relationshipType=None, direction='BOTH', project='*', callback=None, output='application/json'):
""" Get neighbors from: /graph/neighbors/{id}
Arguments:
id: This ID should be either a CURIE or an IRI
depth: How far to t... | How would you code a function in Python 3 to
get neighbors from a CURIE. | You are a Python code generator, capable of creating scripts from specifications. |
def enrich(self, sample, ontologyClass, path, callback=None, output='application/json'):
""" Class Enrichment Service from: /analyzer/enrichment
Arguments:
sample: A list of CURIEs for nodes whose attributes are to be tested for enrichment. For example, a list of genes.
ontol... | Can you implement a function in Python 3 that
classes Enrichment Service from: /analyzer/enrichment Arguments: sample: A list of CURIEs for nodes whose attributes are to be tested for enrichment. For example, a list of genes. ontologyClass: CURIE for parent ontology class for the attribute to be tested. For example, GO... | You are a Python code analyst, evaluating scripts for potential improvements. |
def annotatePost(self, content, includeCat=None, excludeCat=None, minLength=4, longestOnly='false', includeAbbrev='false', includeAcronym='false', includeNumbers='false', ignoreTag=None, stylesheet=None, scripts=None, targetId=None, targetClass=None):
""" Annotate text from: /annotations
Arguments:
... | How would you implement a function in Python 3 that
annotates text from the annotations API. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get the POS of the text in the current language. | Can you tell what is the following Python 3 function doing
def getPos(self, text):
kwargs = {'text':text}
kwargs = {k:dumps(v) if type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest('text', **kwargs)
url = self._basePath + ('/lexical/pos').format(**kwargs)
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Find a concept by its prefix from the Vocabulary Autocomplete API. | Can you tell what is the following Python 3 function doing
def findByPrefix(self, term, limit=20, searchSynonyms='true', searchAbbreviations='false', searchAcronyms='false', includeDeprecated='false', category=None, prefix=None):
kwargs = {'term':term, 'limit':limit, 'searchSynonyms':searchSynonyms, 'searchAbb... | You are a Python code analyst, evaluating scripts for potential improvements. |
def load_cell(fname="HL60_field.zip"):
"Load zip file and return complex field"
here = op.dirname(op.abspath(__file__))
data = op.join(here, "data")
arc = zipfile.ZipFile(op.join(data, fname))
for f in arc.filelist:
with arc.open(f) as fd:
if f.filename.count("imag"):
... | Can you implement a function in Python 3 that
loads zip file and return complex field | You are a Python code architect, reviewing and designing scalable and efficient code |
This function will bootstrap the data based on the sky coverage of a random sample. | Make a summary of the following Python 3 code
def bootstrap(nside, rand, nbar, *data):
def split(data, indices, axis):
""" This function splits array. It fixes the bug
in numpy that zero length array are improperly handled.
In the future this will be fixed.
"""
s = ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def load_project_flag_list_file(self, project_exceptions, project):
""" Loads project specific lists """
if self.loaded:
return
exception_file = None
for item in project_exceptions:
if project in item:
exception_file = item.get(project)
if ... | Create a Python 3 function to
load project specific flag list file | As a Python code composer, you craft elegant and concise scripts. |
def binary_hash(self, project, patch_file):
""" Gathers sha256 hashes from binary lists """
global il
exception_file = None
try:
project_exceptions = il.get('project_exceptions')
except KeyError:
logger.info('project_exceptions missing in %s for %s', ignor... | Create a Python 3 function to
gather sha256 hashes from binary lists | As a Python code translator, you convert algorithms and pseudocode into Python. |
Gathers file name lists | Given the following Python 3 function, write the documentation
def file_audit_list(self, project):
project_list = False
self.load_project_flag_list_file(il.get('project_exceptions'), project)
try:
default_list = set((fl['file_audits']['file_names']))
except KeyError:
... | As a python code expert, you are capable of creating scripts from specifications. |
def ignore_directories(self, project):
""" Gathers a list of directories to ignore """
project_list = False
try:
ignore_directories = il['ignore_directories']
except KeyError:
logger.error('Key Error processing ignore_directories list values')
try:
... | Write a Python 3 function for
gathering a list of directories to ignore | As a Python code translator, you convert algorithms and pseudocode into Python. |
Gathers a list of URLs to ignore for a project | Can you generate a brief explanation for the following Python 3 code
def url_ignore(self, project):
project_list = False
try:
url_ignore = il['url_ignore']
except KeyError:
logger.error('Key Error processing url_ignore list values')
try:
project_excep... | As a Python code analyst, you investigate and solve complex coding mysteries |
Gathers a list of URLs to ignore for a project | Given the following Python 3 function, write the documentation
def ip_ignore(self, project):
project_list = False
try:
ip_ignore = il['ip_ignore']
except KeyError:
logger.error('Key Error processing ip_ignore list values')
try:
project_exceptions = il... | You are a Python code architect, reviewing and designing scalable and efficient code |
Download database from GitHub and save it to path. | Here you have a function in Python 3, explain what it does
def download_from_github(fname, path):
base_url = 'https://github.com/ornlneutronimaging/ImagingReso/blob/master/ImagingReso/reference_data/'
# Add GitHub junk to the file name for downloading.
f = fname + '?raw=true'
url = base_url + f
bloc... | As a Python code analyst, you investigate and solve complex coding mysteries |
returns a string array of all the element from the database | Here you have a function in Python 3, explain what it does
def get_list_element_from_database(database='ENDF_VII'):
_file_path = os.path.abspath(os.path.dirname(__file__))
_ref_data_folder = os.path.join(_file_path, 'reference_data')
_database_folder = os.path.join(_ref_data_folder, database)
if not os... | As a python code expert, you are capable of creating scripts from specifications. |
returns True if the element is found in the database False otherwise | Can you generate a brief explanation for the following Python 3 code
def is_element_in_database(element='', database='ENDF_VII'):
if element == '':
return False
list_entry_from_database = get_list_element_from_database(database=database)
if element in list_entry_from_database:
return True
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def formula_to_dictionary(formula='', thickness=np.NaN, density=np.NaN, database='ENDF_VII'):
"""create dictionary based on formula given
Parameters:
===========
formula: string
ex: 'AgCo2'
ex: 'Ag'
thickness: float (in mm) default is np.NaN
density: float (in g/cm3) default i... | Implement a function in Python 3 to
function to create a dictionary from a formula | You are a Python code analyst, evaluating scripts for potential improvements. |
returns a dictionary with list of isotopes found in database and name of database files | Can you tell what is the following Python 3 function doing
def get_isotope_dicts(element='', database='ENDF_VII'):
_file_path = os.path.abspath(os.path.dirname(__file__))
_database_folder = os.path.join(_file_path, 'reference_data', database)
_element_search_path = os.path.join(_database_folder, element + '... | You are a Python code generator, capable of creating scripts from specifications. |
return the energy and sigma from the file_name
| Can you generate a brief explanation for the following Python 3 code
def get_database_data(file_name=''):
if not os.path.exists(file_name):
raise IOError("File {} does not exist!".format(file_name))
df = pd.read_csv(file_name, header=1)
return df | You are a Python code analyst, evaluating scripts for potential improvements. |
return the interpolated x and y axis for the given x range e_min e_max with step defined
| Explain what the following Python 3 code does
def get_interpolated_data(df: pd.DataFrame, e_min=np.nan, e_max=np.nan, e_step=np.nan):
nbr_point = int((e_max - e_min) / e_step + 1)
x_axis = np.linspace(e_min, e_max, nbr_point).round(6)
y_axis_function = interp1d(x=df['E_eV'], y=df['Sig_b'], kind='linear')
... | You are a Python code generator, capable of creating scripts from specifications. |
retrieve the Energy and sigma axis for the given isotope | Make a summary of the following Python 3 code
def get_sigma(database_file_name='', e_min=np.NaN, e_max=np.NaN, e_step=np.NaN, t_kelvin=None):
file_extension = os.path.splitext(database_file_name)[1]
if t_kelvin is None:
# '.csv' files
if file_extension != '.csv':
raise IOError("Cro... | You are a Python code analyst, evaluating scripts for potential improvements. |
calculate the atoms per cm3 of the given compound | Here you have a function in Python 3, explain what it does
def get_atoms_per_cm3_of_layer(compound_dict: dict):
# atoms_per_cm3 = {}
_list_of_elements = compound_dict['elements']
_stoichiometric_list = compound_dict['stoichiometric_ratio']
_element_stoichio = zip(_list_of_elements, _stoichiometric_lis... | As a Python code composer, you craft elegant and concise scripts. |
calculate the linear attenuation coefficient using the formula
| Given the following Python 3 function, write the documentation
def calculate_linear_attenuation_coefficient(atoms_per_cm3: np.float, sigma_b: np.array):
miu_per_cm = 1e-24 * sigma_b * atoms_per_cm3
return np.array(miu_per_cm) | You are a Python code architect, reviewing and designing scalable and efficient code |
def calculate_trans(thickness_cm: np.float, miu_per_cm: np.array):
"""calculate the transmission signal using the formula
transmission = exp( - thickness_cm * atoms_per_cm3 * 1e-24 * sigma_b)
Parameters:
===========
thickness: float (in cm)
atoms_per_cm3: float (number of atoms per cm3 of elem... | How would you code a function in Python 3 to
calculate the transmission signal using the formula | You are a Python code architect, reviewing and designing scalable and efficient code |
calculate the transmission signal using the formula
| Can you generate the documentation for the following Python 3 function
def calculate_transmission(thickness_cm: np.float, atoms_per_cm3: np.float, sigma_b: np.array):
miu_per_cm = calculate_linear_attenuation_coefficient(atoms_per_cm3=atoms_per_cm3, sigma_b=sigma_b)
transmission = calculate_trans(thickness_cm=t... | You are a Python code generator, capable of creating scripts from specifications. |
def set_distance_units(value=np.NaN, from_units='mm', to_units='cm'):
"""convert distance into new units
Parameters:
===========
value: float. value to convert
from_units: string. Must be 'mm', 'cm' or 'm'
to_units: string. must be 'mm','cm' or 'm'
Returns:
========
convert... | Can you write a function in Python 3 where it
converts distance into new units | You are a Python code architect, reviewing and designing scalable and efficient code |
def ev_to_s(offset_us, source_to_detector_m, array):
# delay values is normal 2.99 us with NONE actual MCP delay settings
"""convert energy (eV) to time (us)
Parameters:
===========
array: array (in eV)
offset_us: float. Delay of detector in us
source_to_detector_m: float. Distance source t... | Can you write a function in Python 3 where it
converts energy to time | As a python code expert, you are capable of creating scripts from specifications. |
convert time ( s ) to energy ( eV | Can you generate a brief explanation for the following Python 3 code
def s_to_ev(offset_us, source_to_detector_m, array):
lambda_a = 3956. * (array + offset_us * 1e-6) / source_to_detector_m
return (81.787 / pow(lambda_a, 2)) / 1000. | You are a Python code architect, reviewing and designing scalable and efficient code |
def ev_to_image_number(offset_us, source_to_detector_m, time_resolution_us, t_start_us, array):
# delay values is normal 2.99 us with NONE actual MCP delay settings
"""convert energy (eV) to image numbers (#)
Parameters:
===========
numpy array of energy in eV
offset_us: float. Delay of detecto... | Write a Python 3 function for
converting energy in eV to image number | As a Python code composer, you craft elegant and concise scripts. |
def temp_repo(url, branch, commit=''):
""" Clone a git repository inside a temporary folder, yield the folder then delete the folder.
:param string url: url of the repo to clone.
:param string branch: name of the branch to checkout to.
:param string commit: Optional commit rev to checkout to. If mentio... | Can you write a function in Python 3 where it
clones a git repository inside a temporary folder then delete the folder. | As a python code expert, you are capable of creating scripts from specifications. |
Force the move of the source folder to the destination folder. | Here you have a function in Python 3, explain what it does
def force_move(source, destination):
if not os.path.exists(destination):
raise RuntimeError(
'The code could not be moved to {destination} '
'because the folder does not exist'.format(destination=destination))
destinatio... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Run a command inside the folder. | Explain what the following Python 3 code does
def _run_command_inside_folder(command, folder):
logger.debug("command: %s", command)
# avoid usage of shell = True
# see https://docs.openstack.org/bandit/latest/plugins/subprocess_popen_with_shell_equals_true.html
process = subprocess.Popen(command.split()... | You are a Python code analyst, evaluating scripts for potential improvements. |
def parse_url(url):
""" Parse the given url and update it with environment value if required.
:param basestring url:
:rtype: basestring
:raise: KeyError if environment variable is needed but not found.
"""
# the url has to be a unicode by pystache's design, but the unicode concept has been rewa... | Can you create a Python 3 function that
parses the given url and update the environment variable if required. | As a Python code analyst, you investigate and solve complex coding mysteries |
def install(self, destination):
""" Install a third party odoo add-on
:param string destination: the folder where the add-on should end up at.
"""
logger.info(
"Installing %s@%s to %s",
self.repo, self.commit if self.commit else self.branch, destination
)... | Write a Python 3 function that can
install a third party odoo add - on to destination. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _move_modules(self, temp_repo, destination):
"""Move modules froom the temp directory to the destination.
:param string temp_repo: the folder containing the code.
:param string destination: the folder where the add-on should end up at.
"""
folders = self._get_module_folders(... | Write a Python 3 function for
moving modules froom the temp directory to the destination. | As a Python code analyst, you investigate and solve complex coding mysteries |
Get a list of module paths contained in a temp directory. | Make a summary of the following Python 3 code
def _get_module_folders(self, temp_repo):
paths = (
os.path.join(temp_repo, path) for path in os.listdir(temp_repo)
if self._is_module_included(path)
)
return (path for path in paths if os.path.isdir(path)) | You are a Python code architect, reviewing and designing scalable and efficient code |
def _is_module_included(self, module):
"""Evaluate if the module must be included in the Odoo addons.
:param string module: the name of the module
:rtype: bool
"""
if module in self.exclude_modules:
return False
if self.include_modules is None:
r... | Can you write a function in Python 3 where it
evaluates if the module must be included in the Odoo addons. | As a Python code composer, you craft elegant and concise scripts. |
Move modules from the temp directory to the destination. | Explain what the following Python 3 code does
def _move_modules(self, temp_repo, destination):
tmp_addons = os.path.join(temp_repo, 'addons')
tmp_odoo_addons = os.path.join(temp_repo, 'odoo/addons')
folders = self._get_module_folders(tmp_addons)
for folder in folders:
force_m... | As a Python code analyst, you investigate and solve complex coding mysteries |
def apply(self, folder):
""" Merge code from the given repo url to the git repo contained in the given folder.
:param string folder: path of the folder where is the git repo cloned at.
:raise: RuntimeError if the patch could not be applied.
"""
logger.info("Apply Patch %s@%s (co... | Write a Python 3 function that can
merge code from the given repo url to the git repo contained in the given folder. | You are a Python code analyst, evaluating scripts for potential improvements. |
Apply a git patch file to a folder. | Here you have a function in Python 3, explain what it does
def apply(self, folder):
logger.info("Apply Patch File %s", self.file_path)
command = "git apply {}".format(self.file_path)
return_code, stream_data = _run_command_inside_folder(command, folder)
if return_code:
msg =... | As a Python code composer, you craft elegant and concise scripts. |
def _set_up_context(cls):
"""Create context to keep all needed variables in."""
cls.context = AttributeDict()
cls.context.new_meta = {}
cls.context.new_transitions = {}
cls.context.new_methods = {} | Write a Python 3 function for
creating context to keep all needed variables in. | As a python code expert, you are capable of creating scripts from specifications. |
Check if states enum exists and is proper one. | Here you have a function in Python 3, explain what it does
def _check_states_enum(cls):
states_enum_name = cls.context.get_config('states_enum_name')
try:
cls.context['states_enum'] = getattr(
cls.context.new_class, states_enum_name)
except AttributeError:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Check if all states are strings. | How would you explain what the following Python 3 function does
def _check_if_states_are_strings(cls):
for item in list(cls.context.states_enum):
if not isinstance(item.value, six.string_types):
raise ValueError(
'Item {name} is not string. Only strings are allowe... | You are a Python code generator, capable of creating scripts from specifications. |
Check initial state value - if is proper and translate it. | Given the following Python 3 function, write the documentation
def _check_state_value(cls):
state_value = cls.context.get_config('initial_state', None)
state_value = state_value or getattr(
cls.context.new_class, cls.context.state_name, None
)
if not state_value:
... | As a Python code composer, you craft elegant and concise scripts. |
def _add_standard_attributes(cls):
"""Add attributes common to all state machines.
These are methods for setting and checking state etc.
"""
setattr(
cls.context.new_class,
cls.context.new_meta['state_attribute_name'],
cls.context.state_value)
... | Create a Python 3 function for
adding attributes common to all state machines. | You are a Python code analyst, evaluating scripts for potential improvements. |
Generate methods used for transitions. | How would you explain what the following Python 3 function does
def _generate_standard_transitions(cls):
allowed_transitions = cls.context.get_config('transitions', {})
for key, transitions in allowed_transitions.items():
key = cls.context.new_meta['translator'].translate(key)
n... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _generate_standard_methods(cls):
"""Generate standard setters, getters and checkers."""
for state in cls.context.states_enum:
getter_name = 'is_{name}'.format(name=state.value)
cls.context.new_methods[getter_name] = utils.generate_getter(state)
setter_name = 'set... | Implement a Python 3 function for
generating standard setters getters and checkers. | You are a Python code architect, reviewing and designing scalable and efficient code |
Add all generated methods to result class. | Make a summary of the following Python 3 code
def _add_new_methods(cls):
for name, method in cls.context.new_methods.items():
if hasattr(cls.context.new_class, name):
raise ValueError(
"Name collision in state machine class - '{name}'."
.format... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _set_complete_option(cls):
"""Check and set complete option."""
get_config = cls.context.get_config
complete = get_config('complete', None)
if complete is None:
conditions = [
get_config('transitions', False),
get_config('named_transitions'... | Write a Python 3 script to
check and set complete option. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def data_directory():
"""Return the absolute path to the directory containing the package data."""
package_directory = os.path.abspath(os.path.dirname(__file__))
return os.path.join(package_directory, "data") | Create a Python 3 function to
return the absolute path to the directory containing the package data. | You are a Python code analyst, evaluating scripts for potential improvements. |
def selectMap(name=None, excludeName=False, closestMatch=True, **tags):
"""select a map by name and/or critiera"""
matches = filterMapAttrs(**tags)
if not matches: raise c.InvalidMapSelection("could not find any matching maps given criteria: %s"%tags)
if name: # if name is specified, consider only the b... | How would you implement a function in Python 3 that
selects a map by name or critiera | As a Python code composer, you craft elegant and concise scripts. |
returns a list of records that match the given tags | Here you have a function in Python 3, explain what it does
def filterMapAttrs(records=getIndex(), **tags):
if len(tags) == 0: return records # otherwise if unspecified, all given records match
ret = []
for record in records: # attempt to match attributes
if matchRecordAttrs(record, tags):
... | As a python code expert, you are capable of creating scripts from specifications. |
attempt to match given attributes against a single map object s attributes | How would you explain what the following Python 3 function does
def matchRecordAttrs(mapobj, attrs):
for k,v in iteritems(attrs):
try: val = getattr(mapobj, k)
except AttributeError: # k isn't an attr of record
if bool(v): return False # if k doesn't exist in mapobj but was requ... | As a Python code composer, you craft elegant and concise scripts. |
matches each record against regexText according to parameters
returns a list of maps that match the regexText | Make a summary of the following Python 3 code
def filterMapNames(regexText, records=getIndex(), excludeRegex=False, closestMatch=True):
bestScr = 99999 # a big enough number to not be a valid file system path
regex = re.compile(regexText, flags=re.IGNORECASE)
ret = []
if excludeRegex: # match only reco... | You are a Python code generator, capable of creating scripts from specifications. |
def to_boolean(value, ctx):
"""
Tries conversion of any value to a boolean
"""
if isinstance(value, bool):
return value
elif isinstance(value, int):
return value != 0
elif isinstance(value, Decimal):
return value != Decimal(0)
elif isinstance(value, str):
valu... | Create a Python 3 function to
try conversion of any value to a boolean | You are a Python code architect, reviewing and designing scalable and efficient code |
def to_integer(value, ctx):
"""
Tries conversion of any value to an integer
"""
if isinstance(value, bool):
return 1 if value else 0
elif isinstance(value, int):
return value
elif isinstance(value, Decimal):
try:
val = int(value.to_integral_exact(ROUND_HALF_UP... | Write a Python 3 script for
trying conversion of any value to an integer | You are a Python code generator, capable of creating scripts from specifications. |
def to_decimal(value, ctx):
"""
Tries conversion of any value to a decimal
"""
if isinstance(value, bool):
return Decimal(1) if value else Decimal(0)
elif isinstance(value, int):
return Decimal(value)
elif isinstance(value, Decimal):
return value
elif isinstance(value... | Can you implement a function in Python 3 that
tries conversion of any value to a decimal | You are a Python code analyst, evaluating scripts for potential improvements. |
Converts any value to a string | Can you generate a brief explanation for the following Python 3 code
def to_string(value, ctx):
if isinstance(value, bool):
return "TRUE" if value else "FALSE"
elif isinstance(value, int):
return str(value)
elif isinstance(value, Decimal):
return format_decimal(value)
elif isinst... | You are a Python code generator, capable of creating scripts from specifications. |
Tries conversion of any value to a date | Given the following Python 3 function, write the documentation
def to_date(value, ctx):
if isinstance(value, str):
temporal = ctx.get_date_parser().auto(value)
if temporal is not None:
return to_date(temporal, ctx)
elif type(value) == datetime.date:
return value
elif isin... | You are a Python code analyst, evaluating scripts for potential improvements. |
def to_datetime(value, ctx):
"""
Tries conversion of any value to a datetime
"""
if isinstance(value, str):
temporal = ctx.get_date_parser().auto(value)
if temporal is not None:
return to_datetime(temporal, ctx)
elif type(value) == datetime.date:
return ctx.timezo... | Create a Python 3 function to
try conversion of any value to a datetime | As a python code expert, you are capable of creating scripts from specifications. |
Tries conversion of any value to a date or datetime | Here you have a function in Python 3, explain what it does
def to_date_or_datetime(value, ctx):
if isinstance(value, str):
temporal = ctx.get_date_parser().auto(value)
if temporal is not None:
return temporal
elif type(value) == datetime.date:
return value
elif isinstance... | As a python code expert, you are capable of creating scripts from specifications. |
def to_time(value, ctx):
"""
Tries conversion of any value to a time
"""
if isinstance(value, str):
time = ctx.get_date_parser().time(value)
if time is not None:
return time
elif isinstance(value, datetime.time):
return value
elif isinstance(value, datetime.da... | How would you code a function in Python 3 to
try conversion of any value to a time | As a Python code analyst, you investigate and solve complex coding mysteries |
Converts two values to the most - likely type. | How would you explain what the following Python 3 function does
def to_same(value1, value2, ctx):
if type(value1) == type(value2):
return value1, value2
try:
# try converting to two decimals
return to_decimal(value1, ctx), to_decimal(value2, ctx)
except EvaluationError:
pass... | You are a Python code analyst, evaluating scripts for potential improvements. |
Converts a value back to its representation form e. g. x -> x | Explain what the following Python 3 code does
def to_repr(value, ctx):
as_string = to_string(value, ctx)
if isinstance(value, str) or isinstance(value, datetime.date) or isinstance(value, datetime.time):
as_string = as_string.replace('"', '""') # escape quotes by doubling
as_string = '"%s"' % ... | As a Python code composer, you craft elegant and concise scripts. |
def format_decimal(decimal):
"""
Formats a decimal number
:param decimal: the decimal value
:return: the formatted string value
"""
# strip trailing fractional zeros
normalized = decimal.normalize()
sign, digits, exponent = normalized.as_tuple()
if exponent >= 1:
normalized =... | Can you write a function in Python 3 where it
formats a decimal number | As a python code expert, you are capable of creating scripts from specifications. |
def is_containerized() -> bool:
'''
Check if I am running inside a Linux container.
'''
try:
cginfo = Path('/proc/self/cgroup').read_text()
if '/docker/' in cginfo or '/lxc/' in cginfo:
return True
except IOError:
return False | How would you code a function in Python 3 to
check if I am running inside a Linux container. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Detect the cloud provider where I am running on. | Make a summary of the following Python 3 code
def detect_cloud() -> str:
'''
Detect the cloud provider where I am running on.
'''
# NOTE: Contributions are welcome!
# Please add other cloud providers such as Rackspace, IBM BlueMix, etc.
if sys.platform.startswith('linux'):
# Google Cloud... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Add block definition to list of blocks in material
| How would you explain what the following Python 3 function does
def addBlock(self,branch=None,btype=None,mtype=None,attributes=None):
'''
Add block definition to list of blocks in material
Order for list entry: branch level (0=root), block type (material,solid,fluid,etc.), matid (integer if root... | You are a Python code generator, capable of creating scripts from specifications. |
Refocus a 1D or 2D array of electric fields at d. | Explain what the following Python 3 code does
def refocus(field, d, nm, res, method="helmholtz", num_cpus=1, padding=True):
# FFT of field
fshape = len(field.shape)
assert fshape in [1, 2], "Dimension of `field` must be 1 or 2."
func = fft_propagate
names = func.__code__.co_varnames[:func.__code__.... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Refocuses a stack of electric fields at d. | Explain what the following Python 3 code does
def refocus_stack(fieldstack, d, nm, res, method="helmholtz",
num_cpus=_cpu_count, copy=True, padding=True):
"""Refocus a stack of 1D or 2D fields
Parameters
----------
fieldstack : 2d or 3d array
Stack of 1D or 2D background corr... | As a Python code analyst, you investigate and solve complex coding mysteries |
def fft_propagate(fftfield, d, nm, res, method="helmholtz",
ret_fft=False):
"""Propagates a 1D or 2D Fourier transformed field
Parameters
----------
fftfield : 1-dimensional or 2-dimensional ndarray
Fourier transform of 1D Electric field component
d : float
Distan... | How would you implement a function in Python 3 that
propagates a 1D or 2D Fourier transformed field at d nm res | As a Python code analyst, you investigate and solve complex coding mysteries |
Propagate a 1D Fourier transformed field in 2D. | Can you generate the documentation for the following Python 3 function
def fft_propagate_2d(fftfield, d, nm, res, method="helmholtz",
ret_fft=False):
"""Propagate a 1D Fourier transformed field in 2D
Parameters
----------
fftfield : 1d array
Fourier transform of 1D Electr... | You are a Python code architect, reviewing and designing scalable and efficient code |
Propagate a 2D Fourier transformed field in 3D | Here you have a function in Python 3, explain what it does
def fft_propagate_3d(fftfield, d, nm, res, method="helmholtz",
ret_fft=False):
"""Propagate a 2D Fourier transformed field in 3D
Parameters
----------
fftfield : 2d array
Fourier transform of 2D Electric field com... | As a python code expert, you are capable of creating scripts from specifications. |
def push(self):
"""
Adding the no_thin argument to the GIT push because we had some issues pushing previously.
According to http://stackoverflow.com/questions/16586642/git-unpack-error-on-push-to-gerrit#comment42953435_23610917,
"a new optimization which causes git to send as little d... | Write a Python 3 script for
pushing the object to the GIT repository. | As a python code expert, you are capable of creating scripts from specifications. |
This function calculates the autofocusing of a single stack of sinograms. | Can you generate a brief explanation for the following Python 3 code
def autofocus_stack(fieldstack, nm, res, ival, roi=None,
metric="average gradient", padding=True,
same_dist=False, ret_ds=False, ret_grads=False,
num_cpus=_cpu_count, copy=True):
"""Numer... | You are a Python code analyst, evaluating scripts for potential improvements. |
Find the focus by minimizing a metric of an image. | Can you generate a brief explanation for the following Python 3 code
def minimize_metric(field, metric_func, nm, res, ival, roi=None,
coarse_acc=1, fine_acc=.005,
return_gradient=True, padding=True):
"""Find the focus by minimizing the `metric` of an image
Parameters
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Prepares the project for rudimentary analysis | Can you generate the documentation for the following Python 3 function
def prepare_project(project, project_dir, binaries, ips, urls):
# Get Various Lists / Project Waivers
lists = get_lists.GetLists()
# Get file name black list and project waivers
file_audit_list, file_audit_project_list = lists.file... | You are a Python code analyst, evaluating scripts for potential improvements. |
def scan_file(project, project_dir, binaries, ips, urls, file_audit_list,
file_audit_project_list, flag_list, ignore_list, hashlist,
file_ignore, ignore_directories, url_ignore, ip_ignore, apikey):
"""
Main scan tasks begin
"""
logger.info("Commencing scan tasks..")
for r... | Can you write a function in Python 3 where it
scans a file for a specific project. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Scan the VirusTotal API for a single IP Address. | Here you have a function in Python 3, explain what it does
def scan_ipaddr(ipaddr, line, project, split_path, apikey):
logger.info('Found what I believe is an IP Address: %s', line.strip())
logger.info('File %s. Parsed IP Address: %s', split_path, ipaddr)
with open(reports_dir + "ips-" + project + ".log", "... | As a python code expert, you are capable of creating scripts from specifications. |
def scan_url(url, line, project, split_path, apikey):
"""
If URL is found, scan it
"""
logger.info('File %s contains what I believe is a URL: %s', split_path, line.strip())
logger.info('Scanning: %s', url)
with open(reports_dir + "urls-" + project + ".log", "a") as gate_report:
gate_repo... | Write a Python 3 script for
scanning a URL and return a list of the VirusTotal objects. | As a Python code translator, you convert algorithms and pseudocode into Python. |
parse the Maps subfolder directory divining criteria for valid maps | Can you generate the documentation for the following Python 3 function
def getIndex(folderPath=None):
try: return cache.structure
except AttributeError: pass # if it doesn't exist, generate and cache the map file data
if folderPath == None:
from sc2maptool.startup import setup
folderPath ... | You are a Python code generator, capable of creating scripts from specifications. |
Stringify a number preventing unwanted scientific notations. | Can you generate the documentation for the following Python 3 function
def _stringify_number(v):
'''
Stringify a number, preventing unwanted scientific notations.
'''
if isinstance(v, (float, Decimal)):
if math.isinf(v) and v > 0:
v = 'Infinity'
elif math.isinf(v) and v < 0:
... | As a Python code composer, you craft elegant and concise scripts. |
Resolve the tag using etcd so that the current instance indicates that the given image name is a concrete latest image. | How would you explain what the following Python 3 function does
async def resolve_alias(cls, alias_key: str, etcd: etcd.AsyncEtcd):
'''
Resolve the tag using etcd so that the current instance indicates
a concrete, latest image.
Note that alias resolving does not take the registry compon... | You are a Python code architect, reviewing and designing scalable and efficient code |
def getOntoCategory(curie, alwaysFetch=False):
"""
Accessing web-based ontology service is too long, so we cache the
information in a pickle file and query the services only if the info
has not already been cached.
"""
fileName = os.path.join(os.path.dirname(__file__), "ontoCategories.... | Can you write a function in Python 3 where it
gets the list of categories for a given curie. | You are a Python code generator, capable of creating scripts from specifications. |
Setup root logger for the AETTLE package | Can you generate a brief explanation for the following Python 3 code
def _init_logging(anteater_log):
LOG.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - '
'%(levelname)s - %(message)s')
ch.setFormatter(forma... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.