output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def get_initial(s, delimiter=' '):
"""Return the 1st char of pinyin of string, the string must be unicode
"""
initials = (p[0] for p in _pinyin_generator(u(s), format="strip"))
return delimiter.join(initials) | How would you implement a function in Python 3 that
returns the 1st char of pinyin of string | You are a Python code architect, reviewing and designing scalable and efficient code |
def _add_to_tree(tree, word, meaning):
'''
We build word search trees, where we walk down
the letters of a word. For example:
你 Good
你好 Hello
Would build the tree
你
/ \
You 好
\
Hello
'''
if len(word) == 0:
tree[''] = meaning
... | Write a Python 3 script to
add a word to the tree. | You are a Python code analyst, evaluating scripts for potential improvements. |
def init():
'''
Load in the Chinese-English dictionary. This takes 1-2 seconds. It
is done when the other functions are used, but this is public since
preloading sometimes makes sense.
'''
global dictionaries, trees
dictionaries = {
'traditional': {},
'simplified': {}
}
... | Implement a Python 3 function for
loading in the Chinese - English dictionary. This takes 1 - 2 seconds. It is done when other functions are used. | As a Python code composer, you craft elegant and concise scripts. |
def translate_word(word, dictionary=['simplified']):
'''
Return the set of translations for a single character or word, if
available.
'''
if not dictionaries:
init()
for d in dictionary:
if word in dictionaries[d]:
return dictionaries[d][word]
return None | Can you implement a function in Python 3 that
translates a single character or word into a set of translations. | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns all words in the tree corresponding to the beginning of the word. | Explain what the following Python 3 code does
def _words_at_the_beginning(word, tree, prefix=""):
'''
We return all portions of the tree corresponding to the beginning
of `word`. This is used recursively, so we pass the prefix so we
can return meaningful words+translations.
'''
l = []
if "" ... | You are a Python code generator, capable of creating scripts from specifications. |
Yields all possible translations for all possible words in a full
. | Given the following Python 3 function, write the documentation
def all_phrase_translations(phrase):
'''
Return the set of translations for all possible words in a full
phrase. Chinese is sometimes ambiguous. We do not attempt to
disambiguate, or handle unknown letters especially well. Full
parsing i... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_status_key(self, instance):
"""Generates a key used to set a status on a field"""
key_id = "inst_%s" % id(instance) if instance.pk is None else instance.pk
return "%s.%s-%s-%s" % (instance._meta.app_label,
get_model_name(instance),
... | Write a Python 3 script for
generating a key used to set a status on a field | As a Python code translator, you convert algorithms and pseudocode into Python. |
Retrives a status of a field from cache. | Explain what the following Python 3 code does
def get_status(self, instance):
status_key, status = self._get_status(instance)
if status['state'] in ['complete', 'error']:
cache.delete(status_key)
return status | You are a Python code architect, reviewing and designing scalable and efficient code |
def set_status(self, instance, status):
"""Sets the field status for up to 5 minutes."""
status_key = self.get_status_key(instance)
cache.set(status_key, status, timeout=300) | Can you implement a function in Python 3 that
sets the status of the given instance in the cache. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns output mode. If mode is not set it will try to guess best mode from old mode and if it is not available. | Can you tell what is the following Python 3 function doing
def get_mode(self, old_mode=None):
if self.mode is not None:
return self.mode
assert self.can_write, "This format does not have a supported output mode."
if old_mode is None:
return self.output_modes[0]
if... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def token_at_cursor(code, pos=0):
"""
Find the token present at the passed position in the code buffer
:return (tuple): a pair (token, start_position)
"""
l = len(code)
end = start = pos
# Go forwards while we get alphanumeric chars
while end < l and code[end].isalpha():
end += ... | Write a Python 3 script for
finding the token present at the cursor position in the code buffer. | As a Python code composer, you craft elegant and concise scripts. |
Send a response to the frontend and return an execute message
| How would you explain what the following Python 3 function does
def _send(self, data, msg_type='ok', silent=False):
# Data to send back
if data is not None:
# log the message
try:
self._klog.debug(u"msg to frontend (%d): %.160s...", silent, data)
excep... | You are a Python code generator, capable of creating scripts from specifications. |
Execute a cell and return the result | Here you have a function in Python 3, explain what it does
def do_execute(self, code, silent, store_history=True,
user_expressions=None, allow_stdin=False):
"""
Method called to execute a cell
"""
self._klog.info("[%.30s] [%d] [%s]", code, silent, user_expressions)
... | You are a Python code generator, capable of creating scripts from specifications. |
Escape a string with HTML - reserved characters. | Can you generate the documentation for the following Python 3 function
def escape( x, lb=False ):
# Insert a linebreak? Roughly around the middle of the string,
if lb:
l = len(x)
if l >= 10:
l >>= 1 # middle of the string
s1 = x.find( ' ', l ) # ... | You are a Python code architect, reviewing and designing scalable and efficient code |
Create & return an HTML div element by wrapping the passed text buffer. | Here you have a function in Python 3, explain what it does
def div( txt, *args, **kwargs ):
if args:
txt = txt.format( *args )
css = kwargs.get('css',HTML_DIV_CLASS)
return u'<div class="{}">{!s}</div>'.format( css, txt ) | As a python code expert, you are capable of creating scripts from specifications. |
def data_msglist( msglist ):
"""
Return a Jupyter display_data message, in both HTML & text formats, by
joining together all passed messages.
@param msglist (iterable): an iterable containing a list of tuples
(message, css_style)
Each message is either a text string, or a list. In... | Create a Python 3 function to
return a Jupyter display_data message in both HTML & text formats by joining together all passed messages. | You are a Python code generator, capable of creating scripts from specifications. |
def data_msg( msg, mtype=None ):
"""
Return a Jupyter display_data message, in both HTML & text formats, by
formatting a given single message. The passed message may be:
* An exception (including a KrnlException): will generate an error message
* A list of messages (with \c mtype equal to \c mu... | Write a Python 3 function for
returning a Jupyter display_data message in both HTML & text formats by | You are a Python code architect, reviewing and designing scalable and efficient code |
def copyresource( resource, filename, destdir ):
"""
Copy a resource file to a destination
"""
data = pkgutil.get_data(resource, os.path.join('resources',filename) )
#log.info( "Installing %s", os.path.join(destdir,filename) )
with open( os.path.join(destdir,filename), 'wb' ) as fp:
fp.w... | Write a Python 3 script for
copying a resource file to a destination directory | You are a Python code generator, capable of creating scripts from specifications. |
Copy the kernel resources to the kernelspec folder. | Make a summary of the following Python 3 code
def install_kernel_resources( destdir, resource=PKGNAME, files=None ):
if files is None:
files = ['logo-64x64.png', 'logo-32x32.png']
for filename in files:
try:
copyresource( resource, filename, destdir )
except Exception as e:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Installs the kernel CSS file in the specified destination directory. | Can you generate the documentation for the following Python 3 function
def install_custom_css( destdir, cssfile, resource=PKGNAME ):
ensure_dir_exists( destdir )
custom = os.path.join( destdir, 'custom.css' )
prefix = css_frame_prefix(resource)
# Check if custom.css already includes it. If so, let's re... | As a python code expert, you are capable of creating scripts from specifications. |
Remove the kernel CSS from custom. css | How would you explain what the following Python 3 function does
def remove_custom_css(destdir, resource=PKGNAME ):
# Remove the inclusion in the main CSS
if not os.path.isdir( destdir ):
return False
custom = os.path.join( destdir, 'custom.css' )
copy = True
found = False
prefix = css_f... | As a Python code composer, you craft elegant and concise scripts. |
def html_elem(e, ct, withtype=False):
"""
Format a result element as an HTML table cell.
@param e (list): a pair \c (value,type)
@param ct (str): cell type (th or td)
@param withtype (bool): add an additional cell with the element type
"""
# Header cell
if ct == 'th':
retur... | Write a Python 3 script for
formatting a result element as an HTML table cell. | As a python code expert, you are capable of creating scripts from specifications. |
Returns a double iterable as an HTML table. | Explain what the following Python 3 code does
def html_table(data, header=True, limit=None, withtype=False):
if header and limit:
limit += 1
ct = 'th' if header else 'td'
rc = 'hdr' if header else 'odd'
# import codecs
# import datetime
# with codecs.open( '/tmp/dump', 'w', encoding='ut... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the data type of a value for JSON data | Make a summary of the following Python 3 code
def jtype(c):
ct = c['type']
return ct if ct != 'literal' else '{}, {}'.format(ct, c.get('xml:lang')) | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the data type of a value for Graph data
| Given the following Python 3 function, write the documentation
def gtype(n):
t = type(n).__name__
return str(t) if t != 'Literal' else 'Literal, {}'.format(n.language) | You are a Python code generator, capable of creating scripts from specifications. |
Find if the JSON row contains acceptable language data | Can you generate a brief explanation for the following Python 3 code
def lang_match_json(row, hdr, accepted_languages):
'''Find if the JSON row contains acceptable language data'''
if not accepted_languages:
return True
languages = set([row[c].get('xml:lang') for c in hdr
if c i... | You are a Python code analyst, evaluating scripts for potential improvements. |
def lang_match_rdf(triple, accepted_languages):
'''Find if the RDF triple contains acceptable language data'''
if not accepted_languages:
return True
languages = set([n.language for n in triple if isinstance(n, Literal)])
return (not languages) or (languages & accepted_languages) | Can you create a Python 3 function that
finds if the RDF triple contains acceptable language data | As a python code expert, you are capable of creating scripts from specifications. |
Find if the XML row contains acceptable language data | Here you have a function in Python 3, explain what it does
def lang_match_xml(row, accepted_languages):
'''Find if the XML row contains acceptable language data'''
if not accepted_languages:
return True
column_languages = set()
for elem in row:
lang = elem[0].attrib.get(XML_LANG, None)
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Convert a JSON response into a double iterable by rows and columns | Here you have a function in Python 3, explain what it does
def json_iterator(hdr, rowlist, lang, add_vtype=False):
# Return the header row
yield hdr if not add_vtype else ((h, 'type') for h in hdr)
# Now the data rows
for row in rowlist:
if lang and not lang_match_json(row, hdr, lang):
... | As a python code expert, you are capable of creating scripts from specifications. |
Convert a Graph response into a double iterable by triples and elements. lang - Language of the resource to be used. add_vtype - True to add type if not added to the header. lang - Language of the resource to be used to filter the data by language | Can you generate a brief explanation for the following Python 3 code
def rdf_iterator(graph, lang, add_vtype=False):
# Return the header row
hdr = ('subject', 'predicate', 'object')
yield hdr if not add_vtype else ((h, 'type') for h in hdr)
# Now the data rows
for row in graph:
if lang and n... | As a python code expert, you are capable of creating scripts from specifications. |
Render to output a result in JSON format
| Can you generate the documentation for the following Python 3 function
def render_json(result, cfg, **kwargs):
result = json.loads(result.decode('utf-8'))
head = result['head']
if 'results' not in result:
if 'boolean' in result:
r = u'Result: {}'.format(result['boolean'])
else:
... | As a python code expert, you are capable of creating scripts from specifications. |
def xml_iterator(columns, rowlist, lang, add_vtype=False):
"""
Convert an XML response into a double iterable, by rows and columns
Options are: filter triples by language (on literals), add element type
"""
# Return the header row
yield columns if not add_vtype else ((h, 'type') for h in columns... | Create a Python 3 function for
converting an XML response into a double iterable by rows and columns | As a Python code analyst, you investigate and solve complex coding mysteries |
def render_xml(result, cfg, **kwargs):
"""
Render to output a result in XML format
"""
# Raw mode
if cfg.dis == 'raw':
return {'data': {'text/plain': result.decode('utf-8')},
'metadata': {}}
# Table
try:
import xml.etree.cElementTree as ET
except ImportErr... | Implement a Python 3 function for
rendering to output a result in XML format | As a Python code composer, you craft elegant and concise scripts. |
Render to output a result that can be parsed as an RDF graph | How would you explain what the following Python 3 function does
def render_graph(result, cfg, **kwargs):
# Mapping from MIME types to formats accepted by RDFlib
rdflib_formats = {'text/rdf+n3': 'n3',
'text/turtle': 'turtle',
'application/x-turtle': 'turtle',
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Launch an SPARQL query and process the results and return them | Can you generate the documentation for the following Python 3 function
def query(self, query, num=0, silent=False):
if self.srv is None:
raise KrnlException('no endpoint defined')
# Add to the query all predefined SPARQL prefixes
if self.cfg.pfx:
prefix = '\n'.join(('PRE... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Set a logging configuration with a rolling file appender. | Explain what the following Python 3 code does
def set_logging( logfilename=None, level=None ):
if logfilename is None:
# Find the logging diectory
logdir = os.environ.get( 'LOGDIR' )
if logdir is None:
logdir = os.environ.get( 'LOGDIR_DEFAULT', tempfile.gettempdir() )
# D... | You are a Python code architect, reviewing and designing scalable and efficient code |
A way to find out a status of a filed. | Can you generate the documentation for the following Python 3 function
def smartfields_get_field_status(self, field_name):
manager = self._smartfields_managers.get(field_name, None)
if manager is not None:
return manager.get_status(self)
return {'state': 'ready'} | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns new file extension based on a processor s format parameter. | Make a summary of the following Python 3 code
def get_ext(self, format=None, **kwargs):
try:
format = format or self.default_params['format']
return ".%s" % format.lower()
except KeyError: pass | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_output_file(self, in_file, instance, field, **kwargs):
"""Creates a temporary file. With regular `FileSystemStorage` it does not
need to be deleted, instaed file is safely moved over. With other cloud
based storage it is a good idea to set `delete=True`."""
return NamedTemporary... | Write a Python 3 script for
creating a temporary file. | As a python code expert, you are capable of creating scripts from specifications. |
def label(x, gr, preferred_languages=None):
"""
@param x : graph entity
@param gr (Graph): RDF graph
@param preferred_languages (iterable)
Return the best available label in the graph for the passed entity.
If a set of preferred languages is given, try them in order. If none is
found,... | Write a Python 3 function for
returning the best available label for the passed entity in the passed graph. | You are a Python code generator, capable of creating scripts from specifications. |
def rdf2dot( g, stream, opts={} ):
"""
Convert the RDF graph to DOT
Write the dot output to the stream
"""
accept_lang = set( opts.get('lang',[]) )
do_literal = opts.get('literal')
nodes = {}
links = []
def node_id(x):
if x not in nodes:
nodes[x] = "node%d" % le... | How would you implement a function in Python 3 that
converts the RDF graph to DOT format | You are a Python code architect, reviewing and designing scalable and efficient code |
Draw an RDF graph as an image
| Can you tell what is the following Python 3 function doing
def draw_graph( g, fmt='svg', prg='dot', options={} ):
# Convert RDF to Graphviz
buf = StringIO()
rdf2dot( g, buf, options )
gv_options = options.get('graphviz',[])
if fmt == 'png':
gv_options += [ '-Gdpi=220', '-Gsize=25,10!' ]
... | As a python code expert, you are capable of creating scripts from specifications. |
Compute the S and Z matrices for the given PSD and geometries. | Make a summary of the following Python 3 code
def get_SZ(self, psd, geometry):
if (self._S_table is None) or (self._Z_table is None):
raise AttributeError(
"Initialize or load the scattering table first.")
if (not isinstance(psd, PSD)) or self._previous_psd != psd:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Initialize the scattering lookup tables for the given object. | Can you tell what is the following Python 3 function doing
def init_scatter_table(self, tm, angular_integration=False, verbose=False):
self._psd_D = np.linspace(self.D_max/self.num_points, self.D_max,
self.num_points)
self._S_table = {}
self._Z_table = {}
self._previous_psd... | You are a Python code analyst, evaluating scripts for potential improvements. |
Save the state of the scattering lookup tables to a file. | How would you explain what the following Python 3 function does
def save_scatter_table(self, fn, description=""):
data = {
"description": description,
"time": datetime.now(),
"psd_scatter": (self.num_points, self.D_max, self._psd_D,
self._S_table, self._Z_table,... | As a python code expert, you are capable of creating scripts from specifications. |
Loads the scattering lookup tables from a file. | Given the following Python 3 function, write the documentation
def load_scatter_table(self, fn):
data = pickle.load(file(fn))
if ("version" not in data) or (data["version"]!=tmatrix_aux.VERSION):
warnings.warn("Loading data saved with another version.", Warning)
(self.num_points, s... | As a Python code composer, you craft elegant and concise scripts. |
Returns the spherical Jacobian - edition standard deviation Gaussian PDF for orientation averaging. | Make a summary of the following Python 3 code
def gaussian_pdf(std=10.0, mean=0.0):
norm_const = 1.0
def pdf(x):
return norm_const*np.exp(-0.5 * ((x-mean)/std)**2) * \
np.sin(np.pi/180.0 * x)
norm_dev = quad(pdf, 0.0, 180.0)[0]
# ensure that the integral over the distribution equals ... | You are a Python code analyst, evaluating scripts for potential improvements. |
def uniform_pdf():
"""Uniform PDF for orientation averaging.
Returns:
pdf(x), a function that returns the value of the spherical Jacobian-
normalized uniform PDF. It is normalized for the interval [0, 180].
"""
norm_const = 1.0
def pdf(x):
return norm_const * np.sin(np.pi/18... | Implement a function in Python 3 to
uniform PDF for orientation averaging. | As a Python code analyst, you investigate and solve complex coding mysteries |
def orient_averaged_adaptive(tm):
"""Compute the T-matrix using variable orientation scatterers.
This method uses a very slow adaptive routine and should mainly be used
for reference purposes. Uses the set particle orientation PDF, ignoring
the alpha and beta attributes.
Args:
tm: TMat... | Create a Python 3 function to
compute the T - matrix using variable orientation scatterers. | You are a Python code analyst, evaluating scripts for potential improvements. |
def orient_averaged_fixed(tm):
"""Compute the T-matrix using variable orientation scatterers.
This method uses a fast Gaussian quadrature and is suitable
for most use. Uses the set particle orientation PDF, ignoring
the alpha and beta attributes.
Args:
tm: TMatrix (or descendant) insta... | Write a Python 3 function for
computing the T - matrix using variable orientation scatterers. | As a Python code composer, you craft elegant and concise scripts. |
Initialize the T - matrix. | How would you explain what the following Python 3 function does
def _init_tmatrix(self):
if self.radius_type == Scatterer.RADIUS_MAXIMUM:
# Maximum radius is not directly supported in the original
# so we convert it to equal volume radius
radius_type = Scatterer.RADIUS_EQUAL... | You are a Python code analyst, evaluating scripts for potential improvements. |
Retrieve the quadrature points and weights if needed. | Given the following Python 3 function, write the documentation
def _init_orient(self):
if self.orient == orientation.orient_averaged_fixed:
(self.beta_p, self.beta_w) = quadrature.get_points_and_weights(
self.or_pdf, 0, 180, self.n_beta)
self._set_orient_signature() | As a Python code translator, you convert algorithms and pseudocode into Python. |
Mark the amplitude and scattering matrices as up to date. | Given the following Python 3 function, write the documentation
def _set_scatter_signature(self):
self._scatter_signature = (self.thet0, self.thet, self.phi0, self.phi,
self.alpha, self.beta, self.orient) | As a python code expert, you are capable of creating scripts from specifications. |
Get the S and Z matrices for a single orientation. | Can you generate the documentation for the following Python 3 function
def get_SZ_single(self, alpha=None, beta=None):
if alpha == None:
alpha = self.alpha
if beta == None:
beta = self.beta
tm_outdated = self._tm_signature != (self.radius, self.radius_type,
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_SZ_orient(self):
"""Get the S and Z matrices using the specified orientation averaging.
"""
tm_outdated = self._tm_signature != (self.radius, self.radius_type,
self.wavelength, self.m, self.axis_ratio, self.shape, self.ddelt,
self.ndgs)
scatter_outdated... | Write a Python 3 function for
getting the S and Z matrices using the specified orientation averaging. | You are a Python code architect, reviewing and designing scalable and efficient code |
Get the S and Z matrices using the current parameters. | Can you generate the documentation for the following Python 3 function
def get_SZ(self):
if self.psd_integrator is None:
(self._S, self._Z) = self.get_SZ_orient()
else:
scatter_outdated = self._scatter_signature != (self.thet0,
self.thet, self.phi0, self.phi, sel... | You are a Python code architect, reviewing and designing scalable and efficient code |
def sca_intensity(scatterer, h_pol=True):
"""Scattering intensity (phase function) for the current setup.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The differential scatter... | Write a Python 3 script to
scatter intensity for the current setup. | As a Python code analyst, you investigate and solve complex coding mysteries |
def sca_xsect(scatterer, h_pol=True):
"""Scattering cross section for the current setup, with polarization.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The scattering cross s... | Write a Python 3 script to
scatter cross section for the current setup with polarization. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the extinction cross section for the current setup. | Can you generate the documentation for the following Python 3 function
def ext_xsect(scatterer, h_pol=True):
if scatterer.psd_integrator is not None:
try:
return scatterer.psd_integrator.get_angular_integrated(
scatterer.psd, scatterer.get_geometry(), "ext_xsect")
except... | As a python code expert, you are capable of creating scripts from specifications. |
def ssa(scatterer, h_pol=True):
"""Single-scattering albedo for the current setup, with polarization.
Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.
Returns:
The single-scattering albedo... | How would you implement a function in Python 3 that
singles - scattering albedo for the current setup with polarization. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Asymmetry parameter for the current setup. | Make a summary of the following Python 3 code
def asym(scatterer, h_pol=True):
if scatterer.psd_integrator is not None:
return scatterer.psd_integrator.get_angular_integrated(
scatterer.psd, scatterer.get_geometry(), "asym")
old_geom = scatterer.get_geometry()
cos_t0 = np.cos(scattere... | You are a Python code generator, capable of creating scripts from specifications. |
Radar cross section for the current setup. | Can you generate a brief explanation for the following Python 3 code
def radar_xsect(scatterer, h_pol=True):
Z = scatterer.get_Z()
if h_pol:
return 2 * np.pi * \
(Z[0,0] - Z[0,1] - Z[1,0] + Z[1,1])
else:
return 2 * np.pi * \
(Z[0,0] + Z[0,1] + Z[1,0] + Z[1,1]) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Reflectivity of the current setup. | Can you tell what is the following Python 3 function doing
def refl(scatterer, h_pol=True):
return scatterer.wavelength**4/(np.pi**5*scatterer.Kw_sqr) * \
radar_xsect(scatterer, h_pol) | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the delta_hv for the current setup. | Make a summary of the following Python 3 code
def delta_hv(scatterer):
Z = scatterer.get_Z()
return np.arctan2(Z[2,3] - Z[3,2], -Z[2,2] - Z[3,3]) | You are a Python code analyst, evaluating scripts for potential improvements. |
def rho_hv(scatterer):
"""
Copolarized correlation (rho_hv) for the current setup.
Args:
scatterer: a Scatterer instance.
Returns:
rho_hv.
"""
Z = scatterer.get_Z()
a = (Z[2,2] + Z[3,3])**2 + (Z[3,2] - Z[2,3])**2
b = (Z[0,0] - Z[0,1] - Z[1,0] + Z[1,1])
c = (Z[0,0] + ... | Create a Python 3 function to
return the Copolarized correlation coefficient for the current setup. | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the K_dp of the current setup. | Can you generate a brief explanation for the following Python 3 code
def Kdp(scatterer):
if (scatterer.thet0 != scatterer.thet) or \
(scatterer.phi0 != scatterer.phi):
raise ValueError("A forward scattering geometry is needed to " + \
"compute the specific differential phase.")
... | As a python code expert, you are capable of creating scripts from specifications. |
Maxwell - Garnett approximation for the complex refractive index of
. | Can you generate the documentation for the following Python 3 function
def mg_refractive(m, mix):
if len(m) == 2:
cF = float(mix[1]) / (mix[0]+mix[1]) * \
(m[1]**2-m[0]**2) / (m[1]**2+2*m[0]**2)
er = m[0]**2 * (1.0+2.0*cF) / (1.0-cF)
m = np.sqrt(er)
else:
m_last = mg... | As a Python code analyst, you investigate and solve complex coding mysteries |
D_eq is the drop - volume - equivalent diameter of the class in the Thurai 2007. | Make a summary of the following Python 3 code
def dsr_thurai_2007(D_eq):
if D_eq < 0.7:
return 1.0
elif D_eq < 1.5:
return 1.173 - 0.5165*D_eq + 0.4698*D_eq**2 - 0.1317*D_eq**3 - \
8.5e-3*D_eq**4
else:
return 1.065 - 6.25e-2*D_eq - 3.99e-3*D_eq**2 + 7.66e-4*D_eq**3 - \
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def feature_importances(data, top_n=None, feature_names=None):
"""
Get and order feature importances from a scikit-learn model
or from an array-like structure.
If data is a scikit-learn model with sub-estimators (e.g. RandomForest,
AdaBoost) the function will compute the standard deviation of each
... | Write a Python 3 script for
getting and order feature importances from a sklearn model or array - like structure. | As a python code expert, you are capable of creating scripts from specifications. |
Group the data by a function or a key | Here you have a function in Python 3, explain what it does
def _group_by(data, criteria):
if isinstance(criteria, str):
criteria_str = criteria
def criteria(x):
return x[criteria_str]
res = defaultdict(list)
for element in data:
key = criteria(element)
res[key].... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _get_params_value(params):
"""
Given an iterator (k1, k2), returns a function that when called
with an object obj returns a tuple of the form:
((k1, obj.parameters[k1]), (k2, obj.parameters[k2]))
"""
# sort params for consistency
ord_params = sorted(params)
def fn(obj):
... | Implement a function in Python 3 to
return a function that takes a list of parameters and returns a tuple of the form k1 k2 | As a Python code composer, you craft elegant and concise scripts. |
def _product(k, v):
"""
Perform the product between two objects
even if they don't support iteration
"""
if not _can_iterate(k):
k = [k]
if not _can_iterate(v):
v = [v]
return list(product(k, v)) | Write a Python 3 function that can
perform the product between two objects even if they don t support iteration | As a Python code composer, you craft elegant and concise scripts. |
def _mapping_to_tuple_pairs(d):
"""
Convert a mapping object (such as a dictionary) to tuple pairs,
using its keys and values to generate the pairs and then generating
all possible combinations between those
e.g. {1: (1,2,3)} -> (((1, 1),), ((1, 2),), ((1, 3),))
"""
# order t... | Can you create a Python 3 function that
converts a mapping object such as a dictionary to tuple pairs | You are a Python code generator, capable of creating scripts from specifications. |
def learning_curve(train_scores, test_scores, train_sizes, ax=None):
"""Plot a learning curve
Plot a metric vs number of examples for the training and test set
Parameters
----------
train_scores : array-like
Scores for the training set
test_scores : array-like
Scores for the te... | How would you code a function in Python 3 to
plot a learning curve for the training set and test set. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def precision_recall(y_true, y_score, ax=None):
"""
Plot precision-recall curve.
Parameters
----------
y_true : array-like, shape = [n_samples]
Correct target values (ground truth).
y_score : array-like, shape = [n_samples] or [n_samples, 2] for binary
classification or [n... | Write a Python 3 script for
plotting precision - recall curve. | As a Python code composer, you craft elegant and concise scripts. |
Plot precision - recall curve. | How would you explain what the following Python 3 function does
def _precision_recall(y_true, y_score, ax=None):
precision, recall, _ = precision_recall_curve(y_true, y_score)
average_precision = average_precision_score(y_true, y_score)
if ax is None:
ax = plt.gca()
ax.plot(recall, precision, ... | As a python code expert, you are capable of creating scripts from specifications. |
Plots precision - recall curve for a single base class. | Explain what the following Python 3 code does
def _precision_recall_multi(y_true, y_score, ax=None):
# Compute micro-average ROC curve and ROC area
precision, recall, _ = precision_recall_curve(y_true.ravel(),
y_score.ravel())
avg_prec = average_precision_s... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Calculates precision at a given proportion. | Explain what the following Python 3 code does
def precision_at(y_true, y_score, proportion, ignore_nas=False):
'''
Calculates precision at a given proportion.
Only supports binary classification.
'''
# Sort scores in descending order
scores_sorted = np.sort(y_score)[::-1]
# Based on the pro... | As a python code expert, you are capable of creating scripts from specifications. |
def __precision(y_true, y_pred):
'''
Precision metric tolerant to unlabeled data in y_true,
NA values are ignored for the precision calculation
'''
# make copies of the arrays to avoid modifying the original ones
y_true = np.copy(y_true)
y_pred = np.copy(y_pred)
# precision = tp... | Create a Python 3 function for
computing the precision of the data in the cluster hierarchy. | You are a Python code analyst, evaluating scripts for potential improvements. |
Return the number of labels encountered in the top X proportion | Can you generate the documentation for the following Python 3 function
def labels_at(y_true, y_score, proportion, normalize=False):
'''
Return the number of labels encountered in the top X proportion
'''
# Get indexes of scores sorted in descending order
indexes = np.argsort(y_score)[::-1]
... | As a Python code composer, you craft elegant and concise scripts. |
def validation_curve(train_scores, test_scores, param_range, param_name=None,
semilogx=False, ax=None):
"""Plot a validation curve
Plot a metric vs hyperpameter values for the training and test set
Parameters
----------
train_scores : array-like
Scores for the training... | Can you write a function in Python 3 where it
plots a validation curve for the training set and test set. | You are a Python code generator, capable of creating scripts from specifications. |
Plots the confusion matrix for the current language. | Can you generate a brief explanation for the following Python 3 code
def confusion_matrix(y_true, y_pred, target_names=None, normalize=False,
cmap=None, ax=None):
"""
Plot confustion matrix.
Parameters
----------
y_true : array-like, shape = [n_samples]
Correct target v... | You are a Python code generator, capable of creating scripts from specifications. |
Returns a matplotlib Axes object containing the feature importances of each feature in the top_n features. | Can you generate a brief explanation for the following Python 3 code
def feature_importances(data, top_n=None, feature_names=None, ax=None):
if data is None:
raise ValueError('data is needed to plot feature importances. '
'When plotting using the evaluator you need to pass '
... | You are a Python code generator, capable of creating scripts from specifications. |
def precision_at_proportions(y_true, y_score, ax=None):
"""
Plot precision values at different proportions.
Parameters
----------
y_true : array-like
Correct target values (ground truth).
y_score : array-like
Target scores (estimator predictions).
ax : matplotlib Axes
... | How would you code a function in Python 3 to
plot precision values at different proportions. | You are a Python code architect, reviewing and designing scalable and efficient code |
def feature_importances(data, top_n=None, feature_names=None):
"""
Get and order feature importances from a scikit-learn model
or from an array-like structure.
If data is a scikit-learn model with sub-estimators (e.g. RandomForest,
AdaBoost) the function will compute the standard deviation of each
... | How would you code a function in Python 3 to
return a table with the feature importances for the given data. | As a Python code analyst, you investigate and solve complex coding mysteries |
def block_parser(part, rgxin, rgxout, fmtin, fmtout):
"""
part is a string of ipython text, comprised of at most one
input, one output, comments, and blank lines. The block parser
parses the text into a list of::
blocks = [ (TOKEN0, data0), (TOKEN1, data1), ...]
where TOKEN is one of [COMME... | Can you write a function in Python 3 where it
parts is a string of ipython text, comprised of at most one input, one output, comments, and blank lines. The block parser parses the text into a list of:: blocks = [ (TOKEN0, data0), (TOKEN1, data1), ...] where TOKEN is one of [COMMENT | INPUT | OUTPUT ] and data is, depen... | You are a Python code architect, reviewing and designing scalable and efficient code |
def process_block(self, block):
"""
process block from the block_parser and return a list of processed lines
"""
ret = []
output = None
input_lines = None
lineno = self.IP.execution_count
input_prompt = self.promptin % lineno
output_prompt = self.... | Write a Python 3 function for
processing a block from the block parser and return a list of processed lines | You are a Python code generator, capable of creating scripts from specifications. |
def grid_search(grid_scores, change, subset=None, kind='line', cmap=None,
ax=None):
"""
Plot results from a sklearn grid search by changing two parameters at most.
Parameters
----------
grid_scores : list of named tuples
Results from a sklearn grid search (get them using the... | Write a Python 3 script to
plot a sklearn grid search for a set of items in the order of the items in the list of named tuples. | As a python code expert, you are capable of creating scripts from specifications. |
ROC plot for this object | Make a summary of the following Python 3 code
def roc(self):
return plot.roc(self.y_true, self.y_score, ax=_gen_ax()) | You are a Python code generator, capable of creating scripts from specifications. |
Precision - recall plot | Can you generate the documentation for the following Python 3 function
def precision_recall(self):
return plot.precision_recall(self.y_true, self.y_score, ax=_gen_ax()) | As a Python code composer, you craft elegant and concise scripts. |
Precision at proportions plot | Can you generate a brief explanation for the following Python 3 code
def precision_at_proportions(self):
return plot.precision_at_proportions(self.y_true, self.y_score,
ax=_gen_ax()) | You are a Python code architect, reviewing and designing scalable and efficient code |
Generate the HTML report for the current configuration. | Can you generate a brief explanation for the following Python 3 code
def generate_report(self, template, path=None, style=None):
from .report import generate
return generate(self, template, path, style) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Plots ROC curve for the current binary entry set. | How would you explain what the following Python 3 function does
def roc(y_true, y_score, ax=None):
if any((val is None for val in (y_true, y_score))):
raise ValueError("y_true and y_score are needed to plot ROC")
if ax is None:
ax = plt.gca()
# get the number of classes based on the shape ... | As a Python code composer, you craft elegant and concise scripts. |
Plots ROC curve for binary classification. | Make a summary of the following Python 3 code
def _roc(y_true, y_score, ax=None):
# check dimensions
fpr, tpr, _ = roc_curve(y_true, y_score)
roc_auc = auc(fpr, tpr)
ax.plot(fpr, tpr, label=('ROC curve (area = {0:0.2f})'.format(roc_auc)))
_set_ax_settings(ax)
return ax | As a Python code composer, you craft elegant and concise scripts. |
def _roc_multi(y_true, y_score, ax=None):
"""
Plot ROC curve for multi classification.
Parameters
----------
y_true : array-like, shape = [n_samples, n_classes]
Correct target values (ground truth).
y_score : array-like, shape = [n_samples, n_classes]
Target scores (estimator pr... | Create a Python 3 function for
plotting ROC curve for multi classification. | As a python code expert, you are capable of creating scripts from specifications. |
Get an exclusive connection. | How would you explain what the following Python 3 function does
async def get_connection(self, container):
'''
Get an exclusive connection, useful for blocked commands and transactions.
You must call release or shutdown (not recommanded) to return the connection after use.
... | You are a Python code architect, reviewing and designing scalable and efficient code |
async def execute_command(self, container, *args):
'''
Execute command on Redis server:
- For (P)SUBSCRIBE/(P)UNSUBSCRIBE, the command is sent to the subscribe connection.
It is recommended to use (p)subscribe/(p)unsubscribe method instead of directly call the command
- F... | Create a Python 3 function for
executing a command on Redis server. | As a python code expert, you are capable of creating scripts from specifications. |
async def subscribe(self, container, *keys):
'''
Subscribe to specified channels
:param container: routine container
:param *keys: subscribed channels
:returns: list of event matchers for the specified channels
'''
await self._get_subscr... | Implement a Python 3 function for
subscribing to the specified channels. | As a Python code analyst, you investigate and solve complex coding mysteries |
Unsubscribe specified channels. Every subscribed key should be unsubscribed exactly once, even if duplicated subscribed.
:param container: routine container
:param \*keys: subscribed channels | Given the following Python 3 function, write the documentation
async def unsubscribe(self, container, *keys):
'''
Unsubscribe specified channels. Every subscribed key should be unsubscribed exactly once, even if duplicated subscribed.
:param container: routine container
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
async def psubscribe(self, container, *keys):
'''
Subscribe to specified globs
:param container: routine container
:param \*keys: subscribed globs
:returns: list of event matchers for the specified globs
'''
await self._get_subscribe_co... | Create a Python 3 function for
subscribing to specified globs | As a Python code translator, you convert algorithms and pseudocode into Python. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.