output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def getpeercert(self, binary_form=False):
"""Retrieve the peer's certificate
When binary form is requested, the peer's DER-encoded certficate is
returned if it was transmitted during the handshake.
When binary form is not requested, and the peer's certificate has been
validated... | Can you write a function in Python 3 where it
retrieves the peer s certificate and return it as a dictionary. | You are a Python code generator, capable of creating scripts from specifications. |
Retrieve information about the current cipher and return a triple consisting of the cipher name SSL protocol version and number of secret bits. | Here you have a function in Python 3, explain what it does
def cipher(self):
if not self._handshake_done:
return
current_cipher = SSL_get_current_cipher(self._ssl.value)
cipher_name = SSL_CIPHER_get_name(current_cipher)
cipher_version = SSL_CIPHER_get_version(current_cipher... | As a python code expert, you are capable of creating scripts from specifications. |
def _prep_bins():
"""
Support for running straight out of a cloned source directory instead
of an installed distribution
"""
from os import path
from sys import platform, maxsize
from shutil import copy
bit_suffix = "-x86_64" if maxsize > 2**32 else "-x86"
package_root = path.abspat... | Can you create a Python 3 function that
prepares the base directories for the next bin of the current platform. | As a python code expert, you are capable of creating scripts from specifications. |
Create or retrieve a muxed datagram socket instance for the given peer endpoint. | Given the following Python 3 function, write the documentation
def get_connection(self, address):
if not address:
return self._datagram_socket
# Create a new datagram socket bound to the same interface and port as
# the root socket, but connected to the given peer
conn = so... | As a Python code analyst, you investigate and solve complex coding mysteries |
def SSL_CTX_set_info_callback(ctx, app_info_cb):
"""
Set the info callback
:param callback: The Python callback to use
:return: None
"""
def py_info_callback(ssl, where, ret):
try:
app_info_cb(SSL(ssl), where, ret)
except:
pass
return
global ... | Implement a function in Python 3 to
set the info callback for the current context. | You are a Python code analyst, evaluating scripts for potential improvements. |
Raise an SSL error with the given error code. | How would you explain what the following Python 3 function does
def raise_ssl_error(code, nested=None):
err_string = str(code) + ": " + _ssl_errors[code]
if nested:
raise SSLError(code, err_string + str(nested))
raise SSLError(code, err_string) | You are a Python code architect, reviewing and designing scalable and efficient code |
Create or retrieve a muxed connection for the given peer endpoint. | Can you generate a brief explanation for the following Python 3 code
def get_connection(self, address):
if self.connections.has_key(address):
return self.connections[address]
# We need a new datagram socket on a dynamically assigned ephemeral port
conn = socket.socket(self.... | You are a Python code generator, capable of creating scripts from specifications. |
def service(self):
"""Service the root socket
Read from the root socket and forward one datagram to a
connection. The call will return without forwarding data
if any of the following occurs:
* An error is encountered while reading from the root socket
* Reading from... | Write a Python 3 script to
service the root socket and forward one datagram to the next connection. | You are a Python code generator, capable of creating scripts from specifications. |
def forward(self):
"""Forward a stored datagram
When the service method returns the address of a new peer, it holds
the datagram from that peer in this instance. In this case, this
method will perform the forwarding step. The target connection is the
one associated with address ... | How would you implement a function in Python 3 that
forwards a stored datagram from another peer to the new peer. | You are a Python code generator, capable of creating scripts from specifications. |
def emojificate_filter(content, autoescape=True):
"Convert any emoji in a string into accessible content."
# return mark_safe(emojificate(content))
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
return mark_safe(emojificate(esc(content))) | Write a Python 3 function for
converting any emoji in a string into accessible content. | You are a Python code architect, reviewing and designing scalable and efficient code |
def updateorders(self):
""" Update the orders
"""
log.info("Replacing orders")
# Canceling orders
self.cancelall()
# Target
target = self.bot.get("target", {})
price = self.getprice()
# prices
buy_price = price * (1 - target["offsets"]["... | Implement a Python 3 function for
updating the orders with the latest price and price. | As a python code expert, you are capable of creating scripts from specifications. |
def getprice(self):
""" Here we obtain the price for the quote and make sure it has
a feed price
"""
target = self.bot.get("target", {})
if target.get("reference") == "feed":
assert self.market == self.market.core_quote_market(), "Wrong market for 'feed' reference... | Can you write a function in Python 3 where it
gets the price for the quote and make sure it has a feed price | As a Python code analyst, you investigate and solve complex coding mysteries |
tick come in on every block
| Given the following Python 3 function, write the documentation
def tick(self, d):
if self.test_blocks:
if not (self.counter["blocks"] or 0) % self.test_blocks:
self.test()
self.counter["blocks"] += 1 | You are a Python code analyst, evaluating scripts for potential improvements. |
Return the bot s open orders in the current market | Here you have a function in Python 3, explain what it does
def orders(self):
self.account.refresh()
return [o for o in self.account.openorders if self.bot["market"] == o.market and self.account.openorders] | As a python code expert, you are capable of creating scripts from specifications. |
Execute a bundle of operations | Here you have a function in Python 3, explain what it does
def execute(self):
self.bitshares.blocking = "head"
r = self.bitshares.txbuffer.broadcast()
self.bitshares.blocking = False
return r | You are a Python code analyst, evaluating scripts for potential improvements. |
def cancelall(self):
""" Cancel all orders of this bot
"""
if self.orders:
return self.bitshares.cancel(
[o["id"] for o in self.orders],
account=self.account
) | Can you create a Python 3 function that
cancels all orders of this bot | As a Python code translator, you convert algorithms and pseudocode into Python. |
def raw_xml(self) -> _RawXML:
"""Bytes representation of the XML content.
(`learn more <http://www.diveintopython3.net/strings.html>`_).
"""
if self._xml:
return self._xml
else:
return etree.tostring(self.element, encoding='unicode').strip().encode(self.en... | Write a Python 3 function for
returning the XML representation of the current object. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def pq(self) -> PyQuery:
"""`PyQuery <https://pythonhosted.org/pyquery/>`_ representation
of the :class:`Element <Element>` or :class:`HTML <HTML>`.
"""
if self._pq is None:
self._pq = PyQuery(self.raw_xml)
return self._pq | How would you implement a function in Python 3 that
returns the PyQuery representation of the XML. | You are a Python code generator, capable of creating scripts from specifications. |
All found links on page in as–is form. Only works for Atom feeds. | Here you have a function in Python 3, explain what it does
def links(self) -> _Links:
return list(set(x.text for x in self.xpath('//link'))) | As a Python code translator, you convert algorithms and pseudocode into Python. |
The encoding string to be used extracted from the XML and the XML header. | Given the following Python 3 function, write the documentation
def encoding(self) -> _Encoding:
if self._encoding:
return self._encoding
# Scan meta tags for charset.
if self._xml:
self._encoding = html_to_unicode(self.default_encoding, self._xml)[0]
return self... | You are a Python code architect, reviewing and designing scalable and efficient code |
Given an XPath selector returns a list of Element <Element > objects or a single one. | How would you explain what the following Python 3 function does
def xpath(self, selector: str, *, first: bool = False, _encoding: str = None) -> _XPath:
selected = self.lxml.xpath(selector)
elements = [
Element(element=selection, default_encoding=_encoding or self.encoding)
if n... | As a python code expert, you are capable of creating scripts from specifications. |
def search(self, template: str, first: bool = False) -> _Result:
"""Search the :class:`Element <Element>` for the given parse
template.
:param template: The Parse template to use.
"""
elements = [r for r in findall(template, self.xml)]
return _get_first_or_list(elements... | Write a Python 3 script for
searching the parse XML for the given parse template. | As a python code expert, you are capable of creating scripts from specifications. |
def find(self, selector: str = '*', containing: _Containing = None, first: bool = False, _encoding: str = None) -> _Find:
"""Given a simple element name, returns a list of
:class:`Element <Element>` objects or a single one.
:param selector: Element name to find.
:param c... | Write a Python 3 function for
finding an element in the list of elements that match the provided selector. | You are a Python code architect, reviewing and designing scalable and efficient code |
Requests HTTP Response handler. Attaches .html property to
class:`requests.Response <requests.Response>` objects. | How would you explain what the following Python 3 function does
def _handle_response(response, **kwargs) -> XMLResponse:
if not response.encoding:
response.encoding = DEFAULT_ENCODING
return response | You are a Python code architect, reviewing and designing scalable and efficient code |
def request(self, *args, **kwargs) -> XMLResponse:
"""Makes an HTTP Request, with mocked User–Agent headers.
Returns a class:`HTTPResponse <HTTPResponse>`.
"""
# Convert Request object into HTTPRequest object.
r = super(XMLSession, self).request(*args, **kwargs)
return X... | Create a Python 3 function for
making an HTTP Request with mocked User - Agent headers. Returns a class : HTTPResponse <HTTPResponse >. | As a Python code composer, you craft elegant and concise scripts. |
def response_hook(response, **kwargs) -> XMLResponse:
""" Change response enconding and replace it by a HTMLResponse. """
response.encoding = DEFAULT_ENCODING
return XMLResponse._from_response(response) | Can you implement a function in Python 3 that
changes response enconding and replace it by a HTMLResponse. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def start(self):
"""Start the background process."""
self._lc = LoopingCall(self._download)
# Run immediately, and then every 30 seconds:
self._lc.start(30, now=True) | Create a Python 3 function to
start the background process. | As a Python code analyst, you investigate and solve complex coding mysteries |
def register(self, result):
"""
Register an EventualResult.
May be called in any thread.
"""
if self._stopped:
raise ReactorStopped()
self._results.add(result) | Create a Python 3 function to
register an EventualResult. May be called in any thread. | As a Python code composer, you craft elegant and concise scripts. |
def stop(self):
"""
Indicate no more results will get pushed into EventualResults, since
the reactor has stopped.
This should be called in the reactor thread.
"""
self._stopped = True
for result in self._results:
result._set_result(Failure(ReactorStop... | Can you write a function in Python 3 where it
indicates no more results will get pushed into EventualResults, since the reactor has stopped. This should be called in the reactor thread. | As a Python code analyst, you investigate and solve complex coding mysteries |
Connect the Deferred that will be the result of the eventual. | How would you explain what the following Python 3 function does
def _connect_deferred(self, deferred):
self._deferred = deferred
# Because we use __del__, we need to make sure there are no cycles
# involving this object, which is why we use a weakref:
def put(result, eventual=weakref.re... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _set_result(self, result):
"""
Set the result of the EventualResult, if not already set.
This can only happen in the reactor thread, either as a result of
Deferred firing, or as a result of ResultRegistry.stop(). So, no need
for thread-safety.
"""
if self._re... | Create a Python 3 function to
set the result of the EventualResult. | You are a Python code analyst, evaluating scripts for potential improvements. |
Return the result of the current call. | Can you tell what is the following Python 3 function doing
def _result(self, timeout=None):
if timeout is None:
warnings.warn(
"Unlimited timeouts are deprecated.",
DeprecationWarning,
stacklevel=3)
# Queue.get(None) won't get interrupted b... | You are a Python code architect, reviewing and designing scalable and efficient code |
def wait(self, timeout=None):
"""
Return the result, or throw the exception if result is a failure.
It may take an unknown amount of time to return the result, so a
timeout option is provided. If the given number of seconds pass with
no result, a TimeoutError will be thrown.
... | Write a Python 3 script for
waiting for the result of the eventual result. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return the underlying Failure object or None if the result is an error. | Can you generate a brief explanation for the following Python 3 code
def original_failure(self):
try:
result = self._result(0.0)
except TimeoutError:
return None
if isinstance(result, Failure):
return result
else:
return None | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _startReapingProcesses(self):
"""
Start a LoopingCall that calls reapAllProcesses.
"""
lc = LoopingCall(self._reapAllProcesses)
lc.clock = self._reactor
lc.start(0.1, False) | Write a Python 3 script for
starting a LoopingCall that calls reapAllProcesses. | You are a Python code analyst, evaluating scripts for potential improvements. |
Initializes the crochet library. | Make a summary of the following Python 3 code
def setup(self):
if self._started:
return
self._common_setup()
if platform.type == "posix":
self._reactor.callFromThread(self._startReapingProcesses)
if self._startLoggingWithObserver:
observer = ThreadLogO... | As a Python code analyst, you investigate and solve complex coding mysteries |
A decorator that ensures the wrapped function runs in the reactor thread. | Can you generate the documentation for the following Python 3 function
def run_in_reactor(self, function):
result = self._run_in_reactor(function)
# Backwards compatibility; use __wrapped__ instead.
try:
result.wrapped_function = function
except AttributeError:
pa... | You are a Python code generator, capable of creating scripts from specifications. |
A decorator that ensures that the wrapped function runs in the reactor s thread. | How would you explain what the following Python 3 function does
def wait_for_reactor(self, function):
warnings.warn(
"@wait_for_reactor is deprecated, use @wait_for instead",
DeprecationWarning,
stacklevel=2)
# This will timeout, in theory. In practice the process wil... | As a Python code composer, you craft elegant and concise scripts. |
A function that ensures that the passed in function runs in the reactor thread. | Here you have a function in Python 3, explain what it does
def in_reactor(self, function):
warnings.warn(
"@in_reactor is deprecated, use @run_in_reactor",
DeprecationWarning,
stacklevel=2)
@self.run_in_reactor
@wraps(function)
def add_reactor(*args, ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a Deferred that fires with a list of MX domain tuples for
a given domain. | Here you have a function in Python 3, explain what it does
def _mx(domain):
def got_records(result):
return sorted(
[(int(record.payload.preference), str(record.payload.name))
for record in result[0]])
d = lookupMailExchange(domain)
d.addCallback(got_records)
return d | As a Python code analyst, you investigate and solve complex coding mysteries |
def store(self, deferred_result):
"""
Store a EventualResult.
Return an integer, a unique identifier that can be used to retrieve
the object.
"""
self._counter += 1
self._stored[self._counter] = deferred_result
return self._counter | Implement a function in Python 3 to
store a EventualResult. Return an integer, a unique identifier that can be used to retrieve the object. | As a python code expert, you are capable of creating scripts from specifications. |
def log_errors(self):
"""
Log errors for all stored EventualResults that have error results.
"""
for result in self._stored.values():
failure = result.original_failure()
if failure is not None:
log.err(failure, "Unhandled error in stashed EventualR... | How would you implement a function in Python 3 that
logs errors for all stored EventualResults that have error results. | You are a Python code generator, capable of creating scripts from specifications. |
Start an SSH server on the given port. | Given the following Python 3 function, write the documentation
def start_ssh_server(port, username, password, namespace):
# This is a lot of boilerplate, see http://tm.tl/6429 for a ticket to
# provide a utility function that simplifies this.
from twisted.internet import reactor
from twisted.conch.insul... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Register a function and arguments to be called later. | Can you generate the documentation for the following Python 3 function
def register(self, f, *args, **kwargs):
self._functions.append(lambda: f(*args, **kwargs)) | As a Python code composer, you craft elegant and concise scripts. |
Register a function to be called from EPC client. | Explain what the following Python 3 code does
def register_function(self, function, name=None):
if name is None:
name = function.__name__
self.funcs[name] = function
return function | You are a Python code analyst, evaluating scripts for potential improvements. |
Get registered method callend name. | Explain what the following Python 3 code does
def get_method(self, name):
try:
return self.funcs[name]
except KeyError:
try:
return self.instance._get_method(name)
except AttributeError:
return SimpleXMLRPCServer.resolve_dotted_attribut... | As a python code expert, you are capable of creating scripts from specifications. |
Sets the debugger to run when an error occurs in published method. | Can you tell what is the following Python 3 function doing
def set_debugger(self, debugger):
if debugger == 'pdb':
import pdb
self.debugger = pdb
elif debugger == 'ipdb':
import ipdb
self.debugger = ipdb
else:
self.debugger = debugger | You are a Python code architect, reviewing and designing scalable and efficient code |
def connect(self, socket_or_address):
"""
Connect to server and start serving registered functions.
:type socket_or_address: tuple or socket object
:arg socket_or_address: A ``(host, port)`` pair to be passed
to `socket.create_connection`, or
... | Implement a function in Python 3 to
connect to server and start serving registered functions. | As a Python code composer, you craft elegant and concise scripts. |
def print_port(self, stream=sys.stdout):
"""
Print port this EPC server runs on.
As Emacs client reads port number from STDOUT, you need to
call this just before calling :meth:`serve_forever`.
:type stream: text stream
:arg stream: A stream object to write port on.
... | Write a Python 3 script for
printing the port number of this EPC server runs on. | You are a Python code architect, reviewing and designing scalable and efficient code |
Call a method on the current object. | Make a summary of the following Python 3 code
def call(self, name, *args, **kwds):
self.callmanager.call(self, name, *args, **kwds) | As a python code expert, you are capable of creating scripts from specifications. |
def methods(self, *args, **kwds):
"""
Request info of callable remote methods.
Arguments for :meth:`call` except for `name` can be applied to
this function too.
"""
self.callmanager.methods(self, *args, **kwds) | Implement a Python 3 function for
requesting info of callable remote methods. | As a Python code analyst, you investigate and solve complex coding mysteries |
This method is blocking and will call the remote function with the given name and arguments. | Here you have a function in Python 3, explain what it does
def call_sync(self, name, args, timeout=None):
return self._blocking_request(self.call, timeout, name, args) | You are a Python code architect, reviewing and designing scalable and efficient code |
Return arguments and keyword arguments as formatted string
ArcGIS API call | Can you generate a brief explanation for the following Python 3 code
def func_call_as_str(name, *args, **kwds):
return '{0}({1})'.format(
name,
', '.join(itertools.chain(
map('{0!r}'.format, args),
map('{0[0]!s}={0[1]!r}'.format, sorted(kwds.items()))))) | As a Python code composer, you craft elegant and concise scripts. |
Instantiate a new thread with an appropriate name. | How would you explain what the following Python 3 function does
def newthread(template="EPCThread-{0}", **kwds):
if not isinstance(template, str):
template = '{0}.{1}-{{0}}'.format(template.__module__,
template.__class__.__name__)
return threading.Thread(
... | You are a Python code generator, capable of creating scripts from specifications. |
A decorator to wrap execution of function with a context manager. | Can you generate the documentation for the following Python 3 function
def callwith(context_manager):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwds):
with context_manager:
return func(*args, **kwds)
return wrapper
return decorator | As a python code expert, you are capable of creating scripts from specifications. |
Compute image center coordinates in lat lon | Can you generate the documentation for the following Python 3 function
def _scene_centroid(self):
ul_lat = self.corner_ul_lat_product
ll_lat = self.corner_ll_lat_product
ul_lon = self.corner_ul_lon_product
ur_lon = self.corner_ur_lon_product
lat = (ul_lat + ll_lat) / 2.
l... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Earth - sun distance in AU
| Explain what the following Python 3 code does
def earth_sun_d(dtime):
doy = int(dtime.strftime('%j'))
rad_term = 0.9856 * (doy - 4) * pi / 180
distance_au = 1 - 0.01672 * cos(rad_term)
return distance_au | As a Python code composer, you craft elegant and concise scripts. |
def reflectance(self, band):
"""
:param band: An optical band, i.e. 1-5, 7
:return: At satellite reflectance, [-]
"""
if band == 6:
raise ValueError('LT5 reflectance must be other than band 6')
rad = self.radiance(band)
esun = self.ex_atm_irrad[band... | Can you write a function in Python 3 where it
returns the reflectance of the satellite in the specified band | As a Python code translator, you convert algorithms and pseudocode into Python. |
Finds the albedo of the resource in the given model | Explain what the following Python 3 code does
def albedo(self, model='smith'):
if model == 'smith':
blue, red, nir, swir1, swir2 = (self.reflectance(1), self.reflectance(3), self.reflectance(4),
self.reflectance(5), self.reflectance(7))
alb = (... | As a python code expert, you are capable of creating scripts from specifications. |
Mask saturated pixels 1 is saturated. | Can you tell what is the following Python 3 function doing
def saturation_mask(self, band, value=255):
dn = self._get_band('b{}'.format(band))
mask = self.mask()
mask = where((dn == value) & (mask > 0), True, False)
return mask | As a python code expert, you are capable of creating scripts from specifications. |
def ndvi(self):
""" Normalized difference vegetation index.
:return: NDVI
"""
red, nir = self.reflectance(3), self.reflectance(4)
ndvi = self._divide_zero((nir - red), (nir + red), nan)
return ndvi | Write a Python 3 script for
normalizing difference vegetation index. | You are a Python code analyst, evaluating scripts for potential improvements. |
get the LAI of the leaf area | Here you have a function in Python 3, explain what it does
def lai(self):
ndvi = self.ndvi()
lai = 7.0 * (ndvi ** 3)
lai = where(lai > 6., 6., lai)
return lai | As a Python code translator, you convert algorithms and pseudocode into Python. |
Mean values from Allen 2007 - > land surface temperature | How would you explain what the following Python 3 function does
def land_surface_temp(self):
rp = 0.91
tau = 0.866
rsky = 1.32
epsilon = self.emissivity(approach='tasumi')
radiance = self.radiance(6)
rc = ((radiance - rp) / tau) - ((1 - epsilon) * rsky)
lst = self... | You are a Python code architect, reviewing and designing scalable and efficient code |
def brightness_temp(self, band, temp_scale='K'):
"""Calculate brightness temperature of Landsat 8
as outlined here: http://landsat.usgs.gov/Landsat8_Using_Product.php
T = K2 / log((K1 / L) + 1)
and
L = ML * Q + AL
where:
T = At-satellite brightness temperature (degrees kelvin)
... | How would you implement a function in Python 3 that
calculates the brightness temperature of the Landsat 8 module | As a Python code composer, you craft elegant and concise scripts. |
def reflectance(self, band):
"""Calculate top of atmosphere reflectance of Landsat 8
as outlined here: http://landsat.usgs.gov/Landsat8_Using_Product.php
R_raw = MR * Q + AR
R = R_raw / cos(Z) = R_raw / sin(E)
Z = 90 - E (in degrees)
where:
... | Can you create a Python 3 function that
calculates the top of atmosphere reflectance of the Landsat 8. | You are a Python code generator, capable of creating scripts from specifications. |
Calculate top of atmosphere radiance of Landsat 8
| Can you generate the documentation for the following Python 3 function
def radiance(self, band):
ml = getattr(self, 'radiance_mult_band_{}'.format(band))
al = getattr(self, 'radiance_add_band_{}'.format(band))
dn = self._get_band('b{}'.format(band))
rad = ml * dn.astype(float32) + al
... | As a python code expert, you are capable of creating scripts from specifications. |
Normalized difference snow index. | How would you explain what the following Python 3 function does
def ndsi(self):
green, swir1 = self.reflectance(3), self.reflectance(6)
ndsi = self._divide_zero((green - swir1), (green + swir1), nan)
return ndsi | You are a Python code analyst, evaluating scripts for potential improvements. |
def whiteness_index(self):
"""Index of "Whiteness" based on visible bands.
Parameters
----------
Output
------
ndarray:
whiteness index
"""
mean_vis = (self.blue + self.green + self.red) / 3
blue_absdiff = np.absolute(self._divide_zer... | Create a Python 3 function to
return the index of the whiteness of the color bands. | You are a Python code generator, capable of creating scripts from specifications. |
Return a boolean array containing the potential cloud pixels for the given cloud class. | How would you explain what the following Python 3 function does
def potential_cloud_pixels(self):
eq1 = self.basic_test()
eq2 = self.whiteness_test()
eq3 = self.hot_test()
eq4 = self.nirswir_test()
if self.sat == 'LC8':
cir = self.cirrus_test()
return (eq1... | As a python code expert, you are capable of creating scripts from specifications. |
def temp_water(self):
"""Use water to mask tirs and find 82.5 pctile
Equation 7 and 8 (Zhu and Woodcock, 2012)
Parameters
----------
is_water: ndarray, boolean
water mask, water is True, land is False
swir2: ndarray
tirs1: ndarray
Output
... | Implement a function in Python 3 to
use water to mask tirs and find 82. 5th percentile temperature over water | As a python code expert, you are capable of creating scripts from specifications. |
The brightness probability of the brightest water. | Given the following Python 3 function, write the documentation
def brightness_prob(self, clip=True):
thresh = 0.11
bp = np.minimum(thresh, self.nir) / thresh
if clip:
bp[bp > 1] = 1
bp[bp < 0] = 0
return bp | You are a Python code architect, reviewing and designing scalable and efficient code |
Derive high and low percentiles of land temperature over clearsky land
| Explain what the following Python 3 code does
def temp_land(self, pcps, water):
# eq 12
clearsky_land = ~(pcps | water)
# use clearsky_land to mask tirs1
clear_land_temp = self.tirs1.copy()
clear_land_temp[~clearsky_land] = np.nan
clear_land_temp[~self.mask] = np.nan
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def variability_prob(self, whiteness):
"""Use the probability of the spectral variability
to identify clouds over land.
Equation 15 (Zhu and Woodcock, 2012)
Parameters
----------
ndvi: ndarray
ndsi: ndarray
whiteness: ndarray
Output
------
... | Write a Python 3 script for
using the probability of the spectral variability of clouds over land based on the variability of clouds over land. | You are a Python code generator, capable of creating scripts from specifications. |
def cloud_mask(self, min_filter=(3, 3), max_filter=(10, 10), combined=False, cloud_and_shadow=False):
"""Calculate the potential cloud layer from source data
*This is the high level function which ties together all
the equations for generating potential clouds*
Parameters
-------... | Create a Python 3 function for
calculating the potential cloud layer from source data *This is the high level function which ties together all the equations for generating potential clouds* Parameters ---------- blue: ndarray green: ndarray red: ndarray nir: ndarray swir1: ndarray swir2: ndarray cirrus: ndarray tirs1: ... | You are a Python code analyst, evaluating scripts for potential improvements. |
def gdal_nodata_mask(pcl, pcsl, tirs_arr):
"""
Given a boolean potential cloud layer,
a potential cloud shadow layer and a thermal band
Calculate the GDAL-style uint8 mask
"""
tirs_mask = np.isnan(tirs_arr) | (tirs_arr == 0)
return ((~(pcl | pcsl | tirs_mask)) * 2... | Can you create a Python 3 function that
calculates the GDAL - style uint8 mask for missing data. | As a python code expert, you are capable of creating scripts from specifications. |
def parsemeta(metadataloc):
"""Parses the metadata from a Landsat image bundle.
Arguments:
metadataloc: a filename or a directory.
Returns metadata dictionary
"""
# filename or directory? if several fit, use first one and warn
if os.path.isdir(metadataloc):
me... | Implement a Python 3 function for
parsing the metadata file and returns a dictionary of the object that represents the metadata. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _checkstatus(status, line):
"""Returns state/status after reading the next line.
The status codes are::
LE07_clip_L1TP_039027_20150529_20160902_01_T1_B1.TIF - BEGIN parsing; 1 - ENTER METADATA GROUP, 2 - READ METADATA LINE,
3 - END METDADATA GROUP, 4 - END PARSING
Permitted Transitions::... | Create a Python 3 function for
checking the status of a single line of a segmented log file. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _transstat(status, grouppath, dictpath, line):
"""Executes processing steps when reading a line"""
if status == 0:
raise MTLParseError(
"Status should not be '%s' after reading line:\n%s"
% (STATUSCODE[status], line))
elif status == 1:
currentdict = dictpath[-1]
... | Write a Python 3 function for
executing processing steps when reading a line. | You are a Python code architect, reviewing and designing scalable and efficient code |
Takes value as str returns int float date datetime or time
| How would you explain what the following Python 3 function does
def _postprocess(valuestr):
# USGS has started quoting time sometimes. Grr, strip quotes in this case
intpattern = re.compile(r'^\-?\d+$')
floatpattern = re.compile(r'^\-?\d+\.\d+(E[+-]?\d\d+)?$')
datedtpattern = '%Y-%m-%d'
datedttimep... | You are a Python code architect, reviewing and designing scalable and efficient code |
def warp_vrt(directory, delete_extra=False, use_band_map=False,
overwrite=False, remove_bqa=True, return_profile=False):
""" Read in image geometry, resample subsequent images to same grid.
The purpose of this function is to snap many Landsat images to one geometry. Use Landsat578
to download ... | Can you implement a function in Python 3 that
warps all images in a directory to a single image. | As a Python code composer, you craft elegant and concise scripts. |
Return a python executable for the given testenv base name. | Make a summary of the following Python 3 code
def tox_get_python_executable(envconfig):
try:
# pylint: disable=no-member
pyenv = (getattr(py.path.local.sysfind('pyenv'), 'strpath', 'pyenv')
or 'pyenv')
cmd = [pyenv, 'which', envconfig.basepython]
pipe = subprocess.Po... | You are a Python code analyst, evaluating scripts for potential improvements. |
Setups the option for the no - fallback plugin. | Can you tell what is the following Python 3 function doing
def _setup_no_fallback(parser):
cli_dest = 'tox_pyenv_fallback'
halp = ('If `pyenv which {basepython}` exits non-zero when looking '
'up the python executable, do not allow fallback to tox\'s '
'built-in default logic.')
# A... | You are a Python code generator, capable of creating scripts from specifications. |
def sendEmail(self, emails, massType='SingleEmailMessage'):
"""
Send one or more emails from Salesforce.
Parameters:
emails - a dictionary or list of dictionaries, each representing a
single email as described by https://www.salesforce.com/us
... | Create a Python 3 function for
sending one or more emails from Salesforce. | As a Python code composer, you craft elegant and concise scripts. |
This function is makes changes in - place. | Can you generate the documentation for the following Python 3 function
def _doPrep(field_dict):
fieldsToNull = []
for key, value in field_dict.items():
if value is None:
fieldsToNull.append(key)
field_dict[key] = []
if hasattr(value, '__iter__'):
if len(value)... | As a Python code analyst, you investigate and solve complex coding mysteries |
Prepare a list of SObjects. | Here you have a function in Python 3, explain what it does
def _prepareSObjects(sObjects):
'''Prepare a SObject'''
sObjectsCopy = copy.deepcopy(sObjects)
if isinstance(sObjectsCopy, dict):
# If root element is a dict, then this is a single object not an array
_doPrep(sObjectsCopy)
else:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def sendEmail(self, emails, mass_type='SingleEmailMessage'):
"""
Send one or more emails from Salesforce.
Parameters:
emails - a dictionary or list of dictionaries, each representing
a single email as described by https://www.salesforce.com
... | Can you write a function in Python 3 where it
sends one or more emails from Salesforce. | You are a Python code generator, capable of creating scripts from specifications. |
def queryTypesDescriptions(self, types):
"""
Given a list of types, construct a dictionary such that
each key is a type, and each value is the corresponding sObject
for that type.
"""
types = list(types)
if types:
types_descs = self.describeSObjects(ty... | Write a Python 3 function for
giving a list of types construct a dictionary such that each key is a type and each value is the corresponding sObject for that type. | You are a Python code generator, capable of creating scripts from specifications. |
def create_token(self):
"""Create a session protection token for this client.
This method generates a session protection token for the cilent, which
consists in a hash of the user agent and the IP address. This method
can be overriden by subclasses to implement different token generatio... | Create a Python 3 function for
creating a session protection token for this client. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Clear the session.
This method is invoked when the session is found to be invalid.
Subclasses can override this method to implement a custom session
reset. | Can you generate the documentation for the following Python 3 function
def clear_session(self, response):
session.clear()
# if flask-login is installed, we try to clear the
# "remember me" cookie, just in case it is set
if 'flask_login' in sys.modules:
remember_cookie = curr... | As a python code expert, you are capable of creating scripts from specifications. |
def haikunate(self, delimiter='-', token_length=4, token_hex=False, token_chars='0123456789'):
"""
Generate heroku-like random names to use in your python applications
:param delimiter: Delimiter
:param token_length: TokenLength
:param token_hex: TokenHex
:param token_ch... | Implement a function in Python 3 to
generate a random Haikunate - style random name. | As a Python code composer, you craft elegant and concise scripts. |
Returns the parser class according to the system platform | Can you tell what is the following Python 3 function doing
def get_parser_class():
global distro
if distro == 'Linux':
Parser = parser.LinuxParser
if not os.path.exists(Parser.get_command()[0]):
Parser = parser.UnixIPParser
elif distro in ['Darwin', 'MacOSX']:
Parser = pa... | You are a Python code generator, capable of creating scripts from specifications. |
Return just the default interface device dictionary. | Here you have a function in Python 3, explain what it does
def default_interface(ifconfig=None, route_output=None):
global Parser
return Parser(ifconfig=ifconfig)._default_interface(route_output=route_output) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Parse the output of the ifconfig command into the internal dictionary. | Can you generate a brief explanation for the following Python 3 code
def parse(self, ifconfig=None): # noqa: max-complexity=12
if not ifconfig:
ifconfig, __, __ = exec_cmd(self.get_command())
self.ifconfig_data = ifconfig
cur = None
patterns = self.get_patterns()
for... | You are a Python code analyst, evaluating scripts for potential improvements. |
This function is used to alter the internal dictionary of the interfaces dictionary. | Explain what the following Python 3 code does
def alter(self, interfaces):
# fixup some things
for device, device_dict in interfaces.items():
if len(device_dict['inet4']) > 0:
device_dict['inet'] = device_dict['inet4'][0]
if 'inet' in device_dict and not device_di... | As a python code expert, you are capable of creating scripts from specifications. |
def _default_interface(self, route_output=None):
"""
:param route_output: For mocking actual output
"""
if not route_output:
out, __, __ = exec_cmd('/sbin/ip route')
lines = out.splitlines()
else:
lines = route_output.split("\n")
for l... | Write a Python 3 script for
returning the default interface for the current user. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return the needle positions for a specific line. | How would you explain what the following Python 3 function does
def get(self, line_number):
if line_number not in self._get_cache:
self._get_cache[line_number] = self._get(line_number)
return self._get_cache[line_number] | You are a Python code generator, capable of creating scripts from specifications. |
Get the bytes that represent the needle positions or None. | How would you explain what the following Python 3 function does
def get_bytes(self, line_number):
if line_number not in self._needle_position_bytes_cache:
line = self._get(line_number)
if line is None:
line_bytes = None
else:
line_bytes = self.... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_line_configuration_message(self, line_number):
"""Return the cnfLine content without id for the line.
:param int line_number: the number of the line
:rtype: bytes
:return: a cnfLine message without id as defined in :ref:`cnfLine`
"""
if line_number not in self._l... | Can you write a function in Python 3 where it
returns the cnfLine message without id for the line. | As a Python code composer, you craft elegant and concise scripts. |
Read the message type from a file. | Given the following Python 3 function, write the documentation
def read_message_type(file):
message_byte = file.read(1)
if message_byte == b'':
return ConnectionClosed
message_number = message_byte[0]
return _message_types.get(message_number, UnknownMessage) | As a Python code composer, you craft elegant and concise scripts. |
def read_end_of_message(self):
"""Read the b"\\r\\n" at the end of the message."""
read = self._file.read
last = read(1)
current = read(1)
while last != b'' and current != b'' and not \
(last == b'\r' and current == b'\n'):
last = current
c... | How would you code a function in Python 3 to
read the b\\ r \ n at the end of the message. | You are a Python code generator, capable of creating scripts from specifications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.