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 update_subtask_positions_obj(self, positions_obj_id, revision, values):
'''
Updates the ordering of subtasks in the positions object with the given ID to the ordering in the given values.
See https://developer.wunderlist.com/documentation/endpoints/positions for more info
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 _check_date_format(date, api):
''' Checks that the given date string conforms to the given API's date format specification '''
try:
datetime.datetime.strptime(date, api.DATE_FORMAT)
except ValueError:
raise ValueError("Date '{}' does not conform to API format: {}".format(date, api.DATE_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 get_task(client, task_id):
''' Gets task information for the given ID '''
endpoint = '/'.join([client.api.Endpoints.TASKS, str(task_id)])
response = client.authenticated_request(endpoint)
return response.json() |
<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_task(client, list_id, title, assignee_id=None, completed=None, recurrence_type=None, recurrence_count=None, due_date=None, starred=None):
'''
Creates a task in the given list
See https://developer.wunderlist.com/documentation/endpoints/task for detailed parameter information
'''
_check... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def update_task(client, task_id, revision, title=None, assignee_id=None, completed=None, recurrence_type=None, recurrence_count=None, due_date=None, starred=None, remove=None):
'''
Updates the task with the given ID
See https://developer.wunderlist.com/documentation/endpoints/task for detailed parameter in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_lists(client):
''' Gets all the client's lists '''
response = client.authenticated_request(client.api.Endpoints.LISTS)
return response.json() |
<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_list(client, list_id):
''' Gets the given list '''
endpoint = '/'.join([client.api.Endpoints.LISTS, str(list_id)])
response = client.authenticated_request(endpoint)
return response.json() |
<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_list(client, title):
''' Creates a new list with the given title '''
_check_title_length(title, client.api)
data = {
'title' : title,
}
response = client.authenticated_request(client.api.Endpoints.LISTS, method='POST', data=data)
return response.json() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def update_list(client, list_id, revision, title=None, public=None):
'''
Updates the list with the given ID to have the given properties
See https://developer.wunderlist.com/documentation/endpoints/list for detailed parameter information
'''
if title is not None:
_check_title_length(title, ... |
<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_task_positions_objs(client, list_id):
'''
Gets a list containing the object that encapsulates information about the order lists are laid out in. This list will always contain exactly one object.
See https://developer.wunderlist.com/documentation/endpoints/positions for more info
Return:
A ... |
<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_task_subtask_positions_objs(client, task_id):
'''
Gets a list of the positions of a single task's subtasks
Each task should (will?) only have one positions object defining how its subtasks are laid out
'''
params = {
'task_id' : int(task_id)
}
response = client.a... |
<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_list_subtask_positions_objs(client, list_id):
'''
Gets all subtask positions objects for the tasks within a given list. This is a convenience method so you don't have to get all the list's tasks before getting subtasks, though I can't fathom how mass subtask reordering is useful.
Returns:
List ... |
<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_subtask(client, subtask_id):
''' Gets the subtask with the given ID '''
endpoint = '/'.join([client.api.Endpoints.SUBTASKS, str(subtask_id)])
response = client.authenticated_request(endpoint)
return response.json() |
<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_subtask(client, task_id, title, completed=False):
''' Creates a subtask with the given title under the task with the given ID '''
_check_title_length(title, client.api)
data = {
'task_id' : int(task_id) if task_id else None,
'title' : title,
'completed' : compl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def delete_subtask(client, subtask_id, revision):
''' Deletes the subtask with the given ID provided the given revision equals the revision the server has '''
params = {
'revision' : int(revision),
}
endpoint = '/'.join([client.api.Endpoints.SUBTASKS, str(subtask_id)])
client.aut... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wait(animation='elipses', text='', speed=0.2):
""" Decorator for adding wait animation to long running functions. Args: animation (str, tuple):
String refer... |
def decorator(func):
func.animation = animation
func.speed = speed
func.text = text
@wraps(func)
def wrapper(*args, **kwargs):
animation = func.animation
text = func.text
if not isinstance(animation, (list, tuple)) and \
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def simple_wait(func):
""" Decorator for adding simple text wait animation to long running functions. Examples: """ |
@wraps(func)
def wrapper(*args, **kwargs):
wait = Wait()
wait.start()
try:
ret = func(*args, **kwargs)
finally:
wait.stop()
sys.stdout.write('\n')
return ret
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self):
""" Start animation thread. """ |
self.thread = threading.Thread(target=self._animate)
self.thread.start()
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 stop(self):
""" Stop animation thread. """ |
time.sleep(self.speed)
self._count = -9999
sys.stdout.write(self.reverser + '\r\033[K\033[A')
sys.stdout.flush()
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 angle(self, deg=False):
"""Return the angle of the complex argument. Args: deg (bool, optional):
Return angle in degrees if True, radians if False (default)... |
if self.dtype.str[1] != 'c':
warnings.warn('angle() is intended for complex-valued timeseries',
RuntimeWarning, 1)
return Timeseries(np.angle(self, deg=deg), self.tspan, self.labels) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def swapaxes(self, axis1, axis2):
"""Interchange two axes of a Timeseries.""" |
if self.ndim <=1 or axis1 == axis2:
return self
ar = np.asarray(self).swapaxes(axis1, axis2)
if axis1 != 0 and axis2 != 0:
# then axis 0 is unaffected by the swap
labels = self.labels[:]
labels[axis1], labels[axis2] = labels[axis2], labels[axis1]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transpose(self, *axes):
"""Permute the dimensions of a Timeseries.""" |
if self.ndim <= 1:
return self
ar = np.asarray(self).transpose(*axes)
if axes[0] != 0:
# then axis 0 is unaffected by the transposition
newlabels = [self.labels[ax] for ax in axes]
return Timeseries(ar, self.tspan, newlabels)
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 split(self, indices_or_sections, axis=0):
"""Split a timeseries into multiple sub-timeseries""" |
if not isinstance(indices_or_sections, numbers.Integral):
raise Error('splitting by array of indices is not yet implemented')
n = indices_or_sections
if self.shape[axis] % n != 0:
raise ValueError("Array split doesn't result in an equal division")
step = self.sha... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def psd(ts, nperseg=1500, noverlap=1200, plot=True):
"""plot Welch estimate of power spectral density, using nperseg samples per segment, with noverlap samples o... |
ts = ts.squeeze()
if ts.ndim is 1:
ts = ts.reshape((-1, 1))
fs = (len(ts) - 1.0) / (ts.tspan[-1] - ts.tspan[0])
window = signal.hamming(nperseg, sym=False)
nfft = max(256, 2**np.int(np.log2(nperseg) + 1))
freqs, pxx = signal.welch(ts, fs, window, nperseg, noverlap, nfft,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lowpass(ts, cutoff_hz, order=3):
"""forward-backward butterworth low-pass filter""" |
orig_ndim = ts.ndim
if ts.ndim is 1:
ts = ts[:, np.newaxis]
channels = ts.shape[1]
fs = (len(ts) - 1.0) / (ts.tspan[-1] - ts.tspan[0])
nyq = 0.5 * fs
cutoff = cutoff_hz/nyq
b, a = signal.butter(order, cutoff, btype='low')
if not np.all(np.abs(np.roots(a)) < 1.0):
raise V... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bandpass(ts, low_hz, high_hz, order=3):
"""forward-backward butterworth band-pass filter""" |
orig_ndim = ts.ndim
if ts.ndim is 1:
ts = ts[:, np.newaxis]
channels = ts.shape[1]
fs = (len(ts) - 1.0) / (ts.tspan[-1] - ts.tspan[0])
nyq = 0.5 * fs
low = low_hz/nyq
high = high_hz/nyq
b, a = signal.butter(order, [low, high], btype='band')
if not np.all(np.abs(np.roots(a)) ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def notch(ts, freq_hz, bandwidth_hz=1.0):
"""notch filter to remove remove a particular frequency Adapted from code by Sturla Molden """ |
orig_ndim = ts.ndim
if ts.ndim is 1:
ts = ts[:, np.newaxis]
channels = ts.shape[1]
fs = (len(ts) - 1.0) / (ts.tspan[-1] - ts.tspan[0])
nyq = 0.5 * fs
freq = freq_hz/nyq
bandwidth = bandwidth_hz/nyq
R = 1.0 - 3.0*(bandwidth/2.0)
K = ((1.0 - 2.0*R*np.cos(np.pi*freq) + R**2) /
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hilbert(ts):
"""Analytic signal, using the Hilbert transform""" |
output = signal.hilbert(signal.detrend(ts, axis=0), axis=0)
return Timeseries(output, ts.tspan, labels=ts.labels) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hilbert_amplitude(ts):
"""Amplitude of the analytic signal, using the Hilbert transform""" |
output = np.abs(signal.hilbert(signal.detrend(ts, axis=0), axis=0))
return Timeseries(output, ts.tspan, labels=ts.labels) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hilbert_phase(ts):
"""Phase of the analytic signal, using the Hilbert transform""" |
output = np.angle(signal.hilbert(signal.detrend(ts, axis=0), axis=0))
return Timeseries(output, ts.tspan, labels=ts.labels) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cwt(ts, freqs=np.logspace(0, 2), wavelet=cwtmorlet, plot=True):
"""Continuous wavelet transform Note the full results can use a huge amount of memory at 64-b... |
orig_ndim = ts.ndim
if ts.ndim is 1:
ts = ts[:, np.newaxis]
channels = ts.shape[1]
fs = (len(ts) - 1.0) / (1.0*ts.tspan[-1] - ts.tspan[0])
x = signal.detrend(ts, axis=0)
dtype = wavelet(fs/freqs[0], fs/freqs[0]).dtype
coefs = np.zeros((len(ts), len(freqs), channels), dtype)
for ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def first_return_times(dts, c=None, d=0.0):
"""For an ensemble of time series, return the set of all time intervals between successive returns to value c for all... |
if c is None:
c = dts.mean()
vmrt = distob.vectorize(analyses1.first_return_times)
all_intervals = vmrt(dts, c, d)
if hasattr(type(all_intervals), '__array_interface__'):
return np.ravel(all_intervals)
else:
return np.hstack([distob.gather(ilist) for ilist in all_intervals]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def periods(dts, phi=0.0):
"""For an ensemble of oscillators, return the set of periods lengths of all successive oscillations of all oscillators. An individual ... |
vperiods = distob.vectorize(analyses1.periods)
all_periods = vperiods(dts, phi)
if hasattr(type(all_periods), '__array_interface__'):
return np.ravel(all_periods)
else:
return np.hstack([distob.gather(plist) for plist in all_periods]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def circstd(dts, axis=2):
"""Circular standard deviation""" |
R = np.abs(np.exp(1.0j * dts).mean(axis=axis))
return np.sqrt(-2.0 * np.log(R)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hurst(X):
""" Compute the Hurst exponent of X. If the output H=0.5,the behavior of the time-series is similar to random walk. If H<0.5, the time-series cover... |
X = numpy.array(X)
N = X.size
T = numpy.arange(1, N + 1)
Y = numpy.cumsum(X)
Ave_T = Y / T
S_T = numpy.zeros(N)
R_T = numpy.zeros(N)
for i in range(N):
S_T[i] = numpy.std(X[:i + 1])
X_T = Y - T * Ave_T[i]
R_T[i] = numpy.ptp(X_T[:i + 1])
R_S = R_T / S_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 bin_power(X, Band, Fs):
"""Compute power in each frequency bin specified by Band from FFT result of X. By default, X is a real signal. Note ----- A real sign... |
C = numpy.fft.fft(X)
C = abs(C)
Power = numpy.zeros(len(Band) - 1)
for Freq_Index in range(0, len(Band) - 1):
Freq = float(Band[Freq_Index])
Next_Freq = float(Band[Freq_Index + 1])
Power[Freq_Index] = sum(
C[numpy.floor(
Freq / Fs * len(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 hfd(X, Kmax):
""" Compute Hjorth Fractal Dimension of a time series X, kmax is an HFD parameter """ |
L = []
x = []
N = len(X)
for k in range(1, Kmax):
Lk = []
for m in range(0, k):
Lmk = 0
for i in range(1, int(numpy.floor((N - m) / k))):
Lmk += abs(X[m + i * k] - X[m + i * k - k])
Lmk = Lmk * (N - 1) / numpy.floor((N - m) / float(k))... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dfa(X, Ave=None, L=None):
"""Compute Detrended Fluctuation Analysis from a time series X and length of boxes L. The first step to compute DFA is to integrate... |
X = numpy.array(X)
if Ave is None:
Ave = numpy.mean(X)
Y = numpy.cumsum(X)
Y -= Ave
if L is None:
L = numpy.floor(len(X) * 1 / (
2 ** numpy.array(list(range(4, int(numpy.log2(len(X))) - 4))))
)
F = numpy.zeros(len(L)) # F(n) of different given box lengt... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def permutation_entropy(x, n, tau):
"""Compute Permutation Entropy of a given time series x, specified by permutation order n and embedding lag tau. Parameters x... |
PeSeq = []
Em = embed_seq(x, tau, n)
for i in range(0, len(Em)):
r = []
z = []
for j in range(0, len(Em[i])):
z.append(Em[i][j])
for j in range(0, len(Em[i])):
z.sort()
r.append(z.index(Em[i][j]))
z[z.index(Em[i][j])] = -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 LLE(x, tau, n, T, fs):
"""Calculate largest Lyauponov exponent of a given time series x using Rosenstein algorithm. Parameters x list a time series n integer... |
Em = embed_seq(x, tau, n)
M = len(Em)
A = numpy.tile(Em, (len(Em), 1, 1))
B = numpy.transpose(A, [1, 0, 2])
square_dists = (A - B) ** 2 # square_dists[i,j,k] = (Em[i][k]-Em[j][k])^2
D = numpy.sqrt(square_dists[:,:,:].sum(axis=2)) # D[i,j] = ||Em[i]-Em[j]||_2
# Exclude elements within 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 phase_crossings(ts, phi=0.0):
"""For a single variable timeseries representing the phase of an oscillator, find the times at which the phase crosses angle ph... |
#TODO support multivariate time series
ts = ts.squeeze()
if ts.ndim is not 1:
raise ValueError('Currently can only use on single variable timeseries')
# Interpret the timeseries as belonging to a phase variable.
# Map its range to the interval (-pi, pi] with critical angle at zero:
ts... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def periods(ts, phi=0.0):
"""For a single variable timeseries representing the phase of an oscillator, measure the period of each successive oscillation. An indi... |
ts = np.squeeze(ts)
if ts.ndim <= 1:
return np.diff(phase_crossings(ts, phi))
else:
return np.hstack([ts[...,i].periods(phi) for i in range(ts.shape[-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 roughcwt(data, wavelet, widths):
""" Continuous wavelet transform. Performs a continuous wavelet transform on `data`, using the `wavelet` function. A CWT per... |
out_dtype = wavelet(widths[0], widths[0]).dtype
output = np.zeros([len(widths), len(data)], dtype=out_dtype)
for ind, width in enumerate(widths):
wavelet_data = wavelet(min(3 * width, len(data)), width)
output[ind, :] = convolve(data, wavelet_data,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_color_list():
"""Get cycle of colors in a way compatible with all matplotlib versions""" |
if 'axes.prop_cycle' in plt.rcParams:
return [p['color'] for p in list(plt.rcParams['axes.prop_cycle'])]
else:
return plt.rcParams['axes.color_cycle'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _remove_pi_crossings(ts):
"""For each variable in the Timeseries, checks whether it represents a phase variable ranging from -pi to pi. If so, set all points... |
orig_ts = ts
if ts.ndim is 1:
ts = ts[:, np.newaxis, np.newaxis]
elif ts.ndim is 2:
ts = ts[:, np.newaxis]
# Get the indices of those variables that have range of approx -pi to pi
tsmax = ts.max(axis=0)
tsmin = ts.min(axis=0)
phase_vars = np.transpose(np.nonzero((np.abs(tsma... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def timeseries_from_mat(filename, varname=None, fs=1.0):
"""load a multi-channel Timeseries from a MATLAB .mat file Args: filename (str):
.mat file to load varn... |
import scipy.io as sio
if varname is None:
mat_dict = sio.loadmat(filename)
if len(mat_dict) > 1:
raise ValueError('Must specify varname: file contains '
'more than one variable. ')
else:
mat_dict = sio.loadmat(filename, variable_names=(varna... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def annotations_from_file(filename):
"""Get a list of event annotations from an EDF (European Data Format file or EDF+ file, using edflib. Args: filename: EDF+ f... |
import edflib
e = edflib.EdfReader(filename, annotations_mode='all')
return e.read_annotations() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _rts_from_ra(ra, tspan, labels, block=True):
"""construct a RemoteTimeseries from a RemoteArray""" |
def _convert(a, tspan, labels):
from nsim import Timeseries
return Timeseries(a, tspan, labels)
return distob.call(
_convert, ra, tspan, labels, prefer_local=False, block=block) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dts_from_da(da, tspan, labels):
"""construct a DistTimeseries from a DistArray""" |
sublabels = labels[:]
new_subarrays = []
for i, ra in enumerate(da._subarrays):
if isinstance(ra, RemoteTimeseries):
new_subarrays.append(ra)
else:
if labels[da._distaxis]:
sublabels[da._distaxis] = labels[da._distaxis][
da._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 newsim(f, G, y0, name='NewModel', modelType=ItoModel, T=60.0, dt=0.005, repeat=1, identical=True):
"""Make a simulation of the system defined by functions f ... |
NewModel = newmodel(f, G, y0, name, modelType)
if repeat == 1:
return Simulation(NewModel(), T, dt)
else:
return RepeatedSim(NewModel, T, dt, repeat, identical) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def newmodel(f, G, y0, name='NewModel', modelType=ItoModel):
"""Use the functions f and G to define a new Model class for simulations. It will take functions f a... |
if not issubclass(modelType, Model):
raise SimTypeError('modelType must be a subclass of nsim.Model')
if not callable(f) or (G is not None and not callable(G)):
raise SimTypeError('f and G must be functions of y and t.')
if G is not None and f.__globals__ is not G.__globals__:
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 __clone_function(f, name=None):
"""Make a new version of a function that has its own independent copy of any globals that it uses directly, and has its own n... |
if not isinstance(f, types.FunctionType):
raise SimTypeError('Given parameter is not a function.')
if name is None:
name = f.__name__
newglobals = f.__globals__.copy()
globals_used = [x for x in f.__globals__ if x in f.__code__.co_names]
for x in globals_used:
gv = f.__globa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def angle(self, deg=False):
"""Return the angle of a complex Timeseries Args: deg (bool, optional):
Return angle in degrees if True, radians if False (default).... |
if self.dtype.str[1] != 'c':
warnings.warn('angle() is intended for complex-valued timeseries',
RuntimeWarning, 1)
da = distob.vectorize(np.angle)(self, deg)
return _dts_from_da(da, self.tspan, self.labels) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def coupling(self, source_y, target_y, weight):
"""How to couple the output of one subsystem to the input of another. This is a fallback default coupling functio... |
return np.ones_like(target_y)*np.mean(source_y)*weight |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def timeseries(self):
"""Simulated time series""" |
if self._timeseries is None:
self.compute()
if isinstance(self.system, NetworkModel):
return self.system._reshape_timeseries(self._timeseries)
else:
return self._timeseries |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def output(self):
"""Simulated model output""" |
if self._timeseries is None:
self.compute()
output = self._timeseries[:, self.system.output_vars]
if isinstance(self.system, NetworkModel):
return self.system._reshape_output(output)
else:
return output |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def crossing_times(ts, c=0.0, d=0.0):
"""For a single variable timeseries, find the times at which the value crosses ``c`` from above or below. Can optionally se... |
#TODO support multivariate time series
ts = ts.squeeze()
if ts.ndim is not 1:
raise ValueError('Currently can only use on single variable timeseries')
# Translate to put the critical value at zero:
ts = ts - c
tsa = ts[0:-1]
tsb = ts[1:]
# Time indices where phase crosses or r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def autocorrelation(ts, normalized=False, unbiased=False):
""" Returns the discrete, linear convolution of a time series with itself, optionally using unbiased n... |
ts = np.squeeze(ts)
if ts.ndim <= 1:
if normalized:
ts = (ts - ts.mean())/ts.std()
N = ts.shape[0]
ar = np.asarray(ts)
acf = np.correlate(ar, ar, mode='full')
outlen = (acf.shape[0] + 1) / 2
acf = acf[(outlen - 1):]
if unbiased:
fa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fan_speed(self, value):
"""Verifies the value is between 1 and 9 inclusively.""" |
if value not in range(1, 10):
raise exceptions.RoasterValueError
self._fan_speed.value = 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 heat_setting(self, value):
"""Verifies that the heat setting is between 0 and 3.""" |
if value not in range(0, 4):
raise exceptions.RoasterValueError
self._heat_setting.value = 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 heater_level(self, value):
"""Verifies that the heater_level is between 0 and heater_segments. Can only be called when freshroastsr700 object is initialized ... |
if self._ext_sw_heater_drive:
if value not in range(0, self._heater_bangbang_segments+1):
raise exceptions.RoasterValueError
self._heater_level.value = value
else:
raise exceptions.RoasterValueError |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_data_run(self, event_to_wait_on):
"""This is the thread that listens to an event from the comm process to execute the update_data_func callback in the... |
# with the daemon=Turue setting, this thread should
# quit 'automatically'
while event_to_wait_on.wait():
event_to_wait_on.clear()
if self.update_data_callback_kill_event.is_set():
return
self.update_data_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 state_transition_run(self, event_to_wait_on):
"""This is the thread that listens to an event from the timer process to execute the state_transition_func call... |
# with the daemon=Turue setting, this thread should
# quit 'automatically'
while event_to_wait_on.wait():
event_to_wait_on.clear()
if self.state_transition_callback_kill_event.is_set():
return
self.state_transition_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 _initialize(self):
"""Sends the initialization packet to the roaster.""" |
self._header.value = b'\xAA\x55'
self._current_state.value = b'\x00\x00'
s = self._generate_packet()
self._ser.write(s)
self._header.value = b'\xAA\xAA'
self._current_state.value = b'\x02\x01'
return self._read_existing_recipe() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _auto_connect(self):
"""Attempts to connect to the roaster every quarter of a second.""" |
while not self._teardown.value:
try:
self._connect()
return True
except exceptions.RoasterLookupError:
time.sleep(.25)
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 _timer(self, state_transition_event=None):
"""Timer loop used to keep track of the time while roasting or cooling. If the time remaining reaches zero, the ro... |
while not self._teardown.value:
state = self.get_roaster_state()
if(state == 'roasting' or state == 'cooling'):
time.sleep(1)
self.total_time += 1
if(self.time_remaining > 0):
self.time_remaining -= 1
el... |
<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_roaster_state(self):
"""Returns a string based upon the current state of the roaster. Will raise an exception if the state is unknown. Returns: 'idle' if... |
value = self._current_state.value
if(value == b'\x02\x01'):
return 'idle'
elif(value == b'\x04\x04'):
return 'cooling'
elif(value == b'\x08\x01'):
return 'sleeping'
# handle null bytes as empty strings
elif(value == b'\x00\x00' or valu... |
<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_packet(self):
"""Generates a packet based upon the current class variables. Note that current temperature is not sent, as the original application ... |
roaster_time = utils.seconds_to_float(self._time_remaining.value)
packet = (
self._header.value +
self._temp_unit.value +
self._flags.value +
self._current_state.value +
struct.pack(">B", self._fan_speed.value) +
struct.pack(">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 heat_level(self, value):
"""Set the desired output level. Must be between 0 and number_of_segments inclusive.""" |
if value < 0:
self._heat_level = 0
elif round(value) > self._num_segments:
self._heat_level = self._num_segments
else:
self._heat_level = int(round(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 update_data(self):
"""This is a method that will be called every time a packet is opened from the roaster.""" |
time_elapsed = datetime.datetime.now() - self.start_time
crntTemp = self.roaster.current_temp
targetTemp = self.roaster.target_temp
heaterLevel = self.roaster.heater_level
# print(
# "Time: %4.6f, crntTemp: %d, targetTemp: %d, heaterLevel: %d" %
# (time_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 process_results(self):
""" Process results by providers """ |
for result in self._results:
provider = result.provider
self.providers.append(provider)
if result.error:
self.failed_providers.append(provider)
continue
if not result.response:
continue
# set blacklisted... |
<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_ips(self, addrs):
""" sync check multiple ips """ |
tasks = []
for addr in addrs:
tasks.append(self._check_ip(addr))
return self._loop.run_until_complete(asyncio.gather(*tasks)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def frange(start, stop, step, precision):
"""A generator that will generate a range of floats.""" |
value = start
while round(value, precision) < stop:
yield round(value, precision)
value += step |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, currentTemp, targetTemp):
"""Calculate PID output value for given reference input and feedback.""" |
# in this implementation, ki includes the dt multiplier term,
# and kd includes the dt divisor term. This is typical practice in
# industry.
self.targetTemp = targetTemp
self.error = targetTemp - currentTemp
self.P_value = self.Kp * self.error
# it is common pr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setPoint(self, targetTemp):
"""Initilize the setpoint of PID.""" |
self.targetTemp = targetTemp
self.Integrator = 0
self.Derivator = 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 load_nouns(self, file):
""" Load dict from file for random words. :param str file: filename """ |
with open(os.path.join(main_dir, file + '.dat'), 'r') as f:
self.nouns = json.load(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 load_dmails(self, file):
""" Load list from file for random mails :param str file: filename """ |
with open(os.path.join(main_dir, file + '.dat'), 'r') as f:
self.dmails = frozenset(json.load(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 load_nicknames(self, file):
""" Load dict from file for random nicknames. :param str file: filename """ |
with open(os.path.join(main_dir, file + '.dat'), 'r') as f:
self.nicknames = json.load(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 random_words(self, letter=None, count=1):
""" Returns list of random words. :param str letter: letter :param int count: how much words :rtype: list :returns:... |
self.check_count(count)
words = []
if letter is None:
all_words = list(
chain.from_iterable(self.nouns.values()))
try:
words = sample(all_words, count)
except ValueError:
len_sample = len(all_words)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def random_nicks(self, letter=None, gender='u', count=1):
""" Return list of random nicks. :param str letter: letter :param str gender: ``'f'`` for female, ``'m'... |
self.check_count(count)
nicks = []
if gender not in ('f', 'm', 'u'):
raise ValueError('Param "gender" must be in (f, m, u)')
if letter is None:
all_nicks = list(
chain.from_iterable(self.nicknames[gender].values()))
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 randomMails(self, count=1):
""" Return random e-mails. :rtype: list :returns: list of random e-mails """ |
self.check_count(count)
random_nicks = self.rn.random_nicks(count=count)
random_domains = sample(self.dmails, count)
return [
nick.lower() + "@" + domain for nick, domain in zip(random_nicks,
random_domains)
... |
<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_sentences_list(self, sentences=1):
""" Return sentences in list. :param int sentences: how many sentences :returns: list of strings with sentence :rtype:... |
if sentences < 1:
raise ValueError('Param "sentences" must be greater than 0.')
sentences_list = []
while sentences:
num_rand_words = random.randint(self.MIN_WORDS, self.MAX_WORDS)
random_sentence = self.make_sentence(
random.sample(self.wo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_sentence(list_words):
""" Return a sentence from list of words. :param list list_words: list of words :returns: sentence :rtype: str """ |
lw_len = len(list_words)
if lw_len > 6:
list_words.insert(lw_len // 2 + random.choice(range(-2, 2)), ',')
sentence = ' '.join(list_words).replace(' ,', ',')
return sentence.capitalize() + '.' |
<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_epub_opf_xml(filepath):
'''
Returns the file.OPF contents of the ePub file
'''
if not zipfile.is_zipfile(filepath):
raise EPubException('Unknown file')
# print('Reading ePub file: {}'.format(filepath))
zf = zipfile.ZipFile(filepath, 'r', compression=zipfile.ZIP_DEFLATED, allowZi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expand(expression):
""" Expand a reference expression to individual spans. Also works on space-separated ID lists, although a sequence of space characters wi... |
tokens = []
for (pre, _id, _range) in robust_ref_re.findall(expression):
if not _range:
tokens.append('{}{}'.format(pre, _id))
else:
tokens.append(pre)
tokens.extend(
'{}{}[{}:{}]'.format(delim, _id, start, end)
for delim, star... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compress(expression):
""" Compress a reference expression to group spans on the same id. Also works on space-separated ID lists, although a sequence of space... |
tokens = []
selection = []
last_id = None
for (pre, _id, _range) in robust_ref_re.findall(expression):
if _range and _id == last_id:
selection.extend([pre, _range])
continue
if selection:
tokens.extend(selection + [']'])
selection = []
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def selections(expression, keep_delimiters=True):
""" Split the expression into individual selection expressions. The delimiters will be kept as separate items i... |
tokens = []
for (pre, _id, _range) in robust_ref_re.findall(expression):
if keep_delimiters and pre:
tokens.append(pre)
if _id:
if _range:
tokens.append('{}[{}]'.format(_id, _range))
else:
tokens.append(_id)
return tokens |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve(container, expression):
""" Return the string that is the resolution of the alignment expression `expression`, which selects ids from `container`. ""... |
itemgetter = getattr(container, 'get_item', container.get)
tokens = []
expression = expression.strip()
for sel_delim, _id, _range in selection_re.findall(expression):
tokens.append(delimiters.get(sel_delim, ''))
item = itemgetter(_id)
if item is None:
raise XigtStruc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def default_decode(events, mode='full'):
"""Decode a XigtCorpus element.""" |
event, elem = next(events)
root = elem # store root for later instantiation
while (event, elem.tag) not in [('start', 'igt'), ('end', 'xigt-corpus')]:
event, elem = next(events)
igts = None
if event == 'start' and elem.tag == 'igt':
igts = (
decode_igt(e)
fo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_file_content(source):
"""Return a tuple, each value being a line of the source file. Remove empty lines and comments (lines starting with a '#'). """ |
filepath = os.path.join('siglists', source + '.txt')
lines = []
with resource_stream(__name__, filepath) as f:
for i, line in enumerate(f):
line = line.decode('utf-8', 'strict').strip()
if not line or line.startswith('#'):
continue
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 _get_rar_version(xfile):
"""Check quickly whether file is rar archive. """ |
buf = xfile.read(len(RAR5_ID))
if buf.startswith(RAR_ID):
return 3
elif buf.startswith(RAR5_ID):
xfile.read(1)
return 5
return 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_next(self):
"""Proceed to next volume.""" |
# is the file split over archives?
if (self._cur.flags & rarfile.RAR_FILE_SPLIT_AFTER) == 0:
return False
if self._fd:
self._fd.close()
self._fd = None
# open next part
self._volfile = self._parser._next_volname(self._volfile)
fd = ... |
<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(self):
# TODO: fix? """Do not check final CRC.""" |
if self._returncode:
rarfile.check_returncode(self, '')
if self._remain != 0:
raise rarfile.BadRarFile("Failed the read enough 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 _normalize(mat: np.ndarray):
"""rescales a numpy array, so that min is 0 and max is 255""" |
return ((mat - mat.min()) * (255 / mat.max())).astype(np.uint8) |
<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_24bit_gray(mat: np.ndarray):
"""returns a matrix that contains RGB channels, and colors scaled from 0 to 255""" |
return np.repeat(np.expand_dims(_normalize(mat), axis=2), 3, axis=2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_color_map(name: str, mat: np.ndarray = None):
"""returns an RGB matrix scaled by a matplotlib color map""" |
def apply_map(mat):
return (cm.get_cmap(name)(_normalize(mat))[:, :, :3] * 255).astype(np.uint8)
return apply_map if mat is None else apply_map(mat) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mat_to_surface(mat: np.ndarray, transformer=to_24bit_gray):
"""Can be used to create a pygame.Surface from a 2d numpy array. By default a grey image with sca... |
return pygame.pixelcopy.make_surface(transformer(mat.transpose())
if transformer is not None else mat.transpose()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge_dict(data, *args):
"""Merge any number of dictionaries """ |
results = {}
for current in (data,) + args:
results.update(current)
return results |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_url(url, *paths):
"""Joins individual URL strings together, and returns a single string. """ |
for path in paths:
url = re.sub(r'/?$', re.sub(r'^/?', '/', path), url)
return url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unicode_char(ignored_chars=None):
"""returns a handler that listens for unicode characters""" |
return lambda e: e.unicode if e.type == pygame.KEYDOWN \
and ((ignored_chars is None)
or (e.unicode not in ignored_chars))\
else EventConsumerInfo.DONT_CARE |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.