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 plot_samples(self,prop,fig=None,label=True, histtype='step',bins=50,lw=3, **kwargs):
"""Plots histogram of samples of desired property. :param prop: Desired ... |
setfig(fig)
samples,stats = self.prop_samples(prop)
fig = plt.hist(samples,bins=bins,normed=True,
histtype=histtype,lw=lw,**kwargs)
plt.xlabel(prop)
plt.ylabel('Normalized count')
if label:
med,lo,hi = stats
plt.annotate(... |
<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_band(cls, b, **kwargs):
"""Defines what a "shortcut" band name refers to. """ |
phot = None
# Default to SDSS for these
if b in ['u','g','r','i','z']:
phot = 'SDSSugriz'
band = 'sdss_{}'.format(b)
elif b in ['U','B','V','R','I','J','H','Ks']:
phot = 'UBVRIJHKsKp'
band = b
elif b=='K':
phot = 'UBVR... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def searchsorted(arr, N, x):
"""N is length of arr """ |
L = 0
R = N-1
done = False
m = (L+R)//2
while not done:
if arr[m] < x:
L = m + 1
elif arr[m] > x:
R = m - 1
elif arr[m] == x:
done = True
m = (L+R)//2
if L>R:
done = True
return L |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wrap_flask_restful_resource( fun: Callable, flask_restful_api: FlaskRestfulApi, injector: Injector ) -> Callable: """ This is needed because of how flask_rest... |
# The following fragment of code is copied from flask_restful project
"""
Copyright (c) 2013, Twilio, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def complete_url(self, url):
""" Completes a given URL with this instance's URL base. """ |
if self.base_url:
return urlparse.urljoin(self.base_url, url)
else:
return url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interact(self, **local):
""" Drops the user into an interactive Python session with the ``sess`` variable set to the current session instance. If keyword arg... |
import code
code.interact(local=dict(sess=self, **local)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wait_for(self, condition, interval = DEFAULT_WAIT_INTERVAL, timeout = DEFAULT_WAIT_TIMEOUT):
""" Wait until a condition holds by checking it in regular inter... |
start = time.time()
# at least execute the check once!
while True:
res = condition()
if res:
return res
# timeout?
if time.time() - start > timeout:
break
# wait a bit
time.sleep(interval)
# timeout occured!
raise WaitTimeoutError("wait_for t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wait_while(self, condition, *args, **kw):
""" Wait while a condition holds. """ |
return self.wait_for(lambda: not condition(), *args, **kw) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def at_css(self, css, timeout = DEFAULT_AT_TIMEOUT, **kw):
""" Returns the first node matching the given CSSv3 expression or ``None`` if a timeout occurs. """ |
return self.wait_for_safe(lambda: super(WaitMixin, self).at_css(css),
timeout = timeout,
**kw) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def at_xpath(self, xpath, timeout = DEFAULT_AT_TIMEOUT, **kw):
""" Returns the first node matching the given XPath 2.0 expression or ``None`` if a timeout occurs... |
return self.wait_for_safe(lambda: super(WaitMixin, self).at_xpath(xpath),
timeout = timeout,
**kw) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def switch_axis_limits(ax, which_axis):
'''
Switch the axis limits of either x or y. Or both!
'''
for a in which_axis:
assert a in ('x', 'y')
ax_limits = ax.axis()
if a == 'x':
ax.set_xlim(ax_limits[1], ax_limits[0])
else:
ax.set_ylim(ax_limits[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 remove_chartjunk(ax, spines, grid=None, ticklabels=None, show_ticks=False,
xkcd=False):
'''
Removes "chartjunk", such as extra lines of axes and tick marks.
If grid="y" or "x", will add a white grid at the "y" or "x" axes,
respectively
If ticklabels="y" or "x", or ['x', 'y... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maybe_get_ax(*args, **kwargs):
""" It used to be that the first argument of prettyplotlib had to be the 'ax' object, but that's not the case anymore. @param ... |
if 'ax' in kwargs:
ax = kwargs.pop('ax')
elif len(args) == 0:
fig = plt.gcf()
ax = plt.gca()
elif isinstance(args[0], mpl.axes.Axes):
ax = args[0]
args = args[1:]
else:
ax = plt.gca()
return ax, args, dict(kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maybe_get_fig_ax(*args, **kwargs):
""" It used to be that the first argument of prettyplotlib had to be the 'ax' object, but that's not the case anymore. Thi... |
if 'ax' in kwargs:
ax = kwargs.pop('ax')
if 'fig' in kwargs:
fig = kwargs.pop('fig')
else:
fig = plt.gcf()
elif len(args) == 0:
fig = plt.gcf()
ax = plt.gca()
elif isinstance(args[0], mpl.figure.Figure) and \
isinstance(args[1], mp... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scatter(*args, **kwargs):
""" This will plot a scatterplot of x and y, iterating over the ColorBrewer "Set2" color cycle unless a color is specified. The sym... |
# Force 'color' to indicate the edge color, so the middle of the
# scatter patches are empty. Can specify
ax, args, kwargs = utils.maybe_get_ax(*args, **kwargs)
if 'color' not in kwargs:
# Assume that color means the edge color. You can assign the
color_cycle = ax._get_lines.color_cycl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def boxplot(*args, **kwargs):
""" Create a box-and-whisker plot showing the mean, 25th percentile, and 75th percentile. The difference from matplotlib is only th... |
ax, args, kwargs = maybe_get_ax(*args, **kwargs)
# If no ticklabels are specified, don't draw any
xticklabels = kwargs.pop('xticklabels', None)
fontsize = kwargs.pop('fontsize', 10)
kwargs.setdefault('widths', 0.15)
bp = ax.boxplot(*args, **kwargs)
if xticklabels:
ax.xaxis.set_ti... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hist(*args, **kwargs):
""" Plots a histogram of the provided data. Can provide optional argument "grid='x'" or "grid='y'" to draw a white grid over the histo... |
ax, args, kwargs = maybe_get_ax(*args, **kwargs)
color_cycle = ax._get_lines.color_cycle
# Reassign the default colors to Set2 by Colorbrewer
if iterable(args[0]):
if isinstance(args[0], list):
ncolors = len(args[0])
else:
if len(args[0].shape) == 2:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def beeswarm(*args, **kwargs):
""" Create a R-like beeswarm plot showing the mean and datapoints. The difference from matplotlib is only the left axis line is sh... |
ax, args, kwargs = maybe_get_ax(*args, **kwargs)
# If no ticklabels are specified, don't draw any
xticklabels = kwargs.pop('xticklabels', None)
colors = kwargs.pop('colors', None)
fontsize = kwargs.pop('fontsize', 10)
gray = _colors.set1[8]
red = _colors.set1[0]
blue = kwargs.pop('... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tags(self):
""" Convert the ugly Tags JSON into a real dictionary and memorize the result. """ |
if self._tags is None:
LOG.debug('need to build tags')
self._tags = {}
if hasattr(self.Meta, 'tags_spec') and (self.Meta.tags_spec is not None):
LOG.debug('have a tags_spec')
method, path, param_name, param_value = self.Meta.tags_spec[:4]
... |
<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_metric_data(self, metric_name=None, metric=None, days=None, hours=1, minutes=None, statistics=None, period=None):
""" Get metric data for this resource. ... |
if not statistics:
statistics = ['Average']
if days:
delta = datetime.timedelta(days=days)
elif hours:
delta = datetime.timedelta(hours=hours)
else:
delta = datetime.timedelta(minutes=minutes)
if not period:
period = ma... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fit(self):
r"""Loop over distributions and find best parameter to fit the data for each When a distribution is fitted onto the data, we populate a set of dat... |
for distribution in self.distributions:
try:
# need a subprocess to check time it takes. If too long, skip it
dist = eval("scipy.stats." + distribution)
# TODO here, dist.fit may take a while or just hang forever
# with some distribut... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_pdf(self, names=None, Nbest=5, lw=2):
"""Plots Probability density functions of the distributions :param str,list names: names can be a single distribut... |
assert Nbest > 0
if Nbest > len(self.distributions):
Nbest = len(self.distributions)
if isinstance(names, list):
for name in names:
pylab.plot(self.x, self.fitted_pdf[name], lw=lw, label=name)
elif names:
pylab.plot(self.x, self.fitte... |
<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_best(self):
"""Return best fitted distribution and its parameters a dictionary with one key (the distribution name) and its parameters """ |
# self.df should be sorted, so then us take the first one as the best
name = self.df_errors.sort_values('sumsquare_error').iloc[0].name
params = self.fitted_param[name]
return {name: params} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def summary(self, Nbest=5, lw=2, plot=True):
"""Plots the distribution of the data and Nbest distribution """ |
if plot:
pylab.clf()
self.hist()
self.plot_pdf(Nbest=Nbest, lw=lw)
pylab.grid(True)
Nbest = min(Nbest, len(self.distributions))
try:
names = self.df_errors.sort_values(
by="sumsquare_error").index[0:Nbest]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _timed_run(self, func, distribution, args=(), kwargs={}, default=None):
"""This function will spawn a thread and run the given function using the args, kwarg... |
class InterruptableThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.result = default
self.exc_info = (None, None, None)
def run(self):
try:
self.result = func(args, **k... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_avg_adj_deg(G):
r""" Compute the average adjacency degree for each node. The average adjacency degree is the average of the degrees of a node and its... |
return np.sum(np.dot(G.A, G.A), axis=1) / (np.sum(G.A, axis=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 compute_spectrogram(G, atom=None, M=100, **kwargs):
r""" Compute the norm of the Tig for all nodes with a kernel shifted along the spectral axis. Parameters ... |
if not atom:
def atom(x):
return np.exp(-M * (x / G.lmax)**2)
scale = np.linspace(0, G.lmax, M)
spectr = np.empty((G.N, M))
for shift_idx in range(M):
shift_filter = filters.Filter(G, lambda x: atom(x - scale[shift_idx]))
tig = compute_norm_tig(shift_filter, **kwa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluate(self, x):
r"""Evaluate the kernels at given frequencies. Parameters x : array_like Graph frequencies at which to evaluate the filter. Returns ------... |
x = np.asanyarray(x)
# Avoid to copy data as with np.array([g(x) for g in self._kernels]).
y = np.empty([self.Nf] + list(x.shape))
for i, kernel in enumerate(self._kernels):
y[i] = kernel(x)
return y |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def estimate_frame_bounds(self, x=None):
r"""Estimate lower and upper frame bounds. A filter bank forms a frame if there are positive real numbers :math:`A` and ... |
if x is None:
x = np.linspace(0, self.G.lmax, 1000)
else:
x = np.asanyarray(x)
sum_filters = np.sum(self.evaluate(x)**2, axis=0)
return sum_filters.min(), sum_filters.max() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_frame(self, **kwargs):
r"""Compute the associated frame. A filter bank defines a frame, which is a generalization of a basis to sets of vectors that ... |
if self.G.N > 2000:
_logger.warning('Creating a big matrix. '
'You should prefer the filter method.')
# Filter one delta per vertex.
s = np.identity(self.G.N)
return self.filter(s, **kwargs).T.reshape(-1, self.G.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 complement(self, frame_bound=None):
r"""Return the filter that makes the frame tight. The complementary filter is designed such that the union of a filter ba... |
def kernel(x, *args, **kwargs):
y = self.evaluate(x)
np.power(y, 2, out=y)
y = np.sum(y, axis=0)
if frame_bound is None:
bound = y.max()
elif y.max() > frame_bound:
raise ValueError('The chosen bound is not feasible.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inverse(self):
r"""Return the pseudo-inverse filter bank. The pseudo-inverse of the *analysis filter bank* :math:`g` is the *synthesis filter bank* :math:`g^... |
A, _ = self.estimate_frame_bounds()
if A == 0:
_logger.warning('The filter bank is not invertible as it is not '
'a frame (lower frame bound A=0).')
def kernel(g, i, x):
y = g.evaluate(x).T
z = np.linalg.pinv(np.expand_dims(y, 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 grad(self, x):
r"""Compute the gradient of a signal defined on the vertices. The gradient :math:`y` of a signal :math:`x` is defined as .. math:: y = \nabla_... |
x = self._check_signal(x)
return self.D.T.dot(x) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def div(self, y):
r"""Compute the divergence of a signal defined on the edges. The divergence :math:`z` of a signal :math:`y` is defined as .. math:: z = \operat... |
y = np.asanyarray(y)
if y.shape[0] != self.Ne:
raise ValueError('First dimension must be the number of edges '
'G.Ne = {}, got {}.'.format(self.Ne, y.shape))
return self.D.dot(y) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gft(self, s):
r"""Compute the graph Fourier transform. The graph Fourier transform of a signal :math:`s` is defined as .. math:: \hat{s} = U^* s, where :math... |
s = self._check_signal(s)
U = np.conjugate(self.U) # True Hermitian. (Although U is often real.)
return np.tensordot(U, s, ([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 igft(self, s_hat):
r"""Compute the inverse graph Fourier transform. The inverse graph Fourier transform of a Fourier domain signal :math:`\hat{s}` is defined... |
s_hat = self._check_signal(s_hat)
return np.tensordot(self.U, s_hat, ([1], [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 compute_cheby_coeff(f, m=30, N=None, *args, **kwargs):
r""" Compute Chebyshev coefficients for a Filterbank. Parameters f : Filter Filterbank with at least 1... |
G = f.G
i = kwargs.pop('i', 0)
if not N:
N = m + 1
a_arange = [0, G.lmax]
a1 = (a_arange[1] - a_arange[0]) / 2
a2 = (a_arange[1] + a_arange[0]) / 2
c = np.zeros(m + 1)
tmpN = np.arange(N)
num = np.cos(np.pi * (tmpN + 0.5) / N)
for o in range(m + 1):
c[o] = 2.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cheby_op(G, c, signal, **kwargs):
r""" Chebyshev polynomial of graph Laplacian applied to vector. Parameters G : Graph c : ndarray or list of ndarrays Chebys... |
# Handle if we do not have a list of filters but only a simple filter in cheby_coeff.
if not isinstance(c, np.ndarray):
c = np.array(c)
c = np.atleast_2d(c)
Nscales, M = c.shape
if M < 2:
raise TypeError("The coefficients have an invalid shape")
# thanks to that, we can also ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cheby_rect(G, bounds, signal, **kwargs):
r""" Fast filtering using Chebyshev polynomial for a perfect rectangle filter. Parameters G : Graph bounds : array_l... |
if not (isinstance(bounds, (list, np.ndarray)) and len(bounds) == 2):
raise ValueError('Bounds of wrong shape.')
bounds = np.array(bounds)
m = int(kwargs.pop('order', 30) + 1)
try:
Nv = np.shape(signal)[1]
r = np.zeros((G.N, Nv))
except IndexError:
r = np.zeros((G... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_jackson_cheby_coeff(filter_bounds, delta_lambda, m):
r""" To compute the m+1 coefficients of the polynomial approximation of an ideal band-pass betwe... |
# Parameters check
if delta_lambda[0] > filter_bounds[0] or delta_lambda[1] < filter_bounds[1]:
_logger.error("Bounds of the filter are out of the lambda values")
raise()
elif delta_lambda[0] > delta_lambda[1]:
_logger.error("lambda_min is greater than lambda_max")
raise()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lanczos_op(f, s, order=30):
r""" Perform the lanczos approximation of the signal s. Parameters f: Filter s : ndarray Signal to approximate. order : int Degre... |
G = f.G
Nf = len(f.g)
# To have the right shape for the output array depending on the signal dim
try:
Nv = np.shape(s)[1]
is2d = True
c = np.zeros((G.N*Nf, Nv))
except IndexError:
Nv = 1
is2d = False
c = np.zeros((G.N*Nf))
tmpN = np.arange(G.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 interpolate(G, f_subsampled, keep_inds, order=100, reg_eps=0.005, **kwargs):
r"""Interpolate a graph signal. Parameters G : Graph f_subsampled : ndarray A gr... |
L_reg = G.L + reg_eps * sparse.eye(G.N)
K_reg = getattr(G.mr, 'K_reg', kron_reduction(L_reg, keep_inds))
green_kernel = getattr(G.mr, 'green_kernel',
filters.Filter(G, lambda x: 1. / (reg_eps + x)))
alpha = K_reg.dot(f_subsampled)
try:
Nv = np.shape(f_subsampled... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def kron_reduction(G, ind):
r"""Compute the Kron reduction. This function perform the Kron reduction of the weight matrix in the graph *G*, with boundary nodes l... |
if isinstance(G, graphs.Graph):
if G.lap_type != 'combinatorial':
msg = 'Unknown reduction for {} Laplacian.'.format(G.lap_type)
raise NotImplementedError(msg)
if G.is_directed():
msg = 'This method only work for undirected graphs.'
raise No... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pyramid_analysis(Gs, f, **kwargs):
r"""Compute the graph pyramid transform coefficients. Parameters Gs : list of graphs A multiresolution sequence of graph s... |
if np.shape(f)[0] != Gs[0].N:
raise ValueError("PYRAMID ANALYSIS: The signal to analyze should have the same dimension as the first graph.")
levels = len(Gs) - 1
# check if the type of filters is right.
h_filters = kwargs.pop('h_filters', lambda x: 1. / (2*x+1))
if not isinstance(h_filte... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pyramid_synthesis(Gs, cap, pe, order=30, **kwargs):
r"""Synthesize a signal from its pyramid coefficients. Parameters Gs : Array of Graphs A multiresolution ... |
least_squares = bool(kwargs.pop('least_squares', False))
def_ul = Gs[0].N > 3000 or Gs[0]._e is None or Gs[0]._U is None
use_landweber = bool(kwargs.pop('use_landweber', def_ul))
reg_eps = float(kwargs.get('reg_eps', 0.005))
if least_squares and 'h_filters' not in kwargs:
ValueError('h-fil... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tree_multiresolution(G, Nlevel, reduction_method='resistance_distance', compute_full_eigen=False, root=None):
r"""Compute a multiresolution of trees Paramete... |
if not root:
if hasattr(G, 'root'):
root = G.root
else:
root = 1
Gs = [G]
if compute_full_eigen:
Gs[0].compute_fourier_basis()
subsampled_vertex_indices = []
depths, parents = _tree_depths(G.A, root)
old_W = G.W
for lev in range(Nlevel):
... |
<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_all():
r"""Close all opened windows.""" |
# Windows can be closed by releasing all references to them so they can be
# garbage collected. May not be necessary to call close().
global _qtg_windows
for window in _qtg_windows:
window.close()
_qtg_windows = []
global _qtg_widgets
for widget in _qtg_widgets:
widget.clo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _plot_filter(filters, n, eigenvalues, sum, title, ax, **kwargs):
r"""Plot the spectral response of a filter bank. Parameters n : int Number of points where t... |
if eigenvalues is None:
eigenvalues = (filters.G._e is not None)
if sum is None:
sum = filters.n_filters > 1
if title is None:
title = repr(filters)
return _plt_plot_filter(filters, n=n, eigenvalues=eigenvalues, sum=sum,
title=title, ax=ax, **kwar... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _plot_spectrogram(G, node_idx):
r"""Plot the graph's spectrogram. Parameters node_idx : ndarray Order to sort the nodes in the spectrogram. By default, does ... |
from pygsp import features
qtg, _, _ = _import_qtg()
if not hasattr(G, 'spectr'):
features.compute_spectrogram(G)
M = G.spectr.shape[1]
spectr = G.spectr[node_idx, :] if node_idx is not None else G.spectr
spectr = np.ravel(spectr)
min_spec, max_spec = spectr.min(), spectr.max()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def classification_tikhonov(G, y, M, tau=0):
r"""Solve a classification problem on graph via Tikhonov minimization. The function first transforms :math:`y` in lo... |
y[M == False] = 0
Y = _to_logits(y.astype(np.int))
return regression_tikhonov(G, Y, M, tau) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def regression_tikhonov(G, y, M, tau=0):
r"""Solve a regression problem on graph via Tikhonov minimization. The function solves .. math:: \operatorname*{arg min}... |
if tau > 0:
y[M == False] = 0
if sparse.issparse(G.L):
def Op(x):
return (M * x.T).T + tau * (G.L.dot(x))
LinearOp = sparse.linalg.LinearOperator([G.N, G.N], Op)
if y.ndim > 1:
sol = np.empty(shape=y.shape)
re... |
<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_signal(self, signal, name):
r"""Attach a signal to the graph. Attached signals can be accessed (and modified or deleted) through the :attr:`signals` dict... |
signal = self._check_signal(signal)
self.signals[name] = signal |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def subgraph(self, vertices):
r"""Create a subgraph from a list of vertices. Parameters vertices : list Vertices to keep. Either a list of indices or an indicato... |
adjacency = self.W[vertices, :][:, vertices]
try:
coords = self.coords[vertices]
except AttributeError:
coords = None
graph = Graph(adjacency, self.lap_type, coords, self.plotting)
for name, signal in self.signals.items():
graph.set_signal(sig... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_components(self):
r"""Split the graph into connected components. See :func:`is_connected` for the method used to determine connectedness. Returns ---... |
if self.A.shape[0] != self.A.shape[1]:
self.logger.error('Inconsistent shape to extract components. '
'Square matrix required.')
return None
if self.is_directed():
raise NotImplementedError('Directed graphs not supported yet.')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_laplacian(self, lap_type='combinatorial'):
r"""Compute a graph Laplacian. For undirected graphs, the combinatorial Laplacian is defined as .. math:: ... |
if lap_type != self.lap_type:
# Those attributes are invalidated when the Laplacian is changed.
# Alternative: don't allow the user to change the Laplacian.
self._lmax = None
self._U = None
self._e = None
self._coherence = 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 _check_signal(self, s):
r"""Check if signal is valid.""" |
s = np.asanyarray(s)
if s.shape[0] != self.n_vertices:
raise ValueError('First dimension must be the number of vertices '
'G.N = {}, got {}.'.format(self.N, s.shape))
return s |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dirichlet_energy(self, x):
r"""Compute the Dirichlet energy of a signal defined on the vertices. The Dirichlet energy of a signal :math:`x` is defined as .. ... |
x = self._check_signal(x)
return x.T.dot(self.L.dot(x)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dw(self):
r"""The weighted degree of vertices. For undirected graphs, the weighted degree of the vertex :math:`v_i` is defined as .. math:: d[i] = \sum_j W[j... |
if self._dw is None:
if not self.is_directed():
# Shortcut for undirected graphs.
self._dw = np.ravel(self.W.sum(axis=0))
else:
degree_in = np.ravel(self.W.sum(axis=0))
degree_out = np.ravel(self.W.sum(axis=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 lmax(self):
r"""Largest eigenvalue of the graph Laplacian. Can be exactly computed by :func:`compute_fourier_basis` or approximated by :func:`estimate_lmax`.... |
if self._lmax is None:
self.logger.warning('The largest eigenvalue G.lmax is not '
'available, we need to estimate it. '
'Explicitly call G.estimate_lmax() or '
'G.compute_fourier_basis() '
... |
<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_upper_bound(self):
r"""Return an upper bound on the eigenvalues of the Laplacian.""" |
if self.lap_type == 'normalized':
return 2 # Equal iff the graph is bipartite.
elif self.lap_type == 'combinatorial':
bounds = []
# Equal for full graphs.
bounds += [self.n_vertices * np.max(self.W)]
# Gershgorin circle theorem. Equal for re... |
<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_edge_list(self):
r"""Return an edge list, an alternative representation of the graph. Each edge :math:`e_k = (v_i, v_j) \in \mathcal{E}` from :math:`v_i`... |
if self.is_directed():
W = self.W.tocoo()
else:
W = sparse.triu(self.W, format='coo')
sources = W.row
targets = W.col
weights = W.data
assert self.n_edges == sources.size == targets.size == weights.size
return sources, targets, 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 prox_tv(x, gamma, G, A=None, At=None, nu=1, tol=10e-4, maxit=200, use_matrix=True):
r""" Total Variation proximal operator for graphs. This function computes... |
if A is None:
def A(x):
return x
if At is None:
def At(x):
return x
tight = 0
l1_nu = 2 * G.lmax * nu
if use_matrix:
def l1_a(x):
return G.Diff * A(x)
def l1_at(x):
return G.Diff * At(D.T * x)
else:
def l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_regular(self):
r""" Troubleshoot a given regular graph. """ |
warn = False
msg = 'The given matrix'
# check symmetry
if np.abs(self.A - self.A.T).sum() > 0:
warn = True
msg = '{} is not symmetric,'.format(msg)
# check parallel edged
if self.A.max(axis=None) > 1:
warn = True
msg = '{... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _break_signals(self):
r"""Break N-dimensional signals into N 1D signals.""" |
for name in list(self.signals.keys()):
if self.signals[name].ndim == 2:
for i, signal_1d in enumerate(self.signals[name].T):
self.signals[name + '_' + str(i)] = signal_1d
del self.signals[name] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _join_signals(self):
r"""Join N 1D signals into one N-dimensional signal.""" |
joined = dict()
for name in self.signals:
name_base = name.rsplit('_', 1)[0]
names = joined.get(name_base, list())
names.append(name)
joined[name_base] = names
for name_base, names in joined.items():
if len(names) > 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 to_networkx(self):
r"""Export the graph to NetworkX. Edge weights are stored as an edge attribute, under the name "weight". Signals are stored as node attrib... |
nx = _import_networkx()
def convert(number):
# NetworkX accepts arbitrary python objects as attributes, but:
# * the GEXF writer does not accept any NumPy types (on signals),
# * the GraphML writer does not accept NumPy ints.
if issubclass(number.dtype.t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_graphtool(self):
r"""Export the graph to graph-tool. Edge weights are stored as an edge property map, under the name "weight". Signals are stored as verte... |
# See gt.value_types() for the list of accepted types.
# See the definition of _type_alias() for a list of aliases.
# Mapping from https://docs.scipy.org/doc/numpy/user/basics.types.html.
convert = {
np.bool_: 'bool',
np.int8: 'int8_t',
np.int16: 'in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_networkx(cls, graph, weight='weight'):
r"""Import a graph from NetworkX. Edge weights are retrieved as an edge attribute, under the name specified by th... |
nx = _import_networkx()
from .graph import Graph
adjacency = nx.to_scipy_sparse_matrix(graph, weight=weight)
graph_pg = Graph(adjacency)
for i, node in enumerate(graph.nodes()):
for name in graph.nodes[node].keys():
try:
signal =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_graphtool(cls, graph, weight='weight'):
r"""Import a graph from graph-tool. Edge weights are retrieved as an edge property, under the name specified by ... |
gt = _import_graphtool()
import graph_tool.spectral
from .graph import Graph
weight = graph.edge_properties.get(weight, None)
adjacency = gt.spectral.adjacency(graph, weight=weight)
graph_pg = Graph(adjacency.T)
for name, signal in graph.vertex_properties.items... |
<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(cls, path, fmt=None, backend=None):
r"""Load a graph from a file. Edge weights are retrieved as an edge attribute named "weight". Signals are retrieved ... |
if fmt is None:
fmt = os.path.splitext(path)[1][1:]
if fmt not in ['graphml', 'gml', 'gexf']:
raise ValueError('Unsupported format {}.'.format(fmt))
def load_networkx(path, fmt):
nx = _import_networkx()
load = getattr(nx, 'read_' + fmt)
... |
<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(self, path, fmt=None, backend=None):
r"""Save the graph to a file. Edge weights are stored as an edge attribute, under the name "weight". Signals are st... |
if fmt is None:
fmt = os.path.splitext(path)[1][1:]
if fmt not in ['graphml', 'gml', 'gexf']:
raise ValueError('Unsupported format {}.'.format(fmt))
def save_networkx(graph, path, fmt):
nx = _import_networkx()
graph = graph.to_networkx()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loadmat(path):
r""" Load a matlab data file. Parameters path : string Path to the mat file from the data folder, without the .mat extension. Returns ------- ... |
data = pkgutil.get_data('pygsp', 'data/' + path + '.mat')
data = io.BytesIO(data)
return scipy.io.loadmat(data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def distanz(x, y=None):
r""" Calculate the distance between two colon vectors. Parameters x : ndarray First colon vector y : ndarray Second colon vector Returns ... |
try:
x.shape[1]
except IndexError:
x = x.reshape(1, x.shape[0])
if y is None:
y = x
else:
try:
y.shape[1]
except IndexError:
y = y.reshape(1, y.shape[0])
rx, cx = x.shape
ry, cy = y.shape
# Size verification
if rx != ry... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resistance_distance(G):
r""" Compute the resistance distances of a graph. Parameters G : Graph or sparse matrix Graph structure or Laplacian matrix (L) Retur... |
if sparse.issparse(G):
L = G.tocsc()
else:
if G.lap_type != 'combinatorial':
raise ValueError('Need a combinatorial Laplacian.')
L = G.L.tocsc()
try:
pseudo = sparse.linalg.inv(L)
except RuntimeError:
pseudo = sparse.lil_matrix(np.linalg.pinv(L.toa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def symmetrize(W, method='average'):
r""" Symmetrize a square matrix. Parameters W : array_like Square matrix to be symmetrized method : string * 'average' : sym... |
if W.shape[0] != W.shape[1]:
raise ValueError('Matrix must be square.')
if method == 'average':
return (W + W.T) / 2
elif method == 'maximum':
if sparse.issparse(W):
bigger = (W.T > W)
return W - W.multiply(bigger) + W.T.multiply(bigger)
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_log_scales(lmin, lmax, Nscales, t1=1, t2=2):
r""" Compute logarithm scales for wavelets. Parameters lmin : float Smallest non-zero eigenvalue. lmax :... |
scale_min = t1 / lmax
scale_max = t2 / lmin
return np.exp(np.linspace(np.log(scale_max), np.log(scale_min), Nscales)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_modules(names, src, dst):
"""Import modules in package.""" |
for name in names:
module = importlib.import_module(src + '.' + name)
setattr(sys.modules[dst], name, module) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_classes(names, src, dst):
"""Import classes in package from their implementation modules.""" |
for name in names:
module = importlib.import_module('pygsp.' + src + '.' + name.lower())
setattr(sys.modules['pygsp.' + dst], name, getattr(module, name)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_functions(names, src, dst):
"""Import functions in package from their implementation modules.""" |
for name in names:
module = importlib.import_module('pygsp.' + src)
setattr(sys.modules['pygsp.' + dst], name, getattr(module, name)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_api_result(result: Optional[Dict[str, Any]]) -> Any: """ Retrieve 'data' field from the API result object. :param result: API result that received fro... |
if isinstance(result, dict):
if result.get('status') == 'failed':
raise ActionFailed(retcode=result.get('retcode'))
return result.get('data') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reduce(self) -> None: """ Remove redundant segments. Since this class is implemented based on list, this method may require O(n) time. """ |
idx = 0
while idx < len(self):
if idx > 0 and \
self[idx - 1].type == 'text' and self[idx].type == 'text':
self[idx - 1].data['text'] += self[idx].data['text']
del self[idx]
else:
idx += 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 extract_plain_text(self, reduce: bool = False) -> str: """ Extract text segments from the message, joined by single space. :param reduce: reduce the message b... |
if reduce:
self.reduce()
result = ''
for seg in self:
if seg.type == 'text':
result += ' ' + seg.data['text']
if result:
result = result[1:]
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_html_mail(subject, message, message_html, from_email, recipient_list, priority=None, fail_silently=False, auth_user=None, auth_password=None, headers={})... |
from django.utils.encoding import force_text
from django.core.mail import EmailMultiAlternatives
from mailer.models import make_message
priority = get_priority(priority)
# need to do this in case subject used lazy version of ugettext
subject = force_text(subject)
message = force_text(mess... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_message(subject="", body="", from_email=None, to=None, bcc=None, attachments=None, headers=None, priority=None):
""" Creates a simple message for the em... |
to = filter_recipient_list(to)
bcc = filter_recipient_list(bcc)
core_msg = EmailMessage(
subject=subject,
body=body,
from_email=from_email,
to=to,
bcc=bcc,
attachments=attachments,
headers=headers
)
db_msg = Message(priority=priority)
db_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 has_address(self, address):
""" is the given address on the don't send list? """ |
queryset = self.filter(to_address__iexact=address)
return queryset.exists() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prioritize():
""" Yield the messages in the queue in the order they should be sent. """ |
while True:
hp_qs = Message.objects.high_priority().using('default')
mp_qs = Message.objects.medium_priority().using('default')
lp_qs = Message.objects.low_priority().using('default')
while hp_qs.count() or mp_qs.count():
while hp_qs.count():
for message... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_all():
""" Send all eligible messages in the queue. """ |
# The actual backend to use for sending, defaulting to the Django default.
# To make testing easier this is not stored at module level.
EMAIL_BACKEND = getattr(
settings,
"MAILER_EMAIL_BACKEND",
"django.core.mail.backends.smtp.EmailBackend"
)
acquired, lock = acquire_lock()... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_loop():
""" Loop indefinitely, checking queue at intervals of EMPTY_QUEUE_SLEEP and sending messages if any are on queue. """ |
while True:
while not Message.objects.all():
logging.debug("sleeping for %s seconds before checking queue again" % EMPTY_QUEUE_SLEEP)
time.sleep(EMPTY_QUEUE_SLEEP)
send_all() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_name(name):
""" import module given by str or pass the module if it is not str """ |
if isinstance(name, str):
components = name.split('.')
mod = __import__('.'.join(components[0:-1]), globals(), locals(), [components[-1]] )
return getattr(mod, components[-1])
else:
return name |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy_plan(modeladmin, request, queryset):
""" Admin command for duplicating plans preserving quotas and pricings. """ |
for plan in queryset:
plan_copy = deepcopy(plan)
plan_copy.id = None
plan_copy.available = False
plan_copy.default = False
plan_copy.created = None
plan_copy.save(force_insert=True)
for pricing in plan.planpricing_set.all():
pricing.id = 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 recalculate(self, amount, billing_info):
""" Calculates and return pre-filled Order """ |
order = Order(pk=-1)
order.amount = amount
order.currency = self.get_currency()
country = getattr(billing_info, 'country', None)
if not country is None:
country = country.code
tax_number = getattr(billing_info, 'tax_number', None)
# Calculating tax c... |
<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_all_context(self):
""" Retrieves Plan and Pricing for current order creation """ |
self.plan_pricing = get_object_or_404(PlanPricing.objects.all().select_related('plan', 'pricing'),
Q(pk=self.kwargs['pk']) & Q(plan__available=True) & (
Q(plan__customized=self.request.user) | Q(
... |
<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_proforma_invoice(sender, instance, created, **kwargs):
""" For every Order if there are defined billing_data creates invoice proforma, which is an ord... |
if created:
Invoice.create(instance, Invoice.INVOICE_TYPES['PROFORMA']) |
<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_quota_value(self, user, quota_dict=None):
""" Returns quota value for a given user """ |
if quota_dict is None:
quota_dict = get_user_quota(user)
return quota_dict.get(self.code, self.default_quota_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 send_template_email(recipients, title_template, body_template, context, language):
"""Sends e-mail using templating system""" |
send_emails = getattr(settings, 'SEND_PLANS_EMAILS', True)
if not send_emails:
return
site_name = getattr(settings, 'SITE_NAME', 'Please define settings.SITE_NAME')
domain = getattr(settings, 'SITE_URL', None)
if domain is None:
try:
Site = apps.get_model('sites', 'Si... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _calculate_day_cost(self, plan, period):
""" Finds most fitted plan pricing for a given period, and calculate day cost """ |
plan_pricings = plan.planpricing_set.order_by('-pricing__period').select_related('pricing')
selected_pricing = None
for plan_pricing in plan_pricings:
selected_pricing = plan_pricing
if plan_pricing.pricing.period <= period:
break
if selected_pr... |
<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_change_price(self, plan_old, plan_new, period):
""" Calculates total price of plan change. Returns None if no payment is required. """ |
if period is None or period < 1:
return None
plan_old_day_cost = self._calculate_day_cost(plan_old, period)
plan_new_day_cost = self._calculate_day_cost(plan_new, period)
if plan_new_day_cost <= plan_old_day_cost:
return self._calculate_final_price(period, 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 comparator(operator):
""" Wrap a VersionInfo binary op method in a type-check """ |
@wraps(operator)
def wrapper(self, other):
if not isinstance(other, (VersionInfo, dict)):
return NotImplemented
return operator(self, other)
return wrapper |
<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_sampled_topics(self, sampled_topics):
""" Allocate sampled topics to the documents rather than estimate them. Automatically generate term-topic and docum... |
assert sampled_topics.dtype == np.int and \
len(sampled_topics.shape) <= 2
if len(sampled_topics.shape) == 1:
self.sampled_topics = \
sampled_topics.reshape(1, sampled_topics.shape[0])
else:
self.sampled_topics = sampled_topics
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 dt_comp(self, sampled_topics):
""" Compute document-topic matrix from sampled_topics. """ |
samples = sampled_topics.shape[0]
dt = np.zeros((self.D, self.K, samples))
for s in range(samples):
dt[:, :, s] = \
samplers_lda.dt_comp(self.docid, sampled_topics[s, :],
self.N, self.K, self.D, self.alph... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.