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 is_regular(self):
"""Determine whether this `Index` contains linearly increasing samples This also works for linear decrease """ |
if self.size <= 1:
return False
return numpy.isclose(numpy.diff(self.value, n=2), 0).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 table_from_omicron(source, *args, **kwargs):
"""Read an `EventTable` from an Omicron ROOT file This function just redirects to the format='root' reader with ... |
if not args: # only default treename if args not given
kwargs.setdefault('treename', 'triggers')
return EventTable.read(source, *args, format='root', **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 plot(self, *args, **kwargs):
"""Plot data onto these axes Parameters args a single instance of - `~gwpy.segments.DataQualityFlag` - `~gwpy.segments.Segment` ... |
out = []
args = list(args)
while args:
try:
plotter = self._plot_method(args[0])
except TypeError:
break
out.append(plotter(args[0], **kwargs))
args.pop(0)
if args:
out.extend(super(SegmentAxes, ... |
<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_dict(self, flags, label='key', known='x', **kwargs):
"""Plot a `~gwpy.segments.DataQualityDict` onto these axes Parameters flags : `~gwpy.segments.DataQ... |
out = []
for lab, flag in flags.items():
if label.lower() == 'name':
lab = flag.name
elif label.lower() != 'key':
lab = label
out.append(self.plot_flag(flag, label=to_string(lab), known=known,
**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 plot_flag(self, flag, y=None, **kwargs):
"""Plot a `~gwpy.segments.DataQualityFlag` onto these axes. Parameters flag : `~gwpy.segments.DataQualityFlag` Data-... |
# get y axis position
if y is None:
y = self.get_next_y()
# default a 'good' flag to green segments and vice-versa
if flag.isgood:
kwargs.setdefault('facecolor', '#33cc33')
kwargs.setdefault('known', '#ff0000')
else:
kwargs.setdef... |
<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_segmentlist(self, segmentlist, y=None, height=.8, label=None, collection=True, rasterized=None, **kwargs):
"""Plot a `~gwpy.segments.SegmentList` onto t... |
# get colour
facecolor = kwargs.pop('facecolor', kwargs.pop('color', '#629fca'))
if is_color_like(facecolor):
kwargs.setdefault('edgecolor', tint(facecolor, factor=.5))
# get y
if y is None:
y = self.get_next_y()
# build patches
patches ... |
<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_segmentlistdict(self, segmentlistdict, y=None, dy=1, **kwargs):
"""Plot a `~gwpy.segments.SegmentListDict` onto these axes Parameters segmentlistdict : ... |
if y is None:
y = self.get_next_y()
collections = []
for name, segmentlist in segmentlistdict.items():
collections.append(self.plot_segmentlist(segmentlist, y=y,
label=name, **kwargs))
y += dy
retur... |
<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_collections(self, ignore=None):
"""Return the collections matching the given `_ignore` value Parameters ignore : `bool`, or `None` value of `_ignore` to ... |
if ignore is None:
return self.collections
return [c for c in self.collections if
getattr(c, '_ignore', None) == ignore] |
<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_keytab(keytab):
"""Read the contents of a KRB5 keytab file, returning a list of credentials listed within Parameters keytab : `str` path to keytab file... |
try:
out = subprocess.check_output(['klist', '-k', keytab],
stderr=subprocess.PIPE)
except OSError:
raise KerberosError("Failed to locate klist, cannot read keytab")
except subprocess.CalledProcessError:
raise KerberosError("Cannot read keytab {... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def y0(self):
"""Y-axis coordinate of the first data point :type: `~astropy.units.Quantity` scalar """ |
try:
return self._y0
except AttributeError:
self._y0 = Quantity(0, self.yunit)
return self._y0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dy(self):
"""Y-axis sample separation :type: `~astropy.units.Quantity` scalar """ |
try:
return self._dy
except AttributeError:
try:
self._yindex
except AttributeError:
self._dy = Quantity(1, self.yunit)
else:
if not self.yindex.regular:
raise AttributeError(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def yunit(self):
"""Unit of Y-axis index :type: `~astropy.units.Unit` """ |
try:
return self._dy.unit
except AttributeError:
try:
return self._y0.unit
except AttributeError:
return self._default_yunit |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def yindex(self):
"""Positions of the data on the y-axis :type: `~astropy.units.Quantity` array """ |
try:
return self._yindex
except AttributeError:
self._yindex = Index.define(self.y0, self.dy, self.shape[1])
return self._yindex |
<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 array and ``other`` have compatible metadata """ |
super(Array2D, self).is_compatible(other)
# check y-axis metadata
if isinstance(other, type(self)):
try:
if not self.dy == other.dy:
raise ValueError("%s sample sizes do not match: "
"%s vs %s." % (type(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 find_flag_groups(h5group, strict=True):
"""Returns all HDF5 Groups under the given group that contain a flag The check is just that the sub-group has a ``'na... |
names = []
for group in h5group:
try:
names.append(h5group[group].attrs['name'])
except KeyError:
if strict:
raise
continue
return names |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _is_flag_group(obj):
"""Returns `True` if `obj` is an `h5py.Group` that looks like if contains a flag """ |
return (
isinstance(obj, h5py.Group) and
isinstance(obj.get("active"), h5py.Dataset) and
isinstance(obj.get("known"), h5py.Dataset)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_flag_groups(h5f):
"""Return all groups in `h5f` that look like flags """ |
flag_groups = []
def _find(name, obj):
if _is_flag_group(obj):
flag_groups.append(name)
h5f.visititems(_find)
return flag_groups |
<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_flag_group(h5f, path):
"""Determine the group to use in order to read a flag """ |
# if user chose the path, just use it
if path:
return h5f[path]
# if the user gave us the group directly, use it
if _is_flag_group(h5f):
return h5f
# otherwise try and find a single group that matches
try:
path, = _find_flag_groups(h5f)
except ValueError:
p... |
<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_hdf5_flag(h5f, path=None, gpstype=LIGOTimeGPS):
"""Read a `DataQualityFlag` object from an HDF5 file or group. """ |
# extract correct group
dataset = _get_flag_group(h5f, path)
# read dataset
active = SegmentList.read(dataset['active'], format='hdf5',
gpstype=gpstype)
try:
known = SegmentList.read(dataset['known'], format='hdf5',
gpstype=gps... |
<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_hdf5_segmentlist(h5f, path=None, gpstype=LIGOTimeGPS, **kwargs):
"""Read a `SegmentList` object from an HDF5 file or group. """ |
# find dataset
dataset = io_hdf5.find_dataset(h5f, path=path)
segtable = Table.read(dataset, format='hdf5', **kwargs)
out = SegmentList()
for row in segtable:
start = LIGOTimeGPS(int(row['start_time']), int(row['start_time_ns']))
end = LIGOTimeGPS(int(row['end_time']), int(row['end... |
<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_hdf5_dict(h5f, names=None, path=None, on_missing='error', **kwargs):
"""Read a `DataQualityDict` from an HDF5 file """ |
if path:
h5f = h5f[path]
# allow alternative keyword argument name (FIXME)
if names is None:
names = kwargs.pop('flags', None)
# try and get list of names automatically
if names is None:
try:
names = find_flag_groups(h5f, strict=True)
except KeyError:
... |
<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_hdf5_flag_group(flag, h5group, **kwargs):
"""Write a `DataQualityFlag` into the given HDF5 group """ |
# write segmentlists
flag.active.write(h5group, 'active', **kwargs)
kwargs['append'] = True
flag.known.write(h5group, 'known', **kwargs)
# store metadata
for attr in ['name', 'label', 'category', 'description', 'isgood',
'padding']:
value = getattr(flag, attr)
... |
<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_hdf5_dict(flags, output, path=None, append=False, overwrite=False, **kwargs):
"""Write this `DataQualityFlag` to a `h5py.Group`. This allows writing to... |
if path:
try:
parent = output[path]
except KeyError:
parent = output.create_group(path)
else:
parent = output
for name in flags:
# handle existing group
if name in parent:
if not (overwrite and append):
raise IOErr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def float_to_latex(x, format="%.2g"):
# pylint: disable=redefined-builtin # pylint: disable=anomalous-backslash-in-string r"""Convert a floating point number to ... |
if x == 0.:
return '0'
base_str = format % x
if "e" not in base_str:
return base_str
mantissa, exponent = base_str.split("e")
if float(mantissa).is_integer():
mantissa = int(float(mantissa))
exponent = exponent.lstrip("0+")
if exponent.startswith('-0'):
expon... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def label_to_latex(text):
# pylint: disable=anomalous-backslash-in-string r"""Convert text into a latex-passable representation. This method just escapes the fol... |
if text is None:
return ''
out = []
x = None
# loop over matches in reverse order and replace
for m in re_latex_control.finditer(text):
a, b = m.span()
char = m.group()[0]
out.append(text[x:a])
out.append(r'\%s' % char)
x = b
if not x: # no match... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def preformat_cache(cache, start=None, end=None):
"""Preprocess a `list` of file paths for reading. - read the cache from the file (if necessary) - sieve the cac... |
# open cache file
if isinstance(cache, FILE_LIKE + string_types):
return read_cache(cache, sort=file_segment,
segment=Segment(start, end))
# format existing cache file
cache = type(cache)(cache) # copy cache
# sort cache
try:
cache.sort(key=file_segm... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def progress_bar(**kwargs):
"""Create a `tqdm.tqdm` progress bar This is just a thin wrapper around `tqdm.tqdm` to set some updated defaults """ |
tqdm_kw = {
'desc': 'Processing',
'file': sys.stdout,
'bar_format': TQDM_BAR_FORMAT,
}
tqdm_kw.update(kwargs)
pbar = tqdm(**tqdm_kw)
if not pbar.disable:
pbar.desc = pbar.desc.rstrip(': ')
pbar.refresh()
return pbar |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def num_taps(sample_rate, transitionwidth, gpass, gstop):
"""Returns the number of taps for an FIR filter with the given shape Parameters sample_rate : `float` s... |
gpass = 10 ** (-gpass / 10.)
gstop = 10 ** (-gstop / 10.)
return int(2/3. * log10(1 / (10 * gpass * gstop)) *
sample_rate / transitionwidth) |
<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_zpk(zpktup):
"""Determin whether the given tuple is a ZPK-format filter definition Returns ------- iszpk : `bool` `True` if the ``zpktup`` looks like a ZP... |
return (
isinstance(zpktup, (tuple, list)) and
len(zpktup) == 3 and
isinstance(zpktup[0], (list, tuple, numpy.ndarray)) and
isinstance(zpktup[1], (list, tuple, numpy.ndarray)) and
isinstance(zpktup[2], float)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def truncate_transfer(transfer, ncorner=None):
"""Smoothly zero the edges of a frequency domain transfer function Parameters transfer : `numpy.ndarray` transfer ... |
nsamp = transfer.size
ncorner = ncorner if ncorner else 0
out = transfer.copy()
out[0:ncorner] = 0
out[ncorner:nsamp] *= planck(nsamp-ncorner, nleft=5, nright=5)
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 truncate_impulse(impulse, ntaps, window='hanning'):
"""Smoothly truncate a time domain impulse response Parameters impulse : `numpy.ndarray` the impulse resp... |
out = impulse.copy()
trunc_start = int(ntaps / 2)
trunc_stop = out.size - trunc_start
window = signal.get_window(window, ntaps)
out[0:trunc_start] *= window[trunc_start:ntaps]
out[trunc_stop:out.size] *= window[0:trunc_start]
out[trunc_start:trunc_stop] = 0
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 fir_from_transfer(transfer, ntaps, window='hanning', ncorner=None):
"""Design a Type II FIR filter given an arbitrary transfer function Parameters transfer :... |
# truncate and highpass the transfer function
transfer = truncate_transfer(transfer, ncorner=ncorner)
# compute and truncate the impulse response
impulse = npfft.irfft(transfer)
impulse = truncate_impulse(impulse, ntaps=ntaps, window=window)
# wrap around and normalise to construct the filter
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bilinear_zpk(zeros, poles, gain, fs=1.0, unit='Hz'):
"""Convert an analogue ZPK filter to digital using a bilinear transform Parameters zeros : array-like li... |
zeros = numpy.array(zeros, dtype=float, copy=False)
zeros = zeros[numpy.isfinite(zeros)]
poles = numpy.array(poles, dtype=float, copy=False)
gain = gain
# convert from Hz to rad/s if needed
unit = Unit(unit)
if unit == Unit('Hz'):
zeros *= -2 * pi
poles *= -2 * pi
elif ... |
<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_filter(args, analog=False, sample_rate=None):
"""Parse arbitrary input args into a TF or ZPK filter definition Parameters args : `tuple`, `~scipy.signa... |
if analog and not sample_rate:
raise ValueError("Must give sample_rate frequency to convert "
"analog filter to digital")
# unpack filter
if isinstance(args, tuple) and len(args) == 1:
# either packed defintion ((z, p, k)) or simple definition (lti,)
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 lowpass(frequency, sample_rate, fstop=None, gpass=2, gstop=30, type='iir', **kwargs):
"""Design a low-pass filter for the given cutoff frequency Parameters f... |
sample_rate = _as_float(sample_rate)
frequency = _as_float(frequency)
if fstop is None:
fstop = min(frequency * 1.5, sample_rate/2.)
if type == 'iir':
return _design_iir(frequency, fstop, sample_rate, gpass, gstop,
**kwargs)
return _design_fir(frequency, f... |
<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(frequency, sample_rate, fstop=None, gpass=2, gstop=30, type='iir', **kwargs):
"""Design a high-pass filter for the given cutoff frequency Parameters... |
sample_rate = _as_float(sample_rate)
frequency = _as_float(frequency)
if fstop is None:
fstop = frequency * 2/3.
if type == 'iir':
return _design_iir(frequency, fstop, sample_rate, gpass, gstop,
**kwargs)
return _design_fir(frequency, fstop, sample_rate, 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 bandpass(flow, fhigh, sample_rate, fstop=None, gpass=2, gstop=30, type='iir', **kwargs):
"""Design a band-pass filter for the given cutoff frequencies Parame... |
sample_rate = _as_float(sample_rate)
flow = _as_float(flow)
fhigh = _as_float(fhigh)
if fstop is None:
fstop = (flow * 2/3.,
min(fhigh * 1.5, sample_rate/2.))
fstop = (_as_float(fstop[0]), _as_float(fstop[1]))
if type == 'iir':
return _design_iir((flow, fhigh), ... |
<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(frequency, sample_rate, type='iir', **kwargs):
"""Design a ZPK notch filter for the given frequency and sampling rate Parameters frequency : `float`, `... |
frequency = Quantity(frequency, 'Hz').value
sample_rate = Quantity(sample_rate, 'Hz').value
nyq = 0.5 * sample_rate
df = 1.0 # pylint: disable=invalid-name
df2 = 0.1
low1 = (frequency - df)/nyq
high1 = (frequency + df)/nyq
low2 = (frequency - df2)/nyq
high2 = (frequency + df2)/nyq
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def welch(timeseries, segmentlength, noverlap=None, **kwargs):
"""Calculate a PSD of this `TimeSeries` using Welch's method. """ |
# calculate PSD
freqs, psd_ = scipy.signal.welch(
timeseries.value,
noverlap=noverlap,
fs=timeseries.sample_rate.decompose().value,
nperseg=segmentlength,
**kwargs
)
# generate FrequencySeries and return
unit = scale_timeseries_unit(
timeseries.unit,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bartlett(timeseries, segmentlength, **kwargs):
"""Calculate a PSD using Bartlett's method """ |
kwargs.pop('noverlap', None)
return welch(timeseries, segmentlength, noverlap=0, **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 median(timeseries, segmentlength, **kwargs):
"""Calculate a PSD using Welch's method with a median average """ |
if scipy_version <= '1.1.9999':
raise ValueError(
"median average PSD estimation requires scipy >= 1.2.0",
)
kwargs.setdefault('average', 'median')
return welch(timeseries, segmentlength, **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 rayleigh(timeseries, segmentlength, noverlap=0):
"""Calculate a Rayleigh statistic spectrum Parameters timeseries : `~gwpy.timeseries.TimeSeries` input `Time... |
stepsize = segmentlength - noverlap
if noverlap:
numsegs = 1 + int((timeseries.size - segmentlength) / float(noverlap))
else:
numsegs = int(timeseries.size // segmentlength)
tmpdata = numpy.ndarray((numsegs, int(segmentlength//2 + 1)))
for i in range(numsegs):
tmpdata[i, :] ... |
<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(timeseries, other, segmentlength, noverlap=None, **kwargs):
"""Calculate the CSD of two `TimeSeries` using Welch's method Parameters timeseries : `~gwpy.... |
# calculate CSD
try:
freqs, csd_ = scipy.signal.csd(
timeseries.value, other.value, noverlap=noverlap,
fs=timeseries.sample_rate.decompose().value,
nperseg=segmentlength, **kwargs)
except AttributeError as exc:
exc.args = ('{}, scipy>=0.16 is required'.fo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def duration(self):
"""Duration of this series in seconds :type: `~astropy.units.Quantity` scalar """ |
return units.Quantity(self.span[1] - self.span[0], self.xunit,
dtype=float) |
<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 data into a `TimeSeries` Arguments and keywords depend on the output format, see the online documentation for ful... |
from .io.core import read as timeseries_reader
return timeseries_reader(cls, source, *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 fetch(cls, channel, start, end, host=None, port=None, verbose=False, connection=None, verify=False, pad=None, allow_tape=None, scaled=None, type=None, dtype=N... |
return cls.DictClass.fetch(
[channel], start, end, host=host, port=port, verbose=verbose,
connection=connection, verify=verify, pad=pad, scaled=scaled,
allow_tape=allow_tape, type=type, dtype=dtype)[str(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 fetch_open_data(cls, ifo, start, end, sample_rate=4096, tag=None, version=None, format='hdf5', host=GWOSC_DEFAULT_HOST, verbose=False, cache=None, **kwargs):
... |
from .io.losc import fetch_losc_data
return fetch_losc_data(ifo, start, end, sample_rate=sample_rate,
tag=tag, version=version, format=format,
verbose=verbose, cache=cache,
host=host, cls=cls, **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 find(cls, channel, start, end, frametype=None, pad=None, scaled=None, dtype=None, nproc=1, verbose=False, **readargs):
"""Find and read data from frames for ... |
return cls.DictClass.find(
[channel], start, end,
frametype=frametype,
verbose=verbose,
pad=pad,
scaled=scaled,
dtype=dtype,
nproc=nproc,
**readargs
)[str(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 plot(self, method='plot', figsize=(12, 4), xscale='auto-gps', **kwargs):
"""Plot the data for this timeseries Returns ------- figure : `~matplotlib.figure.Fi... |
kwargs.update(figsize=figsize, xscale=xscale)
return super(TimeSeriesBase, self).plot(method=method, **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 from_nds2_buffer(cls, buffer_, scaled=None, copy=True, **metadata):
"""Construct a new series from an `nds2.buffer` object **Requires:** |nds2|_ Parameters b... |
# get Channel from buffer
channel = Channel.from_nds2(buffer_.channel)
# set default metadata
metadata.setdefault('channel', channel)
metadata.setdefault('epoch', LIGOTimeGPS(buffer_.gps_seconds,
buffer_.gps_nanoseconds))
... |
<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_lal(cls, lalts, copy=True):
"""Generate a new TimeSeries from a LAL TimeSeries of any type. """ |
from ..utils.lal import from_lal_unit
try:
unit = from_lal_unit(lalts.sampleUnits)
except (TypeError, ValueError) as exc:
warnings.warn("%s, defaulting to 'dimensionless'" % str(exc))
unit = None
channel = Channel(lalts.name, sample_rate=1/lalts.delta... |
<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_lal(self):
"""Convert this `TimeSeries` into a LAL TimeSeries. """ |
import lal
from ..utils.lal import (find_typed_function, to_lal_unit)
# map unit
try:
unit = to_lal_unit(self.unit)
except ValueError as e:
warnings.warn("%s, defaulting to lal.DimensionlessUnit" % str(e))
unit = lal.DimensionlessUnit
... |
<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_pycbc(cls, pycbcseries, copy=True):
"""Convert a `pycbc.types.timeseries.TimeSeries` into a `TimeSeries` Parameters pycbcseries : `pycbc.types.timeserie... |
return cls(pycbcseries.data, t0=pycbcseries.start_time,
dt=pycbcseries.delta_t, copy=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 to_pycbc(self, copy=True):
"""Convert this `TimeSeries` into a PyCBC `~pycbc.types.timeseries.TimeSeries` Parameters copy : `bool`, optional, default: `True`... |
from pycbc import types
return types.TimeSeries(self.value,
delta_t=self.dt.to('s').value,
epoch=self.epoch.gps, copy=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 coalesce(self):
"""Merge contiguous elements of this list into single objects This method implicitly sorts and potentially shortens this list. """ |
self.sort(key=lambda ts: ts.t0.value)
i = j = 0
N = len(self)
while j < N:
this = self[j]
j += 1
if j < N and this.is_contiguous(self[j]) == 1:
while j < N and this.is_contiguous(self[j]):
try:
... |
<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(self, pad=None, gap=None):
"""Concatenate all of the elements of this list into a single object Parameters pad : `float`, optional, default: `0.0` value... |
if not self:
return self.EntryClass(numpy.empty((0,) * self.EntryClass._ndim))
self.sort(key=lambda t: t.epoch.gps)
out = self[0].copy()
for series in self[1:]:
out.append(series, gap=gap, pad=pad)
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 copy(self):
"""Return a copy of this list with each element copied to new memory """ |
out = type(self)()
for series in self:
out.append(series.copy())
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 to_lal_type_str(pytype):
"""Convert the input python type to a LAL type string Examples -------- To convert a python type: 'REAL8' To convert a `numpy.dtype`... |
# noop
if pytype in LAL_TYPE_FROM_STR:
return pytype
# convert type code
if pytype in LAL_TYPE_STR:
return LAL_TYPE_STR[pytype]
# convert python type
try:
dtype = numpy.dtype(pytype)
return LAL_TYPE_STR_FROM_NUMPY[dtype.type]
except (TypeError, KeyError):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_typed_function(pytype, prefix, suffix, module=lal):
"""Returns the lal method for the correct type Parameters pytype : `type`, `numpy.dtype` the python ... |
laltype = to_lal_type_str(pytype)
return getattr(module, '{0}{1}{2}'.format(prefix, laltype, suffix)) |
<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_lal_unit(aunit):
"""Convert the input unit into a `LALUnit` For example:: m^2 kg^-4 Parameters aunit : `~astropy.units.Unit`, `str` the input unit Returns... |
if isinstance(aunit, string_types):
aunit = units.Unit(aunit)
aunit = aunit.decompose()
lunit = lal.Unit()
for base, power in zip(aunit.bases, aunit.powers):
# try this base
try:
lalbase = LAL_UNIT_FROM_ASTROPY[base]
except KeyError:
lalbase = Non... |
<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_lal_unit(lunit):
"""Convert a LALUnit` into a `~astropy.units.Unit` Parameters lunit : `lal.Unit` the input unit Returns ------- unit : `~astropy.units.... |
return reduce(operator.mul, (
units.Unit(str(LAL_UNIT_INDEX[i])) ** exp for
i, exp in enumerate(lunit.unitNumerator))) |
<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_lal_ligotimegps(gps):
"""Convert the given GPS time to a `lal.LIGOTimeGPS` object Parameters gps : `~gwpy.time.LIGOTimeGPS`, `float`, `str` input GPS time... |
gps = to_gps(gps)
return lal.LIGOTimeGPS(gps.gpsSeconds, gps.gpsNanoSeconds) |
<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_property_columns(tabletype, columns):
"""Returns list of GPS columns required to read gpsproperties for a table Examples -------- ['peak_time', 'peak_ti... |
from ligo.lw.lsctables import gpsproperty as GpsProperty
# get properties for row object
rowvars = vars(tabletype.RowType)
# build list of real column names for fancy properties
extracols = {}
for key in columns:
prop = rowvars[key]
if isinstance(prop, GpsProperty):
... |
<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_column_dtype(llwcol):
"""Get the data type of a LIGO_LW `Column` Parameters llwcol : :class:`~ligo.lw.table.Column`, `numpy.ndarray`, iterable a LIGO_LW... |
try: # maybe its a numpy array already!
dtype = llwcol.dtype
if dtype is numpy.dtype('O'): # don't convert
raise AttributeError
return dtype
except AttributeError: # dang
try: # ligo.lw.table.Column
llwtype = llwcol.parentNode.validcolumns[llwcol.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 read_table(source, tablename=None, **kwargs):
"""Read a `Table` from one or more LIGO_LW XML documents source : `file`, `str`, :class:`~ligo.lw.ligolw.Docume... |
from ligo.lw import table as ligolw_table
from ligo.lw.lsctables import TableByName
# -- keyword handling -----------------------
# separate keywords for reading and converting from LIGO_LW to Astropy
read_kw = kwargs # rename for readability
convert_kw = {
'rename': None,
'u... |
<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_table(table, target, tablename=None, ilwdchar_compat=None, **kwargs):
"""Write a `~astropy.table.Table` to file in LIGO_LW XML format This method will ... |
if tablename is None: # try and get tablename from metadata
tablename = table.meta.get('tablename', None)
if tablename is None: # panic
raise ValueError("please pass ``tablename=`` to specify the target "
"LIGO_LW Table Name")
try:
llwtable = table_to_ligo... |
<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_ascii_series(input_, array_type=Series, unpack=True, **kwargs):
"""Read a `Series` from an ASCII file Parameters input : `str`, `file` file to read arra... |
xarr, yarr = loadtxt(input_, unpack=unpack, **kwargs)
return array_type(yarr, xindex=xarr) |
<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_ascii_series(series, output, **kwargs):
"""Write a `Series` to a file in ASCII format Parameters series : :class:`~gwpy.data.Series` data series to wri... |
xarr = series.xindex.value
yarr = series.value
return savetxt(output, column_stack((xarr, yarr)), **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 channel_dict_kwarg(value, channels, types=None, astype=None):
"""Format the given kwarg value in a dict with one value per channel Parameters value : any typ... |
if types is not None and isinstance(value, tuple(types)):
out = dict((c, value) for c in channels)
elif isinstance(value, (tuple, list)):
out = dict(zip(channels, value))
elif value is None:
out = dict()
elif isinstance(value, dict):
out = value.copy()
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 import_gwf_library(library, package=__package__):
"""Utility method to import the relevant timeseries.io.gwf frame API This is just a wrapper around :meth:`i... |
# import the frame library here to have any ImportErrors occur early
try:
return importlib.import_module('.%s' % library, package=package)
except ImportError as exc:
exc.args = ('Cannot import %s frame API: %s' % (library, str(exc)),)
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 get_default_gwf_api():
"""Return the preferred GWF library Examples -------- If you have |LDAStools.frameCPP|_ installed: 'framecpp' Or, if you don't have |l... |
for lib in APIS:
try:
import_gwf_library(lib)
except ImportError:
continue
else:
return lib
raise ImportError("no GWF API available, please install a third-party GWF "
"library ({}) and try again".format(', '.join(APIS))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_verbose(*args, **kwargs):
"""Utility to print something only if verbose=True is given """ |
if kwargs.pop('verbose', False) is True:
gprint(*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 set_parameter(connection, parameter, value, verbose=False):
"""Set a parameter for the connection, handling errors as warnings """ |
value = str(value)
try:
if not connection.set_parameter(parameter, value):
raise ValueError("invalid parameter or value")
except (AttributeError, ValueError) as exc:
warnings.warn(
'failed to set {}={!r}: {}'.format(parameter, value, str(exc)),
io_nds2.ND... |
<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_series(ts, pad, start, end):
"""Pad a timeseries to match the specified [start, end) limits To cover a gap in data returned from NDS """ |
span = ts.span
pada = max(int((span[0] - start) * ts.sample_rate.value), 0)
padb = max(int((end - span[1]) * ts.sample_rate.value), 0)
if pada or padb:
return ts.pad((pada, padb), mode='constant', constant_values=(pad,))
return ts |
<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_series(ndschan, value, start, end, series_class=TimeSeries):
"""Create a timeseries to cover the specified [start, end) limits To cover a gap in data... |
channel = Channel.from_nds2(ndschan)
nsamp = int((end - start) * channel.sample_rate.value)
return series_class(numpy_ones(nsamp) * value, t0=start,
sample_rate=channel.sample_rate, unit=channel.unit,
channel=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 _get_data_segments(channels, start, end, connection):
"""Get available data segments for the given channels """ |
allsegs = io_nds2.get_availability(channels, start, end,
connection=connection)
return allsegs.intersection(allsegs.keys()) |
<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_git_clone():
"""Returns `True` if the current directory is a git repository Logic is 'borrowed' from :func:`git.repo.fun.is_git_dir` """ |
gitdir = '.git'
return os.path.isdir(gitdir) and (
os.path.isdir(os.path.join(gitdir, 'objects')) and
os.path.isdir(os.path.join(gitdir, 'refs')) and
os.path.exists(os.path.join(gitdir, 'HEAD'))
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reuse_dist_file(filename):
"""Returns `True` if a distribution file can be reused Otherwise it should be regenerated """ |
# if target file doesn't exist, we must generate it
if not os.path.isfile(filename):
return False
# if we can interact with git, we can regenerate it, so we may as well
try:
import git
except ImportError:
return True
else:
try:
git.Repo().tags
... |
<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_gitpython_version():
"""Determine the required version of GitPython Because of target systems running very, very old versions of setuptools, we only spec... |
# if not in git clone, it doesn't matter
if not in_git_clone():
return 'GitPython'
# otherwise, call out to get the git version
try:
gitv = subprocess.check_output('git --version', shell=True)
except (OSError, IOError, subprocess.CalledProcessError):
# no git installation, ... |
<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_setup_requires():
"""Return the list of packages required for this setup.py run """ |
# don't force requirements if just asking for help
if {'--help', '--help-commands'}.intersection(sys.argv):
return list()
# otherwise collect all requirements for all known commands
reqlist = []
for cmd, dependencies in SETUP_REQUIRES.items():
if cmd in sys.argv:
reqlis... |
<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_scripts(scripts_dir='bin'):
"""Get relative file paths for all files under the ``scripts_dir`` """ |
scripts = []
for (dirname, _, filenames) in os.walk(scripts_dir):
scripts.extend([os.path.join(dirname, fn) for fn in filenames])
return scripts |
<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_years(years):
"""Parse string of ints include ranges into a `list` of `int` Source: https://stackoverflow.com/a/6405228/1307974 """ |
result = []
for part in years.split(','):
if '-' in part:
a, b = part.split('-')
a, b = int(a), int(b)
result.extend(range(a, b + 1))
else:
a = int(part)
result.append(a)
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 _format_years(years):
"""Format a list of ints into a string including ranges Source: https://stackoverflow.com/a/9471386/1307974 """ |
def sub(x):
return x[1] - x[0]
ranges = []
for k, iterable in groupby(enumerate(sorted(years)), sub):
rng = list(iterable)
if len(rng) == 1:
s = str(rng[0][1])
else:
s = "{}-{}".format(rng[0][1], rng[-1][1])
ranges.append(s)
return ", ".j... |
<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_copyright(path, year):
"""Update a file's copyright statement to include the given year """ |
with open(path, "r") as fobj:
text = fobj.read().rstrip()
match = COPYRIGHT_REGEX.search(text)
x = match.start("years")
y = match.end("years")
if text[y-1] == " ": # don't strip trailing whitespace
y -= 1
yearstr = match.group("years")
years = set(_parse_years(yearstr)) | {... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def percentile(self, percentile):
"""Calculate a given spectral percentile for this `SpectralVariance` Parameters percentile : `float` percentile (0 - 100) of th... |
rows, columns = self.shape
out = numpy.zeros(rows)
# Loop over frequencies
for i in range(rows):
# Calculate cumulative sum for array
cumsumvals = numpy.cumsum(self.value[i, :])
# Find value nearest requested percentile
abs_cumsumvals_min... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ndstype(self):
"""NDS type integer for this channel. This property is mapped to the `Channel.type` string. """ |
if self.type is not None:
return io_nds2.Nds2ChannelType.find(self.type).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 ndsname(self):
"""Name of this channel as stored in the NDS database """ |
if self.type not in [None, 'raw', 'reduced', 'online']:
return '%s,%s' % (self.name, self.type)
return 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 query(cls, name, use_kerberos=None, debug=False):
"""Query the LIGO Channel Information System for the `Channel` matching the given name Parameters name : `s... |
channellist = ChannelList.query(name, use_kerberos=use_kerberos,
debug=debug)
if not channellist:
raise ValueError("No channels found matching '%s'" % name)
if len(channellist) > 1:
raise ValueError("%d channels found matching '%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 from_nds2(cls, nds2channel):
"""Generate a new channel using an existing nds2.channel object """ |
# extract metadata
name = nds2channel.name
sample_rate = nds2channel.sample_rate
unit = nds2channel.signal_units
if not unit:
unit = None
ctype = nds2channel.channel_type_to_string(nds2channel.channel_type)
# get dtype
dtype = { # pylint: dis... |
<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_channel_name(cls, name, strict=True):
"""Decompose a channel name string into its components Parameters name : `str` name to parse strict : `bool`, opt... |
match = cls.MATCH.search(name)
if match is None or (strict and (
match.start() != 0 or match.end() != len(name))):
raise ValueError("Cannot parse channel name according to LIGO "
"channel-naming convention T990033")
return match.groupdict... |
<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):
"""Returns a copy of this channel """ |
new = type(self)(str(self))
new._init_from_channel(self)
return new |
<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_names(cls, *names):
"""Create a new `ChannelList` from a list of names The list of names can include comma-separated sets of names, in which case the re... |
new = cls()
for namestr in names:
for name in cls._split_names(namestr):
new.append(Channel(name))
return new |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _split_names(namestr):
"""Split a comma-separated list of channel names. """ |
out = []
namestr = QUOTE_REGEX.sub('', namestr)
while True:
namestr = namestr.strip('\' \n')
if ',' not in namestr:
break
for nds2type in io_nds2.Nds2ChannelType.names() + ['']:
if nds2type and ',%s' % nds2type in namestr:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find(self, name):
"""Find the `Channel` with a specific name in this `ChannelList`. Parameters name : `str` name of the `Channel` to find Returns ------- ind... |
for i, chan in enumerate(self):
if name == chan.name:
return i
raise ValueError(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 query(cls, name, use_kerberos=None, debug=False):
"""Query the LIGO Channel Information System a `ChannelList`. Parameters name : `str` name of channel, or p... |
from .io import cis
return cis.query(name, use_kerberos=use_kerberos, debug=debug) |
<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_nds2_availability(cls, channels, start, end, ctype=126, connection=None, host=None, port=None):
"""Query for when data are available for these channels... |
start = int(to_gps(start))
end = int(ceil(to_gps(end)))
chans = io_nds2.find_channels(channels, connection=connection,
unique=True, epoch=(start, end),
type=ctype)
availability = io_nds2.get_availability(chans, ... |
<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_gravityspy_triggers(tablename, engine=None, **kwargs):
"""Fetch data into an `GravitySpyTable` Parameters table : `str`, The name of table you are attemp... |
from sqlalchemy.engine import create_engine
from sqlalchemy.exc import ProgrammingError
# connect if needed
if engine is None:
conn_kw = {}
for key in ('db', 'host', 'user', 'passwd'):
try:
conn_kw[key] = kwargs.pop(key)
except KeyError:
... |
<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_connection_str(db='gravityspy', host='gravityspy.ciera.northwestern.edu', user=None, passwd=None):
"""Create string to pass to create_engine Parameters d... |
if (not user) or (not passwd):
user = os.getenv('GRAVITYSPY_DATABASE_USER', None)
passwd = os.getenv('GRAVITYSPY_DATABASE_PASSWD', None)
if (not user) or (not passwd):
raise ValueError('Remember to either pass '
'or export GRAVITYSPY_DATABASE_USER '
... |
<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_timezone_offset(ifo, dt=None):
"""Return the offset in seconds between UTC and the given interferometer Parameters ifo : `str` prefix of interferometer, ... |
import pytz
dt = dt or datetime.datetime.now()
offset = pytz.timezone(get_timezone(ifo)).utcoffset(dt)
return offset.days * 86400 + offset.seconds + offset.microseconds * 1e-6 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalize_fft_params(series, kwargs=None, func=None):
"""Normalize a set of FFT parameters for processing This method reads the ``fftlength`` and ``overlap``... |
# parse keywords
if kwargs is None:
kwargs = dict()
samp = series.sample_rate
fftlength = kwargs.pop('fftlength', None) or series.duration
overlap = kwargs.pop('overlap', None)
window = kwargs.pop('window', None)
# parse function library and name
if func is None:
method... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.