output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def check_dir():
""" Creates a directory for scan reports """
try:
os.makedirs(reports_dir)
logger.info('Creating reports directory: %s', reports_dir)
except OSError as e:
if e.errno != errno.EEXIST:
raise | Implement a function in Python 3 to
create a directory for scan reports | You are a Python code analyst, evaluating scripts for potential improvements. |
Fit a Stan model. | Can you generate the documentation for the following Python 3 function
def fit(model_code, *args, **kwargs):
kwargs = dict(kwargs)
kwargs['model_code'] = model_code
if 'n_jobs' not in kwargs:
kwargs['n_jobs'] = -1
if model_code in FIT_CACHE:
print("Reusing model.")
kwargs['fit'] ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def enumiter(self, other, rmax, bunch=100000):
""" cross correlate with other, for all pairs
closer than rmax, iterate.
for r, i, j in A.enumiter(...):
...
where r is the distance, i and j are the original
input array index of the data.
... | Can you write a function in Python 3 where it
iterates over all pairs of pairs of KDNode objects with distance rmax | As a python code expert, you are capable of creating scripts from specifications. |
cross correlate with other for all pairs
closer than rmax and iterate. | Here you have a function in Python 3, explain what it does
def enum(self, other, rmax, process=None, bunch=100000, **kwargs):
rall = None
if process is None:
rall = [numpy.empty(0, 'f8')]
iall = [numpy.empty(0, 'intp')]
jall = [numpy.empty(0, 'intp')]
def ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Gray & Moore based fast dual tree counting. | Can you generate a brief explanation for the following Python 3 code
def count(self, other, r, attrs=None, info={}):
r = numpy.array(r, dtype='f8')
return _core.KDNode.count(self, other, r, attrs, info=info) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Integrate the number of points between min and max. | Make a summary of the following Python 3 code
def integrate(self, min, max, attr=None, info={}):
if numpy.isscalar(min):
min = [min for i in range(self.ndims)]
if numpy.isscalar(max):
max = [max for i in range(self.ndims)]
min = numpy.array(min, dtype='f8', order='C')
... | As a python code expert, you are capable of creating scripts from specifications. |
def make_forest(self, chunksize):
""" Divide a tree branch to a forest,
each subtree of size at most chunksize """
heap = []
heappush(heap, (-self.size, self))
while True:
w, x = heappop(heap)
if w == 0:
heappush(heap, (0, x))
... | Write a Python 3 script to
divide a tree branch to a forest each subtree of size at most chunksize | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _install_one(
repo_url, branch, destination, commit='', patches=None,
exclude_modules=None, include_modules=None, base=False, work_directory=''
):
""" Install a third party odoo add-on
:param string repo_url: url of the repo that contains the patch.
:param string branch: name of the branch to c... | Create a Python 3 function to
install a third party odoo add - on. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _install_all(destination='', conf_file=''):
"""Use the conf file to list all the third party Odoo add-ons that will be installed
and the patches that should be applied.
:param string destination: the folder where add-ons should end up at.
Default: pwd/3rd
:param strin... | Write a Python 3 script for
installing all the third party add -ons. | As a Python code analyst, you investigate and solve complex coding mysteries |
Find rightmost value less than x | Explain what the following Python 3 code does
def find_lt(a, x):
i = bisect.bisect_left(a, x)
if i:
return a[i-1]
raise ValueError | You are a Python code generator, capable of creating scripts from specifications. |
Entry point to parse an ISA - Tab directory. | Can you tell what is the following Python 3 function doing
def parse(isatab_ref):
if os.path.isdir(isatab_ref):
fnames = glob.glob(os.path.join(isatab_ref, "i_*.txt")) + \
glob.glob(os.path.join(isatab_ref, "*.idf.txt"))
assert len(fnames) == 1
isatab_ref = fnames[0]
ass... | You are a Python code architect, reviewing and designing scalable and efficient code |
Parse a section of an ISA - Tab and assign information to a supplied record. | Given the following Python 3 function, write the documentation
def _parse_region(self, rec, line_iter):
had_info = False
keyvals, section = self._parse_keyvals(line_iter)
if keyvals:
rec.metadata = keyvals[0]
while section and section[0] != "STUDY":
had_info = Tr... | You are a Python code generator, capable of creating scripts from specifications. |
def _line_iter(self, in_handle):
"""Read tab delimited file, handling ISA-Tab special case headers.
"""
reader = csv.reader(in_handle, dialect="excel-tab")
for line in reader:
if len(line) > 0 and line[0]:
# check for section headers; all uppercase and a singl... | How would you implement a function in Python 3 that
iterates over the line of ISA - Tab delimited file. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Generate dictionary from key - value pairs. | Explain what the following Python 3 code does
def _parse_keyvals(self, line_iter):
out = None
line = None
for line in line_iter:
if len(line) == 1 and line[0].upper() == line[0]:
break
else:
# setup output dictionaries, trimming off blank c... | As a python code expert, you are capable of creating scripts from specifications. |
Retrieve row data from files associated with the ISATabRecord. | Explain what the following Python 3 code does
def parse(self, rec):
final_studies = []
for study in rec.studies:
source_data = self._parse_study(study.metadata["Study File Name"],
["Source Name", "Sample Name", "Comment[ENA_SAMPLE]"])
i... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _parse_study(self, fname, node_types):
"""Parse study or assay row oriented file around the supplied base node.
"""
if not os.path.exists(os.path.join(self._dir, fname)):
return None
nodes = {}
with open(os.path.join(self._dir, fname), "rU") as in_handle:
... | Write a Python 3 function that can
parse study or assay row oriented file around the supplied base node. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _finalize_metadata(self, node):
"""Convert node metadata back into a standard dictionary and list.
"""
final = {}
for key, val in iter(node.metadata.items()):
#val = list(val)
#if isinstance(val[0], tuple):
# val = [dict(v) for v in val]
... | Implement a Python 3 function for
converting node metadata back into a standard dictionary and list. | You are a Python code analyst, evaluating scripts for potential improvements. |
Parse out key value pairs based on a line of data. | Can you generate a brief explanation for the following Python 3 code
def _line_by_type(self, line, header, hgroups, htypes, out, want_type,
collapse_quals_fn = None):
"""Parse out key value pairs for line information based on a group of values.
"""
for index, htype in ((i, ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _collapse_attributes(self, line, header, indexes):
"""Combine attributes in multiple columns into single named tuple.
"""
names = []
vals = []
pat = re.compile("[\W]+")
for i in indexes:
names.append(pat.sub("_", self._clean_header(header[i])))
... | Write a Python 3 script for
combining attributes in multiple columns into single named tuple. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _clean_header(self, header):
"""Remove ISA-Tab specific information from Header[real name] headers.
"""
if header.find("[") >= 0:
header = header.replace("]", "").split("[")[-1]
# ISATab can start with numbers but this is not supported in
# the python datastructur... | Can you write a function in Python 3 where it
removes ISA - Tab specific information from Header [ real name ] headers. | You are a Python code generator, capable of creating scripts from specifications. |
def _characterize_header(self, header, hgroups):
"""Characterize header groups into different data types.
"""
out = []
for h in [header[g[0]] for g in hgroups]:
this_ctype = None
for ctype, names in self._col_types.items():
if h.startswith(names):
... | Create a Python 3 function to
characterize header groups into different data types. | As a Python code composer, you craft elegant and concise scripts. |
Combine header columns into related groups. | Can you tell what is the following Python 3 function doing
def _collapse_header(self, header):
out = []
for i, h in enumerate(header):
if h.startswith(self._col_quals):
out[-1].append(i)
else:
out.append([i])
return out | As a Python code composer, you craft elegant and concise scripts. |
def main(): # mini/unit test
"""
PURPOSE: command-line interface for map information
"""
options = optionsParser().parse_args()
params = getSelectionParams(options)
if options.list or options.details:
specifiedMaps = filterMapNames(
options.mapname,
records = filt... | Write a Python 3 script for
naming mapInfo - getmapinfo - getmapinfo - getmapinfo - getmapinfo - getmapinfo - getmapinfo - getmapinfo - getmapinfo - getmapinfo - getmapinfo - getmapinfo - getmapinfo - getmapinfo - getmapinfo - getmapinfo - getmapinfo - getmapinfo - getmapinfo - getmapinfo - getmapinfo - getmapinfo - ge... | You are a Python code architect, reviewing and designing scalable and efficient code |
Parse file extension.
- *.pickle: uncompressed, utf-8 encode pickle file
- *.gz: compressed, utf-8 encode pickle file | Can you generate a brief explanation for the following Python 3 code
def is_pickle_file(abspath):
abspath = abspath.lower()
fname, ext = os.path.splitext(abspath)
if ext in [".pickle", ".pk", ".p"]:
is_pickle = True
elif ext == ".gz":
is_pickle = False
elif ext == ".tmp":
ret... | You are a Python code architect, reviewing and designing scalable and efficient code |
Load a pickle from file. | Given the following Python 3 function, write the documentation
def load(abspath, default=None, enable_verbose=True):
if default is None:
default = dict()
prt("\nLoad from '%s' ..." % abspath, enable_verbose)
abspath = lower_ext(str(abspath))
is_pickle = is_pickle_file(abspath)
if not os.p... | As a python code expert, you are capable of creating scripts from specifications. |
def dump(data, abspath, pk_protocol=py23.pk_protocol,
overwrite=False, enable_verbose=True):
"""Dump picklable object to file.
Provides multiple choice to customize the behavior.
:param data: picklable python object.
:type data: dict or list
:param abspath: ``save as`` path, file extensio... | Create a Python 3 function for
dumping picklable object to file. | As a python code expert, you are capable of creating scripts from specifications. |
A stable version of pickle. | Can you tell what is the following Python 3 function doing
def safe_dump(data, abspath, pk_protocol=py23.pk_protocol, enable_verbose=True):
abspath = lower_ext(str(abspath))
abspath_temp = "%s.tmp" % abspath
dump(data, abspath_temp,
pk_protocol=pk_protocol, enable_verbose=enable_verbose)
shutil... | As a python code expert, you are capable of creating scripts from specifications. |
Convert arbitrary pickable Python Object to bytes. | Can you tell what is the following Python 3 function doing
def obj2bytes(obj, pk_protocol=py23.pk_protocol):
return pickle.dumps(obj, protocol=pk_protocol) | You are a Python code analyst, evaluating scripts for potential improvements. |
Convert arbitrary object to base64 encoded string. | Can you generate a brief explanation for the following Python 3 code
def obj2str(obj, pk_protocol=py23.pk_protocol):
return base64.urlsafe_b64encode(pickle.dumps(
obj, protocol=pk_protocol)).decode("utf-8") | You are a Python code analyst, evaluating scripts for potential improvements. |
def reset_network(message):
"""Resets the users network to make changes take effect"""
for command in settings.RESTART_NETWORK:
try:
subprocess.check_call(command)
except:
pass
print(message) | Create a Python 3 function to
reset the users network to make changes take effect | You are a Python code architect, reviewing and designing scalable and efficient code |
Disables access to websites that are defined as distractors | Can you tell what is the following Python 3 function doing
def improve():
with open(settings.HOSTS_FILE, "r+") as hosts_file:
contents = hosts_file.read()
if not settings.START_TOKEN in contents and not settings.END_TOKEN in contents:
hosts_file.write(settings.START_TOKEN + "\n")
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Enables access to websites that are defined as distractors | Given the following Python 3 function, write the documentation
def lose():
changed = False
with open(settings.HOSTS_FILE, "r") as hosts_file:
new_file = []
in_block = False
for line in hosts_file:
if in_block:
if line.strip() == settings.END_TOKEN:
... | As a python code expert, you are capable of creating scripts from specifications. |
Enables temporarily breaking concentration and performs some additional checks. | Make a summary of the following Python 3 code
def take_break(minutes: hug.types.number=5):
print("")
print("######################################### ARE YOU SURE? #####################################")
try:
for remaining in range(60, -1, -1):
sys.stdout.write("\r")
sys.stdo... | As a Python code analyst, you investigate and solve complex coding mysteries |
Tuple of low_port high_port reflecting the local port range
assigned to inbound connections. | Explain what the following Python 3 code does
def local_port_range(self):
if self._local_port_range is None:
with open('/proc/sys/net/ipv4/ip_local_port_range', 'r') as f:
self._local_port_range = tuple(map(int, f.read().split('\t')))
return self._local_port_range | As a Python code composer, you craft elegant and concise scripts. |
Format a number using base - 2 SI prefixes | Given the following Python 3 function, write the documentation
def _si(number):
prefixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
while number > 1024:
number /= 1024.0
prefixes.pop(0)
return '%0.2f%s' % (number, prefixes.pop(0)) | You are a Python code generator, capable of creating scripts from specifications. |
Extract files while explicitly setting the proper permissions | Explain what the following Python 3 code does
def _extract_file(zip_fp, info, path):
zip_fp.extract(info.filename, path=path)
out_path = os.path.join(path, info.filename)
perm = info.external_attr >> 16
perm |= stat.S_IREAD # make sure we're not accidentally setting this to 0
os.chmod(out_path, pe... | As a Python code composer, you craft elegant and concise scripts. |
def build_string(self):
"""
Taskcluster denotes builds in one of two formats - i.e. linux64-asan or linux64-asan-opt
The latter is generated. If it fails, the caller should try the former.
"""
return (('-ccov' if self.coverage else '') +
('-fuzzing' if self.fuzzin... | Create a Python 3 function for
building a string that can be used to build a Taskcluster entry. | You are a Python code architect, reviewing and designing scalable and efficient code |
def auto_name_prefix(self):
"""
Generate platform prefix for cross-platform downloads.
"""
# if the platform is not native, auto_name would clobber native downloads.
# make a prefix to avoid this
native_system = std_platform.system()
native_machine = self.CPU_ALIA... | Write a Python 3 function that can
generate platform prefix for cross - platform downloads. | As a python code expert, you are capable of creating scripts from specifications. |
def _pushdate_urls(cls, pushdate, branch, target_platform):
"""Multiple entries exist per push date. Iterate over all until a working entry is found"""
url_base = cls.URL_BASE + '/namespaces/gecko.v2.mozilla-' + branch + '.pushdate.' + pushdate
try:
base = HTTP_SESSION.post(url_base... | Can you implement a function in Python 3 that
yields all URLs that are available for a given push date. | You are a Python code generator, capable of creating scripts from specifications. |
Retrieve the URL for revision based builds | How would you explain what the following Python 3 function does
def _revision_url(cls, rev, branch, target_platform):
namespace = 'gecko.v2.mozilla-' + branch + '.revision.' + rev
product = 'mobile' if 'android' in target_platform else 'firefox'
return cls.URL_BASE + '/task/' + namespace + '.' +... | You are a Python code architect, reviewing and designing scalable and efficient code |
Return an iterable for all available builds matching a particular build type | Make a summary of the following Python 3 code
def iterall(cls, target, branch, build, flags, platform=None):
flags = BuildFlags(*flags)
for task in BuildTask.iterall(build, branch, flags, platform):
yield cls(target, branch, task, flags, platform) | As a Python code analyst, you investigate and solve complex coding mysteries |
def _artifacts(self):
"""Retrieve the artifacts json object"""
if '_artifacts' not in self._memo:
json = _get_url(self._artifacts_url).json()
self._memo['_artifacts'] = json['artifacts']
return self._memo['_artifacts'] | Write a Python 3 function for
retrieving the artifacts json object | As a Python code composer, you craft elegant and concise scripts. |
Return the base build name for the artifact | Can you generate the documentation for the following Python 3 function
def _artifact_base(self):
if '_artifact_base' not in self._memo:
for artifact in self._artifacts:
if self.re_target.search(artifact['name']) is not None:
artifact_base = os.path.splitext(artifa... | You are a Python code architect, reviewing and designing scalable and efficient code |
Return the build s info | Make a summary of the following Python 3 code
def build_info(self):
if 'build_info' not in self._memo:
self._memo['build_info'] = _get_url(self.artifact_url('json')).json()
return self._memo['build_info'] | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return the build s mozinfo json | Here you have a function in Python 3, explain what it does
def moz_info(self):
if 'moz_info' not in self._memo:
self._memo['moz_info'] = _get_url(self.artifact_url('mozinfo.json')).json()
return self._memo['moz_info'] | As a Python code translator, you convert algorithms and pseudocode into Python. |
def extract_build(self, path='.', tests=None, full_symbols=False):
"""
Download and extract the build and requested extra artifacts
@type path:
@param path:
@type tests:
@param tests:
@type full_symbols:
@param full_symbols:
"""
if self.... | How would you code a function in Python 3 to
download and extract the build and requested extra artifacts. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _layout_for_domfuzz(self, path):
"""
Update directory to work with DOMFuzz
@type path: str
@param path: A string representation of the fuzzmanager config path
"""
old_dir = os.getcwd()
os.chdir(os.path.join(path))
try:
os.mkdir('dist')
... | Create a Python 3 function for
updating directory to work with DOMFuzz @type path: str @param path: A string representation of the fuzzmanager config path | As a Python code composer, you craft elegant and concise scripts. |
def _write_fuzzmanagerconf(self, path):
"""
Write fuzzmanager config file for selected build
@type path: basestring
@param path: A string representation of the fuzzmanager config path
"""
output = configparser.RawConfigParser()
output.add_section('Main')
... | Write a Python 3 script for
writing fuzzmanager config file for selected build_id. | You are a Python code generator, capable of creating scripts from specifications. |
def extract_zip(self, suffix, path='.'):
"""
Download and extract a zip artifact
@type suffix:
@param suffix:
@type path:
@param path:
"""
zip_fd, zip_fn = tempfile.mkstemp(prefix='fuzzfetch-', suffix='.zip')
os.close(zip_fd)
try:
... | Write a Python 3 script for
downloading and extract a zip artifact . | As a Python code analyst, you investigate and solve complex coding mysteries |
Extract builds with. tar.(*) extension
When unpacking a build archive only extract the firefox directory
| How would you explain what the following Python 3 function does
def extract_tar(self, suffix, path='.'):
mode = suffix.split('.')[-1]
tar_fd, tar_fn = tempfile.mkstemp(prefix='fuzzfetch-', suffix='.tar.%s' % mode)
os.close(tar_fd)
try:
_download_url(self.artifact_url(suffix),... | As a Python code analyst, you investigate and solve complex coding mysteries |
Download Android. apk file and copy it to path. | Can you generate the documentation for the following Python 3 function
def download_apk(self, path='.'):
apk_fd, apk_fn = tempfile.mkstemp(prefix='fuzzfetch-', suffix='.apk')
os.close(apk_fd)
try:
_download_url(self.artifact_url('apk'), apk_fn)
shutil.copy(apk_fn, os.path... | As a Python code composer, you craft elegant and concise scripts. |
Extract builds with. dmg extension. | Given the following Python 3 function, write the documentation
def extract_dmg(self, path='.'):
dmg_fd, dmg_fn = tempfile.mkstemp(prefix='fuzzfetch-', suffix='.dmg')
os.close(dmg_fd)
out_tmp = tempfile.mkdtemp(prefix='fuzzfetch-', suffix='.tmp')
try:
_download_url(self.artifa... | As a Python code composer, you craft elegant and concise scripts. |
def from_args(cls, args=None, skip_dir_check=False):
"""
Construct a Fetcher from given command line arguments.
@type args: list(str)
@param args: Command line arguments (optional). Default is to use args from sys.argv
@type skip_dir_check: bool
@param skip_dir_check: B... | Create a Python 3 function to
construct a Fetcher object from given command line arguments. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def init_original_response(self):
"""Get the original response for comparing, confirm ``is_cookie_necessary``"""
if 'json' in self.request:
self.request['data'] = json.dumps(self.request.pop('json')).encode(
self.encoding)
r1 = self.req.request(
retry=self... | Implement a Python 3 function for
getting the original response for comparing confirm is_cookie_necessary | You are a Python code generator, capable of creating scripts from specifications. |
def init_original_response(self):
"""Get the original response for comparing, confirm is_cookie_necessary"""
no_cookie_resp = None
self.is_cookie_necessary = True
if 'json' in self.request:
self.request['data'] = json.dumps(self.request.pop('json')).encode(
se... | Create a Python 3 function to
get the original response for comparing confirm is_cookie_necessary | As a Python code analyst, you investigate and solve complex coding mysteries |
def sort_url_qsl(cls, raw_url, **kwargs):
"""Do nothing but sort the params of url.
raw_url: the raw url to be sorted;
kwargs: (optional) same kwargs for ``sorted``.
"""
parsed_url = urlparse(raw_url)
qsl = parse_qsl(parsed_url.query)
return cls._join_ur... | Can you create a Python 3 function that
does nothing but sort the params of url. | As a Python code analyst, you investigate and solve complex coding mysteries |
Only clean the cookie from headers and return self. | Can you generate a brief explanation for the following Python 3 code
def clean_cookie(self):
if not self.is_cookie_necessary:
return self
headers = self.request.get('headers', {})
cookies = SimpleCookie(headers['Cookie'])
for k, v in cookies.items():
new_cookie = ... | You are a Python code analyst, evaluating scripts for potential improvements. |
Only clean the headers ( cookie include and return self. | Given the following Python 3 function, write the documentation
def clean_headers(self):
if not isinstance(self.request.get('headers'), dict):
return self
headers = self.request['headers']
if 'Cookie' in headers:
self.clean_cookie()
for key in headers:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Remove the non - sense args from the self. ignore and return self. new_request | Here you have a function in Python 3, explain what it does
def reset_new_request(self):
raw_url = self.new_request['url']
parsed_url = urlparse(raw_url)
qsl = parse_qsl(parsed_url.query)
new_url = self._join_url(
parsed_url, [i for i in qsl if i not in self.ignore['qsl']])
... | As a Python code composer, you craft elegant and concise scripts. |
Whole task clean_all + reset_new_request return self. new_request. | Can you tell what is the following Python 3 function doing
def result(self):
if not self.tasks:
self.clean_all()
tasks_length = len(self.tasks)
self.logger_function(
'%s tasks of request, will cost at least %s seconds.' %
(tasks_length,
round(self... | You are a Python code generator, capable of creating scripts from specifications. |
def get_or_save_default(self, key, default_value):
"""
Get value stored in cache file or store there default value.
:param key:
:param default_value:
:return:
"""
val = self.get_or_none(key)
if val is None:
self.update(key, default_value)
... | How would you code a function in Python 3 to
get value stored in cache file or store there default value. | As a python code expert, you are capable of creating scripts from specifications. |
Save overlay to dicom. | Given the following Python 3 function, write the documentation
def saveOverlayToDicomCopy(input_dcmfilelist, output_dicom_dir, overlays,
crinfo, orig_shape):
""" Save overlay to dicom. """
from . import datawriter as dwriter
# import qmisc
if not os.path.exists(output_dicom_d... | You are a Python code analyst, evaluating scripts for potential improvements. |
def __get_segmentation_path(self, path):
""" Create path with "_segmentation" suffix and keep extension.
:param path:
:return:
"""
startpath, ext = os.path.splitext(path)
segmentation_path = startpath + "_segmentation" + ext
return segmentation_path | Implement a function in Python 3 to
create path with _segmentation suffix and keep extension. | You are a Python code analyst, evaluating scripts for potential improvements. |
Write 3D data to file. | Given the following Python 3 function, write the documentation
def Write3DData(self, data3d, path, filetype='auto', metadata=None, progress_callback=None, sfin=True):
self.orig_path = path
path = os.path.expanduser(path)
try:
d3d = data3d.pop('data3d')
metadata = data3d... | You are a Python code generator, capable of creating scripts from specifications. |
This function fixes the bug in simple ITK for Z axis in 3D images. | Can you generate the documentation for the following Python 3 function
def _fix_sitk_bug(self, path, metadata):
ds = dicom.read_file(path)
ds.SpacingBetweenSlices = str(metadata["voxelsize_mm"][0])[:16]
dicom.write_file(path, ds) | You are a Python code generator, capable of creating scripts from specifications. |
Function make 3D data from dicom files and overlays | Make a summary of the following Python 3 code
def DataCopyWithOverlay(self, dcmfilelist, out_dir, overlays):
dcmlist = dcmfilelist
# data3d = []
for i in range(len(dcmlist)):
onefile = dcmlist[i]
logger.info(onefile)
data = dicom.read_file(onefile)
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def add_overlay_to_slice_file(
self,
filename,
overlay,
i_overlay,
filename_out=None
):
""" Function adds overlay to existing file.
"""
if filename_out is None:
filename_out = filename
filename = op.expanduser(filename)
data... | Can you create a Python 3 function that
functions adds overlay to existing file. | You are a Python code architect, reviewing and designing scalable and efficient code |
A decorator that marks a method as deprecated. | Given the following Python 3 function, write the documentation
def deprecated(instructions):
def decorator(func):
"""This is a decorator which can be used to mark functions as deprecated.
It will result in a warning being emitted when the function is used.
"""
@functools.wraps(func)... | As a Python code analyst, you investigate and solve complex coding mysteries |
Logs a message only when logging level is verbose. | Make a summary of the following Python 3 code
def log_verbose(self, message):
if self.get_verbosity() >= Output.VERBOSITY_VERBOSE:
self.writeln(message) | You are a Python code analyst, evaluating scripts for potential improvements. |
def log_very_verbose(self, message):
"""
Logs a message only when logging level is very verbose.
:param str|list[str] message: The message.
"""
if self.get_verbosity() >= Output.VERBOSITY_VERY_VERBOSE:
self.writeln(message) | How would you implement a function in Python 3 that
logs a message only when logging level is very verbose. | You are a Python code analyst, evaluating scripts for potential improvements. |
async def get_feed(config, url):
""" Get a feed
Arguments:
config -- the configuration
url -- The URL of the feed
retval -- a tuple of feed,previous_version,changed
"""
LOGGER.debug("++WAIT: cache get feed %s", url)
previous = config.cache.get(
'feed', url, schema_version=SCH... | How would you implement a function in Python 3 that
gets a feed from the given URL. | You are a Python code analyst, evaluating scripts for potential improvements. |
def archive_namespace(self):
""" Returns the known namespace of the RFC5005 extension, if any """
try:
for ns_prefix, url in self.feed.namespaces.items():
if url == 'http://purl.org/syndication/history/1.0':
return ns_prefix
except AttributeError:
... | Write a Python 3 script for
returning the known namespace of the RFC5005 extension. | You are a Python code analyst, evaluating scripts for potential improvements. |
Given a parsed feed return the links to its entries including ones
which disappeared | Here you have a function in Python 3, explain what it does
def entry_links(self):
return {entry['link'] for entry in self.feed.entries if entry and entry.get('link')} | You are a Python code architect, reviewing and designing scalable and efficient code |
Given a parsed feed returns True if this is an archive feed False otherwise | Can you generate a brief explanation for the following Python 3 code
def is_archive(self):
ns_prefix = self.archive_namespace
if ns_prefix:
if ns_prefix + '_archive' in self.feed.feed:
# This is declared to be an archive view
return True
if ns_pre... | You are a Python code generator, capable of creating scripts from specifications. |
Update the WebSub hub to know about this feed | Make a summary of the following Python 3 code
async def update_websub(self, config, hub):
try:
LOGGER.debug("WebSub: Notifying %s of %s", hub, self.url)
request = await utils.retry_post(
config,
hub,
data={
'hub.mode': '... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_tags(self, name):
"""
Returns a list of tags.
@param str name: The name of the tag.
:rtype: list[str]
"""
tags = list()
for tag in self._tags:
if tag[0] == name:
tags.append(tag[1])
return tags | How would you implement a function in Python 3 that
returns a list of tags. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Removes leading empty lines from a list of lines. | Given the following Python 3 function, write the documentation
def __remove_leading_empty_lines(lines):
tmp = list()
empty = True
for i in range(0, len(lines)):
empty = empty and lines[i] == ''
if not empty:
tmp.append(lines[i])
return tmp | You are a Python code architect, reviewing and designing scalable and efficient code |
def __remove_trailing_empty_lines(lines):
"""
Removes leading empty lines from a list of lines.
:param list[str] lines: The lines.
"""
lines.reverse()
tmp = DocBlockReflection.__remove_leading_empty_lines(lines)
lines.reverse()
tmp.reverse()
retu... | Can you create a Python 3 function that
removes leading empty lines from a list of lines. | As a Python code analyst, you investigate and solve complex coding mysteries |
def __clean_doc_block(self):
"""
Cleans the DocBlock from leading and trailing white space and comment tokens.
"""
# Return immediately if the DockBlock is empty.
if not self._comment:
return
for i in range(1, len(self._comment) - 1):
self._commen... | Can you write a function in Python 3 where it
cleans the DocBlock from leading and trailing white space and comment tokens. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def __extract_description(self):
"""
Extracts the description from the DocBlock. The description start at the first line and stops at the first tag
or the end of the DocBlock.
"""
tmp = list()
for line in self._comment:
if len(line) >= 1 and line[0] == '@':
... | Can you create a Python 3 function that
extracts the description from the DocBlock. | You are a Python code analyst, evaluating scripts for potential improvements. |
Extract tags from the DocBlock. | Here you have a function in Python 3, explain what it does
def __extract_tags(self):
tags = list()
current = None
for line in self._comment:
parts = re.match(r'^@(\w+)', line)
if parts:
current = (parts.group(1), list())
tags.append(current... | As a Python code analyst, you investigate and solve complex coding mysteries |
Executes constants command when PyStratumCommand is activated. | Can you tell what is the following Python 3 function doing
def handle(self):
self.output = PyStratumStyle(self.input, self.output)
config_file = self.input.get_argument('config_file')
self.run_command(config_file) | You are a Python code architect, reviewing and designing scalable and efficient code |
def run_command(self, config_file):
"""
:param str config_file: The name of config file.
"""
config = configparser.ConfigParser()
config.read(config_file)
rdbms = config.get('database', 'rdbms').lower()
label_regex = config.get('constants', 'label_regex')
... | Implement a Python 3 function for
running the neccesary command. | As a python code expert, you are capable of creating scripts from specifications. |
def create_constants(self, rdbms):
"""
Factory for creating a Constants objects (i.e. objects for creating constants based on column widths, and auto
increment columns and labels).
:param str rdbms: The target RDBMS (i.e. mysql, mssql or pgsql).
:rtype: pystratum.Constants.Cons... | Can you create a Python 3 function that
returns a factory function for creating a Constants objects based on column widths and auto - increment columns and labels. | As a Python code composer, you craft elegant and concise scripts. |
def _format_key_name(self) -> str:
"""Return formatted redis key name."""
key_name = 'ld:{0}:{1}:features'.format(
self.project_key,
self.environment_key
)
return key_name | Write a Python 3 script for
returning formatted redis key name. | As a Python code composer, you craft elegant and concise scripts. |
def connection_string_parser(uri: str) -> list:
"""
Parse Connection string to extract host and port.
:param uri: full URI for redis connection in the form of host:port
:returns: list of RedisConnection objects
"""
redis_connections = []
raw_connections = uri.sp... | Can you implement a function in Python 3 that
parses Connection string to extract host and port. | As a Python code composer, you craft elegant and concise scripts. |
def get_flag_record(self, feature_key: str) -> str:
"""Get feature flag record from redis.
:param feature_key: key for feature flag
:return: value of feature flag key in redis.
:raises: KeyError if key is not found.
"""
key_name = self._format_key_name()
flag =... | Write a Python 3 function that can
get feature flag record from redis. | You are a Python code generator, capable of creating scripts from specifications. |
def update_flag_record(self, state: str, feature_key: str) -> None:
"""Update redis record with new state.
:param state: state for feature flag.
:param feature_key: key for feature flag.
"""
key_name = self._format_key_name()
try:
parsed_flag = json.loads(sel... | Implement a Python 3 function for
updating redis record with new state. | As a python code expert, you are capable of creating scripts from specifications. |
Wrap coro_function into the function return NewTask. | Here you have a function in Python 3, explain what it does
def Asyncme(func, n=None, interval=0, default_callback=None, loop=None):
return coros(n, interval, default_callback, loop)(func) | You are a Python code architect, reviewing and designing scalable and efficient code |
Decorator for wrap coro_function into the function return NewTask. | Explain what the following Python 3 code does
def coros(n=None, interval=0, default_callback=None, loop=None):
submitter = Loop(
n=n, interval=interval, default_callback=default_callback, loop=loop
).submitter
return submitter | As a python code expert, you are capable of creating scripts from specifications. |
def wrap_callback(function):
"""Set the callback's result as self._callback_result."""
@wraps(function)
def wrapped(task):
task._callback_result = function(task)
return task._callback_result
return wrapped | Create a Python 3 function for
wrapping a function to set the result as self. _callback_result. | You are a Python code architect, reviewing and designing scalable and efficient code |
Schedule the callbacks to be called when the task is finished. | Here you have a function in Python 3, explain what it does
def _schedule_callbacks(self, clear_cb=False):
self.task_end_time = time.time()
self.task_cost_time = self.task_end_time - self.task_start_time
callbacks = self._callbacks[:]
if not callbacks:
return
if clear_... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Blocking until the task finish and return the callback_result. until | Here you have a function in Python 3, explain what it does
def callback_result(self):
if self._state == self._PENDING:
self._loop.run_until_complete(self)
if self._callbacks:
result = self._callback_result
else:
result = self.result()
return result | As a python code expert, you are capable of creating scripts from specifications. |
Blocking until the task finish and return the self. result | Here you have a function in Python 3, explain what it does
def x(self):
if self._state == self._PENDING:
self._loop.run_until_complete(self)
return self.result() | As a Python code translator, you convert algorithms and pseudocode into Python. |
Decorator set the coro_func has sem control. | Here you have a function in Python 3, explain what it does
def _wrap_coro_function_with_sem(self, coro_func):
sem = self.frequency.sem
interval = self.frequency.interval
@wraps(coro_func)
async def new_coro_func(*args, **kwargs):
if sem:
async with sem:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Run a function in an executor. | Here you have a function in Python 3, explain what it does
def run_in_executor(self, executor=None, func=None, *args):
return self.loop.run_in_executor(executor, func, *args) | You are a Python code architect, reviewing and designing scalable and efficient code |
Run a function in a thread pool. | Explain what the following Python 3 code does
def run_in_thread_pool(self, pool_size=None, func=None, *args):
executor = Pool(pool_size)
return self.loop.run_in_executor(executor, func, *args) | As a python code expert, you are capable of creating scripts from specifications. |
Run a function in a process pool. | Can you tell what is the following Python 3 function doing
def run_in_process_pool(self, pool_size=None, func=None, *args):
executor = ProcessPool(pool_size)
return self.loop.run_in_executor(executor, func, *args) | As a Python code analyst, you investigate and solve complex coding mysteries |
def run_coroutine_threadsafe(self, coro, loop=None, callback=None):
"""Be used when loop running in a single non-main thread."""
if not asyncio.iscoroutine(coro):
raise TypeError("A await in coroutines. object is required")
loop = loop or self.loop
future = NewFuture(callback... | Can you write a function in Python 3 where it
is used when loop running in a single non - main thread. | As a Python code composer, you craft elegant and concise scripts. |
def apply(self, coro_function, args=None, kwargs=None, callback=None):
"""Submit a coro_function(*args, **kwargs) as NewTask to self.loop with loop.frequncy control.
::
from torequests.dummy import Loop
import asyncio
loop = Loop()
async def test(i):
... | Create a Python 3 function to
submit a coroutine function to self. loop with frequency control. | You are a Python code analyst, evaluating scripts for potential improvements. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.