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 extract_annotation(data): """Extract names and values of rows and columns. Parameter: data : DataFrame | Panel Returns: col_name, col_values, row_name, row_v...
xlabel = None xvalues = None ylabel = None yvalues = None if hasattr(data, 'minor_axis'): xvalues = data.minor_axis if hasattr(data.minor_axis, 'name'): xlabel = data.minor_axis.name if hasattr(data, 'columns'): xvalues = data.columns if hasattr(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 transform_using_this_method(original_sample): """ This function implements a log transformation on the data. """
# Copy the original sample new_sample = original_sample.copy() new_data = new_sample.data # Our transformation goes here new_data['Y2-A'] = log(new_data['Y2-A']) new_data = new_data.dropna() # Removes all NaN entries new_sample.data = new_data return new_sample
<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_data(self, **kwargs): ''' Read the datafile specified in Sample.datafile and return the resulting object. Does NOT assign the data to self.data It's advised not to use this method, but instead to access the data through the FCMeasurement.data attribute. ...
<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_meta_fields(self, fields, kwargs={}): ''' Return a dictionary of metadata fields ''' fields = to_list(fields) meta = self.get_meta() return {field: meta.get(field) for field in fields}
<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, channel_names, kind='histogram', gates=None, gate_colors=None, gate_lw=1, **kwargs): """Plot the flow cytometry data associated with the sample on...
ax = kwargs.get('ax') channel_names = to_list(channel_names) gates = to_list(gates) plot_output = graph.plotFCM(self.data, channel_names, kind=kind, **kwargs) if gates is not None: if gate_colors is None: gate_colors = cycle(('b', 'g', 'r', 'm', '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 view(self, channel_names='auto', gates=None, diag_kw={}, offdiag_kw={}, gate_colors=None, **kwargs): """ Generates a matrix of subplots allowing for a quick ...
if channel_names == 'auto': channel_names = list(self.channel_names) def plot_region(channels, **kwargs): if channels[0] == channels[1]: channels = channels[0] kind = 'histogram' self.plot(channels, kind=kind, gates=gates, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def view_interactively(self, backend='wx'): '''Loads the current sample in a graphical interface for drawing gates. Parameters ---------- backend: 'auto' | 'wx' | 'webagg' Specifies which backend should be used to view the sample. ''' if backend == 'auto': ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform(self, transform, direction='forward', channels=None, return_all=True, auto_range=True, use_spln=True, get_transformer=False, ID=None, apply_now=True...
# Create new measurement new = self.copy() data = new.data channels = to_list(channels) if channels is None: channels = data.columns ## create transformer if isinstance(transform, Transformation): transformer = transform 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 transform(self, transform, direction='forward', share_transform=True, channels=None, return_all=True, auto_range=True, use_spln=True, get_transformer=False, ID=None, apply_now=True, args=(), **kwargs): ''' Apply transform to eac...
<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, gate, ID=None, apply_now=True): ''' Applies the gate to each Measurement in the Collection, returning a new Collection with gated data. {_containers_held_in_memory_warning} Parameters ---------- gate : {_gate_available_classes} ID : [ str, numeri...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def counts(self, ids=None, setdata=False, output_format='DataFrame'): """ Return the counts in each of the specified measurements. Parameters ids : [hashable | i...
return self.apply(lambda x: x.counts, ids=ids, setdata=setdata, output_format=output_format)
<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, channel_names, kind='histogram', gates=None, gate_colors=None, ids=None, row_labels=None, col_labels=None, xlim='auto', ylim='auto', autolabel=True...
## # Note # ------- # The function assumes that grid_plot and FCMeasurement.plot use unique key words. # Any key word arguments that appear in both functions are passed only to grid_plot in the end. ## # Automatically figure out which of the kwargs should ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def obj2unicode(obj): """Return a unicode representation of a python object """
if isinstance(obj, unicode_type): return obj elif isinstance(obj, bytes_type): try: return unicode_type(obj, 'utf-8') except UnicodeDecodeError as strerror: sys.stderr.write("UnicodeDecodeError exception for string '%s': %s\n" % (obj, strerror)) 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 set_chars(self, array): """Set the characters used to draw lines between rows and columns - the array should contain 4 fields: [horizontal, vertical, corner,...
if len(array) != 4: raise ArraySizeError("array should contain 4 characters") array = [ x[:1] for x in [ str(s) for s in array ] ] (self._char_horiz, self._char_vert, self._char_corner, self._char_header) = array 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 set_header_align(self, array): """Set the desired header alignment - the elements of the array should be either "l", "c" or "r": * "l": column flushed left *...
self._check_row_size(array) self._header_align = array 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 set_cols_align(self, array): """Set the desired columns alignment - the elements of the array should be either "l", "c" or "r": * "l": column flushed left * ...
self._check_row_size(array) self._align = array 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 set_cols_valign(self, array): """Set the desired columns vertical alignment - the elements of the array should be either "t", "m" or "b": * "t": column align...
self._check_row_size(array) self._valign = array 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 set_cols_dtype(self, array): """Set the desired columns datatype for the cols. - the elements of the array should be either a callable or any of "a", "t", "f...
self._check_row_size(array) self._dtype = array 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 add_rows(self, rows, header=True): """Add several rows in the rows stack - The 'rows' argument can be either an iterator returning arrays, or a by-dimensiona...
# nb: don't use 'iter' on by-dimensional arrays, to get a # usable code for python 2.1 if header: if hasattr(rows, '__iter__') and hasattr(rows, 'next'): self.header(rows.next()) else: self.header(rows[0]) rows = rows[...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw(self): """Draw the table - the table is returned as a whole string """
if not self._header and not self._rows: return self._compute_cols_width() self._check_align() out = "" if self._has_border(): out += self._hline() if self._header: out += self._draw_line(self._header, isheader=True) if sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fmt_int(cls, x, **kw): """Integer formatting class-method. - x will be float-converted and then used. """
return str(int(round(cls._to_float(x))))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fmt_float(cls, x, **kw): """Float formatting class-method. - x parameter is ignored. Instead kw-argument f being x float-converted will be used. - precision...
n = kw.get('n') return '%.*f' % (n, cls._to_float(x))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fmt_exp(cls, x, **kw): """Exponential formatting class-method. - x parameter is ignored. Instead kw-argument f being x float-converted will be used. - preci...
n = kw.get('n') return '%.*e' % (n, cls._to_float(x))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fmt_auto(cls, x, **kw): """auto formatting class-method."""
f = cls._to_float(x) if abs(f) > 1e8: fn = cls._fmt_exp else: if f - round(f) == 0: fn = cls._fmt_int else: fn = cls._fmt_float return fn(x, **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 _str(self, i, x): """Handles string formatting of cell data i - index of the cell datatype in self._dtype x - cell data to format """
FMT = { 'a':self._fmt_auto, 'i':self._fmt_int, 'f':self._fmt_float, 'e':self._fmt_exp, 't':self._fmt_text, } n = self._precision dtype = self._dtype[i] try: if callable(dtype): return 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 _hline(self): """Print an horizontal line """
if not self._hline_string: self._hline_string = self._build_hline() return self._hline_string
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_hline(self, is_header=False): """Return a string used to separated rows or separate header from rows """
horiz = self._char_horiz if (is_header): horiz = self._char_header # compute cell separator s = "%s%s%s" % (horiz, [horiz, self._char_corner][self._has_vlines()], horiz) # build the line l = s.join([horiz * n for n in self._width]) # add 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 _len_cell(self, cell): """Return the width of the cell Special characters are taken into account to return the width of the cell, such like newlines and tabs...
cell_lines = cell.split('\n') maxi = 0 for line in cell_lines: length = 0 parts = line.split('\t') for part, i in zip(parts, list(range(1, len(parts) + 1))): length = length + len(part) if i < len(parts): 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 region(self, rect): """ Selects a sub-region of the image using the supplied rectangle, x, y, width, height. """
box = (int(rect[0]), int(rect[1]), int(rect[0]) + int(rect[2]), int(rect[1]) + int(rect[3])) if box[2] > self.img.size[0] or box[3] > self.img.size[1]: raise errors.RectangleError("Region out-of-bounds") self.img = self.img.crop(box) 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 derive_signature(key, qs): """Derives the signature from the supplied query string using the key."""
key, qs = (key or "", qs or "") return hmac.new(key.encode(), qs.encode(), hashlib.sha1).hexdigest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sign(key, qs): """Signs the query string using the key."""
sig = derive_signature(key, qs) return "%s&%s" % (qs, urlencode([("sig", sig)]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify_signature(key, qs): """Verifies that the signature in the query string is correct."""
unsigned_qs = re.sub(r'&?sig=[^&]*', '', qs) sig = derive_signature(key, unsigned_qs) return urlparse.parse_qs(qs).get("sig", [None])[0] == sig
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def canonical_name(name): """Find the canonical name for the given window in scipy.signal Parameters name : `str` the name of the window you want Returns -------...
if name.lower() == 'planck': # make sure to handle the Planck window return 'planck' try: # use equivalence introduced in scipy 0.16.0 # pylint: disable=protected-access return scipy_windows._win_equiv[name.lower()].__name__ except AttributeError: # old scipy 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 recommended_overlap(name, nfft=None): """Returns the recommended fractional overlap for the given window If ``nfft`` is given, the return is in samples Param...
try: name = canonical_name(name) except KeyError as exc: raise ValueError(str(exc)) try: rov = ROV[name] except KeyError: raise ValueError("no recommended overlap for %r window" % name) if nfft: return int(ceil(nfft * rov)) return rov
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def planck(N, nleft=0, nright=0): """Return a Planck taper window. Parameters N : `int` Number of samples in the output window nleft : `int`, optional Number of ...
# construct a Planck taper window w = numpy.ones(N) if nleft: w[0] *= 0 zleft = numpy.array([nleft * (1./k + 1./(k-nleft)) for k in range(1, nleft)]) w[1:nleft] *= expit(-zleft) if nright: w[N-1] *= 0 zright = numpy.array([-nright * (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 bool_env(key, default=False): """Parse an environment variable as a boolean switch `True` is returned if the variable value matches one of the following: - `...
try: return os.environ[key].lower() in TRUE except KeyError: return default
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def call(cmd, stdout=PIPE, stderr=PIPE, on_error='raise', **kwargs): """Call out to the shell using `subprocess.Popen` Parameters stdout : `file-like`, optional ...
if isinstance(cmd, (list, tuple)): cmdstr = ' '.join(cmd) kwargs.setdefault('shell', False) else: cmdstr = str(cmd) kwargs.setdefault('shell', True) proc = Popen(cmd, stdout=stdout, stderr=stderr, **kwargs) out, err = proc.communicate() if proc.returncode: 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 read_with_columns(func): """Decorate a Table read method to use the ``columns`` keyword """
def wrapper(*args, **kwargs): # parse columns argument columns = kwargs.pop("columns", None) # read table tab = func(*args, **kwargs) # filter on columns if columns is None: return tab return tab[columns] return _safe_wraps(wrapper, func)
<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_with_selection(func): """Decorate a Table read method to apply ``selection`` keyword """
def wrapper(*args, **kwargs): """Execute a function, then apply a selection filter """ # parse selection selection = kwargs.pop('selection', None) or [] # read table tab = func(*args, **kwargs) # apply selection if selection: return filt...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decorate_registered_reader( name, data_class=EventTable, columns=True, selection=True, ): """Wrap an existing registered reader to use GWpy's input decorator...
reader = registry.get_reader(name, data_class) wrapped = ( # noqa read_with_columns( # use ``columns`` read_with_selection( # use ``selection`` reader )) ) return registry.register_reader(name, data_class, wrapped, force=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def table_from_root(source, treename=None, columns=None, **kwargs): """Read a Table from a ROOT tree """
import root_numpy # parse column filters into tree2array ``selection`` keyword # NOTE: not all filters can be passed directly to root_numpy, so we store # those separately and apply them after-the-fact before returning try: selection = kwargs.pop('selection') 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 table_to_root(table, filename, **kwargs): """Write a Table to a ROOT file """
import root_numpy root_numpy.array2root(table.as_array(), filename, **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 _gps_scale_factory(unit): """Construct a GPSScale for this unit """
class FixedGPSScale(GPSScale): """`GPSScale` for a specific GPS time unit """ name = str('{0}s'.format(unit.long_names[0] if unit.long_names else unit.names[0])) def __init__(self, axis, epoch=None): """ """ super...
<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_epoch(self, epoch): """Set the GPS epoch """
if epoch is None: self._epoch = None return if isinstance(epoch, (Number, Decimal)): self._epoch = float(epoch) else: self._epoch = float(to_gps(epoch))
<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_unit(self, unit): """Set the GPS step scale """
# accept all core time units if unit is None or (isinstance(unit, units.NamedUnit) and unit.physical_type == 'time'): self._unit = unit return # convert float to custom unit in seconds if isinstance(unit, Number): unit = un...
<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_unit_name(self): """Returns the name of the unit for this GPS scale Note that this returns a simply-pluralised version of the name. """
if not self.unit: return None name = sorted(self.unit.names, key=len)[-1] return '%ss' % 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 transform_non_affine(self, values): """Transform an array of GPS times. This method is designed to filter out transformations that will generate text element...
scale = self.scale or 1 epoch = self.epoch or 0 values = numpy.asarray(values) # handle simple or data transformations with floats if self._parents or ( # part of composite transform (from draw()) epoch == 0 and # no large additions scale == 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 deprecated_function(func, warning=DEPRECATED_FUNCTION_WARNING): """Adds a `DeprecationWarning` to a function Parameters func : `callable` the function to dec...
@wraps(func) def wrapped_func(*args, **kwargs): warnings.warn( DEPRECATED_FUNCTION_WARNING.format(func), category=DeprecationWarning, stacklevel=2, ) return func(*args, **kwargs) return wrapped_func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def return_as(returntype): """Decorator to cast return of function as the given type Parameters returntype : `type` the desired return type of the decorated func...
def decorator(func): # @wraps(func) <- we can't use this as normal because it doesn't work # on python < 3 for instance methods, # see workaround below def wrapped(*args, **kwargs): result = func(*args, **kwargs) 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 format_citations(zid, url='https://zenodo.org/', hits=10, tag_prefix='v'): """Query and format a citations page from Zenodo entries Parameters zid : `int`, `...
# query for metadata url = ('{url}/api/records/?' 'page=1&' 'size={hits}&' 'q=conceptrecid:"{id}"&' 'sort=-version&' 'all_versions=True'.format(id=zid, url=url, hits=hits)) metadata = requests.get(url).json() lines = [] for i, hit in enumerate...
<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(source, channels, start=None, end=None, scaled=None, type=None, series_class=TimeSeries): # pylint: disable=redefined-builtin """Read a dict of series f...
# parse input source source = file_list(source) # parse type ctype = channel_dict_kwarg(type, channels, (str,)) # read each individually and append out = series_class.DictClass() for i, file_ in enumerate(source): if i == 1: # force data into fresh memory so that append works ...
<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_gwf(filename, channels, start=None, end=None, scaled=None, ctype=None, series_class=TimeSeries): """Read a dict of series data from a single GWF file Pa...
# parse kwargs if not start: start = 0 if not end: end = 0 span = Segment(start, end) # open file stream = io_gwf.open_gwf(filename, 'r') nframes = stream.GetNumberOfFrames() # find channels out = series_class.DictClass() # loop over frames in GWF i = 0 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _read_channel(stream, num, name, ctype, epoch, start, end, scaled=True, series_class=TimeSeries): """Read a channel from a specific frame in a stream """
data = _get_frdata(stream, num, name, ctype=ctype) return read_frdata(data, epoch, start, end, scaled=scaled, series_class=series_class)
<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_frdata(stream, num, name, ctype=None): """Brute force-ish method to return the FrData structure for a channel This saves on pulling the channel type fro...
ctypes = (ctype,) if ctype else ('adc', 'proc', 'sim') for ctype in ctypes: _reader = getattr(stream, 'ReadFr{0}Data'.format(ctype.title())) try: return _reader(num, name) except IndexError as exc: if FRERR_NO_CHANNEL_OF_TYPE.match(str(exc)): cont...
<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_frdata(frdata, epoch, start, end, scaled=True, series_class=TimeSeries): """Read a series from an `FrData` structure Parameters frdata : `LDAStools.fram...
datastart = epoch + frdata.GetTimeOffset() try: trange = frdata.GetTRange() except AttributeError: # not proc channel trange = 0. # check overlap with user-requested span if (end and datastart >= end) or (trange and datastart + trange < start): raise _Skip() # get sca...
<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_frvect(vect, epoch, start, end, name=None, series_class=TimeSeries): """Read an array from an `FrVect` structure Parameters vect : `LDASTools.frameCPP.F...
# only read FrVect with matching name (or no name set) # frame spec allows for arbitrary other FrVects # to hold other information if vect.GetName() and name and vect.GetName() != name: raise _Skip() # get array arr = vect.GetDataArray() nsamp = arr.size # and dimensions...
<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(tsdict, outfile, start=None, end=None, name='gwpy', run=0, compression=257, compression_level=6): """Write data to a GWF file using the frameCPP API ""...
# set frame header metadata if not start: starts = {LIGOTimeGPS(tsdict[key].x0.value) for key in tsdict} if len(starts) != 1: raise RuntimeError("Cannot write multiple TimeSeries to a single " "frame with different start times, " ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append_to_frame(frame, timeseries, type='proc', channelid=0): # pylint: disable=redefined-builtin """Append data from a `TimeSeries` to a `~frameCPP.FrameH` ...
if timeseries.channel: channel = str(timeseries.channel) else: channel = str(timeseries.name) offset = float(LIGOTimeGPS(timeseries.t0.value) - LIGOTimeGPS(*frame.GetGTime())) # create the data container if type.lower() == 'adc': frdata = frameCPP.FrAdcD...
<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_frvect(timeseries): """Create a `~frameCPP.FrVect` from a `TimeSeries` This method is primarily designed to make writing data to GWF files a bit easie...
# create timing dimension dims = frameCPP.Dimension( timeseries.size, timeseries.dx.value, str(timeseries.dx.unit), 0) # create FrVect vect = frameCPP.FrVect( timeseries.name or '', FRVECT_TYPE_FROM_NUMPY[timeseries.dtype.type], 1, dims, str(timeseries.unit)) # popul...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _bool_segments(array, start=0, delta=1, minlen=1): """Yield segments of consecutive `True` values in a boolean array Parameters array : `iterable` An iterabl...
array = iter(array) i = 0 while True: try: # get next value val = next(array) except StopIteration: # end of array return if val: # start of new segment n = 1 # count consecutive True try: while next(array): # run...
<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_dqflag(self, name=None, minlen=1, dtype=None, round=False, label=None, description=None): """Convert this series into a `~gwpy.segments.DataQualityFlag`. ...
from ..segments import DataQualityFlag # format dtype if dtype is None: dtype = self.t0.dtype if isinstance(dtype, numpy.dtype): # use callable dtype dtype = dtype.type start = dtype(self.t0.value) dt = dtype(self.dt.value) # build 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 bits(self): """list of `Bits` for this `StateVector` :type: `Bits` """
try: return self._bits except AttributeError: if self.dtype.name.startswith(('uint', 'int')): nbits = self.itemsize * 8 self.bits = Bits(['Bit %d' % b for b in range(nbits)], channel=self.channel, epoch=self.epoch)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def boolean(self): """A mapping of this `StateVector` to a 2-D array containing all binary bits as booleans, for each time point. """
try: return self._boolean except AttributeError: nbits = len(self.bits) boolean = numpy.zeros((self.size, nbits), dtype=bool) for i, sample in enumerate(self.value): boolean[i, :] = [int(sample) >> j & 1 for j in range(nbits)] ...
<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_bit_series(self, bits=None): """Get the `StateTimeSeries` for each bit of this `StateVector`. Parameters bits : `list`, optional a list of bit indices or...
if bits is None: bits = [b for b in self.bits if b not in {None, ''}] bindex = [] for bit in bits: try: bindex.append((self.bits.index(bit), bit)) except (IndexError, ValueError) as exc: exc.args = ('Bit %r not found in StateVe...
<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 `StateVector` Parameters source : `str`, `list` Source of data, any of the following: - `str` path of...
return super(StateVector, cls).read(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 to_dqflags(self, bits=None, minlen=1, dtype=float, round=False): """Convert this `StateVector` into a `~gwpy.segments.DataQualityDict` The `StateTimeSeries` ...
from ..segments import DataQualityDict out = DataQualityDict() bitseries = self.get_bit_series(bits=bits) for bit, sts in bitseries.items(): out[bit] = sts.to_dqflag(name=bit, minlen=minlen, round=round, dtype=dtype, ...
<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, bits=None, host=None, port=None, verbose=False, connection=None, type=Nds2ChannelType.any()): """Fetch data from NDS into a `...
new = cls.DictClass.fetch( [channel], start, end, host=host, port=port, verbose=verbose, connection=connection)[channel] if bits: new.bits = bits 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 plot(self, format='segments', bits=None, **kwargs): """Plot the data for this `StateVector` Parameters format : `str`, optional, default: ``'segments'`` The ...
if format == 'timeseries': return super(StateVector, self).plot(**kwargs) if format == 'segments': from ..plot import Plot kwargs.setdefault('xscale', 'auto-gps') return Plot(*self.to_dqflags(bits=bits).values(), projection='segmen...
<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): """Resample this `StateVector` to a new rate Because of the nature of a state-vector, downsampling is done by taking the logical 'and' ...
rate1 = self.sample_rate.value if isinstance(rate, units.Quantity): rate2 = rate.value else: rate2 = float(rate) # upsample if (rate2 / rate1).is_integer(): raise NotImplementedError("StateVector upsampling has not " ...
<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, format=None, coalesce=False, **kwargs): # pylint: disable=redefined-builtin """Read segments from file into a `SegmentList` Parameters file...
def combiner(listofseglists): """Combine `SegmentList` from each file into a single object """ out = cls(seg for seglist in listofseglists for seg in seglist) if coalesce: return out.coalesce() return out return io_read_multi(...
<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(self, target, *args, **kwargs): """Write this `SegmentList` to a file Arguments and keywords depend on the output format, see the online documentation ...
return io_registry.write(self, target, *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 table_from_cwb(source, *args, **kwargs): """Read an `EventTable` from a Coherent WaveBurst ROOT file This function just redirects to the format='root' reader...
return EventTable.read(source, 'waveburst', *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 get_backend_mod(name=None): """Returns the imported module for the given backend name Parameters name : `str`, optional the name of the backend, defaults to ...
if name is None: name = get_backend() backend_name = (name[9:] if name.startswith("module://") else "matplotlib.backends.backend_{}".format(name.lower())) return importlib.import_module(backend_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 _group_axes_data(inputs, separate=None, flat=False): """Determine the number of axes from the input args to this `Plot` Parameters inputs : `list` of array-l...
# determine auto-separation if separate is None and inputs: # if given a nested list of data, multiple axes are required if any(isinstance(x, iterable_types + (dict,)) for x in inputs): separate = True # if data are of different types, default to separate elif not al...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _init_axes(self, data, method='plot', xscale=None, sharex=False, sharey=False, geometry=None, separate=None, **kwargs): """Populate this figure with data, cr...
if isinstance(sharex, bool): sharex = "all" if sharex else "none" if isinstance(sharey, bool): sharey = "all" if sharey else "none" # parse keywords axes_kw = {key: kwargs.pop(key) for key in utils.AXES_PARAMS if key in kwargs} # hand...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refresh(self): """Refresh the current figure """
for cbar in self.colorbars: cbar.draw_all() self.canvas.draw()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """Close the plot and release its memory. """
from matplotlib.pyplot import close for ax in self.axes[::-1]: # avoid matplotlib/matplotlib#9970 ax.set_xscale('linear') ax.set_yscale('linear') # clear the axes ax.cla() # close the figure close(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 get_axes(self, projection=None): """Find all `Axes`, optionally matching the given projection Parameters projection : `str` name of axes types to return Retu...
if projection is None: return self.axes return [ax for ax in self.axes if ax.name == projection.lower()]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def colorbar(self, mappable=None, cax=None, ax=None, fraction=0., label=None, emit=True, **kwargs): """Add a colorbar to the current `Plot` A colorbar must be as...
# pre-process kwargs mappable, kwargs = gcbar.process_colorbar_kwargs( self, mappable, ax, cax=cax, fraction=fraction, **kwargs) # generate colour bar cbar = super(Plot, self).colorbar(mappable, **kwargs) self.colorbars.append(cbar) if label: # mpl<1.3 does...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_colorbar(self, *args, **kwargs): """DEPRECATED, use `Plot.colorbar` instead """
warnings.warn( "{0}.add_colorbar was renamed {0}.colorbar, this warnings will " "result in an error in the future".format(type(self).__name__), DeprecationWarning) return self.colorbar(*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 add_segments_bar(self, segments, ax=None, height=0.14, pad=0.1, sharex=True, location='bottom', **plotargs): """Add a segment bar `Plot` indicating state inf...
# get axes to anchor against if not ax: ax = self.gca() # set options for new axes axes_kw = { 'pad': pad, 'add_to_figure': True, 'sharex': ax if sharex is True else sharex or None, 'axes_class': get_projection_class('segments...
<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_hacr_channels(db=None, gps=None, connection=None, **conectkwargs): """Return the names of all channels present in the given HACR database """
# connect if needed if connection is None: if gps is None: gps = from_gps('now') if db is None: db = get_database_names(gps, gps)[0] connection = connect(db=db, **conectkwargs) # query out = query("select channel from job where monitorName = 'chacr'") ...
<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_hacr_triggers(channel, start, end, columns=HACR_COLUMNS, pid=None, monitor='chacr', selection=None, **connectkwargs): """Fetch a table of HACR triggers i...
if columns is None: columns = HACR_COLUMNS columns = list(columns) span = Segment(*map(to_gps, (start, end))) # parse selection for SQL query (removing leading 'where ') selectionstr = 'and %s' % format_db_selection(selection, engine=None)[6:] # get database names and loop over each o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(db, host=HACR_DATABASE_SERVER, user=HACR_DATABASE_USER, passwd=HACR_DATABASE_PASSWD): """Connect to the given SQL database """
try: import pymysql except ImportError as e: e.args = ('pymysql is required to fetch HACR triggers',) raise return pymysql.connect(host=host, user=user, passwd=passwd, db=db)
<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(querystr, connection=None, **connectkwargs): """Execute a query of the given SQL database """
if connection is None: connection = connect(**connectkwargs) cursor = connection.cursor() cursor.execute(querystr) return cursor.fetchall()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_filter(self, filter_, frequencies=None, dB=True, analog=False, sample_rate=None, **kwargs): """Add a linear time-invariant filter to this BodePlot Parame...
if not analog: if not sample_rate: raise ValueError("Must give sample_rate frequency to display " "digital (analog=False) filter") sample_rate = Quantity(sample_rate, 'Hz').value dt = 2 * pi / sample_rate if not is...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_frequencyseries(self, spectrum, dB=True, power=False, **kwargs): """Plot the magnitude and phase of a complex-valued `FrequencySeries` Parameters spectru...
# parse spectrum arguments kwargs.setdefault('label', spectrum.name) # get magnitude mag = numpy.absolute(spectrum.value) if dB: mag = to_db(mag) if not power: mag *= 2. # get phase phase = numpy.angle(spectrum.value, deg=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 read_omega_scan_config(source): """Parse an Omega-scan configuration file into a `ChannelList` Parameters source : `str` path of Omega configuration file to ...
out = ChannelList() append = out.append if isinstance(source, FILE_LIKE): close = False else: source = open(source, 'r') close = True try: section = None while True: try: line = next(source) except StopIteration: ...
<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_omega_channel(fobj, section=None): """Parse a `Channel` from an Omega-scan configuration file Parameters fobj : `file` the open file-like object to par...
params = OrderedDict() while True: line = next(fobj) if line == '}\n': break key, value = line.split(':', 1) params[key.strip().rstrip()] = omega_param(value) out = Channel(params.get('channelName'), sample_rate=params.get('sampleFrequency'), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def omega_param(val): """Parse a value from an Omega-scan configuration file This method tries to parse matlab-syntax parameters into a `str`, `float`, or `tuple...
val = val.strip().rstrip() if val.startswith(('"', "'")): return str(val[1:-1]) if val.startswith('['): return tuple(map(float, val[1:-1].split())) return float(val)
<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_omega_scan_config(channellist, fobj, header=True): """Write a `ChannelList` to an Omega-pipeline scan configuration file This method is dumb and assume...
if isinstance(fobj, FILE_LIKE): close = False else: fobj = open(fobj, 'w') close = True try: # print header if header: print('# Q Scan configuration file', file=fobj) print('# Generated with GWpy from a ChannelList', file=fobj) group =...
<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_omega_channel(channel, file=sys.stdout): """Print a `Channel` in Omega-pipeline scan format """
print('{', file=file) try: params = channel.params.copy() except AttributeError: params = OrderedDict() params.setdefault('channelName', str(channel)) params.setdefault('alwaysPlotFlag', int(params.pop('important', False))) if channel.frametype: params.setdefault('frameT...
<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_nds2_name(channel): """Returns the NDS2-formatted name for a channel Understands how to format NDS name strings from `gwpy.detector.Channel` and `nds2.c...
if hasattr(channel, 'ndsname'): # gwpy.detector.Channel return channel.ndsname if hasattr(channel, 'channel_type'): # nds2.channel return '%s,%s' % (channel.name, channel.channel_type_to_string(channel.channel_type)) return 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 parse_nds_env(env='NDSSERVER'): """Parse the NDSSERVER environment variable into a list of hosts Parameters env : `str`, optional environment variable name t...
hosts = [] for host in os.getenv(env).split(','): try: host, port = host.rsplit(':', 1) except ValueError: port = None else: port = int(port) if (host, port) not in hosts: hosts.append((host, port)) return hosts
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(host, port=None): """Open an `nds2.connection` to a given host and port Parameters host : `str` name of server with which to connect port : `int`, op...
import nds2 # pylint: disable=no-member # set default port for NDS1 connections (required, I think) if port is None and NDS1_HOSTNAME.match(host): port = 8088 if port is None: return nds2.connection(host) return nds2.connection(host, port)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def auth_connect(host, port=None): """Open an `nds2.connection` handling simple authentication errors This method will catch exceptions related to kerberos authe...
try: return connect(host, port) except RuntimeError as exc: if 'Request SASL authentication' not in str(exc): raise warnings.warn('Error authenticating against {0}:{1}'.format(host, port), NDSWarning) kinit() return connect(host, port)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open_connection(func): """Decorate a function to create a `nds2.connection` if required """
@wraps(func) def wrapped_func(*args, **kwargs): # pylint: disable=missing-docstring if kwargs.get('connection', None) is None: try: host = kwargs.pop('host') except KeyError: raise TypeError("one of `connection` or `host` is required " ...
<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_nds2_enums(func): """Decorate a function to translate a type string into an integer """
@wraps(func) def wrapped_func(*args, **kwargs): # pylint: disable=missing-docstring for kwd, enum_ in (('type', Nds2ChannelType), ('dtype', Nds2DataType)): if kwargs.get(kwd, None) is None: kwargs[kwd] = enum_.any() elif not isinstance...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset_epoch(func): """Wrap a function to reset the epoch when finished This is useful for functions that wish to use `connection.set_epoch`. """
@wraps(func) def wrapped_func(*args, **kwargs): # pylint: disable=missing-docstring connection = kwargs.get('connection', None) epoch = connection.current_epoch() if connection else None try: return func(*args, **kwargs) finally: if epoch is not 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 find_channels(channels, connection=None, host=None, port=None, sample_rate=None, type=Nds2ChannelType.any(), dtype=Nds2DataType.any(), unique=False, epoch='AL...
# set epoch if not isinstance(epoch, tuple): epoch = (epoch or 'All',) connection.set_epoch(*epoch) # format sample_rate as tuple for find_channels call if isinstance(sample_rate, (int, float)): sample_rate = (sample_rate, sample_rate) elif sample_rate is None: sample_r...