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 read_json_flag(fobj):
"""Read a `DataQualityFlag` from a segments-web.ligo.org JSON file """ |
# read from filename
if isinstance(fobj, string_types):
with open(fobj, 'r') as fobj2:
return read_json_flag(fobj2)
# read from open file
txt = fobj.read()
if isinstance(txt, bytes):
txt = txt.decode('utf-8')
data = json.loads(txt)
# format flag
name = '{if... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_json_flag(flag, fobj, **kwargs):
"""Write a `DataQualityFlag` to a JSON file Parameters flag : `DataQualityFlag` data to write fobj : `str`, `file` tar... |
# write to filename
if isinstance(fobj, string_types):
with open(fobj, 'w') as fobj2:
return write_json_flag(flag, fobj2, **kwargs)
# build json packet
data = {}
data['ifo'] = flag.ifo
data['name'] = flag.tag
data['version'] = flag.version
data['active'] = flag.acti... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def in_segmentlist(column, segmentlist):
"""Return the index of values lying inside the given segmentlist A `~gwpy.segments.Segment` represents a semi-open inter... |
segmentlist = type(segmentlist)(segmentlist).coalesce()
idx = column.argsort()
contains = numpy.zeros(column.shape[0], dtype=bool)
j = 0
try:
segstart, segend = segmentlist[j]
except IndexError: # no segments, return all False
return contains
i = 0
while i < contains.sh... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fft(self, nfft=None):
"""Compute the one-dimensional discrete Fourier transform of this `TimeSeries`. Parameters nfft : `int`, optional length of the desired... |
from ..frequencyseries import FrequencySeries
if nfft is None:
nfft = self.size
dft = npfft.rfft(self.value, n=nfft) / nfft
dft[1:] *= 2.0
new = FrequencySeries(dft, epoch=self.epoch, unit=self.unit,
name=self.name, channel=self.channel)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def average_fft(self, fftlength=None, overlap=0, window=None):
"""Compute the averaged one-dimensional DFT of this `TimeSeries`. This method computes a number of... |
from gwpy.spectrogram import Spectrogram
# format lengths
if fftlength is None:
fftlength = self.duration
if isinstance(fftlength, units.Quantity):
fftlength = fftlength.value
nfft = int((fftlength * self.sample_rate).decompose().value)
noverlap =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def psd(self, fftlength=None, overlap=None, window='hann', method=DEFAULT_FFT_METHOD, **kwargs):
"""Calculate the PSD `FrequencySeries` for this `TimeSeries` Par... |
# get method
method_func = spectral.get_method(method)
# calculate PSD using UI method
return spectral.psd(self, method_func, fftlength=fftlength,
overlap=overlap, window=window, **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 asd(self, fftlength=None, overlap=None, window='hann', method=DEFAULT_FFT_METHOD, **kwargs):
"""Calculate the ASD `FrequencySeries` of this `TimeSeries` Para... |
return self.psd(method=method, fftlength=fftlength, overlap=overlap,
window=window, **kwargs) ** (1/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 csd(self, other, fftlength=None, overlap=None, window='hann', **kwargs):
"""Calculate the CSD `FrequencySeries` for two `TimeSeries` Parameters other : `Time... |
return spectral.psd(
(self, other),
spectral.csd,
fftlength=fftlength,
overlap=overlap,
window=window,
**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 spectrogram(self, stride, fftlength=None, overlap=None, window='hann', method=DEFAULT_FFT_METHOD, nproc=1, **kwargs):
"""Calculate the average power spectrog... |
# get method
method_func = spectral.get_method(method)
# calculate PSD using UI method
return spectral.average_spectrogram(
self,
method_func,
stride,
fftlength=fftlength,
overlap=overlap,
window=window,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spectrogram2(self, fftlength, overlap=None, window='hann', **kwargs):
"""Calculate the non-averaged power `Spectrogram` of this `TimeSeries` Parameters fftle... |
# set kwargs for periodogram()
kwargs.setdefault('fs', self.sample_rate.to('Hz').value)
# run
return spectral.spectrogram(self, signal.periodogram,
fftlength=fftlength, overlap=overlap,
window=window, **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 fftgram(self, fftlength, overlap=None, window='hann', **kwargs):
"""Calculate the Fourier-gram of this `TimeSeries`. At every ``stride``, a single, complex F... |
from ..spectrogram import Spectrogram
try:
from scipy.signal import spectrogram
except ImportError:
raise ImportError("Must have scipy>=0.16 to utilize "
"this method.")
# format lengths
if isinstance(fftlength, units.Quanti... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spectral_variance(self, stride, fftlength=None, overlap=None, method=DEFAULT_FFT_METHOD, window='hann', nproc=1, filter=None, bins=None, low=None, high=None, ... |
specgram = self.spectrogram(stride, fftlength=fftlength,
overlap=overlap, method=method,
window=window, nproc=nproc) ** (1/2.)
if filter:
specgram = specgram.filter(*filter)
return specgram.variance(bins=bins, 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 rayleigh_spectrum(self, fftlength=None, overlap=None):
"""Calculate the Rayleigh `FrequencySeries` for this `TimeSeries`. The Rayleigh statistic is calculate... |
return spectral.psd(
self,
spectral.rayleigh,
fftlength=fftlength,
overlap=overlap,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rayleigh_spectrogram(self, stride, fftlength=None, overlap=0, nproc=1, **kwargs):
"""Calculate the Rayleigh statistic spectrogram of this `TimeSeries` Parame... |
specgram = spectral.average_spectrogram(
self,
spectral.rayleigh,
stride,
fftlength=fftlength,
overlap=overlap,
nproc=nproc,
**kwargs
)
specgram.override_unit('')
return specgram |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def csd_spectrogram(self, other, stride, fftlength=None, overlap=0, window='hann', nproc=1, **kwargs):
"""Calculate the cross spectral density spectrogram of thi... |
return spectral.average_spectrogram(
(self, other),
spectral.csd,
stride,
fftlength=fftlength,
overlap=overlap,
window=window,
nproc=nproc,
**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 highpass(self, frequency, gpass=2, gstop=30, fstop=None, type='iir', filtfilt=True, **kwargs):
"""Filter this `TimeSeries` with a high-pass filter. Parameter... |
# design filter
filt = filter_design.highpass(frequency, self.sample_rate,
fstop=fstop, gpass=gpass, gstop=gstop,
analog=False, type=type, **kwargs)
# apply filter
return self.filter(*filt, filtfilt=filtfilt) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bandpass(self, flow, fhigh, gpass=2, gstop=30, fstop=None, type='iir', filtfilt=True, **kwargs):
"""Filter this `TimeSeries` with a band-pass filter. Paramet... |
# design filter
filt = filter_design.bandpass(flow, fhigh, self.sample_rate,
fstop=fstop, gpass=gpass, gstop=gstop,
analog=False, type=type, **kwargs)
# apply filter
return self.filter(*filt, filtfilt=filtfilt) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resample(self, rate, window='hamming', ftype='fir', n=None):
"""Resample this Series to a new rate Parameters rate : `float` rate to which to resample this `... |
if n is None and ftype == 'iir':
n = 8
elif n is None:
n = 60
if isinstance(rate, units.Quantity):
rate = rate.value
factor = (self.sample_rate.value / rate)
# NOTE: use math.isclose when python >= 3.5
if numpy.isclose(factor, 1., rto... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zpk(self, zeros, poles, gain, analog=True, **kwargs):
"""Filter this `TimeSeries` by applying a zero-pole-gain filter Parameters zeros : `array-like` list of... |
return self.filter(zeros, poles, gain, analog=analog, **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 filter(self, *filt, **kwargs):
"""Filter this `TimeSeries` with an IIR or FIR filter Parameters *filt : filter arguments 1, 2, 3, or 4 arguments defining the... |
# parse keyword arguments
filtfilt = kwargs.pop('filtfilt', False)
# parse filter
form, filt = filter_design.parse_filter(
filt, analog=kwargs.pop('analog', False),
sample_rate=self.sample_rate.to('Hz').value,
)
if form == 'zpk':
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def coherence(self, other, fftlength=None, overlap=None, window='hann', **kwargs):
"""Calculate the frequency-coherence between this `TimeSeries` and another. Pa... |
from matplotlib import mlab
from ..frequencyseries import FrequencySeries
# check sampling rates
if self.sample_rate.to('Hertz') != other.sample_rate.to('Hertz'):
sampling = min(self.sample_rate.value, other.sample_rate.value)
# resample higher rate series
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def auto_coherence(self, dt, fftlength=None, overlap=None, window='hann', **kwargs):
"""Calculate the frequency-coherence between this `TimeSeries` and a time-sh... |
# shifting self backwards is the same as forwards
dt = abs(dt)
# crop inputs
self_ = self.crop(self.span[0], self.span[1] - dt)
other = self.crop(self.span[0] + dt, self.span[1])
return self_.coherence(other, fftlength=fftlength,
overlap=ov... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def coherence_spectrogram(self, other, stride, fftlength=None, overlap=None, window='hann', nproc=1):
"""Calculate the coherence spectrogram between this `TimeSe... |
from ..spectrogram.coherence import from_timeseries
return from_timeseries(self, other, stride, fftlength=fftlength,
overlap=overlap, window=window,
nproc=nproc) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rms(self, stride=1):
"""Calculate the root-mean-square value of this `TimeSeries` once per stride. Parameters stride : `float` stride (seconds) between RMS c... |
stridesamp = int(stride * self.sample_rate.value)
nsteps = int(self.size // stridesamp)
# stride through TimeSeries, recording RMS
data = numpy.zeros(nsteps)
for step in range(nsteps):
# find step TimeSeries
idx = int(stridesamp * step)
idx_en... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def demodulate(self, f, stride=1, exp=False, deg=True):
"""Compute the average magnitude and phase of this `TimeSeries` once per stride at a given frequency. Par... |
stridesamp = int(stride * self.sample_rate.value)
nsteps = int(self.size // stridesamp)
# stride through the TimeSeries and mix with a local oscillator,
# taking the average over each stride
out = type(self)(numpy.zeros(nsteps, dtype=complex))
out.__array_finalize__(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 taper(self, side='leftright'):
"""Taper the ends of this `TimeSeries` smoothly to zero. Parameters side : `str`, optional the side of the `TimeSeries` to tap... |
# check window properties
if side not in ('left', 'right', 'leftright'):
raise ValueError("side must be one of 'left', 'right', "
"or 'leftright'")
out = self.copy()
# identify the second stationary point away from each boundary,
# else d... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def whiten(self, fftlength=None, overlap=0, method=DEFAULT_FFT_METHOD, window='hanning', detrend='constant', asd=None, fduration=2, highpass=None, **kwargs):
"""... |
# compute the ASD
fftlength = fftlength if fftlength else _fft_length_default(self.dt)
if asd is None:
asd = self.asd(fftlength, overlap=overlap,
method=method, window=window, **kwargs)
asd = asd.interpolate(1./self.duration.decompose().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 gate(self, tzero=1.0, tpad=0.5, whiten=True, threshold=50., cluster_window=0.5, **whiten_kwargs):
"""Removes high amplitude peaks from data using inverse Pla... |
try:
from scipy.signal import find_peaks
except ImportError as exc:
exc.args = ("Must have scipy>=1.1.0 to utilize this method.",)
raise
# Find points to gate based on a threshold
data = self.whiten(**whiten_kwargs) if whiten else self
window_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convolve(self, fir, window='hanning'):
"""Convolve this `TimeSeries` with an FIR filter using the overlap-save method Parameters fir : `numpy.ndarray` the ti... |
pad = int(numpy.ceil(fir.size/2))
nfft = min(8*fir.size, self.size)
# condition the input data
in_ = self.copy()
window = signal.get_window(window, fir.size)
in_.value[:pad] *= window[:pad]
in_.value[-pad:] *= window[-pad:]
# if FFT length is long enough,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def correlate(self, mfilter, window='hanning', detrend='linear', whiten=False, wduration=2, highpass=None, **asd_kw):
"""Cross-correlate this `TimeSeries` with a... |
self.is_compatible(mfilter)
# condition data
if whiten is True:
fftlength = asd_kw.pop('fftlength',
_fft_length_default(self.dt))
overlap = asd_kw.pop('overlap', None)
if overlap is None:
overlap = recommende... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def detrend(self, detrend='constant'):
"""Remove the trend from this `TimeSeries` This method just wraps :func:`scipy.signal.detrend` to return an object of the ... |
data = signal.detrend(self.value, type=detrend).view(type(self))
data.__metadata_finalize__(self)
data._unit = self.unit
return 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 notch(self, frequency, type='iir', filtfilt=True, **kwargs):
"""Notch out a frequency in this `TimeSeries`. Parameters frequency : `float`, `~astropy.units.Q... |
zpk = filter_design.notch(frequency, self.sample_rate.value,
type=type, **kwargs)
return self.filter(*zpk, filtfilt=filtfilt) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def q_gram(self, qrange=qtransform.DEFAULT_QRANGE, frange=qtransform.DEFAULT_FRANGE, mismatch=qtransform.DEFAULT_MISMATCH, snrthresh=5.5, **kwargs):
"""Scan a `T... |
qscan, _ = qtransform.q_scan(self, mismatch=mismatch, qrange=qrange,
frange=frange, **kwargs)
qgram = qscan.table(snrthresh=snrthresh)
return qgram |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def q_transform(self, qrange=qtransform.DEFAULT_QRANGE, frange=qtransform.DEFAULT_FRANGE, gps=None, search=.5, tres="<default>", fres="<default>", logf=False, nor... | # noqa: E501
from ..frequencyseries import FrequencySeries
# condition data
if whiten is True: # generate ASD dynamically
window = asd_kw.pop('window', 'hann')
fftlength = asd_kw.pop('fftlength',
_fft_length_default(self.dt))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _update_index(self, axis, key, value):
"""Update the current axis index based on a given key or value This is an internal method designed to set the origin o... |
# delete current value if given None
if value is None:
return delattr(self, key)
_key = "_{}".format(key)
index = "{[0]}index".format(axis)
unit = "{[0]}unit".format(axis)
# convert float to Quantity
if not isinstance(value, Quantity):
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 _set_index(self, key, index):
"""Set a new index array for this series """ |
axis = key[0]
origin = "{}0".format(axis)
delta = "d{}".format(axis)
if index is None:
return delattr(self, key)
if not isinstance(index, Index):
try:
unit = index.unit
except AttributeError:
unit = getattr(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 x0(self):
"""X-axis coordinate of the first data point :type: `~astropy.units.Quantity` scalar """ |
try:
return self._x0
except AttributeError:
self._x0 = Quantity(0, self.xunit)
return self._x0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dx(self):
"""X-axis sample separation :type: `~astropy.units.Quantity` scalar """ |
try:
return self._dx
except AttributeError:
try:
self._xindex
except AttributeError:
self._dx = Quantity(1, self.xunit)
else:
if not self.xindex.regular:
raise AttributeError("This series... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def xindex(self):
"""Positions of the data on the x-axis :type: `~astropy.units.Quantity` array """ |
try:
return self._xindex
except AttributeError:
self._xindex = Index.define(self.x0, self.dx, self.shape[0])
return self._xindex |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def xunit(self):
"""Unit of x-axis index :type: `~astropy.units.Unit` """ |
try:
return self._dx.unit
except AttributeError:
try:
return self._x0.unit
except AttributeError:
return self._default_xunit |
<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(self, method='plot', **kwargs):
"""Plot the data for this series Returns ------- figure : `~matplotlib.figure.Figure` the newly created figure, with pop... |
from ..plot import Plot
from ..plot.text import default_unit_label
# correct for log scales and zeros
if kwargs.get('xscale') == 'log' and self.x0.value == 0:
kwargs.setdefault('xlim', (self.dx.value, self.xspan[1]))
# make plot
plot = Plot(self, method=met... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def step(self, **kwargs):
"""Create a step plot of this series """ |
kwargs.setdefault('linestyle', kwargs.pop('where', 'steps-post'))
data = self.append(self.value[-1:], inplace=False)
return data.plot(**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 shift(self, delta):
"""Shift this `Series` forward on the X-axis by ``delta`` This modifies the series in-place. Parameters delta : `float`, `~astropy.units.... |
self.x0 = self.x0 + Quantity(delta, self.xunit) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def value_at(self, x):
"""Return the value of this `Series` at the given `xindex` value Parameters x : `float`, `~astropy.units.Quantity` the `xindex` value at w... |
x = Quantity(x, self.xindex.unit).value
try:
idx = (self.xindex.value == x).nonzero()[0][0]
except IndexError as e:
e.args = ("Value %r not found in array index" % x,)
raise
return self[idx] |
<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_contiguous(self, other, tol=1/2.**18):
"""Check whether other is contiguous with self. Parameters other : `Series`, `numpy.ndarray` another series of the ... |
self.is_compatible(other)
if isinstance(other, type(self)):
if abs(float(self.xspan[1] - other.xspan[0])) < tol:
return 1
elif abs(float(other.xspan[1] - self.xspan[0])) < tol:
return -1
return 0
elif type(other) in [list, tupl... |
<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_compatible(self, other):
"""Check whether this series and other have compatible metadata This method tests that the `sample size <Series.dx>`, and the `~S... |
if isinstance(other, type(self)):
# check step size, if possible
try:
if not self.dx == other.dx:
raise ValueError("%s sample sizes do not match: "
"%s vs %s." % (type(self).__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 prepend(self, other, inplace=True, pad=None, gap=None, resize=True):
"""Connect another series onto the start of the current one. Parameters other : `Series`... |
out = other.append(self, inplace=False, gap=gap, pad=pad,
resize=resize)
if inplace:
self.resize(out.shape, refcheck=False)
self[:] = out[:]
self.x0 = out.x0.copy()
del out
return self
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, other, inplace=True):
"""Update this series by appending new data from an other and dropping the same amount of data off the start. This is a co... |
return self.append(other, inplace=inplace, resize=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 crop(self, start=None, end=None, copy=False):
"""Crop this series to the given x-axis extent. Parameters start : `float`, optional lower limit of x-axis to c... |
x0, x1 = self.xspan
xtype = type(x0)
if isinstance(start, Quantity):
start = start.to(self.xunit).value
if isinstance(end, Quantity):
end = end.to(self.xunit).value
# pin early starts to time-series start
if start == x0:
start = 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 pad(self, pad_width, **kwargs):
"""Pad this series to a new size Parameters pad_width : `int`, pair of `ints` number of samples by which to pad each end of t... |
# format arguments
kwargs.setdefault('mode', 'constant')
if isinstance(pad_width, int):
pad_width = (pad_width,)
# form pad and view to this type
new = numpy.pad(self, pad_width, **kwargs).view(type(self))
# numpy.pad has stripped all metadata, so copy it ove... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inject(self, other):
"""Add two compatible `Series` along their shared x-axis values. Parameters other : `Series` a `Series` whose xindex intersects with `se... |
# check Series compatibility
self.is_compatible(other)
if (self.xunit == second) and (other.xspan[0] < self.xspan[0]):
other = other.crop(start=self.xspan[0])
if (self.xunit == second) and (other.xspan[1] > self.xspan[1]):
other = other.crop(end=self.xspan[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 _select_query_method(cls, url):
"""Select the correct query method based on the URL Works for `DataQualityFlag` and `DataQualityDict` """ |
if urlparse(url).netloc.startswith('geosegdb.'): # only DB2 server
return cls.query_segdb
return cls.query_dqsegdb |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query(cls, flag, *args, **kwargs):
"""Query for segments of a given flag This method intelligently selects the `~DataQualityFlag.query_segdb` or the `~DataQu... |
query_ = _select_query_method(
cls, kwargs.get('url', DEFAULT_SEGMENT_SERVER))
return query_(flag, *args, **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 query_segdb(cls, flag, *args, **kwargs):
"""Query the initial LIGO segment database for the given flag Parameters flag : `str` The name of the flag for which... |
warnings.warn("query_segdb is deprecated and will be removed in a "
"future release", DeprecationWarning)
# parse arguments
qsegs = _parse_query_segments(args, cls.query_segdb)
# process query
try:
flags = DataQualityDict.query_segdb([flag], 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 query_dqsegdb(cls, flag, *args, **kwargs):
"""Query the advanced LIGO DQSegDB for the given flag Parameters flag : `str` The name of the flag for which to qu... |
# parse arguments
qsegs = _parse_query_segments(args, cls.query_dqsegdb)
# get server
url = kwargs.pop('url', DEFAULT_SEGMENT_SERVER)
# parse flag
out = cls(name=flag)
if out.ifo is None or out.tag is None:
raise ValueError("Cannot parse ifo or tag ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_open_data(cls, flag, start, end, **kwargs):
"""Fetch Open Data timeline segments into a flag. flag : `str` the name of the flag to query start : `int`,... |
start = to_gps(start).gpsSeconds
end = to_gps(end).gpsSeconds
known = [(start, end)]
active = timeline.get_segments(flag, start, end, **kwargs)
return cls(flag.replace('_', ':', 1), known=known, active=active,
label=flag) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(cls, source, *args, **kwargs):
"""Read segments from file into a `DataQualityFlag`. Parameters filename : `str` path of file to read name : `str`, optio... |
if 'flag' in kwargs: # pragma: no cover
warnings.warn('\'flag\' keyword was renamed \'name\', this '
'warning will result in an error in the future')
kwargs.setdefault('name', kwargs.pop('flags'))
coalesce = kwargs.pop('coalesce', False)
def 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 from_veto_def(cls, veto):
"""Define a `DataQualityFlag` from a `VetoDef` Parameters veto : :class:`~ligo.lw.lsctables.VetoDef` veto definition to convert fro... |
name = '%s:%s' % (veto.ifo, veto.name)
try:
name += ':%d' % int(veto.version)
except TypeError:
pass
if veto.end_time == 0:
veto.end_time = +inf
known = Segment(veto.start_time, veto.end_time)
pad = (veto.start_pad, veto.end_pad)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def populate(self, source=DEFAULT_SEGMENT_SERVER, segments=None, pad=True, **kwargs):
"""Query the segment database for this flag's active segments. This method ... |
tmp = DataQualityDict()
tmp[self.name] = self
tmp.populate(source=source, segments=segments, pad=pad, **kwargs)
return tmp[self.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 contract(self, x):
"""Contract each of the `active` `Segments` by ``x`` seconds. This method adds ``x`` to each segment's lower bound, and subtracts ``x`` fr... |
self.active = self.active.contract(x)
return self.active |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def protract(self, x):
"""Protract each of the `active` `Segments` by ``x`` seconds. This method subtracts ``x`` from each segment's lower bound, and adds ``x`` ... |
self.active = self.active.protract(x)
return self.active |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pad(self, *args, **kwargs):
"""Apply a padding to each segment in this `DataQualityFlag` This method either takes no arguments, in which case the value of th... |
if not args:
start, end = self.padding
else:
start, end = args
if kwargs.pop('inplace', False):
new = self
else:
new = self.copy()
if kwargs:
raise TypeError("unexpected keyword argument %r"
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def round(self, contract=False):
"""Round this flag to integer segments. Parameters contract : `bool`, optional if `False` (default) expand each segment to the c... |
def _round(seg):
if contract: # round inwards
a = type(seg[0])(ceil(seg[0]))
b = type(seg[1])(floor(seg[1]))
else: # round outwards
a = type(seg[0])(floor(seg[0]))
b = type(seg[1])(ceil(seg[1]))
if a >= b: # ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def coalesce(self):
"""Coalesce the segments for this flag. This method does two things: - `coalesces <SegmentList.coalesce>` the `~DataQualityFlag.known` and `~... |
self.known = self.known.coalesce()
self.active = self.active.coalesce()
self.active = (self.known & self.active).coalesce()
return 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 _parse_name(self, name):
"""Internal method to parse a `string` name into constituent `ifo, `name` and `version` components. Parameters name : `str`, `None` ... |
if name is None:
self.ifo = None
self.tag = None
self.version = None
elif re_IFO_TAG_VERSION.match(name):
match = re_IFO_TAG_VERSION.match(name).groupdict()
self.ifo = match['ifo']
self.tag = match['tag']
self.version =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query_segdb(cls, flags, *args, **kwargs):
"""Query the inital LIGO segment database for a list of flags. Parameters flags : `iterable` A list of flag names f... |
warnings.warn("query_segdb is deprecated and will be removed in a "
"future release", DeprecationWarning)
# parse segments
qsegs = _parse_query_segments(args, cls.query_segdb)
url = kwargs.pop('url', DEFAULT_SEGMENT_SERVER)
if kwargs.pop('on_error', 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 query_dqsegdb(cls, flags, *args, **kwargs):
"""Query the advanced LIGO DQSegDB for a list of flags. Parameters flags : `iterable` A list of flag names for wh... |
# check on_error flag
on_error = kwargs.pop('on_error', 'raise').lower()
if on_error not in ['raise', 'warn', 'ignore']:
raise ValueError("on_error must be one of 'raise', 'warn', "
"or 'ignore'")
# parse segments
qsegs = _parse_query_se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(cls, source, names=None, format=None, **kwargs):
"""Read segments from file into a `DataQualityDict` Parameters source : `str` path of file to read form... |
on_missing = kwargs.pop('on_missing', 'error')
coalesce = kwargs.pop('coalesce', False)
if 'flags' in kwargs: # pragma: no cover
warnings.warn('\'flags\' keyword was renamed \'names\', this '
'warning will result in an error in the future')
na... |
<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_veto_definer_file(cls, fp, start=None, end=None, ifo=None, format='ligolw'):
"""Read a `DataQualityDict` from a LIGO_LW XML VetoDefinerTable. Parameters... |
if format != 'ligolw':
raise NotImplementedError("Reading veto definer from non-ligolw "
"format file is not currently "
"supported")
# read veto definer file
with get_readable_fileobj(fp, show_progress=Fal... |
<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_ligolw_tables(cls, segmentdeftable, segmentsumtable, segmenttable, names=None, gpstype=LIGOTimeGPS, on_missing='error'):
"""Build a `DataQualityDict` fr... |
out = cls()
id_ = dict() # need to record relative IDs from LIGO_LW
# read segment definers and generate DataQualityFlag object
for row in segmentdeftable:
ifos = sorted(row.instruments)
ifo = ''.join(ifos) if ifos else None
tag = row.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 to_ligolw_tables(self, ilwdchar_compat=None, **attrs):
"""Convert this `DataQualityDict` into a trio of LIGO_LW segment tables Parameters ilwdchar_compat : `... |
if ilwdchar_compat is None:
warnings.warn("ilwdchar_compat currently defaults to `True`, "
"but this will change to `False` in the future, to "
"maintain compatibility in future releases, "
"manually specify `ilwdchar_com... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def populate(self, source=DEFAULT_SEGMENT_SERVER, segments=None, pad=True, on_error='raise', **kwargs):
"""Query the segment database for each flag's active segm... |
# check on_error flag
if on_error not in ['raise', 'warn', 'ignore']:
raise ValueError("on_error must be one of 'raise', 'warn', "
"or 'ignore'")
# format source
source = urlparse(source)
# perform query for all segments
if source... |
<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(self, deep=False):
"""Build a copy of this dictionary. Parameters deep : `bool`, optional, default: `False` perform a deep copy of the original dictiona... |
if deep:
return deepcopy(self)
return super(DataQualityDict, self).copy() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def union(self):
"""Return the union of all flags in this dict Returns ------- union : `DataQualityFlag` a new `DataQualityFlag` who's active and known segments ... |
usegs = reduce(operator.or_, self.values())
usegs.name = ' | '.join(self.keys())
return usegs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def intersection(self):
"""Return the intersection of all flags in this dict Returns ------- intersection : `DataQualityFlag` a new `DataQualityFlag` who's activ... |
isegs = reduce(operator.and_, self.values())
isegs.name = ' & '.join(self.keys())
return isegs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rc_params(usetex=None):
"""Returns a new `matplotlib.RcParams` with updated GWpy parameters The updated parameters are globally stored as `gwpy.plot.rc.GWPY_... |
# if user didn't specify to use tex or not, guess based on
# the `GWPY_USETEX` environment variable, or whether tex is
# installed at all.
if usetex is None:
usetex = bool_env(
'GWPY_USETEX',
default=rcParams['text.usetex'] or tex.has_tex())
# build RcParams from 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 get_subplot_params(figsize):
"""Return sensible default `SubplotParams` for a figure of the given size Parameters figsize : `tuple` of `float` the ``(width, ... |
width, height, = figsize
try:
left, right = SUBPLOT_WIDTH[width]
except KeyError:
left = right = None
try:
bottom, top = SUBPLOT_HEIGHT[height]
except KeyError:
bottom = top = None
return SubplotParams(left=left, bottom=bottom, right=right, top=top) |
<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_string(input_):
"""Format an input for representation as text This method is just a convenience that handles default LaTeX formatting """ |
usetex = rcParams['text.usetex']
if isinstance(input_, units.UnitBase):
return input_.to_string('latex_inline')
if isinstance(input_, (float, int)) and usetex:
return tex.float_to_latex(input_)
if usetex:
return tex.label_to_latex(input_)
return str(input_) |
<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_unit_label(axis, unit):
"""Set default label for an axis from a `~astropy.units.Unit` If the axis already has a label, this function does nothing. Pa... |
if not axis.isDefault_label:
return
label = axis.set_label_text(unit.to_string('latex_inline_dimensional'))
axis.isDefault_label = True
return label.get_text() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def initialize(self):
"""Initialize a connection to the LDAP server. :return: LDAP connection object. """ |
try:
conn = ldap.initialize('{0}://{1}:{2}'.format(
current_app.config['LDAP_SCHEMA'],
current_app.config['LDAP_HOST'],
current_app.config['LDAP_PORT']))
conn.set_option(ldap.OPT_NETWORK_TIMEOUT,
current_app.co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bind(self):
"""Attempts to bind to the LDAP server using the credentials of the service account. :return: Bound LDAP connection object if successful or ``Non... |
conn = self.initialize
try:
conn.simple_bind_s(
current_app.config['LDAP_USERNAME'],
current_app.config['LDAP_PASSWORD'])
return conn
except ldap.LDAPError as e:
raise LDAPException(self.error(e.args)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bind_user(self, username, password):
"""Attempts to bind a user to the LDAP server using the credentials supplied. .. note:: Many LDAP servers will grant ano... |
user_dn = self.get_object_details(user=username, dn_only=True)
if user_dn is None:
return
try:
conn = self.initialize
conn.simple_bind_s(user_dn.decode('utf-8'), password)
return True
except ldap.LDAPError:
return |
<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_user_groups(self, user):
"""Returns a ``list`` with the user's groups or ``None`` if unsuccessful. :param str user: User we want groups for. """ |
conn = self.bind
try:
if current_app.config['LDAP_OPENLDAP']:
fields = \
[str(current_app.config['LDAP_GROUP_MEMBER_FILTER_FIELD'])]
records = conn.search_s(
current_app.config['LDAP_BASE_DN'], ldap.SCOPE_SUBTREE,
... |
<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_group_members(self, group):
"""Returns a ``list`` with the group's members or ``None`` if unsuccessful. :param str group: Group we want users for. """ |
conn = self.bind
try:
records = conn.search_s(
current_app.config['LDAP_BASE_DN'], ldap.SCOPE_SUBTREE,
ldap_filter.filter_format(
current_app.config['LDAP_GROUP_OBJECT_FILTER'], (group,)),
[current_app.config['LDAP_GROUP_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 login_required(func):
"""When applied to a view function, any unauthenticated requests will be redirected to the view named in LDAP_LOGIN_VIEW. Authenticated... |
@wraps(func)
def wrapped(*args, **kwargs):
if g.user is None:
return redirect(url_for(current_app.config['LDAP_LOGIN_VIEW'],
next=request.path))
return func(*args, **kwargs)
return wrapped |
<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_required(groups=None):
"""When applied to a view function, any unauthenticated requests will be redirected to the view named in LDAP_LOGIN_VIEW. Authen... |
def wrapper(func):
@wraps(func)
def wrapped(*args, **kwargs):
if g.user is None:
return redirect(
url_for(current_app.config['LDAP_LOGIN_VIEW'],
next=request.path))
match = [grou... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def buy_streak_freeze(self):
""" figure out the users current learning language use this one as parameter for the shop """ |
lang = self.get_abbreviation_of(self.get_user_info()['learning_language_string'])
if lang is None:
raise Exception('No learning language found')
try:
self.buy_item('streak_freeze', lang)
return True
except AlreadyHaveStoreItemException:
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 _compute_dependency_order(skills):
""" Add a field to each skill indicating the order it was learned based on the skill's dependencies. Multiple skills will ... |
# Key skills by first dependency. Dependency sets can be uniquely
# identified by one dependency in the set.
dependency_to_skill = MultiDict([(skill['dependencies_name'][0]
if skill['dependencies_name']
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 get_languages(self, abbreviations=False):
""" Get praticed languages. :param abbreviations: Get language as abbreviation or not :type abbreviations: bool :re... |
data = []
for lang in self.user_data.languages:
if lang['learning']:
if abbreviations:
data.append(lang['language'])
else:
data.append(lang['language_string'])
return 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 get_language_from_abbr(self, abbr):
"""Get language full name from abbreviation.""" |
for language in self.user_data.languages:
if language['language'] == abbr:
return language['language_string']
return 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 get_abbreviation_of(self, name):
"""Get abbreviation of a language.""" |
for language in self.user_data.languages:
if language['language_string'] == name:
return language['language']
return 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 get_language_details(self, language):
"""Get user's status about a language.""" |
for lang in self.user_data.languages:
if language == lang['language_string']:
return lang
return {} |
<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_certificates(self):
"""Get user's certificates.""" |
for certificate in self.user_data.certificates:
certificate['datetime'] = certificate['datetime'].strip()
return self.user_data.certificates |
<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_calendar(self, language_abbr=None):
"""Get user's last actions.""" |
if language_abbr:
if not self._is_current_language(language_abbr):
self._switch_language(language_abbr)
return self.user_data.language_data[language_abbr]['calendar']
else:
return self.user_data.calendar |
<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_language_progress(self, lang):
"""Get informations about user's progression in a language.""" |
if not self._is_current_language(lang):
self._switch_language(lang)
fields = ['streak', 'language_string', 'level_progress',
'num_skills_learned', 'level_percent', 'level_points',
'points_rank', 'next_level', 'level_left', 'language',
'... |
<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_friends(self):
"""Get user's friends.""" |
for k, v in iter(self.user_data.language_data.items()):
data = []
for friend in v['points_ranking_data']:
temp = {'username': friend['username'],
'id': friend['id'],
'points': friend['points_data']['total'],
... |
<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_known_words(self, lang):
"""Get a list of all words learned by user in a language.""" |
words = []
for topic in self.user_data.language_data[lang]['skills']:
if topic['learned']:
words += topic['words']
return set(words) |
<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_learned_skills(self, lang):
""" Return the learned skill objects sorted by the order they were learned in. """ |
skills = [skill for skill in
self.user_data.language_data[lang]['skills']]
self._compute_dependency_order(skills)
return [skill for skill in
sorted(skills, key=lambda skill: skill['dependency_order'])
if skill['learned']] |
<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_known_topics(self, lang):
"""Return the topics learned by a user in a language.""" |
return [topic['title']
for topic in self.user_data.language_data[lang]['skills']
if topic['learned']] |
<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_unknown_topics(self, lang):
"""Return the topics remaining to learn by a user in a language.""" |
return [topic['title']
for topic in self.user_data.language_data[lang]['skills']
if not topic['learned']] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.