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 erb(freq, Hz=None): """ ``B. C. J. Moore and B. R. Glasberg, "Suggested formulae for calculating auditory filter bandwidths and excitation patterns". J. Acou...
if Hz is None: if freq < 7: # Perhaps user tried something up to 2 * pi raise ValueError("Frequency out of range.") Hz = 1 fHz = freq / Hz result = 6.23e-6 * fHz ** 2 + 93.39e-3 * fHz + 28.52 return result * Hz
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gammatone(freq, bandwidth): """ ``A. Klapuri, "Multipich Analysis of Polyphonic Music and Speech Signals Using an Auditory Model". IEEE Transactions on Audio...
bw = thub(bandwidth, 1) bw2 = thub(bw * 2, 4) freq = thub(freq, 4) resons = [resonator.z_exp, resonator.poles_exp] * 2 return CascadeFilter(reson(freq, bw2) for reson in resons)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _generate_window_strategies(): """ Create all window and wsymm strategies """
for wnd_dict in window._content_generation_table: names = wnd_dict["names"] sname = wnd_dict["sname"] = names[0] wnd_dict.setdefault("params_def", "") for sdict in [window, wsymm]: docs_dict = window._doc_kwargs(symm = sdict is wsymm, **wnd_dict) decorators = [format_docstring(**docs_dict...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def acorr(blk, max_lag=None): """ Calculate the autocorrelation of a given 1-D block sequence. Parameters blk : An iterable with well-defined length. Don't use t...
if max_lag is None: max_lag = len(blk) - 1 return [sum(blk[n] * blk[n + tau] for n in xrange(len(blk) - tau)) for tau in xrange(max_lag + 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 lag_matrix(blk, max_lag=None): """ Finds the lag matrix for a given 1-D block sequence. Parameters blk : An iterable with well-defined length. Don't use this...
if max_lag is None: max_lag = len(blk) - 1 elif max_lag >= len(blk): raise ValueError("Block length should be higher than order") return [[sum(blk[n - i] * blk[n - j] for n in xrange(max_lag, len(blk)) ) for i in xrange(max_lag + 1) ] for j in xrange(max_lag + 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 dft(blk, freqs, normalize=True): """ Complex non-optimized Discrete Fourier Transform Finds the DFT for values in a given frequency list, in order, over the ...
dft_data = (sum(xn * cexp(-1j * n * f) for n, xn in enumerate(blk)) for f in freqs) if normalize: lblk = len(blk) return [v / lblk for v in dft_data] return list(dft_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 zcross(seq, hysteresis=0, first_sign=0): """ Zero-crossing stream. Parameters seq : Any iterable to be used as input for the zero crossing analysis hysteresi...
neg_hyst = -hysteresis seq_iter = iter(seq) # Gets the first sign if first_sign == 0: last_sign = 0 for el in seq_iter: yield 0 if (el > hysteresis) or (el < neg_hyst): # Ignores hysteresis region last_sign = -1 if el < 0 else 1 # Define the first sign break else: las...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clip(sig, low=-1., high=1.): """ Clips the signal up to both a lower and a higher limit. Parameters sig : The signal to be clipped, be it a Stream instance, ...
if low is None: if high is None: return Stream(sig) return Stream(el if el < high else high for el in sig) if high is None: return Stream(el if el > low else low for el in sig) if high < low: raise ValueError("Higher clipping limit is smaller than lower one") return Stream(high if el > hi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unwrap(sig, max_delta=pi, step=2*pi): """ Parametrized signal unwrapping. Parameters sig : An iterable seen as an input signal. max_delta : Maximum value of ...
idata = iter(sig) d0 = next(idata) yield d0 delta = d0 - d0 # Get the zero (e.g., integer, float) from data for d1 in idata: d_diff = d1 - d0 if abs(d_diff) > max_delta: delta += - d_diff + min((d_diff) % step, (d_diff) % -step, key=lambda x: abs(x)) yield d1 +...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def amdf(lag, size): """ Average Magnitude Difference Function non-linear filter for a given size and a fixed lag. Parameters lag : Time lag, in samples. See ``f...
filt = (1 - z ** -lag).linearize() @tostream def amdf_filter(sig, zero=0.): return maverage(size)(abs(filt(sig, zero=zero)), zero=zero) return amdf_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 overlap_add(blk_sig, size=None, hop=None, wnd=None, normalize=True): """ Overlap-add algorithm using Numpy arrays. Parameters blk_sig : An iterable of blocks...
import numpy as np # Finds the size from data, if needed if size is None: blk_sig = Stream(blk_sig) size = len(blk_sig.peek()) if hop is None: hop = size # Find the right windowing function to be applied if wnd is None: wnd = np.ones(size) elif callable(wnd) and not isinstance(wnd, Stre...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def overlap_add(blk_sig, size=None, hop=None, wnd=None, normalize=True): """ Overlap-add algorithm using lists instead of Numpy arrays. The behavior is the same ...
# Finds the size from data, if needed if size is None: blk_sig = Stream(blk_sig) size = len(blk_sig.peek()) if hop is None: hop = size # Find the window to be applied, resulting on a list or None if wnd is not None: if callable(wnd) and not isinstance(wnd, Stream): wnd = wnd(size) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stft(func=None, **kwparams): """ Short Time Fourier Transform for complex data. Same to the default STFT strategy, but with new defaults. This is the same to...
from numpy.fft import fft, ifft return stft.base(transform=fft, inverse_transform=ifft)(func, **kwparams)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stft(func=None, **kwparams): """ Short Time Fourier Transform for real data keeping the full FFT block. Same to the default STFT strategy, but with new defau...
from numpy.fft import fft, ifft ifft_r = lambda *args: ifft(*args).real return stft.base(transform=fft, inverse_transform=ifft_r)(func, **kwparams)
<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): """ Destructor for this audio interface. Waits the threads to finish their streams, if desired. """
with self.halting: # Avoid simultaneous "close" threads if not self.finished: # Ignore all "close" calls, but the first, self.finished = True # and any call to play would raise ThreadError # Closes all playing AudioThread instances while True: with self.lock: # Ensure the...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def record(self, chunk_size = None, dfmt = "f", channels = 1, rate = DEFAULT_SAMPLE_RATE, **kwargs ): """ Records audio from device into a Stream. Parameters chu...
if chunk_size is None: chunk_size = chunks.size if hasattr(self, "api"): kwargs.setdefault("input_device_index", self.api["defaultInputDevice"]) channels = kwargs.pop("nchannels", channels) # Backwards compatibility input_stream = RecStream(self, self._pa.ope...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """ Plays the audio. This method plays the audio, and shouldn't be called explicitly, let the constructor do so. """
# From now on, it's multi-thread. Let the force be with them. st = self.stream._stream for chunk in chunks(self.audio, size=self.chunk_size*self.nchannels, dfmt=self.dfmt): #Below is a faster way to call: # self.stream.write(chunk, self.chunk_si...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop(self): """ Stops the playing thread and close """
with self.lock: self.halting = True self.go.clear()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def freq2midi(freq): """ Given a frequency in Hz, returns its MIDI pitch number. """
result = 12 * (log2(freq) - log2(FREQ_A4)) + MIDI_A4 return nan if isinstance(result, complex) else 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 octaves(freq, fmin=20., fmax=2e4): """ Given a frequency and a frequency range, returns all frequencies in that range that is an integer number of octaves re...
# Input validation if any(f <= 0 for f in (freq, fmin, fmax)): raise ValueError("Frequencies have to be positive") # If freq is out of range, avoid range extension while freq < fmin: freq *= 2 while freq > fmax: freq /= 2 if freq < fmin: # Gone back and forth return [] # Finds the range...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def image_path_processor_factory(path): """ Processor for concatenating the ``path`` to relative path images """
def processor(line): markup = ".. image::" if line.startswith(markup): fname = line[len(markup):].strip() if not(fname.startswith("/") or "://" in fname): return "{} {}{}".format(markup, path, fname) return line return processor
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delay(sig): """ Simple feedforward delay effect """
smix = Streamix() sig = thub(sig, 3) # Auto-copy 3 times (remove this line if using feedback) smix.add(0, sig) # To get a feedback delay, use "smix.copy()" below instead of both "sig" smix.add(280 * ms, .1 * sig) # You can also try other constants smix.add(220 * ms, .1 * sig) return smix
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def note2snd(pitch, quarters): """ Creates an audio Stream object for a single note. Parameters pitch : Pitch note like ``"A4"``, as a string, or ``None`` for a ...
dur = quarters * quarter_dur if pitch is None: return zeros(dur) freq = str2freq(pitch) * Hz return synth(freq, dur)
<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_full_name(prefix, suffix="rst"): """ Script path to actual path relative file name converter. Parameters prefix : File name prefix (without extension), ...
return os.path.join(os.path.split(__file__)[0], os.path.extsep.join([prefix, 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 save_to_rst(prefix, data): """ Saves a RST file with the given prefix into the script file location. """
with open(find_full_name(prefix), "w") as rst_file: rst_file.write(full_gpl_for_rst) rst_file.write(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 ks_synth(freq): """ Synthesize the given frequency into a Stream by using a model based on Karplus-Strong. """
ks_mem = (sum(lz.sinusoid(x * freq) for x in [1, 3, 9]) + lz.white_noise() + lz.Stream(-1, 1)) / 5 return lz.karplus_strong(freq, memory=ks_mem)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def m21_to_stream(score, synth=ks_synth, beat=90, fdur=2., pad_dur=.5, rate=lz.DEFAULT_SAMPLE_RATE): """ Converts Music21 data to a Stream object. Parameters sco...
# Configuration s, Hz = lz.sHz(rate) step = 60. / beat * s # Creates a score from the music21 data score = reduce(operator.concat, [[(pitch.frequency * Hz, # Note note.offset * step, # Starting time note.quarterLength * step, # Duration ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pair_strings_sum_formatter(a, b): """ Formats the sum of a and b. Note ---- Both inputs are numbers already converted to strings. """
if b[:1] == "-": return "{0} - {1}".format(a, b[1:]) return "{0} + {1}".format(a, b)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def float_str(value, symbol_str="", symbol_value=1, after=False, max_denominator=1000000): """ Pretty rational string from float numbers. Converts a given numeri...
if value == 0: return "0" frac = Fraction(value/symbol_value).limit_denominator(max_denominator) num, den = frac.numerator, frac.denominator output_data = [] if num < 0: num = -num output_data.append("-") if (num != 1) or (symbol_str == "") or after: output_data.append(str(num)) 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 small_doc(obj, indent="", max_width=80): """ Finds a useful small doc representation of an object. Parameters obj : Any object, which the documentation repre...
if not getattr(obj, "__doc__", False): data = [el.strip() for el in str(obj).splitlines()] if len(data) == 1: if data[0].startswith("<audiolazy.lazy_"): # Instance data = data[0].split("0x", -1)[0] + "0x...>" # Hide its address else: data = "".join(["``", data[0], "``"]) 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 meta(*bases, **kwargs): """ Allows unique syntax similar to Python 3 for working with metaclasses in both Python 2 and Python 3. Examples -------- True 'HUA ...
metaclass = kwargs.get("metaclass", type) if not bases: bases = (object,) class NewMeta(type): def __new__(mcls, name, mbases, namespace): if name: return metaclass.__new__(metaclass, name, bases, namespace) return super(NewMeta, mcls).__new__(mcls, "", mbases, {}) return NewMeta(""...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attack(a, d, s): """ Linear ADS fading attack stream generator, useful to be multiplied with a given stream. Parameters a : "Attack" time, in number of sampl...
# Configure sustain possibilities if isinstance(s, collections.Iterable): it_s = iter(s) s = next(it_s) else: it_s = None # Attack and decay lines m_a = 1. / a m_d = (s - 1.) / d len_a = int(a + .5) len_d = int(d + .5) for sample in xrange(len_a): yield sample * m_a for sample in 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 ones(dur=None): """ Ones stream generator. You may multiply your endless stream by this to enforce an end to it. Parameters dur : Duration, in number of samp...
if dur is None or (isinf(dur) and dur > 0): while True: yield 1.0 for x in xrange(int(.5 + dur)): yield 1.0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def adsr(dur, a, d, s, r): """ Linear ADSR envelope. Parameters dur : Duration, in number of samples, including the release time. a : "Attack" time, in number of...
m_a = 1. / a m_d = (s - 1.) / d m_r = - s * 1. / r len_a = int(a + .5) len_d = int(d + .5) len_r = int(r + .5) len_s = int(dur + .5) - len_a - len_d - len_r for sample in xrange(len_a): yield sample * m_a for sample in xrange(len_d): yield 1. + sample * m_d for sample in xrange(len_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 white_noise(dur=None, low=-1., high=1.): """ White noise stream generator. Parameters dur : Duration, in number of samples; endless if not given (or None). l...
if dur is None or (isinf(dur) and dur > 0): while True: yield random.uniform(low, high) for x in xrange(rint(dur)): yield random.uniform(low, high)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sinusoid(freq, phase=0.): """ Sinusoid based on the optimized math.sin """
# When at 44100 samples / sec, 5 seconds of this leads to an error of 8e-14 # peak to peak. That's fairly enough. for n in modulo_counter(start=phase, modulo=2 * pi, step=freq): yield sin(n)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def impulse(dur=None, one=1., zero=0.): """ Impulse stream generator. Parameters dur : Duration, in number of samples; endless if not given. Returns ------- Stre...
if dur is None or (isinf(dur) and dur > 0): yield one while True: yield zero elif dur >= .5: num_samples = int(dur - .5) yield one for x in xrange(num_samples): yield zero
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def karplus_strong(freq, tau=2e4, memory=white_noise): """ Karplus-Strong "digitar" synthesis algorithm. Parameters freq : Frequency, in rad/sample. tau : Time d...
return comb.tau(2 * pi / freq, tau).linearize()(zeros(), memory=memory)
<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(self): """ Returns a new table with values ranging from -1 to 1, reaching at least one of these, unless there's no data. """
max_abs = max(self.table, key=abs) if max_abs == 0: raise ValueError("Can't normalize zeros") return self / max_abs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def strategy(self, *names, **kwargs): """ StrategyDict wrapping method for adding a new strategy. Parameters *names : Positional arguments with all names (string...
def decorator(func): keep_name = kwargs.pop("keep_name", False) if kwargs: key = next(iter(kwargs)) raise TypeError("Unknown keyword argument '{}'".format(key)) if not keep_name: func.__name__ = str(names[0]) self[names] = func return self return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def call_sphinx(out_type, build_dir = "build"): """ Call the ``sphinx-build`` for the given output type and the ``make`` when the target has this possibility. Pa...
sphinx_string = sphinx_template.format(build_dir=build_dir, out_type=out_type) if sphinx.main(shlex.split(sphinx_string)) != 0: raise RuntimeError("Something went wrong while building '{0}'" .format(out_type)) if out_type in make_target: mak...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def levinson_durbin(acdata, order=None): """ Solve the Yule-Walker linear system of equations. They're given by: .. math:: R . a = r where :math:`R` is a simmetr...
if order is None: order = len(acdata) - 1 elif order >= len(acdata): acdata = Stream(acdata).append(0).take(order + 1) # Inner product for filters based on above statistics def inner(a, b): # Be careful, this depends on acdata !!! return sum(acdata[abs(i-j)] * ai * bj for i, ai in e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def should_skip(app, what, name, obj, skip, options): """ Callback object chooser function for docstring documentation. """
if name in ["__doc__", "__module__", "__dict__", "__weakref__", "__abstractmethods__" ] or name.startswith("_abc_"): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup(app): """ Just connects the docstring pre_processor and should_skip functions to be applied on all docstrings. """
app.connect('autodoc-process-docstring', lambda *args: pre_processor(*args, namer=audiolazy_namer)) app.connect('autodoc-skip-member', should_skip)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def newest_file(file_iterable): """ Returns the name of the newest file given an iterable of file names. """
return max(file_iterable, key=lambda fname: os.path.getmtime(fname))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def overlap_correlation(wnd, hop): """ Overlap correlation percent for the given overlap hop in samples. """
return sum(wnd * Stream(wnd).skip(hop)) / sum(el ** 2 for el in wnd)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scalloping_loss(wnd): """ Positive number with the scalloping loss in dB. """
return -dB20(abs(sum(wnd * cexp(line(len(wnd), 0, -1j * pi)))) / sum(wnd))
<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_xdb_bin(wnd, power=.5, res=1500): """ A not so fast way to find the x-dB cutoff frequency "bin" index. Parameters wnd: The window itself as an iterable....
spectrum = dB20(rfft(wnd, res * len(wnd))) root_at_xdb = spectrum - spectrum[0] - dB10(power) return next(i for i, el in enumerate(zcross(root_at_xdb)) if el) / res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rint(x, step=1): """ Round to integer. Parameters x : Input number (integer or float) to be rounded. step : Quantization level (defaults to 1). If set to 2, ...
div, mod = divmod(x, step) err = min(step / 10., .1) result = div * step if x > 0: result += err elif x < 0: result -= err if (operator.ge if x >= 0 else operator.gt)(2 * mod, step): result += step return int(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 blocks(seq, size=None, hop=None, padval=0.): """ General iterable blockenizer. Generator that gets ``size`` elements from ``seq``, and outputs them in a coll...
# Initialization res = deque(maxlen=size) # Circular queue idx = 0 last_idx = size - 1 if hop is None: hop = size reinit_idx = size - hop # Yields each block, keeping last values when needed if hop <= size: for el in seq: res.append(el) if idx == last_idx: yield res ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def elementwise(name="", pos=None): """ Function auto-map decorator broadcaster. Creates an "elementwise" decorator for one input parameter. To create such, it s...
if (name == "") and (pos is None): pos = 0 def elementwise_decorator(func): """ Element-wise decorator for functions known to have 1 input and 1 output be applied directly on iterables. When made to work with more than 1 input, all "secondary" parameters will the same in all function calls ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def almost_eq(a, b, bits=32, tol=1, ignore_type=True, pad=0.): """ Almost equal, based on the amount of floating point significand bits. Alternative to "a == b" ...
if not (ignore_type or type(a) == type(b)): return False is_it_a = isinstance(a, Iterable) is_it_b = isinstance(b, Iterable) if is_it_a != is_it_b: return False if is_it_a: return all(almost_eq.bits(ai, bi, bits, tol, ignore_type) for ai, bi in xzip_longest(a, b, fillvalue=pad)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cached(func): """ Cache decorator for a function without keyword arguments You can access the cache contents using the ``cache`` attribute in the resulting f...
class Cache(dict): def __missing__(self, key): result = self[key] = func(*key) return result cache = Cache() f = wraps(func)(lambda *key: cache[key]) f.cache = cache return 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 find_dates(text, source=False, index=False, strict=False, base_date=None): """ Extract datetime strings from text :param text: A string that contains one or ...
date_finder = DateFinder(base_date=base_date) return date_finder.find_dates(text, source=source, index=index, strict=strict)
<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_tzinfo(self, datetime_obj, tz_string): """ take a naive datetime and add dateutil.tz.tzinfo object :param datetime_obj: naive datetime object :return: d...
if datetime_obj is None: return None tzinfo_match = tz.gettz(tz_string) return datetime_obj.replace(tzinfo=tzinfo_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 check_style(value): """ Validate a logging format style. :param value: The logging format style to validate (any value). :returns: The logging format charact...
if sys.version_info[:2] >= (3, 2): if value not in FORMAT_STYLE_PATTERNS: msg = "Unsupported logging format style! (%r)" raise ValueError(format(msg, value)) elif value != DEFAULT_FORMAT_STYLE: msg = "Format string styles other than %r require Python 3.2+!" 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 increase_verbosity(): """ Increase the verbosity of the root handler by one defined level. Understands custom logging levels like defined by my ``verboselogs...
defined_levels = sorted(set(find_defined_levels().values())) current_index = defined_levels.index(get_level()) selected_index = max(0, current_index - 1) set_level(defined_levels[selected_index])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decrease_verbosity(): """ Decrease the verbosity of the root handler by one defined level. Understands custom logging levels like defined by my ``verboselogs...
defined_levels = sorted(set(find_defined_levels().values())) current_index = defined_levels.index(get_level()) selected_index = min(current_index + 1, len(defined_levels) - 1) set_level(defined_levels[selected_index])
<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_level(): """ Get the logging level of the root handler. :returns: The logging level of the root handler (an integer) or :data:`DEFAULT_LOG_LEVEL` (if no ...
handler, logger = find_handler(logging.getLogger(), match_stream_handler) return handler.level if handler else DEFAULT_LOG_LEVEL
<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_level(level): """ Set the logging level of the root handler. :param level: The logging level to filter on (an integer or string). If no root handler exis...
handler, logger = find_handler(logging.getLogger(), match_stream_handler) if handler and logger: # Change the level of the existing handler. handler.setLevel(level_to_number(level)) # Adjust the level of the selected logger. adjust_level(logger, level) else: # Create...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def adjust_level(logger, level): """ Increase a logger's verbosity up to the requested level. :param logger: The logger to change (a :class:`~logging.Logger` obj...
level = level_to_number(level) if logger.getEffectiveLevel() > level: logger.setLevel(level)
<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_defined_levels(): """ Find the defined logging levels. :returns: A dictionary with level names as keys and integers as values. Here's what the result lo...
defined_levels = {} for name in dir(logging): if name.isupper(): value = getattr(logging, name) if isinstance(value, int): defined_levels[name] = value return defined_levels
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def level_to_number(value): """ Coerce a logging level name to a number. :param value: A logging level (integer or string). :returns: The number of the log level...
if is_string(value): try: defined_levels = find_defined_levels() value = defined_levels[value.upper()] except KeyError: # Don't fail on unsupported log levels. value = DEFAULT_LOG_LEVEL return 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 find_level_aliases(): """ Find log level names which are aliases of each other. :returns: A dictionary that maps aliases to their canonical name. .. note:: C...
mapping = collections.defaultdict(list) for name, value in find_defined_levels().items(): mapping[value].append(name) aliases = {} for value, names in mapping.items(): if len(names) > 1: names = sorted(names, key=lambda n: len(n)) canonical_name = names.pop() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_encoded_styles(text, normalize_key=None): """ Parse text styles encoded in a string into a nested data structure. :param text: The encoded styles (a st...
parsed_styles = {} for assignment in split(text, ';'): name, _, styles = assignment.partition('=') target = parsed_styles.setdefault(name, {}) for token in split(styles, ','): # When this code was originally written, setting background colors # wasn't supported y...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_hostname(use_chroot=True): """ Find the host name to include in log messages. :param use_chroot: Use the name of the chroot when inside a chroot? (boole...
for chroot_file in CHROOT_FILES: try: with open(chroot_file) as handle: first_line = next(handle) name = first_line.strip() if name: return name except Exception: pass return socket.gethostname()
<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_program_name(): """ Select a suitable program name to embed in log messages. :returns: One of the following strings (in decreasing order of preference):...
# Gotcha: sys.argv[0] is '-c' if Python is started with the -c option. return ((os.path.basename(sys.argv[0]) if sys.argv and sys.argv[0] != '-c' else '') or (os.path.basename(sys.executable) if sys.executable else '') or 'python')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replace_handler(logger, match_handler, reconfigure): """ Prepare to replace a handler. :param logger: Refer to :func:`find_handler()`. :param match_handler: ...
handler, other_logger = find_handler(logger, match_handler) if handler and other_logger and reconfigure: # Remove the existing handler from the logger that its attached to # so that we can install a new handler that behaves differently. other_logger.removeHandler(handler) # Swit...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def walk_propagation_tree(logger): """ Walk through the propagation hierarchy of the given logger. :param logger: The logger whose hierarchy to walk (a :class:`~...
while isinstance(logger, logging.Logger): # Yield the logger to our caller. yield logger # Check if the logger has propagation enabled. if logger.propagate: # Continue with the parent logger. We use getattr() because the # `parent' attribute isn't documented ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def colorize_format(self, fmt, style=DEFAULT_FORMAT_STYLE): """ Rewrite a logging format string to inject ANSI escape sequences. :param fmt: The log format strin...
result = [] parser = FormatStringParser(style=style) for group in parser.get_grouped_pairs(fmt): applicable_styles = [self.nn.get(self.field_styles, token.name) for token in group if token.name] if sum(map(bool, applicable_styles)) == 1: # If exactly one ...
<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(self, record): """ Apply level-specific styling to log records. :param record: A :class:`~logging.LogRecord` object. :returns: The result of :func:`lo...
style = self.nn.get(self.level_styles, record.levelname) # After the introduction of the `Empty' class it was reported in issue # 33 that format() can be called when `Empty' has already been garbage # collected. This explains the (otherwise rather out of place) `Empty # is not N...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_pairs(self, format_string): """ Tokenize a logging format string and extract field names from tokens. :param format_string: The logging format string. :r...
for token in self.get_tokens(format_string): match = self.name_pattern.search(token) name = match.group(1) if match else None yield FormatStringToken(name=name, text=token)
<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_pattern(self, field_name): """ Get a regular expression to match a formatting directive that references the given field name. :param field_name: The name...
return re.compile(self.raw_pattern.replace(r'\w+', field_name), re.VERBOSE)
<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_tokens(self, format_string): """ Tokenize a logging format string. :param format_string: The logging format string. :returns: A list of strings with form...
return [t for t in self.tokenize_pattern.split(format_string) if 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 normalize_name(self, name): """ Normalize a field or level name. :param name: The field or level name (a string). :returns: The normalized name (a string). T...
name = name.lower() if name in self.aliases: name = self.aliases[name] return name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """Command line interface for the ``coloredlogs`` program."""
actions = [] try: # Parse the command line arguments. options, arguments = getopt.getopt(sys.argv[1:], 'cdh', [ 'convert', 'to-html', 'demo', 'help', ]) # Map command line options to actions. for option, value in options: if option in ('-c', '--co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def capture(command, encoding='UTF-8'): """ Capture the output of an external command as if it runs in an interactive terminal. :param command: The command name ...
with open(os.devnull, 'wb') as dev_null: # We start by invoking the `script' program in a form that is supported # by the Linux implementation [1] but fails command line validation on # the MacOS (BSD) implementation [2]: The command is specified using # the -c option and the typesc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert(text, code=True, tabsize=4): """ Convert text with ANSI escape sequences to HTML. :param text: The text with ANSI escape sequences (a string). :param...
output = [] in_span = False compatible_text_styles = { # The following ANSI text styles have an obvious mapping to CSS. ANSI_TEXT_STYLES['bold']: {'font-weight': 'bold'}, ANSI_TEXT_STYLES['strike_through']: {'text-decoration': 'line-through'}, ANSI_TEXT_STYLES['underline']: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode_whitespace(text, tabsize=4): """ Encode whitespace so that web browsers properly render it. :param text: The plain text (a string). :param tabsize: Re...
# Convert Windows line endings (CR+LF) to UNIX line endings (LF). text = text.replace('\r\n', '\n') # Convert UNIX line endings (LF) to HTML line endings (<br>). text = text.replace('\n', '<br>\n') # Convert tabs to spaces. text = text.expandtabs(tabsize) # Convert leading spaces (that is 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 html_encode(text): """ Encode characters with a special meaning as HTML. :param text: The plain text (a string). :returns: The text converted to HTML (a stri...
text = text.replace('&', '&amp;') text = text.replace('<', '&lt;') text = text.replace('>', '&gt;') text = text.replace('"', '&quot;') return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_hex_color(value): """ Convert a CSS color in hexadecimal notation into its R, G, B components. :param value: A CSS color in hexadecimal notation (a str...
if value.startswith('#'): value = value[1:] if len(value) == 3: return ( int(value[0] * 2, 16), int(value[1] * 2, 16), int(value[2] * 2, 16), ) elif len(value) == 6: return ( int(value[0:2], 16), int(value[2:4], 16)...
<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_syslog_address(): """ Find the most suitable destination for system log messages. :returns: The pathname of a log device (a string) or an address/port t...
if sys.platform == 'darwin' and os.path.exists(LOG_DEVICE_MACOSX): return LOG_DEVICE_MACOSX elif os.path.exists(LOG_DEVICE_UNIX): return LOG_DEVICE_UNIX else: return 'localhost', logging.handlers.SYSLOG_UDP_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 generate_screenshots(): """Generate screenshots from shell scripts."""
this_script = os.path.abspath(__file__) this_directory = os.path.dirname(this_script) repository = os.path.join(this_directory, os.pardir) examples_directory = os.path.join(repository, 'docs', 'examples') images_directory = os.path.join(repository, 'docs', 'images') for shell_script in sorted(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 interpret_script(shell_script): """Make it appear as if commands are typed into the terminal."""
with CaptureOutput() as capturer: shell = subprocess.Popen(['bash', '-'], stdin=subprocess.PIPE) with open(shell_script) as handle: for line in handle: sys.stdout.write(ansi_wrap('$', color='green') + ' ' + line) sys.stdout.flush() shell.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 get_version(*args): """Extract the version number from a Python module."""
contents = get_contents(*args) metadata = dict(re.findall('__([a-z]+)__ = [\'"]([^\'"]+)', contents)) return metadata['version']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def have_environment_marker_support(): """ Check whether setuptools has support for PEP-426 environment marker support. Based on the ``setup.py`` script of the `...
try: from pkg_resources import parse_version from setuptools import __version__ return parse_version(__version__) >= parse_version('0.7.2') except Exception: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _log_http_event(response): """ It will create a log event as werkzeug but at the end of request holding the request-id Intended usage is a handler of Flask.a...
logger.info( '{ip} - - "{method} {path} {status_code}"'.format( ip=request.remote_addr, method=request.method, path=request.path, status_code=response.status_code) ) return response
<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_valid_time(time, step): """ Return dimensions and data of the valid_time corresponding to the given ``time`` and ``step``. The data is seconds from the...
step_s = step * 3600 if len(time.shape) == 0 and len(step.shape) == 0: data = time + step_s dims = () # type: T.Tuple[str, ...] elif len(time.shape) > 0 and len(step.shape) == 0: data = time + step_s dims = ('time',) elif len(time.shape) == 0 and len(step.shape) > 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 open_file(path, grib_errors='warn', **kwargs): """Open a GRIB file as a ``cfgrib.Dataset``."""
if 'mode' in kwargs: warnings.warn("the `mode` keyword argument is ignored and deprecated", FutureWarning) kwargs.pop('mode') stream = messages.FileStream(path, message_class=cfmessage.CfMessage, errors=grib_errors) return Dataset(*build_dataset_components(stream, **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 open_dataset(path, **kwargs): # type: (str, T.Any) -> xr.Dataset """ Return a ``xr.Dataset`` with the requested ``backend_kwargs`` from a GRIB file. """
if 'engine' in kwargs and kwargs['engine'] != 'cfgrib': raise ValueError("only engine=='cfgrib' is supported") kwargs['engine'] = 'cfgrib' return xr.backends.api.open_dataset(path, **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 open_datasets(path, backend_kwargs={}, no_warn=False, **kwargs): # type: (str, T.Dict[str, T.Any], bool, T.Any) -> T.List[xr.Dataset] """ Open a GRIB file gr...
if not no_warn: warnings.warn("open_datasets is an experimental API, DO NOT RELY ON IT!", FutureWarning) fbks = [] datasets = [] try: datasets.append(open_dataset(path, backend_kwargs=backend_kwargs, **kwargs)) except DatasetBuildError as ex: fbks.extend(ex.args[2]) # N...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def codes_get_size(handle, key): # type: (cffi.FFI.CData, str) -> int """ Get the number of coded value from a key. If several keys of the same name are present,...
size = ffi.new('size_t *') _codes_get_size(handle, key.encode(ENC), size) return size[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 codes_get_string_length(handle, key): # type: (cffi.FFI.CData, str) -> int """ Get the length of the string representation of the key. If several keys of the...
size = ffi.new('size_t *') _codes_get_length(handle, key.encode(ENC), size) return size[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 codes_get_bytes_array(handle, key, size): # type: (cffi.FFI.CData, str, int) -> T.List[int] """ Get unsigned chars array values from a key. :param bytes key:...
values = ffi.new('unsigned char[]', size) size_p = ffi.new('size_t *', size) _codes_get_bytes(handle, key.encode(ENC), values, size_p) return list(values)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def codes_get_long_array(handle, key, size): # type: (cffi.FFI.CData, str, int) -> T.List[int] """ Get long array values from a key. :param bytes key: the keywor...
values = ffi.new('long[]', size) size_p = ffi.new('size_t *', size) _codes_get_long_array(handle, key.encode(ENC), values, size_p) return list(values)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def codes_get_double_array(handle, key, size): # type: (cffi.FFI.CData, str, int) -> T.List[float] """ Get double array values from a key. :param bytes key: the ...
values = ffi.new('double[]', size) size_p = ffi.new('size_t *', size) _codes_get_double_array(handle, key.encode(ENC), values, size_p) return list(values)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def codes_get_string_array(handle, key, size, length=None): # type: (cffi.FFI.CData, bytes, int, int) -> T.List[bytes] """ Get string array values from a key. :p...
if length is None: length = codes_get_string_length(handle, key) values_keepalive = [ffi.new('char[]', length) for _ in range(size)] values = ffi.new('char*[]', values_keepalive) size_p = ffi.new('size_t *', size) _codes_get_string_array(handle, key.encode(ENC), values, size_p) return [...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def codes_get_string(handle, key, length=None): # type: (cffi.FFI.CData, str, int) -> str """ Get string element from a key. It may or may not fail in case there...
if length is None: length = codes_get_string_length(handle, key) values = ffi.new('char[]', length) length_p = ffi.new('size_t *', length) _codes_get_string = check_return(lib.codes_get_string) _codes_get_string(handle, key.encode(ENC), values, length_p) return ffi.string(values, length...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def codes_get_api_version(): """ Get the API version. Returns the version of the API as a string in the format "major.minor.revision". """
ver = lib.codes_get_api_version() patch = ver % 100 ver = ver // 100 minor = ver % 100 major = ver // 100 return "%d.%d.%d" % (major, minor, patch)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def codes_write(handle, outfile): # type: (cffi.FFI.CData, T.BinaryIO) -> None """ Write a coded message to a file. If the file does not exist, it is created. :p...
mess = ffi.new('const void **') mess_len = ffi.new('size_t*') codes_get_message = check_return(lib.codes_get_message) codes_get_message(handle, mess, mess_len) message = ffi.buffer(mess[0], size=mess_len[0]) outfile.write(message)