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 wrap_node(self, node, options):
'''\
celery registers tasks by decorating them, and so do we, so the user
can pass a celery task and we'll wrap our code with theirs in a nice
package celery can execute.
'''
if 'celery_task' in options:
return options['cele... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def checkpoint(key=0, unpickler=pickle.load, pickler=pickle.dump, work_dir=gettempdir(), refresh=False):
""" A utility decorator to save intermediate results of ... |
def decorator(func):
def wrapped(*args, **kwargs):
# If first arg is a string, use it directly.
if isinstance(key, str):
save_file = os.path.join(work_dir, key)
elif isinstance(key, Template):
save_file = os.path.join(work_dir, key.substi... |
<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():
"""Display the arguments as a braille graph on standard output.""" |
# We override the program name to reflect that this script must be run with
# the python executable.
parser = argparse.ArgumentParser(
prog='python -m braillegraph',
description='Print a braille bar graph of the given integers.'
)
# This flag sets the end string that we'll print. ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _rnd_date(start, end):
"""Internal random date generator. """ |
return date.fromordinal(random.randint(start.toordinal(), end.toordinal())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rnd_date_list_high_performance(size, start=date(1970, 1, 1), end=None, **kwargs):
""" Generate mass random date. :param size: int, number of :param start: da... |
if end is None:
end = date.today()
start_days = to_ordinal(parser.parse_datetime(start))
end_days = to_ordinal(parser.parse_datetime(end))
_assert_correct_start_end(start_days, end_days)
if has_np: # pragma: no cover
return [
from_ordinal(days)
for days in 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 day_interval(year, month, day, milliseconds=False, return_string=False):
""" Return a start datetime and end datetime of a day. :param milliseconds: Minimum ... |
if milliseconds: # pragma: no cover
delta = timedelta(milliseconds=1)
else:
delta = timedelta(seconds=1)
start = datetime(year, month, day)
end = datetime(year, month, day) + timedelta(days=1) - delta
if not return_string:
return start, end
else:
return str(st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def month_interval(year, month, milliseconds=False, return_string=False):
""" Return a start datetime and end datetime of a month. :param milliseconds: Minimum t... |
if milliseconds: # pragma: no cover
delta = timedelta(milliseconds=1)
else:
delta = timedelta(seconds=1)
if month == 12:
start = datetime(year, month, 1)
end = datetime(year + 1, 1, 1) - delta
else:
start = datetime(year, month, 1)
end = datetime(year, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def year_interval(year, milliseconds=False, return_string=False):
""" Return a start datetime and end datetime of a year. :param milliseconds: Minimum time resol... |
if milliseconds: # pragma: no cover
delta = timedelta(milliseconds=1)
else:
delta = timedelta(seconds=1)
start = datetime(year, 1, 1)
end = datetime(year + 1, 1, 1) - delta
if not return_string:
return start, end
else:
return str(start), str(end) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_milestone(self, title):
""" given the title as str, looks for an existing milestone or create a new one, and return the object """ |
if not title:
return GithubObject.NotSet
if not hasattr(self, '_milestones'):
self._milestones = {m.title: m for m in self.repo.get_milestones()}
milestone = self._milestones.get(title)
if not milestone:
milestone = self.repo.create_milestone(title=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 get_assignee(self, login):
""" given the user login, looks for a user in assignee list of the repo and return it if was found. """ |
if not login:
return GithubObject.NotSet
if not hasattr(self, '_assignees'):
self._assignees = {c.login: c for c in self.repo.get_assignees()}
if login not in self._assignees:
# warning
print("{} doesn't belong to this repo. This issue won't be as... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sender(self, issues):
""" push a list of issues to github """ |
for issue in issues:
state = self.get_state(issue.state)
if issue.number:
try:
gh_issue = self.repo.get_issue(issue.number)
original_state = gh_issue.state
if original_state == state:
ac... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def wrap_node(self, node, options):
'''
we have the option to construct nodes here, so we can use different
queues for nodes without having to have different queue objects.
'''
job_kwargs = {
'queue': options.get('queue', 'default'),
'connection': options.... |
<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_albaran_automatic(pk, list_lines):
""" creamos de forma automatica el albaran """ |
line_bd = SalesLineAlbaran.objects.filter(line_order__pk__in=list_lines).values_list('line_order__pk')
if line_bd.count() == 0 or len(list_lines) != len(line_bd[0]):
# solo aquellas lineas de pedidos que no estan ya albarandas
if line_bd.count() != 0:
for x in li... |
<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_invoice_from_albaran(pk, list_lines):
""" la pk y list_lines son de albaranes, necesitamos la info de las lineas de pedidos """ |
context = {}
if list_lines:
new_list_lines = [x[0] for x in SalesLineAlbaran.objects.values_list('line_order__pk').filter(
pk__in=[int(x) for x in list_lines]
).exclude(invoiced=True)]
if new_list_lines:
lo = SalesLineOrder.objects.val... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_invoice_from_ticket(pk, list_lines):
""" la pk y list_lines son de ticket, necesitamos la info de las lineas de pedidos """ |
context = {}
if list_lines:
new_list_lines = [x[0] for x in SalesLineTicket.objects.values_list('line_order__pk').filter(pk__in=[int(x) for x in list_lines])]
if new_list_lines:
lo = SalesLineOrder.objects.values_list('order__pk').filter(pk__in=new_list_lines)[: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 _check_values(in_values):
""" Check if values need to be converted before they get mogrify'd """ |
out_values = []
for value in in_values:
# if isinstance(value, (dict, list)):
# out_values.append(json.dumps(value))
# else:
out_values.append(value)
return tuple(out_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 clone(srcpath, destpath, vcs=None):
"""Clone an existing repository. :param str srcpath: Path to an existing repository :param str destpath: Desired path of ... |
vcs = vcs or probe(srcpath)
cls = _get_repo_class(vcs)
return cls.clone(srcpath, destpath) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def probe(path):
"""Probe a repository for its type. :param str path: The path of the repository :raises UnknownVCSType: if the repository type couldn't be infer... |
import os
from .common import UnknownVCSType
if os.path.isdir(os.path.join(path, '.git')):
return 'git'
elif os.path.isdir(os.path.join(path, '.hg')):
return 'hg'
elif (
os.path.isfile(os.path.join(path, 'config')) and
os.path.isdir(os.path.join(path, 'objects')) 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 open(path, vcs=None):
"""Open an existing repository :param str path: The path of the repository :param vcs: If specified, assume the given repository type t... |
import os
assert os.path.isdir(path), path + ' is not a directory'
vcs = vcs or probe(path)
cls = _get_repo_class(vcs)
return cls(path) |
<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_attributes(self, attributes, extra=None):
"""Check if attributes given to the constructor can be used to instanciate a valid node.""" |
extra = extra or ()
unknown_keys = set(attributes) - set(self._possible_attributes) - set(extra)
if unknown_keys:
logger.warning('%s got unknown attributes: %s' %
(self.__class__.__name__, unknown_keys)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(args=None):
""" Entry point for the tag CLI. Isolated as a method so that the CLI can be called by other Python code (e.g. for testing), in which case t... |
if args is None:
args = tag.cli.parser().parse_args()
assert args.cmd in mains
mainmethod = mains[args.cmd]
mainmethod(args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _build_request(request):
"""Build message to transfer over the socket from a request.""" |
msg = bytes([request['cmd']])
if 'dest' in request:
msg += bytes([request['dest']])
else:
msg += b'\0'
if 'sha' in request:
msg += request['sha']
else:
for dummy in range(64):
msg += b'0'
logging.debug("Request (%d): %s", len(msg), msg)
return msg |
<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():
"""Show example using the API.""" |
__async__ = True
logging.basicConfig(format="%(levelname)-10s %(message)s",
level=logging.DEBUG)
if len(sys.argv) != 2:
logging.error("Must specify configuration file")
sys.exit()
config = configparser.ConfigParser()
config.read(sys.argv[1])
password = ... |
<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 thread.""" |
if not self._thread:
logging.info("Starting asterisk mbox thread")
# Ensure signal queue is empty
try:
while True:
self.signal.get(False)
except queue.Empty:
pass
self._thread = threading.Thread(targ... |
<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 thread.""" |
if self._thread:
self.signal.put("Stop")
self._thread.join()
if self._soc:
self._soc.shutdown()
self._soc.close()
self._thread = None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _recv_msg(self):
"""Read a message from the server.""" |
command = ord(recv_blocking(self._soc, 1))
msglen = recv_blocking(self._soc, 4)
msglen = ((msglen[0] << 24) + (msglen[1] << 16) +
(msglen[2] << 8) + msglen[3])
msg = recv_blocking(self._soc, msglen)
return command, msg |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _loop(self):
"""Handle data.""" |
request = {}
connected = False
while True:
timeout = None
sockets = [self.request_queue, self.signal]
if not connected:
try:
self._clear_request(request)
self._connect()
self._soc.sen... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mp3(self, sha, **kwargs):
"""Get raw MP3 of a message.""" |
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_MP3,
'sha': _get_bytes(sha)}, **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 delete(self, sha, **kwargs):
"""Delete a message.""" |
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_DELETE,
'sha': _get_bytes(sha)}, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_cdr(self, start=0, count=-1, **kwargs):
"""Request range of CDR messages""" |
sha = encode_to_sha("{:d},{:d}".format(start, count))
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_CDR,
'sha': sha}, **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 path(self) -> Path: """A Path for this name object joining field names from `self.get_path_pattern_list` with this object's name""" |
args = list(self._iter_translated_field_names(self.get_path_pattern_list()))
args.append(self.get_name())
return Path(*args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fold(self, predicate):
"""Takes a predicate and applies it to each node starting from the leaves and making the return value propagate.""" |
childs = {x:y.fold(predicate) for (x,y) in self._attributes.items()
if isinstance(y, SerializableTypedAttributesHolder)}
return predicate(self, childs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def the_one(cls):
"""Get the single global HelpUrlExpert object.""" |
if cls.THE_ONE is None:
cls.THE_ONE = cls(settings.HELP_TOKENS_INI_FILE)
return cls.THE_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 get_config_value(self, section_name, option, default_option="default"):
""" Read a value from the configuration, with a default. Args: section_name (str):
n... |
if self.config is None:
self.config = configparser.ConfigParser()
self.config.read(self.ini_file_name)
if option:
try:
return self.config.get(section_name, option)
except configparser.NoOptionError:
log.debug(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def url_for_token(self, token):
"""Find the full URL for a help token.""" |
book_url = self.get_config_value("pages", token)
book, _, url_tail = book_url.partition(':')
book_base = settings.HELP_TOKENS_BOOKS[book]
url = book_base
lang = getattr(settings, "HELP_TOKENS_LANGUAGE_CODE", None)
if lang is not None:
lang = self.get_config... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def multi_load_data_custom(Channel, TraceTitle, RunNos, directoryPath='.', calcPSD=True, NPerSegmentPSD=1000000):
""" Lets you load multiple datasets named with ... |
# files = glob('{}/*'.format(directoryPath))
# files_CorrectChannel = []
# for file_ in files:
# if 'C{}'.format(Channel) in file_:
# files_CorrectChannel.append(file_)
# files_CorrectRunNo = []
# for RunNo in RunNos:
# files_match = _fnmatch.filter(
# files_CorrectCha... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search_data_custom(Channel, TraceTitle, RunNos, directoryPath='.'):
""" Lets you create a list with full file paths of the files named with the LeCroy's cust... |
files = glob('{}/*'.format(directoryPath))
files_CorrectChannel = []
for file_ in files:
if 'C{}'.format(Channel) in file_:
files_CorrectChannel.append(file_)
files_CorrectRunNo = []
for RunNo in RunNos:
files_match = _fnmatch.filter(
files_CorrectChannel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_temp(Data_ref, Data):
""" Calculates the temperature of a data set relative to a reference. The reference is assumed to be at 300K. Parameters Data_ref ... |
T = 300 * ((Data.A * Data_ref.Gamma) / (Data_ref.A * Data.Gamma))
Data.T = T
return 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 fit_curvefit(p0, datax, datay, function, **kwargs):
""" Fits the data to a function using scipy.optimise.curve_fit Parameters p0 : array_like initial paramet... |
pfit, pcov = \
_curve_fit(function, datax, datay, p0=p0,
epsfcn=0.0001, **kwargs)
error = []
for i in range(len(pfit)):
try:
error.append(_np.absolute(pcov[i][i])**0.5)
except:
error.append(_np.NaN)
pfit_curvefit = pfit
perr_curvefi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def moving_average(array, n=3):
""" Calculates the moving average of an array. Parameters array : array The array to have the moving average taken of n : int The... |
ret = _np.cumsum(array, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / 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 fit_autocorrelation(autocorrelation, time, GammaGuess, TrapFreqGuess=None, method='energy', MakeFig=True, show_fig=True):
""" Fits exponential relaxation the... |
datax = time
datay = autocorrelation
method = method.lower()
if method == 'energy':
p0 = _np.array([GammaGuess])
Params_Fit, Params_Fit_Err = fit_curvefit(p0,
datax,
datay,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def IFFT_filter(Signal, SampleFreq, lowerFreq, upperFreq, PyCUDA = False):
""" Filters data using fft -> zeroing out fft bins -> ifft Parameters Signal : ndarray... |
if PyCUDA==True:
Signalfft=calc_fft_with_PyCUDA(Signal)
else:
print("starting fft")
Signalfft = scipy.fftpack.fft(Signal)
print("starting freq calc")
freqs = _np.fft.fftfreq(len(Signal)) * SampleFreq
print("starting bin zeroing")
Signalfft[_np.where(freqs < lowerFreq)] =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_fft_with_PyCUDA(Signal):
""" Calculates the FFT of the passed signal by using the scikit-cuda libary which relies on PyCUDA Parameters Signal : ndarray ... |
print("starting fft")
Signal = Signal.astype(_np.float32)
Signal_gpu = _gpuarray.to_gpu(Signal)
Signalfft_gpu = _gpuarray.empty(len(Signal)//2+1,_np.complex64)
plan = _Plan(Signal.shape,_np.float32,_np.complex64)
_fft(Signal_gpu, Signalfft_gpu, plan)
Signalfft = Signalfft_gpu.get() #only 2N... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_ifft_with_PyCUDA(Signalfft):
""" Calculates the inverse-FFT of the passed FFT-signal by using the scikit-cuda libary which relies on PyCUDA Parameters S... |
print("starting ifft")
Signalfft = Signalfft.astype(_np.complex64)
Signalfft_gpu = _gpuarray.to_gpu(Signalfft[0:len(Signalfft)//2+1])
Signal_gpu = _gpuarray.empty(len(Signalfft),_np.float32)
plan = _Plan(len(Signalfft),_np.complex64,_np.float32)
_ifft(Signalfft_gpu, Signal_gpu, plan)
Signal... |
<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_butterworth_b_a(lowcut, highcut, SampleFreq, order=5, btype='band'):
""" Generates the b and a coefficients for a butterworth IIR filter. Parameters low... |
nyq = 0.5 * SampleFreq
low = lowcut / nyq
high = highcut / nyq
if btype.lower() == 'band':
b, a = scipy.signal.butter(order, [low, high], btype = btype)
elif btype.lower() == 'low':
b, a = scipy.signal.butter(order, low, btype = btype)
elif btype.lower() == 'high':
b, 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 make_butterworth_bandpass_b_a(CenterFreq, bandwidth, SampleFreq, order=5, btype='band'):
""" Generates the b and a coefficients for a butterworth bandpass II... |
lowcut = CenterFreq-bandwidth/2
highcut = CenterFreq+bandwidth/2
b, a = make_butterworth_b_a(lowcut, highcut, SampleFreq, order, btype)
return b, 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_freq_response(a, b, show_fig=True, SampleFreq=(2 * pi), NumOfFreqs=500, whole=False):
""" This function takes an array of coefficients and finds the freq... |
w, h = scipy.signal.freqz(b=b, a=a, worN=NumOfFreqs, whole=whole)
freqList = w / (pi) * SampleFreq / 2.0
himag = _np.array([hi.imag for hi in h])
GainArray = 20 * _np.log10(_np.abs(h))
PhaseDiffArray = _np.unwrap(_np.arctan2(_np.imag(h), _np.real(h)))
fig1 = _plt.figure()
ax1 = fig1.add_su... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def multi_plot_PSD(DataArray, xlim=[0, 500], units="kHz", LabelArray=[], ColorArray=[], alphaArray=[], show_fig=True):
""" plot the pulse spectral density for mu... |
unit_prefix = units[:-2] # removed the last 2 chars
if LabelArray == []:
LabelArray = ["DataSet {}".format(i)
for i in _np.arange(0, len(DataArray), 1)]
if ColorArray == []:
ColorArray = _np.empty(len(DataArray))
ColorArray = list(ColorArray)
for i, ele... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def multi_plot_time(DataArray, SubSampleN=1, units='s', xlim=None, ylim=None, LabelArray=[], show_fig=True):
""" plot the time trace for multiple data sets on th... |
unit_prefix = units[:-1] # removed the last char
if LabelArray == []:
LabelArray = ["DataSet {}".format(i)
for i in _np.arange(0, len(DataArray), 1)]
fig = _plt.figure(figsize=properties['default_fig_size'])
ax = fig.add_subplot(111)
for i, data in enumerate(DataA... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def multi_subplots_time(DataArray, SubSampleN=1, units='s', xlim=None, ylim=None, LabelArray=[], show_fig=True):
""" plot the time trace on multiple axes Paramet... |
unit_prefix = units[:-1] # removed the last char
NumDataSets = len(DataArray)
if LabelArray == []:
LabelArray = ["DataSet {}".format(i)
for i in _np.arange(0, len(DataArray), 1)]
fig, axs = _plt.subplots(NumDataSets, 1)
for i, data in enumerate(DataArray):
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 calc_autocorrelation(Signal, FFT=False, PyCUDA=False):
""" Calculates the autocorrelation from a given Signal via using Parameters Signal : array-like Array ... |
if FFT==True:
Signal_padded = scipy.fftpack.ifftshift((Signal-_np.average(Signal))/_np.std(Signal))
n, = Signal_padded.shape
Signal_padded = _np.r_[Signal_padded[:n//2], _np.zeros_like(Signal_padded), Signal_padded[n//2:]]
if PyCUDA==True:
f = calc_fft_with_PyCUDA(Signal... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _GetRealImagArray(Array):
""" Returns the real and imaginary components of each element in an array and returns them in 2 resulting arrays. Parameters Array ... |
ImagArray = _np.array([num.imag for num in Array])
RealArray = _np.array([num.real for num in Array])
return RealArray, ImagArray |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _GetComplexConjugateArray(Array):
""" Calculates the complex conjugate of each element in an array and returns the resulting array. Parameters Array : ndarra... |
ConjArray = _np.array([num.conj() for num in Array])
return ConjArray |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fm_discriminator(Signal):
""" Calculates the digital FM discriminator from a real-valued time signal. Parameters Signal : array-like A real-valued time signa... |
S_analytic = _hilbert(Signal)
S_analytic_star = _GetComplexConjugateArray(S_analytic)
S_analytic_hat = S_analytic[1:] * S_analytic_star[:-1]
R, I = _GetRealImagArray(S_analytic_hat)
fmDiscriminator = _np.arctan2(I, R)
return fmDiscriminator |
<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_collisions(Signal, tolerance=50):
""" Finds collision events in the signal from the shift in phase of the signal. Parameters Signal : array_like Array c... |
fmd = fm_discriminator(Signal)
mean_fmd = _np.mean(fmd)
Collisions = [_is_this_a_collision(
[value, mean_fmd, tolerance]) for value in fmd]
return Collisions |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count_collisions(Collisions):
""" Counts the number of unique collisions and gets the collision index. Parameters Collisions : array_like Array of booleans, ... |
CollisionCount = 0
CollisionIndicies = []
lastval = True
for i, val in enumerate(Collisions):
if val == True and lastval == False:
CollisionIndicies.append(i)
CollisionCount += 1
lastval = val
return CollisionCount, CollisionIndicies |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def steady_state_potential(xdata,HistBins=100):
""" Calculates the steady state potential. Used in fit_radius_from_potentials. Parameters xdata : ndarray Positio... |
import numpy as _np
pops=_np.histogram(xdata,HistBins)[0]
bins=_np.histogram(xdata,HistBins)[1]
bins=bins[0:-1]
bins=bins+_np.mean(_np.diff(bins))
#normalise pops
pops=pops/float(_np.sum(pops))
return bins,-_np.log(pops) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_z0_and_conv_factor_from_ratio_of_harmonics(z, z2, NA=0.999):
""" Calculates the Conversion Factor and physical amplitude of motion in nms by comparison ... |
V1 = calc_mean_amp(z)
V2 = calc_mean_amp(z2)
ratio = V2/V1
beta = 4*ratio
laserWavelength = 1550e-9 # in m
k0 = (2*pi)/(laserWavelength)
WaistSize = laserWavelength/(pi*NA)
Zr = pi*WaistSize**2/laserWavelength
z0 = beta/(k0 - 1/Zr)
ConvFactor = V1/z0
T0 = 300
return z0, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_mass_from_z0(z0, w0):
""" Calculates the mass of the particle using the equipartition from the angular frequency of the z signal and the average amplitu... |
T0 = 300
mFromEquipartition = Boltzmann*T0/(w0**2 * z0**2)
return mFromEquipartition |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_mass_from_fit_and_conv_factor(A, Damping, ConvFactor):
""" Calculates mass from the A parameter from fitting, the damping from fitting in angular units ... |
T0 = 300
mFromA = 2*Boltzmann*T0/(pi*A) * ConvFactor**2 * Damping
return mFromA |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unit_conversion(array, unit_prefix, current_prefix=""):
""" Converts an array or value to of a certain unit scale to another unit scale. Accepted units are: ... |
UnitDict = {
'E': 1e18,
'P': 1e15,
'T': 1e12,
'G': 1e9,
'M': 1e6,
'k': 1e3,
'': 1,
'm': 1e-3,
'u': 1e-6,
'n': 1e-9,
'p': 1e-12,
'f': 1e-15,
'a': 1e-18,
}
try:
Desired_units = UnitDict[unit_prefix... |
<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_wigner(z, freq, sample_freq, histbins=200, show_plot=False):
""" Calculates an approximation to the wigner quasi-probability distribution by splitting th... |
phase, phase_slices = extract_slices(z, freq, sample_freq, show_plot=False)
counts_array, bin_edges = histogram_phase(phase_slices, phase, histbins, show_plot=show_plot)
diff = bin_edges[1] - bin_edges[0]
bin_centres = bin_edges[:-1] + diff
iradon_output = _iradon_sart(counts_array, theta=p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_wigner3d(iradon_output, bin_centres, bin_centre_units="", cmap=_cm.cubehelix_r, view=(10, -45), figsize=(10, 10)):
""" Plots the wigner space representa... |
fig = _plt.figure(figsize=figsize)
ax = fig.add_subplot(111, projection='3d')
resid1 = iradon_output.sum(axis=0)
resid2 = iradon_output.sum(axis=1)
x = bin_centres # replace with x
y = bin_centres # replace with p (xdot/omega)
xpos, ypos = _np.meshgrid(x, y)
X = xpos
Y = ypos
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_wigner2d(iradon_output, bin_centres, cmap=_cm.cubehelix_r, figsize=(6, 6)):
""" Plots the wigner space representation as a 2D heatmap. Parameters iradon... |
xx, yy = _np.meshgrid(bin_centres, bin_centres)
resid1 = iradon_output.sum(axis=0)
resid2 = iradon_output.sum(axis=1)
wigner_marginal_seperation = 0.001
left, width = 0.2, 0.65-0.1 # left = left side of hexbin and hist_x
bottom, height = 0.1, 0.65-0.1 # bottom = bottom of hexbin and hist_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 get_time_data(self, timeStart=None, timeEnd=None):
""" Gets the time and voltage data. Parameters timeStart : float, optional The time get data from. By defa... |
if timeStart == None:
timeStart = self.timeStart
if timeEnd == None:
timeEnd = self.timeEnd
time = self.time.get_array()
StartIndex = _np.where(time == take_closest(time, timeStart))[0][0]
EndIndex = _np.where(time == take_close... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_time_data(self, timeStart=None, timeEnd=None, units='s', show_fig=True):
""" plot time data against voltage data. Parameters timeStart : float, optional... |
unit_prefix = units[:-1] # removed the last char
if timeStart == None:
timeStart = self.timeStart
if timeEnd == None:
timeEnd = self.timeEnd
time = self.time.get_array()
StartIndex = _np.where(time == take_closest(time, timeStart))[0][0]
EndInde... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_PSD(self, xlim=None, units="kHz", show_fig=True, timeStart=None, timeEnd=None, *args, **kwargs):
""" plot the pulse spectral density. Parameters xlim : ... |
# self.get_PSD()
if timeStart == None and timeEnd == None:
freqs = self.freqs
PSD = self.PSD
else:
freqs, PSD = self.get_PSD(timeStart=timeStart, timeEnd=timeEnd)
unit_prefix = units[:-2]
if xlim == None:
xlim =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_area_under_PSD(self, lowerFreq, upperFreq):
""" Sums the area under the PSD from lowerFreq to upperFreq. Parameters lowerFreq : float The lower limit of... |
Freq_startAreaPSD = take_closest(self.freqs, lowerFreq)
index_startAreaPSD = int(_np.where(self.freqs == Freq_startAreaPSD)[0][0])
Freq_endAreaPSD = take_closest(self.freqs, upperFreq)
index_endAreaPSD = int(_np.where(self.freqs == Freq_endAreaPSD)[0][0])
AreaUnderPSD = sum(self... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_fit_auto(self, CentralFreq, MaxWidth=15000, MinWidth=500, WidthIntervals=500, MakeFig=True, show_fig=True, silent=False):
""" Tries a range of regions to... |
MinTotalSumSquaredError = _np.infty
for Width in _np.arange(MaxWidth, MinWidth - WidthIntervals, -WidthIntervals):
try:
OmegaTrap, A, Gamma,_ , _ \
= self.get_fit_from_peak(
CentralFreq - Width / 2,
CentralF... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_gamma_from_variance_autocorrelation_fit(self, NumberOfOscillations, GammaGuess=None, silent=False, MakeFig=True, show_fig=True):
""" Calculates the tota... |
try:
SplittedArraySize = int(self.SampleFreq/self.FTrap.n) * NumberOfOscillations
except KeyError:
ValueError('You forgot to do the spectrum fit to specify self.FTrap exactly.')
VoltageArraySize = len(self.voltage)
SnippetsVariances = _np.var(self.voltage[:Voltag... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_gamma_from_energy_autocorrelation_fit(self, GammaGuess=None, silent=False, MakeFig=True, show_fig=True):
""" Calculates the total damping, i.e. Gamma, b... |
autocorrelation = calc_autocorrelation(self.voltage[:-1]**2*self.OmegaTrap.n**2+(_np.diff(self.voltage)*self.SampleFreq)**2)
time = self.time.get_array()[:len(autocorrelation)]
if GammaGuess==None:
Gamma_Initial = (time[4]-time[0])/(autocorrelation[0]-autocorrelation[4])
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 extract_parameters(self, P_mbar, P_Error, method="chang"):
""" Extracts the Radius, mass and Conversion factor for a particle. Parameters P_mbar : float The ... |
[R, M, ConvFactor], [RErr, MErr, ConvFactorErr] = \
extract_parameters(P_mbar, P_Error,
self.A.n, self.A.std_dev,
self.Gamma.n, self.Gamma.std_dev,
method = method)
self.Radius = _uncertainties.ufl... |
<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_value(self, ColumnName, RunNo):
""" Retreives the value of the collumn named ColumnName associated with a particular run number. Parameters ColumnName : ... |
Value = float(self.ORGTableData[self.ORGTableData.RunNo == '{}'.format(
RunNo)][ColumnName])
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 steady_state_potential(xdata,HistBins=100):
""" Calculates the steady state potential. Parameters xdata : ndarray Position data for a degree of freedom HistB... |
import numpy as np
pops=np.histogram(xdata,HistBins)[0]
bins=np.histogram(xdata,HistBins)[1]
bins=bins[0:-1]
bins=bins+np.mean(np.diff(bins))
#normalise pops
pops=pops/float(np.sum(pops))
return bins,-np.log(pops) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def finished(finished_status, update_interval, status_key, edit_at_key):
""" Create dict query for pymongo that getting all finished task. :param finished_status... |
return {
status_key: {"$gte": finished_status},
edit_at_key: {
"$gte": x_seconds_before_now(update_interval),
},
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unfinished(finished_status, update_interval, status_key, edit_at_key):
""" Create dict query for pymongo that getting all unfinished task. :param finished_st... |
return {
"$or": [
{status_key: {"$lt": finished_status}},
{edit_at_key: {"$lt": x_seconds_before_now(update_interval)}},
]
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getCommandLine(self):
"""Insert the precursor and change directory commands """ |
commandLine = self.precursor + self.sep if self.precursor else ''
commandLine += self.cd + ' ' + self.path + self.sep if self.path else ''
commandLine += PosixCommand.getCommandLine(self)
return commandLine |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _policy_psets(policy_instances):
"""Find all permission sets making use of all of a list of policy_instances. The input is an array of policy instances. """ |
if len(policy_instances) == 0:
# Special case: find any permission sets that don't have
# associated policy instances.
return PermissionSet.objects.filter(policyinstance__isnull=True)
else:
return PermissionSet.objects.filter(
policyinstance__policy__in=policy_instan... |
<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_permission_set_tree(user):
""" Helper to return cached permission set tree from user instance if set, else generates and returns analyzed permission set... |
if hasattr(user, CACHED_PSET_PROPERTY_KEY):
return getattr(user, CACHED_PSET_PROPERTY_KEY)
if user.is_authenticated():
try:
return user.permissionset.first().tree()
except AttributeError:
raise ObjectDoesNotExist
return PermissionSet.objects.get(anonymous_use... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ensure_permission_set_tree_cached(user):
""" Helper to cache permission set tree on user instance """ |
if hasattr(user, CACHED_PSET_PROPERTY_KEY):
return
try:
setattr(
user, CACHED_PSET_PROPERTY_KEY, _get_permission_set_tree(user))
except ObjectDoesNotExist: # No permission set
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parsed(self):
"""Get the JSON dictionary object which represents the content. This property is cached and only parses the content once. """ |
if not self._parsed:
self._parsed = json.loads(self.content)
return self._parsed |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cleanup_logger(self):
"""Clean up logger to close out file handles. After this is called, writing to self.log will get logs ending up getting discarded. """ |
self.log_handler.close()
self.log.removeHandler(self.log_handler) |
<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_configs(self, release):
""" Update the fedora-atomic.git repositories for a given release """ |
git_repo = release['git_repo']
git_cache = release['git_cache']
if not os.path.isdir(git_cache):
self.call(['git', 'clone', '--mirror', git_repo, git_cache])
else:
self.call(['git', 'fetch', '--all', '--prune'], cwd=git_cache)
git_dir = release['git_dir']... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mock_cmd(self, release, *cmd, **kwargs):
"""Run a mock command in the chroot for a given release""" |
fmt = '{mock_cmd}'
if kwargs.get('new_chroot') is True:
fmt +=' --new-chroot'
fmt += ' --configdir={mock_dir}'
return self.call(fmt.format(**release).split()
+ list(cmd)) |
<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_mock_config(self, release):
"""Dynamically generate our mock configuration""" |
mock_tmpl = pkg_resources.resource_string(__name__, 'templates/mock.mako')
mock_dir = release['mock_dir'] = os.path.join(release['tmp_dir'], 'mock')
mock_cfg = os.path.join(release['mock_dir'], release['mock'] + '.cfg')
os.mkdir(mock_dir)
for cfg in ('site-defaults.cfg', 'loggin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mock_chroot(self, release, cmd, **kwargs):
"""Run a commend in the mock container for a release""" |
return self.mock_cmd(release, '--chroot', cmd, **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 generate_repo_files(self, release):
"""Dynamically generate our yum repo configuration""" |
repo_tmpl = pkg_resources.resource_string(__name__, 'templates/repo.mako')
repo_file = os.path.join(release['git_dir'], '%s.repo' % release['repo'])
with file(repo_file, 'w') as repo:
repo_out = Template(repo_tmpl).render(**release)
self.log.debug('Writing repo file %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 ostree_init(self, release):
"""Initialize the OSTree for a release""" |
out = release['output_dir'].rstrip('/')
base = os.path.dirname(out)
if not os.path.isdir(base):
self.log.info('Creating %s', base)
os.makedirs(base, mode=0755)
if not os.path.isdir(out):
self.mock_chroot(release, release['ostree_init']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ostree_compose(self, release):
"""Compose the OSTree in the mock container""" |
start = datetime.utcnow()
treefile = os.path.join(release['git_dir'], 'treefile.json')
cmd = release['ostree_compose'] % treefile
with file(treefile, 'w') as tree:
json.dump(release['treefile'], tree)
# Only use new_chroot for the invocation, as --clean and --new-chr... |
<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_ostree_summary(self, release):
"""Update the ostree summary file and return a path to it""" |
self.log.info('Updating the ostree summary for %s', release['name'])
self.mock_chroot(release, release['ostree_summary'])
return os.path.join(release['output_dir'], 'summary') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sync_in(self, release):
"""Sync the canonical repo to our local working directory""" |
tree = release['canonical_dir']
if os.path.exists(tree) and release.get('rsync_in_objs'):
out = release['output_dir']
if not os.path.isdir(out):
self.log.info('Creating %s', out)
os.makedirs(out)
self.call(release['rsync_in_objs'])
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sync_out(self, release):
"""Sync our tree to the canonical location""" |
if release.get('rsync_out_objs'):
tree = release['canonical_dir']
if not os.path.isdir(tree):
self.log.info('Creating %s', tree)
os.makedirs(tree)
self.call(release['rsync_out_objs'])
self.call(release['rsync_out_rest']) |
<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(self, cmd, **kwargs):
"""A simple subprocess wrapper""" |
if isinstance(cmd, basestring):
cmd = cmd.split()
self.log.info('Running %s', cmd)
p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, **kwargs)
out, err = p.communicate()
if out:
self.log.info(out)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def intersect(self, other):
""" Determine the interval of overlap between this range and another. :returns: a new Range object representing the overlapping inter... |
if not self.overlap(other):
return None
newstart = max(self._start, other.start)
newend = min(self._end, other.end)
return Range(newstart, newend) |
<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(self, other):
"""Determine whether this range overlaps with another.""" |
if self._start < other.end and self._end > other.start:
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 contains(self, other):
"""Determine whether this range contains another.""" |
return self._start <= other.start and self._end >= other.end |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transform(self, offset):
""" Shift this range by the specified offset. Note: the resulting range must be a valid interval. """ |
assert self._start + offset > 0, \
('offset {} invalid; resulting range [{}, {}) is '
'undefined'.format(offset, self._start+offset, self._end+offset))
self._start += offset
self._end += offset |
<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(cls, command, cwd=".", **kwargs):
""" Make a subprocess call, collect its output and returncode. Returns CommandResult instance as ValueObject. """ |
assert isinstance(command, six.string_types)
command_result = CommandResult()
command_result.command = command
use_shell = cls.USE_SHELL
if "shell" in kwargs:
use_shell = kwargs.pop("shell")
# -- BUILD COMMAND ARGS:
if six.PY2 and isinstance(command,... |
<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_field_template(self, bound_field, template_name=None):
""" Uses a special field template for widget with multiple inputs. It only applies if no other tem... |
template_name = super().get_field_template(bound_field, template_name)
if (template_name == self.field_template and
isinstance(bound_field.field.widget, (
forms.RadioSelect, forms.CheckboxSelectMultiple))):
return 'tapeforms/fields/foundation_fieldset.ht... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def printer(self):
"""Prints PDA state attributes""" |
print " ID " + repr(self.id)
if self.type == 0:
print " Tag: - "
print " Start State - "
elif self.type == 1:
print " Push " + repr(self.sym)
elif self.type == 2:
print " Pop State " + repr(self.sym)
elif self.type == 3:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.