text_prompt
stringlengths 157
13.1k
| code_prompt
stringlengths 7
19.8k
⌀ |
---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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" % len(nodes)
return nodes[x]
def qname(x, g):
try:
q = g.compute_qname(x)
return q[0] + ":" + q[2]
except:
return x
def accept( node ):
if isinstance( node, (rdflib.URIRef,rdflib.BNode) ):
return True
if not do_literal:
return False
return (not accept_lang) or (node.language in accept_lang)
stream.write( u'digraph { \n node [ fontname="DejaVu Sans,Tahoma,Geneva,sans-serif" ] ; \n' )
# Write all edges. In the process make a list of all nodes
for s, p, o in g:
# skip triples for labels
if p == rdflib.RDFS.label:
continue
# Create a link if both objects are graph nodes
# (or, if literals are also included, if their languages match)
if not (accept(s) and accept(o)):
continue
# add the nodes to the list
sn = node_id(s)
on = node_id(o)
# add the link
q = qname(p,g)
if isinstance(p, rdflib.URIRef):
opstr = u'\t%s -> %s [ arrowhead="open", color="#9FC9E560", fontsize=9, fontcolor="#204080", label="%s", href="%s", target="_other" ] ;\n' % (sn,on,q,p)
else:
opstr = u'\t%s -> %s [ arrowhead="open", color="#9FC9E560", fontsize=9, fontcolor="#204080", label="%s" ] ;\n'%(sn,on,q)
stream.write( opstr )
# Write all nodes
for u, n in nodes.items():
lbl = escape( label(u,g,accept_lang), True )
if isinstance(u, rdflib.URIRef):
opstr = u'%s [ shape=none, fontsize=10, fontcolor=%s, label="%s", href="%s", target=_other ] \n' % (n, 'blue', lbl, u )
else:
opstr = u'%s [ shape=none, fontsize=10, fontcolor=%s, label="%s" ] \n' % (n, 'black', lbl )
stream.write( u"# %s %s\n" % (u, n) )
stream.write( opstr )
stream.write(u'}\n') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw_graph( g, fmt='svg', prg='dot', options={} ):
""" Draw an RDF graph as an image """ |
# 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!' ]
metadata = { "width": 5500, "height": 2200, "unconfined" : True }
#import codecs
#with codecs.open('/tmp/sparqlkernel-img.dot','w',encoding='utf-8') as f:
# f.write( buf.getvalue() )
# Now use Graphviz to generate the graph
image = run_dot( buf.getvalue(), fmt=fmt, options=gv_options, prg=prg )
#with open('/tmp/sparqlkernel-img.'+fmt,'w') as f:
# f.write( image )
# Return it
if fmt == 'png':
return { 'image/png' : base64.b64encode(image).decode('ascii') }, \
{ "image/png" : metadata }
elif fmt == 'svg':
return { 'image/svg+xml' : image.decode('utf-8').replace('<svg','<svg class="unconfined"',1) }, \
{ "unconfined" : True } |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_SZ(self, psd, geometry):
""" Compute the scattering matrices for the given PSD and geometries. Returns: The new amplitude (S) and phase (Z) matrices. """ |
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:
self._S_dict = {}
self._Z_dict = {}
psd_w = psd(self._psd_D)
for geom in self.geometries:
self._S_dict[geom] = \
trapz(self._S_table[geom] * psd_w, self._psd_D)
self._Z_dict[geom] = \
trapz(self._Z_table[geom] * psd_w, self._psd_D)
self._previous_psd = psd
return (self._S_dict[geometry], self._Z_dict[geometry]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_scatter_table(self, fn, description=""):
"""Save the scattering lookup tables. Save the state of the scattering lookup tables to a file. This can be loaded later with load_scatter_table. Other variables will not be saved, but this does not matter because the results of the computations are based only on the contents of the table. Args: fn: The name of the scattering table file. description (optional):
A description of the table. """ |
data = {
"description": description,
"time": datetime.now(),
"psd_scatter": (self.num_points, self.D_max, self._psd_D,
self._S_table, self._Z_table, self._angular_table,
self._m_table, self.geometries),
"version": tmatrix_aux.VERSION
}
pickle.dump(data, file(fn, 'w'), pickle.HIGHEST_PROTOCOL) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_scatter_table(self, fn):
"""Load the scattering lookup tables. Load the scattering lookup tables saved with save_scatter_table. Args: fn: The name of the scattering table file. """ |
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, self.D_max, self._psd_D, self._S_table,
self._Z_table, self._angular_table, self._m_table,
self.geometries) = data["psd_scatter"]
return (data["time"], data["description"]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gaussian_pdf(std=10.0, mean=0.0):
"""Gaussian PDF for orientation averaging. Args: std: The standard deviation in degrees of the Gaussian PDF mean: The mean in degrees of the Gaussian PDF. This should be a number in the interval [0, 180) Returns: pdf(x), a function that returns the value of the spherical Jacobian- normalized Gaussian PDF with the given STD at x (degrees). It is normalized for the interval [0, 180]. """ |
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 1
norm_const /= norm_dev
return pdf |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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/180.0 * x)
norm_dev = quad(pdf, 0.0, 180.0)[0]
# ensure that the integral over the distribution equals 1
norm_const /= norm_dev
return pdf |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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: TMatrix (or descendant) instance Returns: The amplitude (S) and phase (Z) matrices. """ |
S = np.zeros((2,2), dtype=complex)
Z = np.zeros((4,4))
def Sfunc(beta, alpha, i, j, real):
(S_ang, Z_ang) = tm.get_SZ_single(alpha=alpha, beta=beta)
s = S_ang[i,j].real if real else S_ang[i,j].imag
return s * tm.or_pdf(beta)
ind = range(2)
for i in ind:
for j in ind:
S.real[i,j] = dblquad(Sfunc, 0.0, 360.0,
lambda x: 0.0, lambda x: 180.0, (i,j,True))[0]/360.0
S.imag[i,j] = dblquad(Sfunc, 0.0, 360.0,
lambda x: 0.0, lambda x: 180.0, (i,j,False))[0]/360.0
def Zfunc(beta, alpha, i, j):
(S_and, Z_ang) = tm.get_SZ_single(alpha=alpha, beta=beta)
return Z_ang[i,j] * tm.or_pdf(beta)
ind = range(4)
for i in ind:
for j in ind:
Z[i,j] = dblquad(Zfunc, 0.0, 360.0,
lambda x: 0.0, lambda x: 180.0, (i,j))[0]/360.0
return (S, Z) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) instance. Returns: The amplitude (S) and phase (Z) matrices. """ |
S = np.zeros((2,2), dtype=complex)
Z = np.zeros((4,4))
ap = np.linspace(0, 360, tm.n_alpha+1)[:-1]
aw = 1.0/tm.n_alpha
for alpha in ap:
for (beta, w) in zip(tm.beta_p, tm.beta_w):
(S_ang, Z_ang) = tm.get_SZ_single(alpha=alpha, beta=beta)
S += w * S_ang
Z += w * Z_ang
sw = tm.beta_w.sum()
#normalize to get a proper average
S *= aw/sw
Z *= aw/sw
return (S, Z) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_geometry(self, geom):
"""A convenience function to set the geometry variables. Args: geom: A tuple containing (thet0, thet, phi0, phi, alpha, beta). See the Scatterer class documentation for a description of these angles. """ |
(self.thet0, self.thet, self.phi0, self.phi, self.alpha,
self.beta) = geom |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_geometry(self):
"""A convenience function to get the geometry variables. Returns: A tuple containing (thet0, thet, phi0, phi, alpha, beta). See the Scatterer class documentation for a description of these angles. """ |
return (self.thet0, self.thet, self.phi0, self.phi, self.alpha,
self.beta) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_tmatrix(self):
"""Initialize the T-matrix. """ |
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_VOLUME
radius = self.equal_volume_from_maximum()
else:
radius_type = self.radius_type
radius = self.radius
self.nmax = pytmatrix.calctmat(radius, radius_type,
self.wavelength, self.m.real, self.m.imag, self.axis_ratio,
self.shape, self.ddelt, self.ndgs)
self._tm_signature = (self.radius, self.radius_type, self.wavelength,
self.m, self.axis_ratio, self.shape, self.ddelt, self.ndgs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_orient(self):
"""Retrieve the quadrature points and weights if needed. """ |
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set_scatter_signature(self):
"""Mark the amplitude and scattering matrices as up to date. """ |
self._scatter_signature = (self.thet0, self.thet, self.phi0, self.phi,
self.alpha, self.beta, self.orient) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_SZ_single(self, alpha=None, beta=None):
"""Get the S and Z matrices for a single orientation. """ |
if alpha == None:
alpha = self.alpha
if beta == None:
beta = self.beta
tm_outdated = self._tm_signature != (self.radius, self.radius_type,
self.wavelength, self.m, self.axis_ratio, self.shape, self.ddelt,
self.ndgs)
if tm_outdated:
self._init_tmatrix()
scatter_outdated = self._scatter_signature != (self.thet0, self.thet,
self.phi0, self.phi, alpha, beta, self.orient)
outdated = tm_outdated or scatter_outdated
if outdated:
(self._S_single, self._Z_single) = pytmatrix.calcampl(self.nmax,
self.wavelength, self.thet0, self.thet, self.phi0, self.phi,
alpha, beta)
self._set_scatter_signature()
return (self._S_single, self._Z_single) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 = self._scatter_signature != (self.thet0, self.thet,
self.phi0, self.phi, self.alpha, self.beta, self.orient)
orient_outdated = self._orient_signature != \
(self.orient, self.or_pdf, self.n_alpha, self.n_beta)
if orient_outdated:
self._init_orient()
outdated = tm_outdated or scatter_outdated or orient_outdated
if outdated:
(self._S_orient, self._Z_orient) = self.orient(self)
self._set_scatter_signature()
return (self._S_orient, self._Z_orient) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_SZ(self):
"""Get the S and Z matrices using the current parameters. """ |
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, self.alpha, self.beta,
self.orient)
psd_outdated = self._psd_signature != (self.psd,)
outdated = scatter_outdated or psd_outdated
if outdated:
(self._S, self._Z) = self.psd_integrator(self.psd,
self.get_geometry())
self._set_scatter_signature()
self._set_psd_signature()
return (self._S, self._Z) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_points_and_weights(w_func=lambda x : np.ones(x.shape), left=-1.0, right=1.0, num_points=5, n=4096):
"""Quadratude points and weights for a weighting function. Points and weights for approximating the integral I = \int_left^right f(x) w(x) dx given the weighting function w(x) using the approximation I ~ w_i f(x_i) Args: w_func: The weighting function w(x). Must be a function that takes one argument and is valid over the open interval (left, right). left: The left boundary of the interval right: The left boundary of the interval num_points: number of integration points to return n: the number of points to evaluate w_func at. Returns: A tuple (points, weights) where points is a sorted array of the points x_i and weights gives the corresponding weights w_i. """ |
dx = (float(right)-left)/n
z = np.hstack(np.linspace(left+0.5*dx, right-0.5*dx, n))
w = dx*w_func(z)
(a, b) = discrete_gautschi(z, w, num_points)
alpha = a
beta = np.sqrt(b)
J = np.diag(alpha)
J += np.diag(beta, k=-1)
J += np.diag(beta, k=1)
(points,v) = np.linalg.eigh(J)
ind = points.argsort()
points = points[ind]
weights = v[0,:]**2 * w.sum()
weights = weights[ind]
return (points, weights) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 section. """ |
if scatterer.psd_integrator is not None:
return scatterer.psd_integrator.get_angular_integrated(
scatterer.psd, scatterer.get_geometry(), "sca_xsect")
old_geom = scatterer.get_geometry()
def d_xsect(thet, phi):
(scatterer.phi, scatterer.thet) = (phi*rad_to_deg, thet*rad_to_deg)
Z = scatterer.get_Z()
I = sca_intensity(scatterer, h_pol)
return I * np.sin(thet)
try:
xsect = dblquad(d_xsect, 0.0, 2*np.pi, lambda x: 0.0,
lambda x: np.pi)[0]
finally:
scatterer.set_geometry(old_geom)
return xsect |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ext_xsect(scatterer, h_pol=True):
"""Extinction 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 extinction cross section. """ |
if scatterer.psd_integrator is not None:
try:
return scatterer.psd_integrator.get_angular_integrated(
scatterer.psd, scatterer.get_geometry(), "ext_xsect")
except AttributeError:
# Fall back to the usual method of computing this from S
pass
old_geom = scatterer.get_geometry()
(thet0, thet, phi0, phi, alpha, beta) = old_geom
try:
scatterer.set_geometry((thet0, thet0, phi0, phi0, alpha, beta))
S = scatterer.get_S()
finally:
scatterer.set_geometry(old_geom)
if h_pol:
return 2 * scatterer.wavelength * S[1,1].imag
else:
return 2 * scatterer.wavelength * S[0,0].imag |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. """ |
ext_xs = ext_xsect(scatterer, h_pol=h_pol)
return sca_xsect(scatterer, h_pol=h_pol)/ext_xs if ext_xs > 0.0 else 0.0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def asym(scatterer, h_pol=True):
"""Asymmetry parameter 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 asymmetry parameter. """ |
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(scatterer.thet0 * deg_to_rad)
sin_t0 = np.sin(scatterer.thet0 * deg_to_rad)
p0 = scatterer.phi0 * deg_to_rad
def integrand(thet, phi):
(scatterer.phi, scatterer.thet) = (phi*rad_to_deg, thet*rad_to_deg)
cos_T_sin_t = 0.5 * (np.sin(2*thet)*cos_t0 + \
(1-np.cos(2*thet))*sin_t0*np.cos(p0-phi))
I = sca_intensity(scatterer, h_pol)
return I * cos_T_sin_t
try:
cos_int = dblquad(integrand, 0.0, 2*np.pi, lambda x: 0.0,
lambda x: np.pi)[0]
finally:
scatterer.set_geometry(old_geom)
return cos_int/sca_xsect(scatterer, h_pol) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def radar_xsect(scatterer, h_pol=True):
"""Radar cross section for the current setup. Args: scatterer: a Scatterer instance. h_pol: If True (default), use horizontal polarization. If False, use vertical polarization. Returns: The radar cross section. """ |
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]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delta_hv(scatterer):
""" Delta_hv for the current setup. Args: scatterer: a Scatterer instance. Returns: Delta_hv [rad]. """ |
Z = scatterer.get_Z()
return np.arctan2(Z[2,3] - Z[3,2], -Z[2,2] - Z[3,3]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mg_refractive(m, mix):
"""Maxwell-Garnett EMA for the refractive index. Args: m: Tuple of the complex refractive indices of the media. mix: Tuple of the volume fractions of the media, len(mix)==len(m) (if sum(mix)!=1, these are taken relative to sum(mix)) Returns: The Maxwell-Garnett approximation for the complex refractive index of the effective medium If len(m)==2, the first element is taken as the matrix and the second as the inclusion. If len(m)>2, the media are mixed recursively so that the last element is used as the inclusion and the second to last as the matrix, then this mixture is used as the last element on the next iteration, and so on. """ |
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_refractive(m[-2:], mix[-2:])
mix_last = mix[-2] + mix[-1]
m = mg_refractive(m[:-2] + (m_last,), mix[:-2] + (mix_last,))
return m |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bruggeman_refractive(m, mix):
"""Bruggeman EMA for the refractive index. For instructions, see mg_refractive in this module, except this routine only works for two components. """ |
f1 = mix[0]/sum(mix)
f2 = mix[1]/sum(mix)
e1 = m[0]**2
e2 = m[1]**2
a = -2*(f1+f2)
b = (2*f1*e1 - f1*e2 + 2*f2*e2 - f2*e1)
c = (f1+f2)*e1*e2
e_eff = (-b - np.sqrt(b**2-4*a*c))/(2*a)
return np.sqrt(e_eff) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ice_refractive(file):
""" Interpolator for the refractive indices of ice. Inputs: File to read the refractive index lookup table from. This is supplied as "ice_refr.dat", retrieved from http://www.atmos.washington.edu/ice_optical_constants/ Returns: A callable object that takes as parameters the wavelength [mm] and the snow density [g/cm^3]. """ |
D = np.loadtxt(file)
log_wl = np.log10(D[:,0]/1000)
re = D[:,1]
log_im = np.log10(D[:,2])
iobj_re = interpolate.interp1d(log_wl, re)
iobj_log_im = interpolate.interp1d(log_wl, log_im)
def ref(wl, snow_density):
lwl = np.log10(wl)
try:
len(lwl)
except TypeError:
mi_sqr = complex(iobj_re(lwl), 10**iobj_log_im(lwl))**2
else:
mi_sqr = np.array([complex(a,b) for (a,b) in zip(iobj_re(lwl),
10**iobj_log_im(lwl))])**2
c = (mi_sqr-1)/(mi_sqr+2) * snow_density/ice_density
return np.sqrt( (1+2*c) / (1-c) )
return ref |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _group_by(data, criteria):
""" Group objects in data using a function or a key """ |
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].append(element)
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 test set train_sizes : array-like Relative or absolute numbers of training examples used to generate the learning curve ax : matplotlib Axes Axes object to draw the plot onto, otherwise uses current Axes Returns ------- ax: matplotlib Axes Axes containing the plot Examples -------- .. plot:: ../../examples/learning_curve.py """ |
if ax is None:
ax = plt.gca()
ax.grid()
ax.set_title("Learning Curve")
ax.set_xlabel("Training examples")
ax.set_ylabel("Score mean")
train_scores_mean = np.mean(train_scores, axis=1)
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_std = np.std(test_scores, axis=1)
ax.fill_between(train_sizes, train_scores_mean - train_scores_std,
train_scores_mean + train_scores_std, alpha=0.1,
color="r")
ax.fill_between(train_sizes, test_scores_mean - test_scores_std,
test_scores_mean + test_scores_std, alpha=0.1, color="g")
ax.plot(train_sizes, train_scores_mean, 'o-', color="r",
label="Training score")
ax.plot(train_sizes, test_scores_mean, 'o-', color="g",
label="Cross-validation score")
ax.legend(loc="best")
ax.margins(0.05)
return ax |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 proportion, get the index to split the data
# if value is negative, return 0
cutoff_index = max(int(len(y_true) * proportion) - 1, 0)
# Get the cutoff value
cutoff_value = scores_sorted[cutoff_index]
# Convert scores to binary, by comparing them with the cutoff value
scores_binary = np.array([int(y >= cutoff_value) for y in y_score])
# Calculate precision using sklearn function
if ignore_nas:
precision = __precision(y_true, scores_binary)
else:
precision = precision_score(y_true, scores_binary)
return precision, cutoff_value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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/(tp+fp)
# True nehatives do not affect precision value, so for every missing
# value in y_true, replace it with 0 and also replace the value
# in y_pred with 0
is_nan = np.isnan(y_true)
y_true[is_nan] = 0
y_pred[is_nan] = 0
precision = precision_score(y_true, y_pred)
return precision |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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]
# Sort true values in the same order
y_true_sorted = y_true[indexes]
# Grab top x proportion of true values
cutoff_index = max(int(len(y_true_sorted) * proportion) - 1, 0)
# add one to index to grab values including that index
y_true_top = y_true_sorted[:cutoff_index+1]
# Count the number of non-nas in the top x proportion
# we are returning a count so it should be an int
values = int((~np.isnan(y_true_top)).sum())
if normalize:
values = float(values)/(~np.isnan(y_true)).sum()
return values |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 set test_scores : array-like Scores for the test set param_range : array-like Hyperparameter values used to generate the curve param_range : str Hyperparameter name semilgo : bool Sets a log scale on the x axis ax : matplotlib Axes Axes object to draw the plot onto, otherwise uses current Axes Returns ------- ax: matplotlib Axes Axes containing the plot Examples -------- .. plot:: ../../examples/validation_curve.py """ |
if ax is None:
ax = plt.gca()
if semilogx:
ax.set_xscale('log')
train_scores_mean = np.mean(train_scores, axis=1)
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_std = np.std(test_scores, axis=1)
ax.set_title("Validation Curve")
ax.set_ylabel("Score mean")
if param_name:
ax.set_xlabel(param_name)
ax.plot(param_range, train_scores_mean, label="Training score", color="r")
ax.plot(param_range, test_scores_mean, label="Cross-validation score",
color="g")
ax.fill_between(param_range, train_scores_mean - train_scores_std,
train_scores_mean + train_scores_std, alpha=0.2, color="r")
ax.fill_between(param_range, test_scores_mean - test_scores_std,
test_scores_mean + test_scores_std, alpha=0.2, color="g")
ax.legend(loc="best")
ax.margins(0.05)
return ax |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 values (ground truth). y_pred : array-like, shape = [n_samples] Target predicted classes (estimator predictions). target_names : list List containing the names of the target classes. List must be in order e.g. ``['Label for class 0', 'Label for class 1']``. If ``None``, generic labels will be generated e.g. ``['Class 0', 'Class 1']`` ax: matplotlib Axes Axes object to draw the plot onto, otherwise uses current Axes normalize : bool Normalize the confusion matrix cmap : matplotlib Colormap If ``None`` uses a modified version of matplotlib's OrRd colormap. Returns ------- ax: matplotlib Axes Axes containing the plot Examples -------- .. plot:: ../../examples/confusion_matrix.py """ |
if any((val is None for val in (y_true, y_pred))):
raise ValueError("y_true and y_pred are needed to plot confusion "
"matrix")
# calculate how many names you expect
values = set(y_true).union(set(y_pred))
expected_len = len(values)
if target_names and (expected_len != len(target_names)):
raise ValueError(('Data cointains {} different values, but target'
' names contains {} values.'.format(expected_len,
len(target_names)
)))
# if the user didn't pass target_names, create generic ones
if not target_names:
values = list(values)
values.sort()
target_names = ['Class {}'.format(v) for v in values]
cm = sk_confusion_matrix(y_true, y_pred)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
np.set_printoptions(precision=2)
if ax is None:
ax = plt.gca()
# this (y, x) may sound counterintuitive. The reason is that
# in a matrix cell (i, j) is in row=i and col=j, translating that
# to an x, y plane (which matplotlib uses to plot), we need to use
# i as the y coordinate (how many steps down) and j as the x coordinate
# how many steps to the right.
for (y, x), v in np.ndenumerate(cm):
try:
label = '{:.2}'.format(v)
except:
label = v
ax.text(x, y, label, horizontalalignment='center',
verticalalignment='center')
if cmap is None:
cmap = default_heatmap()
im = ax.imshow(cm, interpolation='nearest', cmap=cmap)
plt.colorbar(im, ax=ax)
tick_marks = np.arange(len(target_names))
ax.set_xticks(tick_marks)
ax.set_xticklabels(target_names)
ax.set_yticks(tick_marks)
ax.set_yticklabels(target_names)
title = 'Confusion matrix'
if normalize:
title += ' (normalized)'
ax.set_title(title)
ax.set_ylabel('True label')
ax.set_xlabel('Predicted label')
return ax |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 Axes object to draw the plot onto, otherwise uses current Axes Returns ------- ax: matplotlib Axes Axes containing the plot """ |
if any((val is None for val in (y_true, y_score))):
raise ValueError('y_true and y_score are needed to plot precision at '
'proportions')
if ax is None:
ax = plt.gca()
y_score_is_vector = is_column_vector(y_score) or is_row_vector(y_score)
if not y_score_is_vector:
y_score = y_score[:, 1]
# Calculate points
proportions = [0.01 * i for i in range(1, 101)]
precs_and_cutoffs = [precision_at(y_true, y_score, p) for p in proportions]
precs, cutoffs = zip(*precs_and_cutoffs)
# Plot and set nice defaults for title and axis labels
ax.plot(proportions, precs)
ax.set_title('Precision at various proportions')
ax.set_ylabel('Precision')
ax.set_xlabel('Proportion')
ticks = [0.1 * i for i in range(1, 11)]
ax.set_xticks(ticks)
ax.set_xticklabels(ticks)
ax.set_yticks(ticks)
ax.set_yticklabels(ticks)
ax.set_ylim([0, 1.0])
ax.set_xlim([0, 1.0])
return ax |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 `grid_scores_` parameter) change : str or iterable with len<=2 Parameter to change subset : dictionary-like parameter-value(s) pairs to subset from grid_scores. (e.g. ``{'n_estimartors': [1, 10]}``), if None all combinations will be used. kind : ['line', 'bar'] This only applies whe change is a single parameter. Changes the type of plot cmap : matplotlib Colormap This only applies when change are two parameters. Colormap used for the matrix. If None uses a modified version of matplotlib's OrRd colormap. ax: matplotlib Axes Axes object to draw the plot onto, otherwise uses current Axes Returns ------- ax: matplotlib Axes Axes containing the plot Examples -------- .. plot:: ../../examples/grid_search.py """ |
if change is None:
raise ValueError(('change can\'t be None, you need to select at least'
' one value to make the plot.'))
if ax is None:
ax = plt.gca()
if cmap is None:
cmap = default_heatmap()
if isinstance(change, string_types) or len(change) == 1:
return _grid_search_single(grid_scores, change, subset, kind, ax)
elif len(change) == 2:
return _grid_search_double(grid_scores, change, subset, cmap, ax)
else:
raise ValueError('change must have length 1 or 2 or be a string') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def confusion_matrix(self):
"""Confusion matrix plot """ |
return plot.confusion_matrix(self.y_true, self.y_pred,
self.target_names, ax=_gen_ax()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def precision_recall(self):
"""Precision-recall plot """ |
return plot.precision_recall(self.y_true, self.y_score, ax=_gen_ax()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def feature_importances(self):
"""Feature importances plot """ |
return plot.feature_importances(self.estimator,
feature_names=self.feature_names,
ax=_gen_ax()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def feature_importances_table(self):
"""Feature importances table """ |
from . import table
return table.feature_importances(self.estimator,
feature_names=self.feature_names) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def precision_at_proportions(self):
"""Precision at proportions plot """ |
return plot.precision_at_proportions(self.y_true, self.y_score,
ax=_gen_ax()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_report(self, template, path=None, style=None):
""" Generate HTML report Parameters template : markdown-formatted string or path to the template file used for rendering the report. Any attribute of this object can be included in the report using the {tag} format. e.g.'# Report{estimator_name}{roc}{precision_recall}'. Apart from every attribute, you can also use {date} and {date_utc} tags to include the date for the report generation using local and UTC timezones repectively. path : str Path to save the HTML report. If None, the function will return the HTML code. style: str Path to a css file to apply style to the report. If None, no style will be applied Returns ------- report: str Returns the contents of the report if path is None. """ |
from .report import generate
return generate(self, template, path, style) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def roc(y_true, y_score, ax=None):
""" Plot ROC 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_samples, n_classes] for multiclass Target scores (estimator predictions). ax: matplotlib Axes Axes object to draw the plot onto, otherwise uses current Axes Notes ----- It is assumed that the y_score parameter columns are in order. For example, if ``y_true = [2, 2, 1, 0, 0, 1, 2]``, then the first column in y_score must countain the scores for class 0, second column for class 1 and so on. Returns ------- ax: matplotlib Axes Axes containing the plot Examples -------- .. plot:: ../../examples/roc.py """ |
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 of y_score
y_score_is_vector = is_column_vector(y_score) or is_row_vector(y_score)
if y_score_is_vector:
n_classes = 2
else:
_, n_classes = y_score.shape
# check data shape?
if n_classes > 2:
# convert y_true to binary format
y_true_bin = label_binarize(y_true, classes=np.unique(y_true))
_roc_multi(y_true_bin, y_score, ax=ax)
for i in range(n_classes):
_roc(y_true_bin[:, i], y_score[:, i], ax=ax)
else:
if y_score_is_vector:
_roc(y_true, y_score, ax)
else:
_roc(y_true, y_score[:, 1], ax)
# raise error if n_classes = 1?
return ax |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _roc(y_true, y_score, ax=None):
""" Plot ROC curve for binary classification. Parameters y_true : array-like, shape = [n_samples] Correct target values (ground truth). y_score : array-like, shape = [n_samples] Target scores (estimator predictions). ax: matplotlib Axes Axes object to draw the plot onto, otherwise uses current Axes Returns ------- ax: matplotlib Axes Axes containing the plot """ |
# 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 predictions). ax: matplotlib Axes Axes object to draw the plot onto, otherwise uses current Axes Returns ------- ax: matplotlib Axes Axes containing the plot """ |
# Compute micro-average ROC curve and ROC area
fpr, tpr, _ = roc_curve(y_true.ravel(), y_score.ravel())
roc_auc = auc(fpr, tpr)
if ax is None:
ax = plt.gca()
ax.plot(fpr, tpr, label=('micro-average ROC curve (area = {0:0.2f})'
.format(roc_auc)))
_set_ax_settings(ax)
return ax |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def reassemble_options(payload):
'''
Reassemble partial options to options, returns a list of dhcp_option
DHCP options are basically `|tag|length|value|` structure. When an
option is longer than 255 bytes, it can be splitted into multiple
structures with the same tag. The splitted structures must be
joined back to get the original option.
`dhcp_option_partial` is used to present the splitted options,
and `dhcp_option` is used for reassembled option.
'''
options = []
option_indices = {}
def process_option_list(partials):
for p in partials:
if p.tag == OPTION_END:
break
if p.tag == OPTION_PAD:
continue
if p.tag in option_indices:
# Reassemble the data
options[option_indices[p.tag]][1].append(p.data)
else:
options.append((p.tag, [p.data]))
option_indices[p.tag] = len(options) - 1
# First process options field
process_option_list(payload.options)
if OPTION_OVERLOAD in option_indices:
# There is an overload option
data = b''.join(options[option_indices[OPTION_OVERLOAD]][1])
overload_option = dhcp_overload.create(data)
if overload_option & OVERLOAD_FILE:
process_option_list(dhcp_option_partial[0].create(payload.file))
if overload_option & OVERLOAD_SNAME:
process_option_list(dhcp_option_partial[0].create(payload.sname))
def _create_dhcp_option(tag, data):
opt = dhcp_option(tag = tag)
opt._setextra(data)
opt._autosubclass()
return opt
return [_create_dhcp_option(tag, b''.join(data)) for tag,data in options] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_option_from_value(tag, value):
""" Set DHCP option with human friendly value """ |
dhcp_option.parser()
fake_opt = dhcp_option(tag = tag)
for c in dhcp_option.subclasses:
if c.criteria(fake_opt):
if hasattr(c, '_parse_from_value'):
return c(tag = tag, value = c._parse_from_value(value))
else:
raise ValueError('Invalid DHCP option ' + str(tag) + ": " + repr(value))
else:
fake_opt._setextra(_tobytes(value))
return fake_opt |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_dhcp_options(input_dict, ignoreError = False, generateNone = False):
""" Try best to create dhcp_options from human friendly values, ignoring invalid values """ |
retdict = {}
for k,v in dict(input_dict).items():
try:
if generateNone and v is None:
retdict[k] = None
else:
try:
retdict[k] = create_option_from_value(k, v)
except _EmptyOptionException:
if generateNone:
retdict[k] = None
except Exception:
if ignoreError:
continue
else:
raise
return retdict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def with_indices(*args):
'''
Create indices for an event class. Every event class must be decorated with this decorator.
'''
def decorator(cls):
for c in cls.__bases__:
if hasattr(c, '_indicesNames'):
cls._classnameIndex = c._classnameIndex + 1
for i in range(0, cls._classnameIndex):
setattr(cls, '_classname' + str(i), getattr(c, '_classname' + str(i)))
setattr(cls, '_classname' + str(cls._classnameIndex), cls._getTypename())
cls._indicesNames = c._indicesNames + ('_classname' + str(cls._classnameIndex),) + args
cls._generateTemplate()
return cls
cls._classnameIndex = -1
cls._indicesNames = args
cls._generateTemplate()
return cls
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| async def lock(self, container = None):
"Wait for lock acquire"
if container is None:
container = RoutineContainer.get_container(self.scheduler)
if self.locked:
pass
elif self.lockroutine:
await LockedEvent.createMatcher(self)
else:
await container.wait_for_send(LockEvent(self.context, self.key, self))
self.locked = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def trylock(self):
"Try to acquire lock and return True; if cannot acquire the lock at this moment, return False."
if self.locked:
return True
if self.lockroutine:
return False
waiter = self.scheduler.send(LockEvent(self.context, self.key, self))
if waiter:
return False
else:
self.locked = True
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def beginlock(self, container):
"Start to acquire lock in another routine. Call trylock or lock later to acquire the lock. Call unlock to cancel the lock routine"
if self.locked:
return True
if self.lockroutine:
return False
self.lockroutine = container.subroutine(self._lockroutine(container), False)
return self.locked |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def unlock(self):
"Unlock the key"
if self.lockroutine:
self.lockroutine.close()
self.lockroutine = None
if self.locked:
self.locked = False
self.scheduler.ignore(LockEvent.createMatcher(self.context, self.key, self)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self):
""" Create the subqueue to change the default behavior of Lock to semaphore. """ |
self.queue = self.scheduler.queue.addSubQueue(self.priority, LockEvent.createMatcher(self.context, self.key),
maxdefault = self.size, defaultQueueClass = CBQueue.AutoClassQueue.initHelper('locker', subqueuelimit = 1)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def destroy(self, container = None):
""" Destroy the created subqueue to change the behavior back to Lock """ |
if container is None:
container = RoutineContainer(self.scheduler)
if self.queue is not None:
await container.syscall_noreturn(syscall_removequeue(self.scheduler.queue, self.queue))
self.queue = None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def default_start():
""" Use `sys.argv` for starting parameters. This is the entry-point of `vlcp-start` """ |
(config, daemon, pidfile, startup, fork) = parsearg()
if config is None:
if os.path.isfile('/etc/vlcp.conf'):
config = '/etc/vlcp.conf'
else:
print('/etc/vlcp.conf is not found; start without configurations.')
elif not config:
config = None
main(config, startup, daemon, pidfile, fork) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def close(self):
"Stop the output stream, but further download will still perform"
if self.stream:
self.stream.close(self.scheduler)
self.stream = None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| async def shutdown(self):
"Force stop the output stream, if there are more data to download, shutdown the connection"
if self.stream:
if not self.stream.dataeof and not self.stream.dataerror:
self.stream.close(self.scheduler)
await self.connection.shutdown()
else:
self.stream.close(self.scheduler)
self.stream = None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def restart_walk(self):
""" Force a re-walk """ |
if not self._restartwalk:
self._restartwalk = True
await self.wait_for_send(FlowUpdaterNotification(self, FlowUpdaterNotification.STARTWALK)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def _dataobject_update_detect(self, _initialkeys, _savedresult):
""" Coroutine that wait for retrieved value update notification """ |
def expr(newvalues, updatedvalues):
if any(v.getkey() in _initialkeys for v in updatedvalues if v is not None):
return True
else:
return self.shouldupdate(newvalues, updatedvalues)
while True:
updatedvalues, _ = await multiwaitif(_savedresult, self, expr, True)
if not self._updatedset:
self.scheduler.emergesend(FlowUpdaterNotification(self, FlowUpdaterNotification.DATAUPDATED))
self._updatedset.update(updatedvalues) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def updateobjects(self, updatedvalues):
""" Force a update notification on specified objects, even if they are not actually updated in ObjectDB """ |
if not self._updatedset:
self.scheduler.emergesend(FlowUpdaterNotification(self, FlowUpdaterNotification.DATAUPDATED))
self._updatedset.update(set(updatedvalues).intersection(self._savedresult)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def syscall_direct(*events):
'''
Directly process these events. This should never be used for normal events.
'''
def _syscall(scheduler, processor):
for e in events:
processor(e)
return _syscall |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def syscall_generator(generator):
'''
Directly process events from a generator function. This should never be used for normal events.
'''
def _syscall(scheduler, processor):
for e in generator():
processor(e)
return _syscall |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def syscall_clearqueue(queue):
'''
Clear a queue
'''
def _syscall(scheduler, processor):
qes, qees = queue.clear()
events = scheduler.queue.unblockqueue(queue)
for e in events:
scheduler.eventtree.remove(e)
for e in qes:
processor(e)
for e in qees:
processor(e)
return _syscall |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def unregisterall(self, runnable):
'''
Unregister all matches and detach the runnable. Automatically called when runnable returns StopIteration.
'''
if runnable in self.registerIndex:
for m in self.registerIndex[runnable]:
self.matchtree.remove(m, runnable)
if m.indices[0] == PollEvent._classname0 and len(m.indices) >= 2:
self.polling.onmatch(m.indices[1], None if len(m.indices) <= 2 else m.indices[2], False)
del self.registerIndex[runnable]
self.daemons.discard(runnable) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def ignore(self, matcher):
'''
Unblock and ignore the matched events, if any.
'''
events = self.eventtree.findAndRemove(matcher)
for e in events:
self.queue.unblock(e)
e.canignore = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def quit(self, daemononly = False):
'''
Send quit event to quit the main loop
'''
if not self.quitting:
self.quitting = True
self.queue.append(SystemControlEvent(SystemControlEvent.QUIT, daemononly = daemononly), True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def setDaemon(self, runnable, isdaemon, noregister = False):
'''
If a runnable is a daemon, it will not keep the main loop running. The main loop will end when all alived runnables are daemons.
'''
if not noregister and runnable not in self.registerIndex:
self.register((), runnable)
if isdaemon:
self.daemons.add(runnable)
else:
self.daemons.discard(runnable) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| async def updateconfig(self):
"Reload configurations, remove non-exist servers, add new servers, and leave others unchanged"
exists = {}
for s in self.connections:
exists[(s.protocol.vhost, s.rawurl)] = s
self._createServers(self, '', exists = exists)
for _,v in exists.items():
await v.shutdown()
self.connections.remove(v) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getconnections(self, vhost = None):
"Return accepted connections, optionally filtered by vhost"
if vhost is None:
return list(self.managed_connections)
else:
return [c for c in self.managed_connections if c.protocol.vhost == vhost] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def watch_context(keys, result, reqid, container, module = 'objectdb'):
""" DEPRECATED - use request_context for most use cases """ |
try:
keys = [k for k,r in zip(keys, result) if r is not None]
yield result
finally:
if keys:
async def clearup():
try:
await send_api(container, module, 'munwatch', {'keys': keys, 'requestid': reqid})
except QuitException:
pass
container.subroutine(clearup(), False) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def updater(f):
"Decorate a function with named arguments into updater for transact"
@functools.wraps(f)
def wrapped_updater(keys, values):
result = f(*values)
return (keys[:len(result)], result)
return wrapped_updater |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def dump(obj, attributes = True, _refset = None):
"Show full value of a data object"
if _refset is None:
_refset = set()
if obj is None:
return None
elif isinstance(obj, DataObject):
if id(obj) in _refset:
attributes = False
else:
_refset.add(id(obj))
cls = type(obj)
clsname = getattr(cls, '__module__', '<unknown>') + '.' + getattr(cls, '__name__', '<unknown>')
baseresult = {'_type': clsname, '_key': obj.getkey()}
if not attributes:
return baseresult
else:
baseresult.update((k,dump(v, attributes, _refset)) for k,v in vars(obj).items() if k[:1] != '_')
_refset.remove(id(obj))
return baseresult
elif isinstance(obj, ReferenceObject):
if obj._ref is not None:
return dump(obj._ref, attributes, _refset)
else:
return {'_ref':obj.getkey()}
elif isinstance(obj, WeakReferenceObject):
return {'_weakref':obj.getkey()}
elif isinstance(obj, DataObjectSet):
return dump(list(obj.dataset()))
elif isinstance(obj, dict):
return dict((k, dump(v, attributes, _refset)) for k,v in obj.items())
elif isinstance(obj, list) or isinstance(obj, tuple) or isinstance(obj, set):
return [dump(v, attributes, _refset) for v in obj]
else:
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def update_ports(self, ports, ovsdb_ports):
""" Called from main module to update port information """ |
new_port_names = dict((p['name'], _to32bitport(p['ofport'])) for p in ovsdb_ports)
new_port_ids = dict((p['id'], _to32bitport(p['ofport'])) for p in ovsdb_ports if p['id'])
if new_port_names == self._portnames and new_port_ids == self._portids:
return
self._portnames.clear()
self._portnames.update(new_port_names)
self._portids.clear()
self._portids.update(new_port_ids)
logicalportkeys = [LogicalPort.default_key(id) for id in self._portids]
self._original_initialkeys = logicalportkeys + [PhysicalPortSet.default_key()]
self._initialkeys = tuple(itertools.chain(self._original_initialkeys, self._append_initialkeys))
phy_walker = partial(self._physicalport_walker, _portnames=new_port_names)
log_walker = partial(self._logicalport_walker, _portids=new_port_ids)
self._walkerdict = dict(itertools.chain(
((PhysicalPortSet.default_key(),phy_walker),),
((lgportkey,log_walker) for lgportkey in logicalportkeys)
))
self._portnames = new_port_names
self._portids = new_port_ids
await self.restart_walk() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def list_proxy(root_package = 'vlcp'):
'''
Walk through all the sub modules, find subclasses of vlcp.server.module._ProxyModule,
list their default values
'''
proxy_dict = OrderedDict()
pkg = __import__(root_package, fromlist=['_'])
for imp, module, _ in walk_packages(pkg.__path__, root_package + '.'):
m = __import__(module, fromlist = ['_'])
for _, v in vars(m).items():
if v is not None and isinstance(v, type) and issubclass(v, _ProxyModule) \
and v is not _ProxyModule \
and v.__module__ == module \
and hasattr(v, '_default'):
name = v.__name__.lower()
if name not in proxy_dict:
proxy_dict[name] = {'defaultmodule': v._default.__name__.lower(),
'class': repr(v._default.__module__ + '.' + v._default.__name__)}
return proxy_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def list_modules(root_package = 'vlcp'):
'''
Walk through all the sub modules, find subclasses of vlcp.server.module.Module,
list their apis through apidefs
'''
pkg = __import__(root_package, fromlist=['_'])
module_dict = OrderedDict()
_server = Server()
for imp, module, _ in walk_packages(pkg.__path__, root_package + '.'):
m = __import__(module, fromlist = ['_'])
for name, v in vars(m).items():
if v is not None and isinstance(v, type) and issubclass(v, Module) \
and v is not Module \
and not isinstance(v, _ProxyModule) \
and hasattr(v, '__dict__') and 'configkey' in v.__dict__ \
and v.__module__ == module:
module_name = v.__name__.lower()
if module_name not in module_dict:
_inst = v(_server)
module_info = OrderedDict((('class', v.__module__ + '.' + v.__name__),
('dependencies', [d.__name__.lower()
for d in v.depends]),
('classdescription', getdoc(v)),
('apis', [])))
if hasattr(_inst, 'apiHandler'):
apidefs = _inst.apiHandler.apidefs
module_info['apis'] = [(d[0], d[3])
for d in apidefs
if len(d) > 3 and \
not d[0].startswith('public/')]
module_dict[module_name] = module_info
return module_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def unblock(self, event):
'''
Remove a block
'''
if event not in self.blockEvents:
return
self.blockEvents[event].unblock(event)
del self.blockEvents[event] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def unblockall(self):
'''
Remove all blocks from the queue and all sub-queues
'''
for q in self.queues.values():
q.unblockall()
self.blockEvents.clear() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def notifyBlock(self, queue, blocked):
'''
Internal notify for sub-queues been blocked
'''
if blocked:
if self.prioritySet[-1] == queue.priority:
self.prioritySet.pop()
else:
pindex = bisect_left(self.prioritySet, queue.priority)
if pindex < len(self.prioritySet) and self.prioritySet[pindex] == queue.priority:
del self.prioritySet[pindex]
else:
if queue.canPop():
pindex = bisect_left(self.prioritySet, queue.priority)
if pindex >= len(self.prioritySet) or self.prioritySet[pindex] != queue.priority:
self.prioritySet.insert(pindex, queue.priority)
newblocked = not self.canPop()
if newblocked != self.blocked:
self.blocked = newblocked
if self.parent is not None:
self.parent.notifyBlock(self, newblocked) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def setPriority(self, queue, priority):
'''
Set priority of a sub-queue
'''
q = self.queueindex[queue]
self.queues[q[0]].removeSubQueue(q[1])
newPriority = self.queues.setdefault(priority, CBQueue.MultiQueue(self, priority))
q[0] = priority
newPriority.addSubQueue(q[1]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ensure_keys(walk, *keys):
""" Use walk to try to retrieve all keys """ |
all_retrieved = True
for k in keys:
try:
walk(k)
except WalkKeyNotRetrieved:
all_retrieved = False
return all_retrieved |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def list_config(root_package = 'vlcp'):
'''
Walk through all the sub modules, find subclasses of vlcp.config.Configurable,
list their available configurations through _default_ prefix
'''
pkg = __import__(root_package, fromlist=['_'])
return_dict = OrderedDict()
for imp, module, _ in walk_packages(pkg.__path__, root_package + '.'):
m = __import__(module, fromlist = ['_'])
for name, v in vars(m).items():
if v is not None and isinstance(v, type) and issubclass(v, Configurable) \
and v is not Configurable \
and hasattr(v, '__dict__') and 'configkey' in v.__dict__ \
and v.__module__ == module:
configkey = v.__dict__['configkey']
if configkey not in return_dict:
configs = OrderedDict()
v2 = v
parents = [v2]
while True:
parent = None
for c in v2.__bases__:
if issubclass(c, Configurable):
parent = c
if parent is None or parent is Configurable:
break
if hasattr(parent, '__dict__') and 'configkey' not in parent.__dict__:
parents.append(parent)
v2 = parent
else:
break
for v2 in reversed(parents):
tmp_configs = {}
for k, default_value in v2.__dict__.items():
if k.startswith('_default_'):
config_attr = k[len('_default_'):]
if config_attr in v.__dict__:
continue
configname = configkey + '.' + config_attr
tmp_configs.setdefault(configname, OrderedDict())['default'] = \
pformat(default_value, width=10)
# Inspect the source lines to find remarks for these configurations
lines, _ = getsourcelines(v2)
last_remark = []
for l in lines:
l = l.strip()
if not l:
continue
if l.startswith('#'):
last_remark.append(l[1:])
else:
if l.startswith('_default_'):
key, sep, _ = l.partition('=')
if sep and key.startswith('_default_'):
configname = configkey + '.' + key[len('_default_'):].strip()
if configname in tmp_configs and configname not in configs:
configs[configname] = tmp_configs.pop(configname)
if configname in configs and last_remark:
configs[configname]['description'] = cleandoc('\n' + '\n'.join(last_remark))
del last_remark[:]
for key in tmp_configs:
if key not in configs:
configs[key] = tmp_configs[key]
if configs:
return_dict[configkey] = OrderedDict((('class', v.__module__ + '.' + name),
('classdescription', getdoc(v)),
('configs', configs)))
return return_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def http(container = None):
"wrap a WSGI-style class method to a HTTPRequest event handler"
def decorator(func):
@functools.wraps(func)
def handler(self, event):
return _handler(self if container is None else container, event, lambda env: func(self, env))
return handler
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def statichttp(container = None):
"wrap a WSGI-style function to a HTTPRequest event handler"
def decorator(func):
@functools.wraps(func)
def handler(event):
return _handler(container, event, func)
if hasattr(func, '__self__'):
handler.__self__ = func.__self__
return handler
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def start_response(self, status = 200, headers = [], clearheaders = True, disabletransferencoding = False):
"Start to send response"
if self._sendHeaders:
raise HttpProtocolException('Cannot modify response, headers already sent')
self.status = status
self.disabledeflate = disabletransferencoding
if clearheaders:
self.sent_headers = headers[:]
else:
self.sent_headers.extend(headers) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def header(self, key, value, replace = True):
"Send a new header"
if hasattr(key, 'encode'):
key = key.encode('ascii')
if hasattr(value, 'encode'):
value = value.encode(self.encoding)
if replace:
self.sent_headers = [(k,v) for k,v in self.sent_headers if k.lower() != key.lower()]
self.sent_headers.append((key, value)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setcookie(self, key, value, max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False):
""" Add a new cookie """ |
newcookie = Morsel()
newcookie.key = key
newcookie.value = value
newcookie.coded_value = value
if max_age is not None:
newcookie['max-age'] = max_age
if expires is not None:
newcookie['expires'] = expires
if path is not None:
newcookie['path'] = path
if domain is not None:
newcookie['domain'] = domain
if secure:
newcookie['secure'] = secure
if httponly:
newcookie['httponly'] = httponly
self.sent_cookies = [c for c in self.sent_cookies if c.key != key]
self.sent_cookies.append(newcookie) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bufferoutput(self):
""" Buffer the whole output until write EOF or flushed. """ |
new_stream = Stream(writebufferlimit=None)
if self._sendHeaders:
# An extra copy
self.container.subroutine(new_stream.copy_to(self.outputstream, self.container, buffering=False))
self.outputstream = Stream(writebufferlimit=None) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| async def rewrite(self, path, method = None, keepresponse = True):
"Rewrite this request to another processor. Must be called before header sent"
if self._sendHeaders:
raise HttpProtocolException('Cannot modify response, headers already sent')
if getattr(self.event, 'rewritedepth', 0) >= getattr(self.protocol, 'rewritedepthlimit', 32):
raise HttpRewriteLoopException
newpath = urljoin(quote_from_bytes(self.path).encode('ascii'), path)
if newpath == self.fullpath or newpath == self.originalpath:
raise HttpRewriteLoopException
extraparams = {}
if keepresponse:
if hasattr(self, 'status'):
extraparams['status'] = self.status
extraparams['sent_headers'] = self.sent_headers
extraparams['sent_cookies'] = self.sent_cookies
r = HttpRequestEvent(self.host,
newpath,
self.method if method is None else method,
self.connection,
self.connmark,
self.xid,
self.protocol,
headers = self.headers,
headerdict = self.headerdict,
setcookies = self.setcookies,
stream = self.inputstream,
rewritefrom = self.fullpath,
originalpath = self.originalpath,
rewritedepth = getattr(self.event, 'rewritedepth', 0) + 1,
**extraparams
)
await self.connection.wait_for_send(r)
self._sendHeaders = True
self.outputstream = None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def redirect(self, path, status = 302):
""" Redirect this request with 3xx status """ |
location = urljoin(urlunsplit((b'https' if self.https else b'http',
self.host,
quote_from_bytes(self.path).encode('ascii'),
'',
''
)), path)
self.start_response(status, [(b'Location', location)])
await self.write(b'<a href="' + self.escape(location, True) + b'">' + self.escape(location) + b'</a>')
await self.flush(True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def escape(self, text, quote = True):
""" Escape special characters in HTML """ |
if isinstance(text, bytes):
return escape_b(text, quote)
else:
return escape(text, quote) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def error(self, status=500, allowredirect = True, close = True, showerror = None, headers = []):
""" Show default error response """ |
if showerror is None:
showerror = self.showerrorinfo
if self._sendHeaders:
if showerror:
typ, exc, tb = sys.exc_info()
if exc:
await self.write('<span style="white-space:pre-wrap">\n', buffering = False)
await self.writelines((self.nl2br(self.escape(v)) for v in traceback.format_exception(typ, exc, tb)), buffering = False)
await self.write('</span>\n', close, False)
elif allowredirect and status in self.protocol.errorrewrite:
await self.rewrite(self.protocol.errorrewrite[status], b'GET')
elif allowredirect and status in self.protocol.errorredirect:
await self.redirect(self.protocol.errorredirect[status])
else:
self.start_response(status, headers)
typ, exc, tb = sys.exc_info()
if showerror and exc:
await self.write('<span style="white-space:pre-wrap">\n', buffering = False)
await self.writelines((self.nl2br(self.escape(v)) for v in traceback.format_exception(typ, exc, tb)), buffering = False)
await self.write('</span>\n', close, False)
else:
await self.write(b'<h1>' + _createstatus(status) + b'</h1>', close, False) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def write(self, data, eof = False, buffering = True):
""" Write output to current output stream """ |
if not self.outputstream:
self.outputstream = Stream()
self._startResponse()
elif (not buffering or eof) and not self._sendHeaders:
self._startResponse()
if not isinstance(data, bytes):
data = data.encode(self.encoding)
await self.outputstream.write(data, self.connection, eof, False, buffering) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def writelines(self, lines, eof = False, buffering = True):
""" Write lines to current output stream """ |
for l in lines:
await self.write(l, False, buffering)
if eof:
await self.write(b'', eof, buffering) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def output(self, stream, disabletransferencoding = None):
""" Set output stream and send response immediately """ |
if self._sendHeaders:
raise HttpProtocolException('Cannot modify response, headers already sent')
self.outputstream = stream
try:
content_length = len(stream)
except Exception:
pass
else:
self.header(b'Content-Length', str(content_length).encode('ascii'))
if disabletransferencoding is not None:
self.disabledeflate = disabletransferencoding
self._startResponse() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def outputdata(self, data):
""" Send output with fixed length data """ |
if not isinstance(data, bytes):
data = str(data).encode(self.encoding)
self.output(MemoryStream(data)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def close(self):
""" Close this request, send all data. You can still run other operations in the handler. """ |
if not self._sendHeaders:
self._startResponse()
if self.inputstream is not None:
self.inputstream.close(self.connection.scheduler)
if self.outputstream is not None:
await self.flush(True)
if hasattr(self, 'session') and self.session:
self.session.unlock() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| async def sessionstart(self):
"Start session. Must start service.utils.session.Session to use this method"
if not hasattr(self, 'session') or not self.session:
self.session, setcookies = await call_api(self.container, 'session', 'start', {'cookies':self.rawcookie})
for nc in setcookies:
self.sent_cookies = [c for c in self.sent_cookies if c.key != nc.key]
self.sent_cookies.append(nc) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def sessiondestroy(self):
""" Destroy current session. The session object is discarded and can no longer be used in other requests. """ |
if hasattr(self, 'session') and self.session:
setcookies = await call_api(self.container, 'session', 'destroy', {'sessionid':self.session.id})
self.session.unlock()
del self.session
for nc in setcookies:
self.sent_cookies = [c for c in self.sent_cookies if c.key != nc.key]
self.sent_cookies.append(nc) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.