output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Same as find but returns a list of all occurences | Explain what the following Python 3 code does
def findAllByBiSearch(self, strSeq) :
arr = self.encode(strSeq)
lst = []
self._dichFind(arr[0], self, 0, lst)
return lst | As a Python code composer, you craft elegant and concise scripts. |
returns the first occurence of strSeq in self. Takes polymorphisms into account | How would you explain what the following Python 3 function does
def find(self, strSeq) :
arr = self.encode(strSeq)
return self._kmp_find(arr[0], self) | You are a Python code generator, capable of creating scripts from specifications. |
Same as find but returns a list of all occurences | Can you generate a brief explanation for the following Python 3 code
def findAll(self, strSeq) :
arr = self.encode(strSeq)
lst = []
lst = self._kmp_find(arr[0], self, lst)
return lst | You are a Python code analyst, evaluating scripts for potential improvements. |
decodes a binary sequence to return a string | Here you have a function in Python 3, explain what it does
def decode(self, binSequence):
try:
binSeq = iter(binSequence[0])
except TypeError, te:
binSeq = binSequence
ret = ''
for b in binSeq :
ch = ''
for c in self.charToBin :
if b & self.forma[self.charToBin[c]] > 0 :
ch += c +'/'
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def parse(self, filename, gziped = False, stream = False) :
"""opens a file"""
self.stream = stream
if gziped :
self.f = gzip.open(filename)
else :
self.f = open(filename)
self.filename = filename
self.gziped = gziped
lineId = 0
inLegend = True
while inLegend :
ll = self.f.readline()... | Write a Python 3 script to
parse a file and returns a dictionary of the object properties | As a Python code translator, you convert algorithms and pseudocode into Python. |
Decode an UTF - 8 String at the given offset. | Can you generate a brief explanation for the following Python 3 code
def _decode8(self, offset):
# UTF-8 Strings contain two lengths, as they might differ:
# 1) the UTF-16 length
str_len, skip = self._decode_length(offset, 1)
offset += skip
# 2) the utf-8 string length
e... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Decode an UTF - 16 String at the given offset. | Can you generate the documentation for the following Python 3 function
def _decode16(self, offset):
str_len, skip = self._decode_length(offset, 2)
offset += skip
# The len is the string len in utf-16 units
encoded_bytes = str_len * 2
data = self.m_charbuff[offset: offset + enco... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _decode_length(self, offset, sizeof_char):
"""
Generic Length Decoding at offset of string
The method works for both 8 and 16 bit Strings.
Length checks are enforced:
* 8 bit strings: maximum of 0x7FFF bytes (See
http://androidxref.com/9.0.0_r3/xref/frameworks/base/l... | Write a Python 3 script to
decode the length of the string at the given offset. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _fix_name(self, name):
"""
Apply some fixes to element named and attribute names.
Try to get conform to:
> Like element names, attribute names are case-sensitive and must start with a letter or underscore.
> The rest of the name can contain letters, digits, hyphens, underscor... | Can you write a function in Python 3 where it
applies some fixes to element named and attribute names. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _fix_value(self, value):
"""
Return a cleaned version of a value
according to the specification:
> Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
See https://www.w3.org/TR/xml/#charsets
:param value: a value to clean
:r... | How would you code a function in Python 3 to
fix the value of the attribute to be a string that is not part of the XML. | You are a Python code generator, capable of creating scripts from specifications. |
Run analysis on the APK file and set all the attributes in the class attribute. | Here you have a function in Python 3, explain what it does
def _apk_analysis(self):
i = "AndroidManifest.xml"
try:
manifest_data = self.zip.read(i)
except KeyError:
log.warning("Missing AndroidManifest.xml. Is this an APK file?")
else:
ap = AXMLPrinter... | As a python code expert, you are capable of creating scripts from specifications. |
def _get_file_magic_name(self, buffer):
"""
Return the filetype guessed for a buffer
:param buffer: bytes
:return: str of filetype
"""
default = "Unknown"
ftype = None
try:
# Magic is optional
import magic
except ImportErro... | Implement a Python 3 function for
getting the filetype guessed for a buffer. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return the files inside the APK with their associated types | Make a summary of the following Python 3 code
def get_files_types(self):
if self._files == {}:
# Generate File Types / CRC List
for i in self.get_files():
buffer = self.zip.read(i)
self.files_crc32[i] = crc32(buffer)
# FIXME why not use the... | You are a Python code generator, capable of creating scripts from specifications. |
def _patch_magic(self, buffer, orig):
"""
Overwrite some probably wrong detections by mime libraries
:param buffer: bytes of the file to detect
:param orig: guess by mime libary
:return: corrected guess
"""
if ("Zip" in orig) or ('(JAR)' in orig):
val... | How would you implement a function in Python 3 that
patches magic to return correct guess by mime libraries | As a python code expert, you are capable of creating scripts from specifications. |
Calculates and returns a dictionary of filenames and CRC32s | Can you tell what is the following Python 3 function doing
def get_files_crc32(self):
if self.files_crc32 == {}:
for i in self.get_files():
buffer = self.zip.read(i)
self.files_crc32[i] = crc32(buffer)
return self.files_crc32 | As a Python code composer, you craft elegant and concise scripts. |
Test if the APK has multiple DEX files | Here you have a function in Python 3, explain what it does
def is_multidex(self):
dexre = re.compile("^classes(\d+)?.dex$")
return len([instance for instance in self.get_files() if dexre.search(instance)]) > 1 | As a Python code composer, you craft elegant and concise scripts. |
def get_elements(self, tag_name, attribute, with_namespace=True):
"""
Deprecated: use `get_all_attribute_value()` instead
Return elements in xml files which match with the tag name and the specific attribute
:param tag_name: a string which specify the tag name
:param attribute: a... | How would you implement a function in Python 3 that
gets the elements in xml files which match with the tag name and the specific attribute name. | As a python code expert, you are capable of creating scripts from specifications. |
Format a value with packagename if not already set | Given the following Python 3 function, write the documentation
def _format_value(self, value):
if len(value) > 0:
if value[0] == ".":
value = self.package + value
else:
v_dot = value.find(".")
if v_dot == 0:
value = self... | As a python code expert, you are capable of creating scripts from specifications. |
Return the element in xml files which match with the tag name and the specific attribute name. | How would you explain what the following Python 3 function does
def get_element(self, tag_name, attribute, **attribute_filter):
for i in self.xml:
if self.xml[i] is None:
continue
tag = self.xml[i].findall('.//' + tag_name)
if len(tag) == 0:
re... | You are a Python code generator, capable of creating scripts from specifications. |
def is_tag_matched(self, tag, **attribute_filter):
"""
Return true if the attributes matches in attribute filter
:param tag: specify the tag element
:type tag: Element
:param attribute: specify the attribute
:type attribute: string
"""
if len(attribute_fil... | Write a Python 3 script to
return true if the attributes of the tag match the ones in attribute filter | You are a Python code architect, reviewing and designing scalable and efficient code |
Return the name of the tag | Given the following Python 3 function, write the documentation
def name(self):
if self.m_name == -1 or (self.m_event != const.START_TAG and self.m_event != const.END_TAG):
return u''
return self.sb[self.m_name] | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return the Namespace URI of the current tag. | Given the following Python 3 function, write the documentation
def namespace(self):
if self.m_name == -1 or (self.m_event != const.START_TAG and self.m_event != const.END_TAG):
return u''
# No Namespace
if self.m_namespaceUri == 0xFFFFFFFF:
return u''
return sel... | You are a Python code generator, capable of creating scripts from specifications. |
def text(self):
"""
Return the String assosicated with the current text
"""
if self.m_name == -1 or self.m_event != const.TEXT:
return u''
return self.sb[self.m_name] | Write a Python 3 function for
returning the current text assosicated with the current text | As a Python code translator, you convert algorithms and pseudocode into Python. |
def getAttributeNamespace(self, index):
"""
Return the Namespace URI (if any) for the attribute
"""
uri = self.getAttributeUri(index)
# No Namespace
if uri == 0xFFFFFFFF:
return u''
return self.sb[uri] | Write a Python 3 function for
returning the Namespace URI for the attribute at the given index. | You are a Python code analyst, evaluating scripts for potential improvements. |
def getAttributeName(self, index):
"""
Returns the String which represents the attribute name
"""
offset = self._get_attribute_offset(index)
name = self.m_attributes[offset + const.ATTRIBUTE_IX_NAME]
res = self.sb[name]
# If the result is a (null) string, we need... | How would you implement a function in Python 3 that
returns the String which represents the attribute name | You are a Python code generator, capable of creating scripts from specifications. |
def getAttributeValueType(self, index):
"""
Return the type of the attribute at the given index
:param index: index of the attribute
"""
offset = self._get_attribute_offset(index)
return self.m_attributes[offset + const.ATTRIBUTE_IX_VALUE_TYPE] | Create a Python 3 function to
return the type of the attribute at the given index | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the data of the attribute at the given index | Explain what the following Python 3 code does
def getAttributeValueData(self, index):
offset = self._get_attribute_offset(index)
return self.m_attributes[offset + const.ATTRIBUTE_IX_VALUE_DATA] | You are a Python code analyst, evaluating scripts for potential improvements. |
Get the resource name qualifier for the current configuration. | Given the following Python 3 function, write the documentation
def get_qualifier(self):
res = []
mcc = self.imsi & 0xFFFF
mnc = (self.imsi & 0xFFFF0000) >> 16
if mcc != 0:
res.append("mcc%d" % mcc)
if mnc != 0:
res.append("mnc%d" % mnc)
if self.l... | You are a Python code generator, capable of creating scripts from specifications. |
Generate a cache key from request object data | How would you explain what the following Python 3 function does
def make_cache_key(request):
headers = frozenset(request._p['header'].items())
path = frozenset(request._p['path'].items())
query = frozenset(request._p['query'])
return (request.url, headers, path, query) | As a Python code analyst, you investigate and solve complex coding mysteries |
check if a cache fits esipy needs or not | Explain what the following Python 3 code does
def check_cache(cache):
if isinstance(cache, BaseCache):
return cache
elif cache is False:
return DictCache()
elif cache is None:
return DummyCache()
else:
raise ValueError('Provided cache must implement BaseCache') | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_cache_time_left(expires_header):
""" return the time left in second for an expires header """
epoch = datetime(1970, 1, 1)
# this date is ALWAYS in UTC (RFC 7231)
expire = (
datetime(
*parsedate(expires_header)[:6]
) - epoch
).total_seconds()
now = (datetime.u... | Create a Python 3 function for
returning the time left in second for an expires header | You are a Python code analyst, evaluating scripts for potential improvements. |
def generate_code_verifier(n_bytes=64):
"""
source: https://github.com/openstack/deb-python-oauth2client
Generates a 'code_verifier' as described in section 4.1 of RFC 7636.
This is a 'high-entropy cryptographic random string' that will be
impractical for an attacker to guess.
Args:
n_by... | Write a Python 3 function that can
generate a code_verifier for the current user. | You are a Python code analyst, evaluating scripts for potential improvements. |
Generate a code_challenge for a given token. | Can you generate a brief explanation for the following Python 3 code
def generate_code_challenge(verifier):
digest = hashlib.sha256(verifier.encode('utf-8')).digest()
return base64.urlsafe_b64encode(digest).rstrip(b'=').decode('utf-8') | As a Python code composer, you craft elegant and concise scripts. |
Adds a receiver to the list of receivers. | Make a summary of the following Python 3 code
def add_receiver(self, receiver):
if not callable(receiver):
raise TypeError("receiver must be callable")
self.event_receivers.append(receiver) | As a python code expert, you are capable of creating scripts from specifications. |
def remove_receiver(self, receiver):
""" Remove a receiver to the list of receivers.
:param receiver: a callable variable
"""
if receiver in self.event_receivers:
self.event_receivers.remove(receiver) | Can you implement a function in Python 3 that
removes a receiver from the list of receivers. | As a Python code analyst, you investigate and solve complex coding mysteries |
def send_robust(self, **kwargs):
""" Trigger all receiver and pass them the parameters
If an exception is raised it will be catched and displayed as error
in the logger (if defined).
:param kwargs: all arguments from the event.
"""
for receiver in self.event_recei... | Create a Python 3 function for
sending a message to all event receivers that have been triggered and pass them the parameters. | You are a Python code generator, capable of creating scripts from specifications. |
def __get_or_create_app(self, url, cache_key):
""" Get the app from cache or generate a new one if required
Because app object doesn't have etag/expiry, we have to make
a head() call before, to have these informations first... """
headers = {"Accept": "application/json"}
app_url... | How would you implement a function in Python 3 that
gets the app from cache or generate a new one if required | As a Python code translator, you convert algorithms and pseudocode into Python. |
def clear_cached_endpoints(self, prefix=None):
""" Invalidate all cached endpoints, meta included
Loop over all meta endpoints to generate all cache key the
invalidate each of them. Doing it this way will prevent the
app not finding keys as the user may change its prefixes
Meta ... | Write a Python 3 function that can
invalidate all cached endpoints meta included | You are a Python code architect, reviewing and designing scalable and efficient code |
Get from jwks_ui all the JWKS keys required to decode JWT Token. | Can you tell what is the following Python 3 function doing
def __get_jwks_key(self, jwks_uri, **kwargs):
jwks_key = kwargs.pop('jwks_key', None)
if not jwks_key:
res = self._session.get(jwks_uri)
res.raise_for_status()
jwks_key = res.json()
self.jwks_k... | You are a Python code generator, capable of creating scripts from specifications. |
def __prepare_token_request(self, params, url=None):
"""Generate the request parameters to execute the POST call to
get or refresh a token.
Parameters
----------
params : dictionary
Contains the parameters that will be given as data to the oauth
e... | How would you implement a function in Python 3 that
prepares the request parameters to execute the POST call to the OAuth token endpoint. | You are a Python code generator, capable of creating scripts from specifications. |
def get_auth_uri(self, state, scopes=None, implicit=False):
"""Constructs the full auth uri and returns it..
Parameters
----------
state : string
The state to pass through the auth process
scopes : list (optional)
The list of scope to have
... | How would you code a function in Python 3 to
construct the auth uri and returns it | As a python code expert, you are capable of creating scripts from specifications. |
def get_refresh_token_params(self, scope_list=None):
""" Return the param object for the post() call to get the access_token
from the refresh_token
:param code: the refresh token
:return: a dict with the url, params and header
"""
if self.refresh_token is None:
... | Write a Python 3 script for
returning the params dict for the post request to get the access_token from the refresh_token | As a python code expert, you are capable of creating scripts from specifications. |
def update_token(self, response_json, **kwargs):
""" Update access_token, refresh_token and token_expiry from the
response body.
The response must be converted to a json object before being passed as
a parameter
:param response_json: the response body to use.
:par... | Write a Python 3 script to
update the access_token refresh_token and token_expiry attributes from the response body. | As a Python code analyst, you investigate and solve complex coding mysteries |
def is_token_expired(self, offset=0):
""" Return true if the token is expired.
The offset can be used to change the expiry time:
- positive value decrease the time (sooner)
- negative value increase the time (later)
If the expiry is not set, always return True. This case a... | Implement a function in Python 3 to
return true if the token is expired. | As a python code expert, you are capable of creating scripts from specifications. |
def refresh(self, scope_list=None):
""" Update the auth data (tokens) using the refresh token in auth.
"""
request_data = self.get_refresh_token_params(scope_list)
res = self._session.post(**request_data)
if res.status_code != 200:
raise APIException(
... | Can you write a function in Python 3 where it
refreshes the auth data using the refresh token in auth. | You are a Python code generator, capable of creating scripts from specifications. |
def auth(self, code):
""" Request the token to the /oauth/token endpoint.
Update the security tokens.
:param code: the code you get from the auth process
"""
request_data = self.get_access_token_params(code)
res = self._session.post(**request_data)
if r... | Write a Python 3 script to
request the token to the auth endpoint. | As a python code expert, you are capable of creating scripts from specifications. |
def revoke(self):
"""Revoke the current tokens then empty all stored tokens
This returns nothing since the endpoint return HTTP/200
whatever the result is...
Currently not working with JWT, left here for compatibility.
"""
if not self.refresh_token and not self.ac... | How would you code a function in Python 3 to
revoke the current tokens then empty all stored tokens | You are a Python code generator, capable of creating scripts from specifications. |
def verify(self, kid='JWT-Signature-Key', options=None):
"""Decode and verify the token and return the decoded informations
Parameters
----------
kid : string
The JWKS key id to identify the key to decode the token.
Default is 'JWT-Signature-Key'. Only cha... | Write a Python 3 script to
decode and verify the token and return the decoded informations. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _retry_request(self, req_and_resp, _retry=0, **kwargs):
"""Uses self._request in a sane retry loop (for 5xx level errors).
Do not use the _retry parameter, use the same params as _request
Used when ESIClient is initialized with retry_requests=True
if raise_on_error is True, t... | Can you write a function in Python 3 where it
tries to send a request and retries the response. | You are a Python code analyst, evaluating scripts for potential improvements. |
Use a threadpool to send multiple requests in parallel. | How would you explain what the following Python 3 function does
def multi_request(self, reqs_and_resps, threads=20, **kwargs):
opt = kwargs.pop('opt', {})
raw_body_only = kwargs.pop('raw_body_only', self.raw_body_only)
# you shouldnt need more than 100, 20 is probably fine in most cases
... | As a Python code composer, you craft elegant and concise scripts. |
def _request(self, req_and_resp, **kwargs):
""" Take a request_and_response object from pyswagger.App and
check auth, token, headers, prepare the actual request and fill the
response
Note on performance : if you need more performance (because you are
using this in a batch)... | Write a Python 3 function that can
make a request and fill the response with the fields from the request and response. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def head(self, req_and_resp, **kwargs):
""" Take a request_and_response object from pyswagger.App, check
and prepare everything to make a valid HEAD request
:param req_and_resp: the request and response object from pyswagger.App
:param opt: options, see pyswagger/blob/master/pyswag... | Can you implement a function in Python 3 that
makes a HEAD request and return a response object. | You are a Python code generator, capable of creating scripts from specifications. |
def __cache_response(self, cache_key, res, method):
""" cache the response
if method is one of self.__uncached_method__, don't cache anything
"""
if ('expires' in res.headers
and method not in self.__uncached_methods__):
cache_timeout = get_cache_time_... | Write a Python 3 script to
cache the response and check if it is expired | As a Python code translator, you convert algorithms and pseudocode into Python. |
def __make_request(self, request, opt, cache_key=None, method=None):
""" Check cache, deal with expiration and etag, make the request and
return the response or cached response.
:param request: the pyswagger.io.Request object to prepare the request
:param opt: options, see pyswagge... | Write a Python 3 script to
make a new request and return the response or cached response. | As a Python code translator, you convert algorithms and pseudocode into Python. |
generate a hash from data object to be used as cache key | Can you tell what is the following Python 3 function doing
def _hash(data):
hash_algo = hashlib.new('md5')
hash_algo.update(pickle.dumps(data))
# prefix allows possibility of multiple applications
# sharing same keyspace
return 'esi_' + hash_algo.hexdigest() | As a python code expert, you are capable of creating scripts from specifications. |
This Method computes feature vector and train model from the data. | Here you have a function in Python 3, explain what it does
def fit_from_image(self, data, voxelsize, seeds, unique_cls):
fvs, clsselected = self.features_from_image(data, voxelsize, seeds, unique_cls)
self.fit(fvs, clsselected) | As a python code expert, you are capable of creating scripts from specifications. |
def load(self, mdl_file):
"""
load model from file. fv_type is not set with this function. It is expected to set it before.
"""
import dill as pickle
mdl_file_e = op.expanduser(mdl_file)
sv = pickle.load(open(mdl_file_e, "rb"))
self.mdl = sv["mdl"]
# sel... | Write a Python 3 function for
loading the current model from a file | As a python code expert, you are capable of creating scripts from specifications. |
def features_from_image(
self, data, voxelsize, seeds=None, unique_cls=None
): # , voxels=None):
"""
Input data is 3d image
:param data: is 3d image
:param seeds: ndimage with same shape as data, nonzero values means seeds.
:param unique_cls: can select only fv for ... | Create a Python 3 function to
function to compute feature vectors from image data. | You are a Python code generator, capable of creating scripts from specifications. |
def _fit_one_class(self, clx, cl):
""" Train clas number cl with data clx.
Use trainFromImageAndSeeds() function if you want to use 3D image data
as an input.
clx: data, 2d matrix
cl: label, integer
label: gmmsame, gaussian_kde, dpgmm, stored
"""
logge... | Create a Python 3 function for
fitting one class in the database. | As a Python code analyst, you investigate and solve complex coding mysteries |
likelihood from data x with fature vector with 4 fatures | How would you explain what the following Python 3 function does
def likelihood(self, x, cl):
# sha = x.shape
# xr = x.reshape(-1, sha[-1])
# outsha = sha[:-1]
# from PyQt4.QtCore import pyqtRemoveInputHook
# pyqtRemoveInputHook()
logger.debug("likel " + str(x.shape))
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def inspect_node_neighborhood(nlinks, msinds, node_msindex):
"""
Get information about one node in graph
:param nlinks: neighboorhood edges
:param msinds: indexes in 3d image
:param node_msindex: int, multiscale index of selected voxel
:return: node_neighboor_edges_and_weights, node_neighboor_s... | Can you implement a function in Python 3 that
gets information about one node in graph | As a Python code composer, you craft elegant and concise scripts. |
Inspects one node in graph and returns unariesalt edges and weights for each node in graph | How would you explain what the following Python 3 function does
def inspect_node(nlinks, unariesalt, msinds, node_msindex):
node_unariesalt = unariesalt[node_msindex]
neigh_edges, neigh_seeds = inspect_node_neighborhood(nlinks, msinds, node_msindex)
return node_unariesalt, neigh_edges, neigh_seeds | As a Python code analyst, you investigate and solve complex coding mysteries |
Convert seeds - like selection of voxel to multiscale index. | Can you tell what is the following Python 3 function doing
def get_node_msindex(msinds, node_seed):
if type(node_seed) == np.ndarray:
seed_indexes = np.nonzero(node_seed)
elif type(node_seed) == list:
seed_indexes = node_seed
else:
seed_indexes = [node_seed]
selected_nodes_msind... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Makes relabeling of data if there are unused values. | Can you tell what is the following Python 3 function doing
def relabel_squeeze(data):
palette, index = np.unique(data, return_inverse=True)
data = index.reshape(data.shape)
# realy slow solution
# unq = np.unique(data)
# actual_label = 0
# for lab in unq:
# da... | You are a Python code analyst, evaluating scripts for potential improvements. |
Load the model stored in the file. | Can you tell what is the following Python 3 function doing
def load(self, filename, fv_extern=None):
self.modelparams["mdl_stored_file"] = filename
if fv_extern is not None:
self.modelparams["fv_extern"] = fv_extern
# segparams['modelparams'] = {
# 'mdl_stored_file': mdl... | You are a Python code architect, reviewing and designing scalable and efficient code |
def __msgc_step12_low_resolution_segmentation(self):
"""
Get the segmentation and the
:return:
"""
import scipy
start = self._start_time
# ===== low resolution data processing
# default parameters
# TODO segparams_lo and segparams_hi je tam asi zb... | Write a Python 3 function that can
get the segmentation and the :return: | As a Python code composer, you craft elegant and concise scripts. |
def __msgc_step3_discontinuity_localization(self):
"""
Estimate discontinuity in basis of low resolution image segmentation.
:return: discontinuity in low resolution
"""
import scipy
start = self._start_time
seg = 1 - self.segmentation.astype(np.int8)
sel... | Write a Python 3 function that can
estimate discontinuity in basis of low resolution image segmentation. :return: discontinuity in low resolution | You are a Python code analyst, evaluating scripts for potential improvements. |
Run Graph - Cut segmentation with refinement of low resolution multiscale graph. | Can you generate the documentation for the following Python 3 function
def __multiscale_gc_lo2hi_run(self): # , pyed):
# from PyQt4.QtCore import pyqtRemoveInputHook
# pyqtRemoveInputHook()
self._msgc_lo2hi_resize_init()
self.__msgc_step0_init()
hard_constraints = self.__msgc_s... | You are a Python code generator, capable of creating scripts from specifications. |
Run Graph - Cut segmentation with simplifiyng of high resolution multiscale graph. | Can you generate a brief explanation for the following Python 3 code
def __multiscale_gc_hi2lo_run(self): # , pyed):
# from PyQt4.QtCore import pyqtRemoveInputHook
# pyqtRemoveInputHook()
self.__msgc_step0_init()
hard_constraints = self.__msgc_step12_low_resolution_segmentation()
... | As a python code expert, you are capable of creating scripts from specifications. |
Return values by indexes. | Can you generate the documentation for the following Python 3 function
def __ordered_values_by_indexes(self, data, inds):
# get unique labels and their first indexes
# lab, linds = np.unique(inds, return_index=True)
# compute values by indexes
# values = data.reshape(-1)[linds]
... | As a python code expert, you are capable of creating scripts from specifications. |
def __hi2lo_multiscale_indexes(self, mask, orig_shape): # , zoom):
"""
Function computes multiscale indexes of ndarray.
mask: Says where is original resolution (0) and where is small
resolution (1). Mask is in small resolution.
orig_shape: Original shape of input data.
... | Write a Python 3 script for
functioning computes multiscale indexes of ndarray. | You are a Python code architect, reviewing and designing scalable and efficient code |
Interactivity setting with 3d seed editor | Here you have a function in Python 3, explain what it does
def interactivity(self, min_val=None, max_val=None, qt_app=None):
from .seed_editor_qt import QTSeedEditor
from PyQt4.QtGui import QApplication
if min_val is None:
min_val = np.min(self.img)
if max_val is None:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def set_seeds(self, seeds):
"""
Function for manual seed setting. Sets variable seeds and prepares
voxels for density model.
:param seeds: ndarray (0 - nothing, 1 - object, 2 - background,
3 - object just hard constraints, no model training, 4 - background
just hard cons... | Write a Python 3 script for
functioning for manual seed setting. Sets variable seeds and prepares voxels for density model. | As a python code expert, you are capable of creating scripts from specifications. |
Run the Graph Cut segmentation according to preset parameters. | Can you generate a brief explanation for the following Python 3 code
def run(self, run_fit_model=True):
if run_fit_model:
self.fit_model(self.img, self.voxelsize, self.seeds)
self._start_time = time.time()
if self.segparams["method"].lower() in ("graphcut", "gc"):
self.... | You are a Python code generator, capable of creating scripts from specifications. |
def __set_hard_hard_constraints(self, tdata1, tdata2, seeds):
"""
it works with seed labels:
0: nothing
1: object 1 - full seeds
2: object 2 - full seeds
3: object 1 - not a training seeds
4: object 2 - not a training seeds
"""
seeds_mask = (seeds ... | Write a Python 3 script for
setting the hard constraints for the tdata1 and tdata2 | You are a Python code analyst, evaluating scripts for potential improvements. |
Compute edge values for tlinks based on image intensity
voxels1 voxels2 and otherfeatures. | How would you explain what the following Python 3 function does
def __similarity_for_tlinks_obj_bgr(
self,
data,
voxelsize,
# voxels1, voxels2,
# seeds, otherfeatures=None
):
"""
Compute edge values for graph cut tlinks based on image intensity
and tex... | As a python code expert, you are capable of creating scripts from specifications. |
Compute nlinks grid from data shape information. | How would you explain what the following Python 3 function does
def __create_nlinks(self, data, inds=None, boundary_penalties_fcn=None):
# use the gerneral graph algorithm
# first, we construct the grid graph
start = time.time()
if inds is None:
inds = np.arange(data.size).re... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def debug_get_reconstructed_similarity(
self,
data3d=None,
voxelsize=None,
seeds=None,
area_weight=1,
hard_constraints=True,
return_unariesalt=False,
):
"""
Use actual model to calculate similarity. If no input is given the last image is used.
... | Implement a Python 3 function for
using actual model to calculate similarity. If no input is given the last image is used. :param data3d: :param voxelsize: :param seeds: :param area_weight: :param hard_constraints: :param return_unariesalt: :return: | As a python code expert, you are capable of creating scripts from specifications. |
Show the reconstructed similarity of a set of tlinks. | Can you generate a brief explanation for the following Python 3 code
def debug_show_reconstructed_similarity(
self,
data3d=None,
voxelsize=None,
seeds=None,
area_weight=1,
hard_constraints=True,
show=True,
bins=20,
slice_number=None,
):
... | As a Python code composer, you craft elegant and concise scripts. |
Get info about the node. See pycut. inspect_node for details. | Can you generate the documentation for the following Python 3 function
def debug_inspect_node(self, node_msindex):
return inspect_node(self.nlinks, self.unariesalt2, self.msinds, node_msindex) | You are a Python code analyst, evaluating scripts for potential improvements. |
Call after segmentation to see selected node neighborhood. | Can you generate a brief explanation for the following Python 3 code
def debug_interactive_inspect_node(self):
if (
np.sum(
np.abs(
np.asarray(self.msinds.shape) - np.asarray(self.segmentation.shape)
)
)
== 0
):
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _ssgc_prepare_data_and_run_computation(
self,
# voxels1, voxels2,
hard_constraints=True,
area_weight=1,
):
"""
Setting of data.
You need set seeds if you want use hard_constraints.
"""
# from PyQt4.QtCore import pyqtRemoveInputHook
... | Implement a Python 3 function for
preparing data and run computation | You are a Python code analyst, evaluating scripts for potential improvements. |
def resize_to_shape(data, shape, zoom=None, mode="nearest", order=0):
"""
Function resize input data to specific shape.
:param data: input 3d array-like data
:param shape: shape of output data
:param zoom: zoom is used for back compatibility
:mode: default is 'nearest'
"""
# @TODO remove... | Create a Python 3 function to
function resize input data to specific shape. | As a python code expert, you are capable of creating scripts from specifications. |
Zooms a set of seeds into a single block. | Can you generate a brief explanation for the following Python 3 code
def seed_zoom(seeds, zoom):
# import scipy
# loseeds=seeds
labels = np.unique(seeds)
# remove first label - 0
labels = np.delete(labels, 0)
# @TODO smart interpolation for seeds in one block
# loseeds = scipy.ndimage... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Zoom data to specific shape. | Can you tell what is the following Python 3 function doing
def zoom_to_shape(data, shape, dtype=None):
import scipy
import scipy.ndimage
zoomd = np.array(shape) / np.array(data.shape, dtype=np.double)
import warnings
datares = scipy.ndimage.interpolation.zoom(data, zoomd, order=0, mode="reflect")
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Crop the data.
crop(data, crinfo)
:param crinfo: min and max for each axis - [[minX, maxX], [minY, maxY], [minZ, maxZ]] | How would you explain what the following Python 3 function does
def crop(data, crinfo):
crinfo = fix_crinfo(crinfo)
return data[
__int_or_none(crinfo[0][0]) : __int_or_none(crinfo[0][1]),
__int_or_none(crinfo[1][0]) : __int_or_none(crinfo[1][1]),
__int_or_none(crinfo[2][0]) : __int_or_no... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def combinecrinfo(crinfo1, crinfo2):
"""
Combine two crinfos. First used is crinfo1, second used is crinfo2.
"""
crinfo1 = fix_crinfo(crinfo1)
crinfo2 = fix_crinfo(crinfo2)
crinfo = [
[crinfo1[0][0] + crinfo2[0][0], crinfo1[0][0] + crinfo2[0][1]],
[crinfo1[1][0] + crinfo2[1][0],... | Implement a function in Python 3 to
combine two crinfos into one crinfo. | You are a Python code generator, capable of creating scripts from specifications. |
def crinfo_from_specific_data(data, margin=0):
"""
Create crinfo of minimum orthogonal nonzero block in input data.
:param data: input data
:param margin: add margin to minimum block
:return:
"""
# hledáme automatický ořez, nonzero dá indexy
logger.debug("crinfo")
logger.debug(str(m... | Create a Python 3 function for
creating crinfo of minimum orthogonal nonzero block in input data. | As a Python code analyst, you investigate and solve complex coding mysteries |
Unrops the image into the next image in the crinfo array. | Make a summary of the following Python 3 code
def uncrop(data, crinfo, orig_shape, resize=False, outside_mode="constant", cval=0):
if crinfo is None:
crinfo = list(zip([0] * data.ndim, orig_shape))
elif np.asarray(crinfo).size == data.ndim:
crinfo = list(zip(crinfo, np.asarray(crinfo) + data.sh... | You are a Python code architect, reviewing and designing scalable and efficient code |
Function recognize order of crinfo and convert it to proper format. | Given the following Python 3 function, write the documentation
def fix_crinfo(crinfo, to="axis"):
crinfo = np.asarray(crinfo)
if crinfo.shape[0] == 2:
crinfo = crinfo.T
return crinfo | You are a Python code generator, capable of creating scripts from specifications. |
Get list of edges for a single segment of a single segment. | Can you generate a brief explanation for the following Python 3 code
def grid_edges(shape, inds=None, return_directions=True):
if inds is None:
inds = np.arange(np.prod(shape)).reshape(shape)
# if not self.segparams['use_boundary_penalties'] and \
# boundary_penalties_fcn is None :
if le... | You are a Python code architect, reviewing and designing scalable and efficient code |
def gen_grid_2d(shape, voxelsize):
"""
Generate list of edges for a base grid.
"""
nr, nc = shape
nrm1, ncm1 = nr - 1, nc - 1
# sh = nm.asarray(shape)
# calculate number of edges, in 2D: (nrows * (ncols - 1)) + ((nrows - 1) * ncols)
nedges = 0
for direction in range(len(shape)):
... | Can you create a Python 3 function that
generates list of edges for a base grid. | As a Python code analyst, you investigate and solve complex coding mysteries |
Writes nodes and edges to VTK file | How would you explain what the following Python 3 function does
def write_grid_to_vtk(fname, nodes, edges, node_flag=None, edge_flag=None):
if node_flag is None:
node_flag = np.ones([nodes.shape[0]], dtype=np.bool)
if edge_flag is None:
edge_flag = np.ones([edges.shape[0]], dtype=np.bool)
n... | You are a Python code architect, reviewing and designing scalable and efficient code |
def add_nodes(self, coors, node_low_or_high=None):
"""
Add new nodes at the end of the list.
"""
last = self.lastnode
if type(coors) is nm.ndarray:
if len(coors.shape) == 1:
coors = coors.reshape((1, coors.size))
nadd = coors.shape[0]
... | Write a Python 3 script for
adding new nodes at the end of the list. | As a Python code composer, you craft elegant and concise scripts. |
def add_edges(self, conn, edge_direction, edge_group=None, edge_low_or_high=None):
"""
Add new edges at the end of the list.
:param edge_direction: direction flag
:param edge_group: describes group of edges from same low super node and same direction
:param edge_low_or_high: zero... | Write a Python 3 script for
adding new edges at the end of the list. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _edge_group_substitution(
self, ndid, nsplit, idxs, sr_tab, ndoffset, ed_remove, into_or_from
):
"""
Reconnect edges.
:param ndid: id of low resolution edges
:param nsplit: number of split
:param idxs: indexes of low resolution
:param sr_tab:
:para... | How would you implement a function in Python 3 that
substitutes low resolution edges. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Generate base grid of the hierarchy. | How would you explain what the following Python 3 function does
def generate_base_grid(self, vtk_filename=None):
nd, ed, ed_dir = self.gen_grid_fcn(self.data.shape, self.voxelsize)
self.add_nodes(nd)
self.add_edges(ed, ed_dir, edge_low_or_high=0)
if vtk_filename is not None:
... | As a python code expert, you are capable of creating scripts from specifications. |
def split_voxels(self, vtk_filename=None):
"""
Second step of algorithm
:return:()
"""
self.cache = {}
self.stats["t graph 10"] = time.time() - self.start_time
self.msi = MultiscaleArray(self.data.shape, block_size=self.nsplit)
# old implementation
... | Create a Python 3 function for
seconding step of algorithm :return:() | As a Python code analyst, you investigate and solve complex coding mysteries |
def mul_block(self, index, val):
"""Multiply values in block"""
self._prepare_cache_slice(index)
self.msinds[self.cache_slice] *= val | Create a Python 3 function to
multiply values in block | As a python code expert, you are capable of creating scripts from specifications. |
def select_from_fv_by_seeds(fv, seeds, unique_cls):
"""
Tool to make simple feature functions take features from feature array by seeds.
:param fv: ndarray with lineariezed feature. It's shape is MxN, where M is number of image pixels and N is number
of features
:param seeds: ndarray with seeds. Doe... | Implement a Python 3 function for
tooling to make simple feature functions take features from feature vector array by seeds. | As a Python code composer, you craft elegant and concise scripts. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.