output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Writes data to SPI device selected by chipselect bit. | Make a summary of the following Python 3 code
def SPI_write(self, chip_select, data):
'Writes data to SPI device selected by chipselect bit. '
dat = list(data)
dat.insert(0, chip_select)
return self.bus.write_i2c_block(self.address, dat); | You are a Python code generator, capable of creating scripts from specifications. |
Configure SPI interface parameters. | Can you tell what is the following Python 3 function doing
def SPI_config(self,config):
'Configure SPI interface parameters.'
self.bus.write_byte_data(self.address, 0xF0, config)
return self.bus.read_byte_data(self.address, 0xF0) | As a Python code composer, you craft elegant and concise scripts. |
def GPIO_read(self):
'Reads logic state on GPIO enabled slave-selects pins.'
self.bus.write_byte_data(self.address, 0xF5, 0x0f)
status = self.bus.read_byte(self.address)
bits_values = dict([('SS0',status & 0x01 == 0x01),('SS1',status & 0x02 == 0x02),('SS2',status & 0x04 == 0x04),('SS3',s... | Write a Python 3 function that can
read logic state on GPIO enabled slave - selects pins. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Enable or disable slave - select pins as gpio. | Here you have a function in Python 3, explain what it does
def GPIO_config(self, gpio_enable, gpio_config):
'Enable or disable slave-select pins as gpio.'
self.bus.write_byte_data(self.address, 0xF6, gpio_enable)
self.bus.write_byte_data(self.address, 0xF7, gpio_config)
return | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns sensors I2C address. | Given the following Python 3 function, write the documentation
def get_address(self):
LOGGER.debug("Reading RPS01A sensor's address.",)
return self.bus.read_byte_data(self.address, self.address_reg) | You are a Python code generator, capable of creating scripts from specifications. |
Returns the programmed zero position in OTP memory. | Here you have a function in Python 3, explain what it does
def get_zero_position(self):
LSB = self.bus.read_byte_data(self.address, self.zero_position_MSB)
MSB = self.bus.read_byte_data(self.address, self.zero_position_LSB)
DATA = (MSB << 6) + LSB
return DATA | As a python code expert, you are capable of creating scripts from specifications. |
Returns sensor s Automatic Gain Control actual value. | Can you generate a brief explanation for the following Python 3 code
def get_agc_value(self):
LOGGER.debug("Reading RPS01A sensor's AGC settings",)
return self.bus.read_byte_data(self.address, self.AGC_reg) | As a Python code composer, you craft elegant and concise scripts. |
def get_diagnostics(self):
"""
Reads diagnostic data from the sensor.
OCF (Offset Compensation Finished) - logic high indicates the finished Offset Compensation Algorithm. After power up the flag remains always to logic high.
COF (Cordic Overflow) - logic high indicates an out of range ... | Can you implement a function in Python 3 that
reads the diagnostic data from the sensor and returns a dictionary of the values. | As a python code expert, you are capable of creating scripts from specifications. |
def get_angle(self, verify = False):
"""
Retuns measured angle in degrees in range 0-360.
"""
LSB = self.bus.read_byte_data(self.address, self.angle_LSB)
MSB = self.bus.read_byte_data(self.address, self.angle_MSB)
DATA = (MSB << 6) + LSB
if not verify:
... | Can you write a function in Python 3 where it
returns measured angle in degrees in range 0 - 360. | As a python code expert, you are capable of creating scripts from specifications. |
This function is used to annotate a single BED file based on reference features annotations. | Given the following Python 3 function, write the documentation
def main(input_bed, output_file, output_features=False, genome=None,
only_canonical=False, short=False, extended=False, high_confidence=False,
ambiguities_method=False, coding_only=False, collapse_exons=False, work_dir=False, is_debug=Fals... | As a Python code analyst, you investigate and solve complex coding mysteries |
def StateOfCharge(self):
""" % of Full Charge """
return (self.bus.read_byte_data(self.address, 0x02) + self.bus.read_byte_data(self.address, 0x03) * 256) | Write a Python 3 function for
returning the state of charge in MHz. | As a python code expert, you are capable of creating scripts from specifications. |
r2D backpropagation of a single object in a 2D manner. | Can you generate the documentation for the following Python 3 function
def backpropagate_2d(uSin, angles, res, nm, lD=0, coords=None,
weight_angles=True,
onlyreal=False, padding=True, padval=0,
count=None, max_count=None, verbose=0):
r"""2D backpropagat... | As a Python code composer, you craft elegant and concise scripts. |
Color of the current image. | Can you generate a brief explanation for the following Python 3 code
def color(x, y):
if (x-4) > (y-4) and -(y-4) <= (x-4):
# right
return "#CDB95B"
elif (x-4) > (y-4) and -(y-4) > (x-4):
# top
return "#CD845B"
elif (x-4) <= (y-4) and -(y-4) <= (x-4):
# bottom
... | As a Python code composer, you craft elegant and concise scripts. |
Reads data from the specified register only once. | Can you tell what is the following Python 3 function doing
def single_read(self, register):
'''
Reads data from desired register only once.
'''
comm_reg = (0b00010 << 3) + register
if register == self.AD7730_STATUS_REG:
bytes_num = 1
elif register =... | As a Python code translator, you convert algorithms and pseudocode into Python. |
This method returns the status of the specific entry in the filter. | Given the following Python 3 function, write the documentation
def getStatus(self):
"""
RDY - Ready Bit. This bit provides the status of the RDY flag from the part. The status and function of this bit is the same as the RDY output pin. A number of events set the RDY bit high as indicated in Table XVIII... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def setMode(self
,mode
,polarity
,den
,iovalue
,data_length
,reference
,input_range
,clock_enable
,burn_out
,c... | Create a Python 3 function to
set the mode of the specified channel. | As a python code expert, you are capable of creating scripts from specifications. |
Downsample a fastq file into memory and return the new file and the new file. | Make a summary of the following Python 3 code
def downsample(work_dir, sample_name, fastq_left_fpath, fastq_right_fpath, downsample_to, num_pairs=None):
sample_name = sample_name or splitext(''.join(lc if lc == rc else '' for lc, rc in zip(fastq_left_fpath, fastq_right_fpath)))[0]
l_out_fpath = make_downsample... | You are a Python code architect, reviewing and designing scalable and efficient code |
4. 12 Checksum Calculation from an unsigned short input | Here you have a function in Python 3, explain what it does
def _calculate_checksum(value):
# CRC
polynomial = 0x131 # //P(x)=x^8+x^5+x^4+1 = 100110001
crc = 0xFF
# calculates 8-Bit checksum with given polynomial
for byteCtr in [ord(x) for x in struct.pack(">H", value)]:
... | You are a Python code generator, capable of creating scripts from specifications. |
Run when button is pressed. | Make a summary of the following Python 3 code
def run(self):
inside = 0
for draws in range(1, self.data['samples']):
# generate points and check whether they are inside the unit circle
r1, r2 = (random(), random())
if r1 ** 2 + r2 ** 2 < 1.0:
inside +... | You are a Python code analyst, evaluating scripts for potential improvements. |
Decorator for action handlers. | Make a summary of the following Python 3 code
def on_action(action):
@wrapt.decorator
@tornado.gen.coroutine
def _execute(wrapped, instance, args, kwargs):
return wrapped(*args, **kwargs)
_execute.action = action
return _execute | As a Python code analyst, you investigate and solve complex coding mysteries |
Initialize datastores for this analysis instance. | How would you explain what the following Python 3 function does
def init_datastores(self):
self.data = Datastore(self.id_)
self.data.subscribe(lambda data: self.emit('data', data))
self.class_data = Datastore(type(self).__name__)
self.class_data.subscribe(lambda data: self.emit('class_da... | You are a Python code architect, reviewing and designing scalable and efficient code |
def emit(self, signal, message='__nomessagetoken__'):
"""Emit a signal to the frontend.
:param str signal: name of the signal
:param message: message to send
:returns: return value from frontend emit function
:rtype: tornado.concurrent.Future
"""
# call pre-emit ... | Can you implement a function in Python 3 that
emits a signal to the frontend. | You are a Python code architect, reviewing and designing scalable and efficient code |
Set value at position i and return a Future. | Explain what the following Python 3 code does
def set(self, i, value):
value_encoded = encode(value, self.get_change_trigger(i))
if i in self.data and self.data[i] == value_encoded:
return self
self.data[i] = value_encoded
return self.trigger_changed(i) | You are a Python code analyst, evaluating scripts for potential improvements. |
def set(self, key, value):
"""Set a value at key and return a Future.
:rtype: tornado.concurrent.Future
"""
value_encoded = encode(value, self.get_change_trigger(key))
if key in self.data and self.data[key] == value_encoded:
return self
self.data[key] = val... | Create a Python 3 function for
setting a value at key and return a Future. | As a Python code composer, you craft elegant and concise scripts. |
Update the dictionary with the new data. | Can you generate the documentation for the following Python 3 function
def update(self, new_data):
for k, v in new_data.items():
self[k] = v
return self | As a Python code composer, you craft elegant and concise scripts. |
def trigger_all_change_callbacks(self):
"""Trigger all callbacks that were set with on_change()."""
return [
ret
for key in DatastoreLegacy.store[self.domain].keys()
for ret in self.trigger_change_callbacks(key)
] | Create a Python 3 function for
triggering all callbacks that were set with on_change. | As a Python code composer, you craft elegant and concise scripts. |
def set(self, key, value):
"""Set value at key and return a Future
:rtype: tornado.concurrent.Future
"""
return DatastoreLegacy.store[self.domain].set(key, value) | Can you write a function in Python 3 where it
sets value at key and return a Future | As a python code expert, you are capable of creating scripts from specifications. |
Initialize datastore.
Only sets values for keys that are not in the datastore already.
:param dict key_value_pairs:
A set of key value pairs to use to initialize the datastore. | Here you have a function in Python 3, explain what it does
def init(self, key_value_pairs):
for k, v in key_value_pairs.items():
if k not in DatastoreLegacy.store[self.domain]:
DatastoreLegacy.store[self.domain][k] = v | You are a Python code analyst, evaluating scripts for potential improvements. |
def close(self):
"""Close and delete instance."""
# remove callbacks
DatastoreLegacy.datastores[self.domain].remove(self)
# delete data after the last instance is gone
if self.release_storage and \
not DatastoreLegacy.datastores[self.domain]:
del Datastor... | Can you write a function in Python 3 where it
closes and delete instance. | As a Python code analyst, you investigate and solve complex coding mysteries |
def gen(skipdirhtml=False):
"""Generate html and dirhtml output."""
docs_changelog = 'docs/changelog.rst'
check_git_unchanged(docs_changelog)
pandoc('--from=markdown', '--to=rst', '--output=' + docs_changelog, 'CHANGELOG.md')
if not skipdirhtml:
sphinx_build['-b', 'dirhtml', '-W', '-E', 'doc... | Write a Python 3 script to
generate html and dirhtml output. | As a python code expert, you are capable of creating scripts from specifications. |
redraw the cross - hair on the horizontal slice plot | Can you tell what is the following Python 3 function doing
def __reset_crosshair(self):
self.lhor.set_ydata(self.y_coord)
self.lver.set_xdata(self.x_coord) | You are a Python code generator, capable of creating scripts from specifications. |
def __init_vertical_plot(self):
"""
set up the vertical profile plot
Returns
-------
"""
# clear the plot if lines have already been drawn on it
if len(self.ax2.lines) > 0:
self.ax2.cla()
# set up the vertical profile plot
self.ax2.set... | Implement a Python 3 function for
initializing the vertical plot for the current locale. | You are a Python code generator, capable of creating scripts from specifications. |
This function is called when the mouse is clicked on the base calendar. It updates the vertical profile and slice plots. | Here you have a function in Python 3, explain what it does
def __onclick(self, event):
# only do something if the first plot has been clicked on
if event.inaxes == self.ax1:
# retrieve the click coordinates
self.x_coord = event.xdata
self.y_coord = event.... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def LookupChain(lookup_func_list):
"""Returns a *function* suitable for passing as the more_formatters argument
to Template.
NOTE: In Java, this would be implemented using the 'Composite' pattern. A
*list* of formatter lookup function behaves the same as a *single* formatter
lookup funcion.
Note the dist... | Write a Python 3 script to
return a function suitable for passing as the more_formatters argument athrow. | As a Python code composer, you craft elegant and concise scripts. |
def PythonPercentFormat(format_str):
"""Use Python % format strings as template format specifiers."""
if format_str.startswith('printf '):
fmt = format_str[len('printf '):]
return lambda value: fmt % value
else:
return None | Create a Python 3 function for
using Python % format strings as template format specifiers. | As a Python code composer, you craft elegant and concise scripts. |
Returns whether the value should be considered a plural value. | Given the following Python 3 function, write the documentation
def Plural(format_str):
if format_str.startswith('plural?'):
i = len('plural?')
try:
splitchar = format_str[i] # Usually a space, but could be something else
_, plural_val, singular_val = format_str.split(splitchar)
except IndexE... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_merged_cds(genome):
"""
Returns all CDS merged, used:
- for TargQC general reports CDS coverage statistics for WGS
- for Seq2C CNV calling when no capture BED available
"""
bed = get_all_features(genome)
debug('Filtering BEDTool for high confidence CDS and stop codons')
return be... | Write a Python 3 function for
returning all merged CDSs for a genome | You are a Python code generator, capable of creating scripts from specifications. |
Returns the BedTools object for the given path. | Can you tell what is the following Python 3 function doing
def _get(relative_path, genome=None):
chrom = None
if genome:
if '-chr' in genome:
genome, chrom = genome.split('-')
check_genome(genome)
relative_path = relative_path.format(genome=genome)
path = abspath(join(di... | You are a Python code generator, capable of creating scripts from specifications. |
Run the provided command and return the path to the output file. | Can you tell what is the following Python 3 function doing
def run(cmd, output_fpath=None, input_fpath=None, checks=None, stdout_to_outputfile=True,
stdout_tx=True, reuse=False, env_vars=None):
"""Run the provided command, logging details and checking for errors.
"""
if output_fpath and reuse:
... | As a Python code composer, you craft elegant and concise scripts. |
fix java. lang. Double. parseDouble error on entries like 6082. 49 | Make a summary of the following Python 3 code
def _correct_qualimap_genome_results(samples):
for s in samples:
if verify_file(s.qualimap_genome_results_fpath):
correction_is_needed = False
with open(s.qualimap_genome_results_fpath, 'r') as f:
content = f.readlines()
... | As a Python code composer, you craft elegant and concise scripts. |
This function takes a list of samples and corrects the insert size histogram. | Can you generate the documentation for the following Python 3 function
def _correct_qualimap_insert_size_histogram(work_dir, samples):
for s in samples:
qualimap1_dirname = dirname(s.qualimap_ins_size_hist_fpath).replace('raw_data_qualimapReport', 'raw_data')
qualimap2_dirname = dirname(s.qualimap_i... | You are a Python code architect, reviewing and designing scalable and efficient code |
Normalize the length of a vector to one | Here you have a function in Python 3, explain what it does
def norm_vec(vector):
assert len(vector) == 3
v = np.array(vector)
return v/np.sqrt(np.sum(v**2)) | As a Python code composer, you craft elegant and concise scripts. |
Rotates a list of points along a reference axis. | Can you tell what is the following Python 3 function doing
def rotate_points_to_axis(points, axis):
axis = norm_vec(axis)
u, v, w = axis
points = np.array(points)
# Determine the rotational angle in the x-z plane
phi = np.arctan2(u, w)
# Determine the tilt angle w.r.t. the y-axis
theta = np.... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def rotation_matrix_from_point(point, ret_inv=False):
"""Compute rotation matrix to go from [0,0,1] to `point`.
First, the matrix rotates to in the polar direction. Then,
a rotation about the y-axis is performed to match the
azimuthal angle in the x-z-plane.
This rotation matrix is required for th... | Write a Python 3 function that can
compute the rotation matrix that rotates from [ 0 1 ) to point. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Compute the rotation matrix that rotates to a point on a 3D plane. | Given the following Python 3 function, write the documentation
def rotation_matrix_from_point_planerot(point, plane_angle, ret_inv=False):
# These matrices are correct if there is no tilt of the
# rotational axis within the detector plane (x-y).
D, Dinv = rotation_matrix_from_point(point, ret_inv=True)
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Compute the points on a unit sphere that correspond to the distribution of points about the given angles and tilt. | Here you have a function in Python 3, explain what it does
def sphere_points_from_angles_and_tilt(angles, tilted_axis):
assert len(angles.shape) == 1
# Normalize tilted axis.
tilted_axis = norm_vec(tilted_axis)
[u, v, w] = tilted_axis
# Initial distribution of points about great circle (x-z).
ne... | As a Python code composer, you craft elegant and concise scripts. |
def filenames_to_uniq(names,new_delim='.'):
'''
Given a set of file names, produce a list of names consisting of the
uniq parts of the names. This works from the end of the name. Chunks of
the name are split on '.' and '-'.
For example:
A.foo.bar.txt
B.foo.bar.txt
retur... | Create a Python 3 function for
giving a set of file names produce a list of names consisting of the uniq parts of the names. This works from the end of the name. | As a Python code composer, you craft elegant and concise scripts. |
Executes an action in the analysis with the given message. | Here you have a function in Python 3, explain what it does
def run_process(self, analysis, action_name, message='__nomessagetoken__'):
if action_name == 'connect':
analysis.on_connect(self.executable, self.zmq_publish)
while not analysis.zmq_handshake:
yield tornado.gen.sleep(0... | As a Python code analyst, you investigate and solve complex coding mysteries |
Check git to avoid overwriting user changes. | Given the following Python 3 function, write the documentation
def check_git_unchanged(filename, yes=False):
if check_staged(filename):
s = 'There are staged changes in {}, overwrite? [y/n] '.format(filename)
if yes or input(s) in ('y', 'yes'):
return
else:
raise Runt... | As a Python code composer, you craft elegant and concise scripts. |
Check if there are changes to be committed in the index. | Can you generate the documentation for the following Python 3 function
def check_staged(filename=None):
retcode, _, stdout = git['diff-index', '--quiet', '--cached', 'HEAD',
filename].run(retcode=None)
if retcode == 1:
return True
elif retcode == 0:
return False
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def run_process(analysis, action_name, message='__nomessagetoken__'):
"""Executes an action in the analysis with the given message.
It also handles the start and stop signals in the case that message
is a `dict` with a key ``__process_id``.
:param str action_name: Name of the action to... | Write a Python 3 function for
executing an action in the analysis with the given message. | You are a Python code analyst, evaluating scripts for potential improvements. |
def dl_file(url, dest, chunk_size=6553):
"""Download `url` to `dest`"""
import urllib3
http = urllib3.PoolManager()
r = http.request('GET', url, preload_content=False)
with dest.open('wb') as out:
while True:
data = r.read(chunk_size)
if data is None or len(data) == 0... | Can you create a Python 3 function that
downloads url to dest | You are a Python code generator, capable of creating scripts from specifications. |
def extract_lzma(path):
"""Extract an lzma file and return the temporary file name"""
tlfile = pathlib.Path(path)
# open lzma file
with tlfile.open("rb") as td:
data = lzma.decompress(td.read())
# write temporary tar file
fd, tmpname = tempfile.mkstemp(prefix="odt_ex_", suffix=".tar")
... | Implement a function in Python 3 to
extract an lzma file and return the temporary file name | As a python code expert, you are capable of creating scripts from specifications. |
def get_file(fname, datapath=datapath):
"""Return path of an example data file
Return the full path to an example data file name.
If the file does not exist in the `datapath` directory,
tries to download it from the ODTbrain GitHub repository.
"""
# download location
datapath = pathlib.Path... | Can you implement a function in Python 3 that
downloads a file from the ODTbrain GitHub repository. | As a Python code analyst, you investigate and solve complex coding mysteries |
def load_tar_lzma_data(tlfile):
"""Load example sinogram data from a .tar.lzma file"""
tmpname = extract_lzma(tlfile)
# open tar file
fields_real = []
fields_imag = []
phantom = []
parms = {}
with tarfile.open(tmpname, "r") as t:
members = t.getmembers()
members.sort(ke... | Implement a function in Python 3 to
load example sinogram data from a. tar. lzma file | You are a Python code architect, reviewing and designing scalable and efficient code |
Load example sinogram data from a. zip file | Can you tell what is the following Python 3 function doing
def load_zip_data(zipname, f_sino_real, f_sino_imag,
f_angles=None, f_phantom=None, f_info=None):
"""Load example sinogram data from a .zip file"""
ret = []
with zipfile.ZipFile(str(zipname)) as arc:
sino_real = np.loadtxt(... | As a python code expert, you are capable of creating scripts from specifications. |
r Returns a 2D Fourier mapping of theorem at the given sinograms and angle res. | Explain what the following Python 3 code does
def fourier_map_2d(uSin, angles, res, nm, lD=0, semi_coverage=False,
coords=None, count=None, max_count=None, verbose=0):
r"""2D Fourier mapping with the Fourier diffraction theorem
Two-dimensional diffraction tomography reconstruction
algori... | As a Python code composer, you craft elegant and concise scripts. |
Decorator to create an output filename from an input file with the specified extension. | Here you have a function in Python 3, explain what it does
def transform_to(ext):
def decor(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
out_file = kwargs.get("out_file", None)
if not out_file:
in_path = kwargs.get("in_file", args[0])
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Context manager to temporarily change to a new directory. | Here you have a function in Python 3, explain what it does
def chdir(new_dir):
cur_dir = os.getcwd()
safe_mkdir(new_dir)
os.chdir(new_dir)
try:
yield
finally:
os.chdir(cur_dir) | You are a Python code generator, capable of creating scripts from specifications. |
def file_uptodate(fname, cmp_fname):
"""Check if a file exists, is non-empty and is more recent than cmp_fname.
"""
try:
return (file_exists(fname) and file_exists(cmp_fname) and
getmtime(fname) >= getmtime(cmp_fname))
except OSError:
return False | Can you create a Python 3 function that
checks if a file exists is non - empty and is more recent than cmp_fname. | You are a Python code architect, reviewing and designing scalable and efficient code |
def save_diskspace(fname, reason, config):
"""Overwrite a file in place with a short message to save disk.
This keeps files as a sanity check on processes working, but saves
disk by replacing them with a short message.
"""
if config["algorithm"].get("save_diskspace", False):
with open(fname... | Write a Python 3 script to
overwrite a file in place with a short message to save disk. | You are a Python code generator, capable of creating scripts from specifications. |
def symlink_plus(orig, new):
"""Create relative symlinks and handle associated biological index files.
"""
for ext in ["", ".idx", ".gbi", ".tbi", ".bai"]:
if os.path.exists(orig + ext) and not os.path.lexists(new + ext):
with chdir(os.path.dirname(new)):
os.symlink(os.pa... | Implement a Python 3 function for
creating relative symlinks and handle associated biological index files. | As a Python code analyst, you investigate and solve complex coding mysteries |
def partition(pred, iterable):
'Use a predicate to partition entries into false entries and true entries'
# partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
t1, t2 = itertools.tee(iterable)
try:
return itertools.ifilterfalse(pred, t1), itertools.ifilter(pred, t2)
except:
r... | Implement a Python 3 function for
using a predicate to partition entries into false entries and true entries | As a Python code composer, you craft elegant and concise scripts. |
def get_in(d, t, default=None):
"""
look up if you can get a tuple of values from a nested dictionary,
each item in the tuple a deeper layer
example: get_in({1: {2: 3}}, (1, 2)) -> 3
example: get_in({1: {2: 3}}, (2, 3)) -> {}
"""
result = reduce(lambda d, t: d.get(t, {}), t, d)
if not r... | Can you implement a function in Python 3 that
looks up if you can get a tuple of values from a nested dictionary | As a Python code analyst, you investigate and solve complex coding mysteries |
def which(program):
"""
returns the path to an executable or None if it can't be found
"""
def is_exe(_fpath):
return os.path.isfile(_fpath) and os.access(_fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
... | Write a Python 3 function that can
return the path to an executable or None if it can t be found | You are a Python code generator, capable of creating scripts from specifications. |
Expand ~ and ~user constructs. | How would you explain what the following Python 3 function does
def expanduser(path):
if path[:1] != '~':
return path
i, n = 1, len(path)
while i < n and path[i] not in '/\\':
i = i + 1
if 'HOME' in os.environ:
userhome = os.environ['HOME']
elif 'USERPROFILE' in os.environ:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Split on file extensions allowing for zipped extensions. | Here you have a function in Python 3, explain what it does
def splitext_plus(fname):
base, ext = splitext(fname)
if ext in [".gz", ".bz2", ".zip"]:
base, ext2 = splitext(base)
ext = ext2 + ext
return base, ext | As a Python code analyst, you investigate and solve complex coding mysteries |
Put dots instead of empty cells in order to view TSV with column - t
| Can you generate a brief explanation for the following Python 3 code
def dots_to_empty_cells(config, tsv_fpath):
def proc_line(l, i):
while '\t\t' in l:
l = l.replace('\t\t', '\t.\t')
return l
return iterate_file(config, tsv_fpath, proc_line, suffix='dots') | As a python code expert, you are capable of creating scripts from specifications. |
Wrap file generation in a transaction moving to output if finishes. | Explain what the following Python 3 code does
def file_transaction(work_dir, *rollback_files):
exts = {".vcf": ".idx", ".bam": ".bai", "vcf.gz": ".tbi"}
safe_fpaths, orig_names = _flatten_plus_safe(work_dir, rollback_files)
__remove_files(safe_fpaths) # remove any half-finished transactions
try:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Flatten names of files and create temporary file names. | How would you explain what the following Python 3 function does
def _flatten_plus_safe(tmp_dir, rollback_files):
tx_fpaths, orig_files = [], []
for fnames in rollback_files:
if isinstance(fnames, six.string_types):
fnames = [fnames]
for fname in fnames:
tx_file = fname + ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def merge_overlaps(work_dir, bed_fpath, distance=None):
"""Merge bed file intervals to avoid overlapping regions.
Overlapping regions (1:1-100, 1:90-100) cause issues with callers like FreeBayes
that don't collapse BEDs prior to using them.
"""
output_fpath = intermediate_fname(work_dir, bed_fpath, ... | Implement a function in Python 3 to
merge bed file intervals to avoid overlapping regions. Overlapping regions (1:1-100, 1:90-100) cause issues with callers like FreeBayes that don't collapse BEDs prior to using them. | You are a Python code architect, reviewing and designing scalable and efficient code |
Checks the format of the BED file for correct format. | Here you have a function in Python 3, explain what it does
def checkformat(self):
fd = open_gzipsafe(self.filename)
line = fd.readline()
while line.startswith('#'):
line = fd.readline()
fields = line.split('\t')
lc = 1
error = ''
# Checks t... | You are a Python code generator, capable of creating scripts from specifications. |
def trigger_all_callbacks(self, callbacks=None):
"""Trigger callbacks for all keys on all or a subset of subscribers.
:param Iterable callbacks: list of callbacks or none for all subscribed
:rtype: Iterable[tornado.concurrent.Future]
"""
return [ret
for key in se... | Write a Python 3 script for
triggering callbacks for all keys on all or a subset of subscribers. | As a Python code composer, you craft elegant and concise scripts. |
def set(self, key, value):
"""Set a value at key and return a Future.
:rtype: Iterable[tornado.concurrent.Future]
"""
value_encoded = encode(value)
if key in self.data and self.data[key] == value_encoded:
return []
self.data[key] = value_encoded
ret... | Create a Python 3 function for
setting a value at key and return a Future. | You are a Python code generator, capable of creating scripts from specifications. |
Update the datastore.
Taxonomy state. | Given the following Python 3 function, write the documentation
def set_state(self, updater=None, **kwargs):
if callable(updater):
state_change = updater(self)
elif updater is not None:
state_change = updater
else:
state_change = kwargs
return [callbac... | As a Python code composer, you craft elegant and concise scripts. |
Initialize datastore.
Only sets values for keys that are not in the datastore already.
:param dict key_value_pairs:
A set of key value pairs to use to initialize the datastore.
:rtype: Iterable[tornado.concurrent.Future] | Here you have a function in Python 3, explain what it does
def init(self, key_value_pairs=None, **kwargs):
if key_value_pairs is None:
key_value_pairs = kwargs
return [self.set(k, v)
for k, v in key_value_pairs.items()
if k not in self] | As a Python code composer, you craft elegant and concise scripts. |
Close and delete instance. | Explain what the following Python 3 code does
def close(self):
# remove callbacks
Datastore.stores[self.domain].remove(self)
# delete data after the last instance is gone
if self.release_storage and not Datastore.stores[self.domain]:
del Datastore.global_data[self.domain]
... | You are a Python code generator, capable of creating scripts from specifications. |
def run_multisample_qualimap(output_dir, work_dir, samples, targqc_full_report):
""" 1. Generates Qualimap2 plots and put into plots_dirpath
2. Adds records to targqc_full_report.plots
"""
plots_dirpath = join(output_dir, 'plots')
individual_report_fpaths = [s.qualimap_html_fpath for s in sample... | Can you write a function in Python 3 where it
runs Qualimap2 for multiple - sample plots. | You are a Python code analyst, evaluating scripts for potential improvements. |
Rasterize a vector object | Can you generate a brief explanation for the following Python 3 code
def rasterize(vectorobject, reference, outname=None, burn_values=1, expressions=None, nodata=0, append=False):
if expressions is None:
expressions = ['']
if isinstance(burn_values, (int, float)):
burn_values = [burn_values]
... | As a python code expert, you are capable of creating scripts from specifications. |
Reproject a raster image to a new file. | Here you have a function in Python 3, explain what it does
def reproject(rasterobject, reference, outname, targetres=None, resampling='bilinear', format='GTiff'):
if isinstance(rasterobject, str):
rasterobject = Raster(rasterobject)
if not isinstance(rasterobject, Raster):
raise RuntimeError('ra... | As a Python code composer, you craft elegant and concise scripts. |
This function creates a 3D data cube that can be used to mosaicked by a set of raster files. | Make a summary of the following Python 3 code
def stack(srcfiles, dstfile, resampling, targetres, dstnodata, srcnodata=None, shapefile=None, layernames=None,
sortfun=None, separate=False, overwrite=False, compress=True, cores=4):
"""
function for mosaicking, resampling and stacking of multiple raster ... | As a python code expert, you are capable of creating scripts from specifications. |
def allstats(self, approximate=False):
"""
Compute some basic raster statistics
Parameters
----------
approximate: bool
approximate statistics from overviews or a subset of all tiles?
Returns
-------
list of dicts
a list with a di... | How would you implement a function in Python 3 that
computes some basic raster statistics for each tile. | As a python code expert, you are capable of creating scripts from specifications. |
read all raster bands into a numpy ndarray | How would you explain what the following Python 3 function does
def array(self):
if self.bands == 1:
return self.matrix()
else:
arr = self.raster.ReadAsArray().transpose(1, 2, 0)
if isinstance(self.nodata, list):
for i in range(0, self.bands):
... | As a Python code composer, you craft elegant and concise scripts. |
set the names of the raster bands
| Explain what the following Python 3 code does
def bandnames(self, names):
if not isinstance(names, list):
raise TypeError('the names to be set must be of type list')
if len(names) != self.bands:
raise ValueError(
'length mismatch of names to be set ({}) and number... | As a Python code composer, you craft elegant and concise scripts. |
Returns the bounding box of the object in the specified format. | Explain what the following Python 3 code does
def bbox(self, outname=None, format='ESRI Shapefile', overwrite=True):
if outname is None:
return bbox(self.geo, self.proj4)
else:
bbox(self.geo, self.proj4, outname=outname, format=format, overwrite=overwrite) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def extract(self, px, py, radius=1, nodata=None):
"""
extract weighted average of pixels intersecting with a defined radius to a point.
Parameters
----------
px: int or float
the x coordinate in units of the Raster SRS
py: int or float
the y coord... | How would you implement a function in Python 3 that
extracts weighted average of pixels intersecting with a defined radius to a point | As a Python code composer, you craft elegant and concise scripts. |
def is_valid(self):
"""
Check image integrity.
Tries to compute the checksum for each raster layer and returns False if this fails.
See this forum entry:
`How to check if image is valid? <https://lists.osgeo.org/pipermail/gdal-dev/2013-November/037520.html>`_.
Returns
... | Can you write a function in Python 3 where it
checks image integrity. Tries to compute the checksum for each raster layer and returns False if this fails. See this forum entry: `How to check if image is valid? <https://lists.osgeo.org/pipermail/gdal-dev/2013-November/037520.html>`_. Returns ------- bool is the file val... | You are a Python code analyst, evaluating scripts for potential improvements. |
Load all raster data to internal memory arrays. | Here you have a function in Python 3, explain what it does
def load(self):
for i in range(1, self.bands + 1):
self.__data[i - 1] = self.matrix(i) | You are a Python code architect, reviewing and designing scalable and efficient code |
read a raster band into a numpy ndarray | Explain what the following Python 3 code does
def matrix(self, band=1, mask_nan=True):
mat = self.__data[band - 1]
if mat is None:
mat = self.raster.GetRasterBand(band).ReadAsArray()
if mask_nan:
if isinstance(self.nodata, list):
nodat... | As a Python code analyst, you investigate and solve complex coding mysteries |
get the raster resolution in x and y direction | Here you have a function in Python 3, explain what it does
def res(self):
return (abs(float(self.geo['xres'])), abs(float(self.geo['yres']))) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def rescale(self, fun):
"""
perform raster computations with custom functions and assign them to the existing raster object in memory
Parameters
----------
fun: function
the custom function to compute on the data
Examples
--------
>>> with Ra... | Write a Python 3 script to
perform raster computations with custom functions and assign them to the existing raster object in memory | You are a Python code analyst, evaluating scripts for potential improvements. |
Write the raster object to a file. | Can you generate the documentation for the following Python 3 function
def write(self, outname, dtype='default', format='ENVI', nodata='default', compress_tif=False, overwrite=False):
if os.path.isfile(outname) and not overwrite:
raise RuntimeError('target file already exists')
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def numpy2gdalint(self):
"""
create a dictionary for mapping numpy data types to GDAL data type codes
Returns
-------
dict
the type map
"""
if not hasattr(self, '__numpy2gdalint'):
tmap = {}
for group in ['int', 'u... | Implement a function in Python 3 to
create a dictionary for mapping numpy data types to GDAL data type codes returns a dictionary for mapping numpy data types to GDAL data type codes returns a dictionary for mapping numpy data types to GDAL data type codes returns None | As a Python code analyst, you investigate and solve complex coding mysteries |
Parse object describing static routes. | Explain what the following Python 3 code does
def static_parser(static):
if static is None:
return
if isinstance(static, dict):
static = static.items()
for group in static:
if not isinstance(group, dict):
yield group
continue
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def analyses_info(self):
"""Add analyses from the analyses folder."""
f_config = os.path.join(self.analyses_path, 'index.yaml')
tornado.autoreload.watch(f_config)
with io.open(f_config, 'r', encoding='utf8') as f:
config = yaml.safe_load(f)
self.info.update(config... | Write a Python 3 script for
adding analyses from the analyses folder. | As a Python code composer, you craft elegant and concise scripts. |
def build(self):
"""Run the build command specified in index.yaml."""
for cmd in self.build_cmds:
log.info('building command: {}'.format(cmd))
full_cmd = 'cd {}; {}'.format(self.analyses_path, cmd)
log.debug('full command: {}'.format(full_cmd))
subprocess.... | Write a Python 3 script to
run the build command specified in index. yaml. | As a python code expert, you are capable of creating scripts from specifications. |
def get(self):
"""Render the List-of-Analyses overview page."""
return self.render(
'index.html',
databench_version=DATABENCH_VERSION,
meta_infos=self.meta_infos(),
**self.info
) | Can you create a Python 3 function that
renders the List - of - Analyses overview page. | As a python code expert, you are capable of creating scripts from specifications. |
def Reset(self):
' Reset Axis and set default parameters for H-bridge '
spi.SPI_write_byte(self.CS, 0xC0) # reset
# spi.SPI_write_byte(self.CS, 0x14) # Stall Treshold setup
# spi.SPI_write_byte(self.CS, 0xFF)
# spi.SPI_write_byte(self.CS, 0x13) # Over Current Tresho... | Create a Python 3 function for
resetting Axis and set default parameters for H - bridge | As a Python code analyst, you investigate and solve complex coding mysteries |
def _init_worker(X, X_shape, X_dtype):
"""Initializer for pool for _mprotate"""
# Using a dictionary is not strictly necessary. You can also
# use global variables.
mprotate_dict["X"] = X
mprotate_dict["X_shape"] = X_shape
mprotate_dict["X_dtype"] = X_dtype | How would you implement a function in Python 3 that
initializes for pool for _mprotate | As a python code expert, you are capable of creating scripts from specifications. |
Uses multiprocessing to rotate the data in - place on an intel i7 - 3820 CPU @ 3. 60GHz with 8 cores. | How would you explain what the following Python 3 function does
def _mprotate(ang, lny, pool, order):
targ_args = list()
slsize = np.int(np.floor(lny / ncores))
for t in range(ncores):
ymin = t * slsize
ymax = (t + 1) * slsize
if t == ncores - 1:
ymax = lny
targ... | As a python code expert, you are capable of creating scripts from specifications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.