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 __public_objs(self):
""" Returns a dictionary mapping a public identifier name to a Python object. """ |
members = dict(inspect.getmembers(self.module))
return dict([(name, obj)
for name, obj in members.items()
if self.__is_exported(name, inspect.getmodule(obj))]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __new_submodule(self, name, obj):
""" Create a new submodule documentation object for this `obj`, which must by a Python module object and pass along any settings in this module. """ |
# Forcefully set the module name so that it is always the absolute
# import path. We can't rely on `obj.__name__`, since it doesn't
# necessarily correspond to the public exported name of the module.
obj.__dict__['__budoc_module_name'] = '%s.%s' % (self.refname, name)
return Module(obj,
docfilter=self._docfilter,
allsubmodules=self._allsubmodules) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def class_variables(self):
""" Returns all documented class variables in the class, sorted alphabetically as a list of `pydoc.Variable`. """ |
p = lambda o: isinstance(o, Variable) and self.module._docfilter(o)
return filter(p, self.doc.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 _fill_inheritance(self):
""" Traverses this class's ancestor list and attempts to fill in missing documentation from its ancestor's documentation. The first pass connects variables, methods and functions with their inherited couterparts. (The templates will decide how to display docstrings.) The second pass attempts to add instance variables to this class that were only explicitly declared in a parent class. This second pass is necessary since instance variables are only discoverable by traversing the abstract syntax tree. """ |
mro = filter(lambda c: c != self and isinstance(c, Class),
self.module.mro(self))
def search(d, fdoc):
for c in mro:
doc = fdoc(c)
if d.name in doc and isinstance(d, type(doc[d.name])):
return doc[d.name]
return None
for fdoc in (lambda c: c.doc_init, lambda c: c.doc):
for d in fdoc(self).values():
dinherit = search(d, fdoc)
if dinherit is not None:
d.inherits = dinherit
# Since instance variables aren't part of a class's members,
# we need to manually deduce inheritance. Oh lawdy.
for c in mro:
for name in filter(lambda n: n not in self.doc_init, c.doc_init):
d = c.doc_init[name]
self.doc_init[name] = Variable(d.name, d.module, '', cls=self)
self.doc_init[name].inherits = d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def params(self):
""" Returns a list where each element is a nicely formatted parameter of this function. This includes argument lists, keyword arguments and default values. """ |
def fmt_param(el):
if isinstance(el, str) or isinstance(el, unicode):
return el
else:
return '(%s)' % (', '.join(map(fmt_param, el)))
try:
getspec = getattr(inspect, 'getfullargspec', inspect.getargspec)
s = getspec(self.func)
except TypeError:
# I guess this is for C builtin functions?
return ['...']
params = []
for i, param in enumerate(s.args):
if param.lower() == 'self':
continue
if s.defaults is not None and len(s.args) - i <= len(s.defaults):
defind = len(s.defaults) - (len(s.args) - i)
default_value = s.defaults[defind]
value = repr(default_value).strip()
if value[0] == '<' and value[-1] == '>':
if type(default_value) == types.TypeType:
value = default_value.__name__
elif type(default_value) == types.ObjectType:
value = '%s()'%(default_value.__class__.__name__)
params.append('%s=%s' % (param, value))
else:
params.append(fmt_param(param))
if s.varargs is not None:
params.append('*%s' % s.varargs)
# TODO: This needs to be adjusted in Python 3. There's more stuff
# returned from getfullargspec than what we're looking at here.
keywords = getattr(s, 'varkw', getattr(s, 'keywords', None))
if keywords is not None:
params.append('**%s' % keywords)
return params |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _defaults():
"""Returns a dict of default args from the environment, which can be overridden by command line args. """ |
d = {}
d['url'] = os.environ.get('BUGZSCOUT_URL')
d['user'] = os.environ.get('BUGZSCOUT_USER')
d['project'] = os.environ.get('BUGZSCOUT_PROJECT')
d['area'] = os.environ.get('BUGZSCOUT_AREA')
return d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _from_args(args):
"""Factory method to create a new instance from command line args. :param args: instance of :class:`argparse.Namespace` """ |
return bugzscout.BugzScout(args.url, args.user, args.project, args.area) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_logging(verbose):
"""Enable logging o stream.""" |
hdlr = logging.StreamHandler()
hdlr.setFormatter(logging.Formatter(
'%(asctime)s [%(levelname)s] [%(module)s] %(message)s'))
LOG.addHandler(hdlr)
if verbose:
LOG.setLevel(logging.DEBUG)
LOG.debug('Verbose output enabled.')
else:
LOG.setLevel(logging.INFO) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_args():
"""Parse and return command line arguments.""" |
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=_CliFormatter)
parser.add_argument('-v', '--verbose', action='store_true',
help='Enable verbose output.')
fb_group = parser.add_argument_group('FogBugz arguments')
fb_group.add_argument(
'-u', '--url', help=(
'URL for bugzscout requests to be sent. Should be something '
'like .../scoutSubmit.asp.'))
fb_group.add_argument(
'--user', help='User to designate when submitting via bugzscout.')
fb_group.add_argument(
'--project', help='Fogbugz project to file cases under.')
fb_group.add_argument(
'--area', help='Fogbugz area to file cases under.')
error_group = parser.add_argument_group('error arguments')
error_group.add_argument('-e', '--extra',
help='Extra data to send with error.')
error_group.add_argument('--default-message',
help='Set default message if case is new.')
error_group.add_argument('description',
help=('Description of error. Will be matched '
'against existing cases.'))
parser.set_defaults(**_defaults())
return parser.parse_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 main():
"""Create a new instance and publish an error from command line args. There is a console script for invoking this function from the command line directly. """ |
args = _parse_args()
_init_logging(args.verbose)
client = _from_args(args)
client.submit_error(args.description, args.extra,
default_message=args.default_message) |
<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_lf_hf(x, xlf, xhf, title=''):
'''Plot original signal, low-pass filtered, and high-pass filtered signals
Args
----
x: ndarray
Signal data array
xlf: ndarray
Low-pass filtered signal
xhf: ndarray
High-pass filtered signal
title: str
Main title of plot
'''
from . import plotutils
fig, (ax1, ax2, ax3) = plt.subplots(3,1, sharex=True, sharey=True)
plt.title(title)
#ax1.title.set_text('All freqencies')
ax1.plot(range(len(x)), x, color=_colors[0], linewidth=_linewidth,
label='original')
ax1.legend(loc='upper right')
#ax2.title.set_text('Low-pass filtered')
ax2.plot(range(len(xlf)), xlf, color=_colors[1], linewidth=_linewidth,
label='low-pass')
ax2.legend(loc='upper right')
ax2.set_ylabel('Frequency (Hz)')
#ax3.title.set_text('High-pass filtered')
ax3.plot(range(len(xhf)), xhf, color=_colors[2], linewidth=_linewidth,
label='high-pass')
ax3.legend(loc='upper right')
ax1, ax2, ax3 = plotutils.add_alpha_labels([ax1, ax2, ax3], color='black',
facecolor='none',
edgecolor='none')
# TODO break into util function
# Convert sample # ticks to times
total_seconds = ax3.get_xticks()/16
# with timedelta: (stop - start).total_seconds()
hours, remainder = divmod(total_seconds, 3600)
minutes, seconds = divmod(remainder, 60)
strtime = lambda minutes, seconds: '{:.0f}:{:02.0f}'.format(minutes, seconds)
labels = list(map(strtime, minutes, seconds))
ax3.set_xticklabels(labels)
plt.xlabel('Sample time (minute:second)')
plt.show()
return 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 plot_acc_pry_depth(A_g_lf, A_g_hf, pry_deg, depths, glide_mask=None):
'''Plot the acceleration with the pitch, roll, and heading
Args
----
A_g_lf: ndarray
Low-pass filtered calibration accelerometer signal
A_g_hf: ndarray
High-pass filtered calibration accelerometer signal
pry_deg: ndarray
Pitch roll and heading in degrees
depths: ndarray
Depth data for all samples
glide_mask: ndarray
Boolean array for slicing glides from tag data
'''
import numpy
fig, (ax1, ax2, ax3) = plt.subplots(3,1, sharex=True)
ax1.title.set_text('acceleromter')
ax1.plot(range(len(A_g_lf)), A_g_lf, color=_colors[0])
ax1.title.set_text('PRH')
ax2.plot(range(len(pry_deg)), pry_deg, color=_colors[1])
ax3.title.set_text('depth')
ax3.plot(range(len(depths)), depths, color=_colors[2])
ax3.invert_yaxis()
if glide_mask is not None:
ind = range(len(glide_mask))
ax1 = plot_shade_mask(ax1, ind, glide_mask)
ax2 = plot_shade_mask(ax2, ind, glide_mask)
ax3 = plot_shade_mask(ax3, ind, glide_mask)
plt.show()
return 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 plot_welch_perdiogram(x, fs, nperseg):
'''Plot Welch perdiogram
Args
----
x: ndarray
Signal array
fs: float
Sampling frequency
nperseg: float
Length of each data segment in PSD
'''
import scipy.signal
import numpy
# Generate a test signal, a 2 Vrms sine wave at 1234 Hz, corrupted by
# 0.001V**2/Hz of white noise sampled at 10 kHz.
N = len(x)
time = numpy.arange(N) / fs
# Compute and plot the power spectral density.
f, Pxx_den = scipy.signal.welch(x, fs, nperseg=nperseg)
plt.semilogy(f, Pxx_den)
plt.ylim([0.5e-3, 1])
plt.xlabel('frequency [Hz]')
plt.ylabel('PSD [V**2/Hz]')
plt.show()
# If we average the last half of the spectral density, to exclude the peak,
# we can recover the noise power on the signal.
numpy.mean(Pxx_den[256:]) # 0.0009924865443739191
# compute power spectrum
f, Pxx_spec = scipy.signal.welch(x, fs, 'flattop', 1024,
scaling='spectrum')
plt.figure()
plt.semilogy(f, numpy.sqrt(Pxx_spec))
plt.xlabel('frequency [Hz]')
plt.ylabel('Linear spectrum [V RMS]')
plt.show()
return 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 plot_data_filter(data, data_f, b, a, cutoff, fs):
'''Plot frequency response and filter overlay for butter filtered data
Args
----
data: ndarray
Signal array
data_f: float
Signal sampling rate
b: array_like
Numerator of a linear filter
a: array_like
Denominator of a linear filter
cutoff: float
Cutoff frequency for the filter
fs: float
Sampling rate of the signal
Notes
-----
http://stackoverflow.com/a/25192640/943773
'''
import matplotlib.pyplot as plt
import numpy
import scipy.signal
n = len(data)
T = n/fs
t = numpy.linspace(0, T, n, endpoint=False)
# Calculate frequency response
w, h = scipy.signal.freqz(b, a, worN=8000)
# Plot the frequency response.
fig, (ax1, ax2) = plt.subplots(2,1)
ax1.title.set_text('Lowpass Filter Frequency Response')
ax1.plot(0.5*fs * w/numpy.pi, numpy.abs(h), 'b')
ax1.plot(cutoff, 0.5*numpy.sqrt(2), 'ko')
ax1.axvline(cutoff, color='k')
ax1.set_xlim(0, 0.5*fs)
ax1.set_xlabel('Frequency [Hz]')
ax2.legend()
# Demonstrate the use of the filter.
ax2.plot(t, data, linewidth=_linewidth, label='data')
ax2.plot(t, data_f, linewidth=_linewidth, label='filtered data')
ax2.set_xlabel('Time [sec]')
ax2.legend()
plt.show()
return 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 _build_url(self, host, sport, method, id, format, parameters):
""" build url from args """ |
path = "/".join(filter(None, (sport, method, id)))
url = "https://" + host + "/" + path + "." + format
if parameters:
paramstring = urllib.parse.urlencode(parameters)
url = url + "?" + paramstring
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 get_teams(self):
""" Return json current roster of team """ |
return self.make_request(host="erikberg.com", sport='nba',
method="teams", id=None,
format="json",
parameters={}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def prh(ax, ay, az):
'''Calculate the pitch, roll and heading for triaxial movement signalsi
Args
----
ax: ndarray
x-axis acceleration values
ay: ndarray
y-axis acceleration values
az: ndarray
z-axis acceleration values
Returns
-------
pitch: ndarray
Pitch angle in radians
roll: ndarray
Pitch angle in radians
yaw: ndarray
Pitch angle in radians
'''
p = pitch(ax, ay, az)
r = roll(ax, ay, az)
y = yaw(ax, ay, az)
#from dtag_toolbox_python.dtag2 import a2pr
#pitch, roll, A_norm = a2pr.a2pr(A_g)
return p, r, 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 absdeg(deg):
'''Change from signed degrees to 0-180 or 0-360 ranges
deg: ndarray
Movement data in pitch, roll, yaw (degrees)
Returns
-------
deg_abs: ndarray
Movement translated from -180:180/-90:90 degrees to 0:360/0:180 degrees
Example
-------
deg = numpy.array([-170, -120, 0, 90])
absdeg(deg) # returns array([190, 240, 0, 90])
'''
import numpy
d = numpy.copy(deg)
if numpy.max(numpy.abs(deg)) > 90.0:
d[deg < 0] = 360 + deg[deg < 0]
else:
d[deg < 0] = 180 + deg[deg < 0]
return d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def acceleration_magnitude(ax, ay, az):
'''Cacluate the magnitude of 3D acceleration
Args
----
ax: ndarray
x-axis acceleration values
ay: ndarray
y-axis acceleration values
az: ndarray
z-axis acceleration values
Returns
-------
acc_mag: ndarray
Magnitude of acceleration from combined acceleration axes
http://physics.stackexchange.com/a/41655/126878
'''
import numpy
return numpy.sqrt(ax**2 + ay**2 + az**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 pstd(self, *args, **kwargs):
""" Console to STDOUT """ |
kwargs['file'] = self.out
self.print(*args, **kwargs)
sys.stdout.flush() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def perr(self, *args, **kwargs):
""" Console to STERR """ |
kwargs['file'] = self.err
self.print(*args, **kwargs)
sys.stderr.flush() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pverb(self, *args, **kwargs):
""" Console verbose message to STDOUT """ |
if not self.verbose:
return
self.pstd(*args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(self, prompt='', clean=lambda x: x):
""" Display a prompt and ask user for input A function to clean the user input can be passed as ``clean`` argument. This function takes a single value, which is the string user entered, and returns a cleaned value. Default is a pass-through function, which is an equivalent of:: def clean(val):
return val """ |
ans = read(prompt + ' ')
return clean(ans) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rvpl(self, prompt, error='Entered value is invalid', intro=None, validator=lambda x: x != '', clean=lambda x: x.strip(), strict=True, default=None):
""" Start a read-validate-print loop The RVPL will read the user input, validate it, and loop until the entered value passes the validation, then return it. Error message can be customized using the ``error`` argument. If the value is a callable, it will be called with the value and it will be expected to return a printable message. Exceptions raised by the ``error`` function are not trapped. When ``intro`` is passed, it is printed above the prompt. The ``validator`` argument is is a function that validates the user input. Default validator simply validates if user entered any value. The ``clean`` argument specifies a function for the ``read()`` method with the same semantics. """ |
if intro:
self.pstd(utils.rewrap_long(intro))
val = self.read(prompt, clean)
while not validator(val):
if not strict:
return default
if hasattr(error, '__call__'):
self.perr(error(val))
else:
self.perr(error)
val = self.read(prompt, clean)
return 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 yesno(self, prompt, error='Please type either y or n', intro=None, default=None):
""" Ask user for yes or no answer The prompt will include a typical '(y/n):
' at the end. Depending on whether ``default`` was specified, this may also be '(Y/n):
' or '(y/N):
'. The ``default`` argument can be ``True`` or ``False``, with meaning of 'yes' and 'no' respectively. Default is ``None`` which means no default. When default value is specified, malformed or empty response will cause the ``default`` value to be returned. Optional ``intro`` text can be specified which will be shown above the prompt. """ |
if default is None:
prompt += ' (y/n):'
else:
if default is True:
prompt += ' (Y/n):'
default = 'y'
if default is False:
prompt += ' (y/N):'
default = 'n'
validator = lambda x: x in ['y', 'yes', 'n', 'no']
val = self.rvpl(prompt, error=error, intro=intro, validator=validator,
clean=lambda x: x.strip().lower(),
strict=default is None, default=default)
return val in ['y', 'yes'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def menu(self, choices, prompt='Please choose from the provided options:', error='Invalid choice', intro=None, strict=True, default=None, numerator=lambda x: [i + 1 for i in range(x)], formatter=lambda x, y: '{0:>3}) {1}'.format(x, y), clean=utils.safeint):
""" Print a menu The choices must be an iterable of two-tuples where the first value is the value of the menu item, and the second is the label for that matches the value. The menu will be printed with numeric choices. For example:: 1) foo 2) bar Formatting of the number is controlled by the formatter function which can be overridden by passing the ``formatter`` argument. The numbers used for the menu are generated using the numerator function which can be specified using the ``numerator`` function. This function must take the number of choices and return the same number of items that will be used as choice characters as a list. The cleaner function is passed to ``pvpl()`` method can be customized using ``clean`` argument. This function should generally be customized whenever ``numerator`` is customized, as default cleaner converts input to integers to match the default numerator. Optional ``intro`` argument can be passed to print a message above the menu. The return value of this method is the value user has chosen. The prompt will keep asking the user for input until a valid choice is selected. Each time an invalid selection is made, error message is printed. This message can be customized using ``error`` argument. If ``strict`` argument is set, then only values in choices are allowed, otherwise any value will be allowed. The ``default`` argument can be used to define what value is returned in case user select an invalid value when strict checking is off. """ |
numbers = list(numerator(len(choices)))
labels = (label for _, label in choices)
values = [value for value, _ in choices]
# Print intro and menu itself
if intro:
self.pstd('\n' + utils.rewrap_long(intro))
for n, label in zip(numbers, labels):
self.pstd(formatter(n, label))
# Define the validator
validator = lambda x: x in numbers
val = self.rvpl(prompt, error=error, validator=validator, clean=clean,
strict=strict, default=default)
if not strict and val == default:
return val
return values[numbers.index(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 readpipe(self, chunk=None):
""" Return iterator that iterates over STDIN line by line If ``chunk`` is set to a positive non-zero integer value, then the reads are performed in chunks of that many lines, and returned as a list. Otherwise the lines are returned one by one. """ |
read = []
while True:
l = sys.stdin.readline()
if not l:
if read:
yield read
return
return
if not chunk:
yield l
else:
read.append(l)
if len(read) == chunk:
yield read |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def error(self, msg='Program error: {err}', exit=None):
""" Error handler factory This function takes a message with optional ``{err}`` placeholder and returns a function that takes an exception object, prints the error message to STDERR and optionally quits. If no message is supplied (e.g., passing ``None`` or ``False`` or empty string), then nothing is output to STDERR. The ``exit`` argument can be set to a non-zero value, in which case the program quits after printing the message using its value as return value of the program. The returned function can be used with the ``progress()`` context manager as error handler. """ |
def handler(exc):
if msg:
self.perr(msg.format(err=exc))
if exit is not None:
self.quit(exit)
return handler |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
prog='.', excs=(Exception,), reraise=True):
""" Context manager for handling interactive prog indication This context manager streamlines presenting banners and prog indicators. To start the prog, pass ``msg`` argument as a start message. For example:: printer = Console(verbose=True) with printer.progress('Checking files') as prog: # Do some checks if errors: prog.abrt() prog.end() The context manager returns a ``Progress`` instance, which provides methods like ``abrt()`` (abort), ``end()`` (end), and ``prog()`` (print prog indicator). The prog methods like ``abrt()`` and ``end()`` will raise an exception that interrupts the prog. These exceptions are ``ProgressEnd`` exception subclasses and are ``ProgressAbrt`` and ``ProgressOK`` respectively. They are silenced and not handled in any way as they only serve the purpose of flow control. Other exceptions are trapped and ``abrt()`` is called. The exceptions that should be trapped can be customized using the ``excs`` argument, which should be a tuple of exception classes. If a handler function is passed using ``onerror`` argument, then this function takes the raised exception and handles it. By default, the ``error()`` factory is called with no arguments to generate the default error handler. If string is passed, then ``error()`` factory is called with that string. Finally, when prog is aborted either naturally or when exception is raised, it is possible to reraise the ``ProgressAbrt`` exception. This is done using the ``reraise`` flag. Default is to reraise. """ |
if not onerror:
onerror = self.error()
if type(onerror) is str:
onerror = self.error(msg=onerror)
self.pverb(msg, end=sep)
prog = progress.Progress(self.pverb, end=end, abrt=abrt, prog=prog)
try:
yield prog
prog.end()
except self.ProgressOK:
pass
except self.ProgressAbrt as err:
if reraise:
raise err
except KeyboardInterrupt:
raise
except excs as err:
prog.abrt(noraise=True)
if onerror:
onerror(err)
if self.debug:
traceback.print_exc()
if reraise:
raise self.ProgressAbrt() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(self, name_or_index, word):
""" Write a word in the Register with the name ``name_or_index`` or with the index ``name_or_index``. ``name_or_index`` hat to be either ``str`` or ``int``. If the type of ``name_or_index`` is wrong an AttributeError will be raised. If there is no Register with the specified name or index, a NameError will be raised. """ |
if(isinstance(name_or_index, str)):
if(name_or_index in self.registers_by_name):
self.registers_by_name[name_or_index].write(word)
else:
raise NameError("No Register with name '{}'".format(name_or_index))
elif( isinstance(name_or_index, int)):
if(name_or_index < len(self.registers_by_index)):
self.registers_by_index[name_or_index].write(word)
else:
raise NameError("No Register with index '{}'".format(name_or_index))
else:
raise AttributeError("name_or_index has to be `str` or `int`, but is {}".format(type(name_or_index))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_interrupt(self, interrupt):
""" Adds the interrupt to the internal interrupt storage ``self.interrupts`` and registers the interrupt address in the internal constants. """ |
self.interrupts.append(interrupt)
self.constants[interrupt.name] = interrupt.address |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interrupt(self, address):
""" Interrupts the Processor and forces him to jump to ``address``. If ``push_pc`` is enabled this will push the PC to the stack. """ |
if(self.push_pc):
self.memory_bus.write_word(self.sp, self.pc)
self._set_sp(self.sp - 1)
self._set_pc(address) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _raw_recv(self):
""" Return the next available IRC message in the buffer. """ |
with self.lock:
if self._index >= len(self._buffer):
self._mcon()
if self._index >= 199:
self._resetbuffer()
self._mcon()
msg = self._buffer[self._index]
while self.find(msg, 'PING :'):
self._index += 1
try:
msg = self._buffer[self._index]
except IndexError:
self._mcon()
self.stepback(append=False)
self._index += 1
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 post(json_data, url, dry_run=False):
""" POST json data to the url provided and verify the requests was successful """ |
if dry_run:
info('POST: %s' % json.dumps(json_data, indent=4))
else:
response = SESSION.post(url,
data=json.dumps(json_data),
headers={'content-type': 'application/json'})
if response.status_code != 200:
raise Exception("Failed to import %s with %s: %s" %
(json_data, response.status_code, response.text)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def push_json_file(json_file, url, dry_run=False, batch_size=100, anonymize_fields=[], remove_fields=[], rename_fields=[]):
""" read the json file provided and POST in batches no bigger than the batch_size specified to the specified url. """ |
batch = []
json_data = json.loads(json_file.read())
if isinstance(json_data, list):
for item in json_data:
# anonymize fields
for field_name in anonymize_fields:
if field_name in item:
item[field_name] = md5sum(item[field_name])
# remove fields
for field_name in remove_fields:
if field_name in item:
del item[field_name]
# rename fields
for (field_name, new_field_name) in rename_fields:
if field_name in item:
item[new_field_name] = item[field_name]
del item[field_name]
batch.append(item)
if len(batch) >= batch_size:
post(batch,
url,
dry_run=dry_run)
batch = []
if len(batch) > 0:
post(batch,
url,
dry_run=dry_run)
else:
post(json_data,
url,
dry_run=dry_run) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(self):
""" Loads the shop name and inventory """ |
pg = self.usr.getPage("http://www.neopets.com/objects.phtml?type=shop&obj_type=" + self.id)
self.name = pg.find("td", "contentModuleHeader").text.strip()
self.inventory = MainShopInventory(self.usr, self.id) |
<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_token(length=10):
""" Builds a random string. :param length: Token length. **Default:** 10 :type length: int :return: str """ |
return ''.join(random.choice(string.ascii_uppercase + string.digits)
for _ in range(length)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_plugins_directory(config_path=None, microdrop_user_root=None):
'''
Resolve plugins directory.
Plugins directory is resolved as follows, highest-priority first:
1. ``plugins`` directory specified in provided :data:`config_path`.
2. ``plugins`` sub-directory of specified MicroDrop profile path (i.e.,
:data:`microdrop_user_root`)
3. ``plugins`` sub-directory of parent directory of configuration file
path specified using ``MICRODROP_CONFIG`` environment variable.
4. ``plugins`` sub-directory of MicroDrop profile path specified using
``MICRODROP_PROFILE`` environment variable.
5. Plugins directory specified in
``<home directory>/MicroDrop/microdrop.ini``.
6. Plugins directory in default profile location, i.e.,
``<home directory>/MicroDrop/plugins``.
Parameters
----------
config_path : str, optional
Configuration file path (i.e., path to ``microdrop.ini``).
microdrop_user_root : str, optional
Path to MicroDrop user data directory.
Returns
-------
path
Absolute path to plugins directory.
'''
RESOLVED_BY_NONE = 'default'
RESOLVED_BY_CONFIG_ARG = 'config_path argument'
RESOLVED_BY_PROFILE_ARG = 'microdrop_user_root argument'
RESOLVED_BY_CONFIG_ENV = 'MICRODROP_CONFIG environment variable'
RESOLVED_BY_PROFILE_ENV = 'MICRODROP_PROFILE environment variable'
resolved_by = [RESOLVED_BY_NONE]
# # Find plugins directory path #
if microdrop_user_root is not None:
microdrop_user_root = path(microdrop_user_root).realpath()
resolved_by.append(RESOLVED_BY_PROFILE_ARG)
elif 'MICRODROP_PROFILE' in os.environ:
microdrop_user_root = path(os.environ['MICRODROP_PROFILE']).realpath()
resolved_by.append(RESOLVED_BY_PROFILE_ENV)
else:
microdrop_user_root = path(home_dir()).joinpath('MicroDrop')
if config_path is not None:
config_path = path(config_path).expand()
resolved_by.append(RESOLVED_BY_CONFIG_ARG)
elif 'MICRODROP_CONFIG' in os.environ:
config_path = path(os.environ['MICRODROP_CONFIG']).realpath()
resolved_by.append(RESOLVED_BY_CONFIG_ENV)
else:
config_path = microdrop_user_root.joinpath('microdrop.ini')
try:
# Look up plugins directory stored in configuration file.
plugins_directory = path(configobj.ConfigObj(config_path)
['plugins']['directory'])
if not plugins_directory.isabs():
# Plugins directory stored in configuration file as relative path.
# Interpret as relative to parent directory of configuration file.
plugins_directory = config_path.parent.joinpath(plugins_directory)
if not plugins_directory.isdir():
raise IOError('Plugins directory does not exist: {}'
.format(plugins_directory))
except Exception, why:
# Error looking up plugins directory in configuration file (maybe no
# plugins directory was listed in configuration file?).
plugins_directory = microdrop_user_root.joinpath('plugins')
logger.warning('%s. Using default plugins directory: %s', why,
plugins_directory)
if resolved_by[-1] in (RESOLVED_BY_CONFIG_ARG, RESOLVED_BY_CONFIG_ENV):
resolved_by.pop()
logger.info('Resolved plugins directory by %s: %s', resolved_by[-1],
plugins_directory)
return plugins_directory |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def plugin_request(plugin_str):
'''
Extract plugin name and version specifiers from plugin descriptor string.
.. versionchanged:: 0.25.2
Import from `pip_helpers` locally to avoid error `sci-bots/mpm#5`_.
.. _sci-bots/mpm#5: https://github.com/sci-bots/mpm/issues/5
'''
from pip_helpers import CRE_PACKAGE
match = CRE_PACKAGE.match(plugin_str)
if not match:
raise ValueError('Invalid plugin descriptor. Must be like "foo", '
'"foo==1.0", "foo>=1.0", etc.')
return match.groupdict() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tweetqueue(ctx, dry_run, config):
"""A command line tool for time-delaying your tweets.""" |
ctx.obj = {}
ctx.obj['DRYRUN'] = dry_run
# If the subcommand is "config", bypass all setup code
if ctx.invoked_subcommand == 'config':
return
# If the config file wasn't provided, attempt to load the default one.
if config is None:
user_home = os.path.expanduser("~")
default_config = os.path.join(user_home, ".tweetqueue")
if not os.path.isfile(default_config):
click.echo("Default configuration was not found and none was provided.")
click.echo("Run 'tweetqueue config' to create one.")
ctx.exit(1)
config = open(default_config, 'rb')
try:
ctx.obj['config'] = json.load(config)
except Exception as e:
click.echo("Unable to read configuration file.")
click.echo("Are you sure it is valid JSON")
click.echo("JSON Error: " + e.message)
ctx.exit(1)
# Verify that the config file has all required options
required_config = [
'API_KEY',
'API_SECRET',
'ACCESS_TOKEN',
'ACCESS_TOKEN_SECRET',
'DATABASE_LOCATION'
]
if not all(key in ctx.obj['config'] for key in required_config):
click.echo("Missing required value in config file.")
ctx.exit(1)
# Make a tweepy api object for the context
auth = tweepy.OAuthHandler(
ctx.obj['config']['API_KEY'],
ctx.obj['config']['API_SECRET']
)
auth.set_access_token(
ctx.obj['config']['ACCESS_TOKEN'],
ctx.obj['config']['ACCESS_TOKEN_SECRET']
)
ctx.obj['TWEEPY_API'] = tweepy.API(auth)
ctx.obj['TWEETLIST'] = TweetList(ctx.obj['config']['DATABASE_LOCATION']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tweet(ctx, message):
"""Sends a tweet directly to your timeline""" |
if not valid_tweet(message):
click.echo("Message is too long for twitter.")
click.echo("Message:" + message)
ctx.exit(2)
if not ctx.obj['DRYRUN']:
ctx.obj['TWEEPY_API'].update_status(message)
else:
click.echo("Tweet not sent due to dry-run mode.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def queue(ctx, message):
"""Adds a message to your twitter queue""" |
if not valid_tweet(message):
click.echo("Message is too long for twitter.")
click.echo("Message: " + message)
ctx.exit(2)
if ctx.obj['DRYRUN']:
click.echo("Message not queue due to dry-run mode.")
ctx.exit(0)
ctx.obj['TWEETLIST'].append(message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dequeue(ctx):
"""Sends a tweet from the queue""" |
tweet =ctx.obj['TWEETLIST'].peek()
if tweet is None:
click.echo("Nothing to dequeue.")
ctx.exit(1)
if ctx.obj['DRYRUN']:
click.echo(tweet)
else:
tweet = ctx.obj['TWEETLIST'].pop()
ctx.obj['TWEEPY_API'].update_status(tweet) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def config(ctx):
"""Creates a tweetqueue configuration file""" |
home_directory = os.path.expanduser('~')
default_config_file = os.path.join(home_directory, '.tweetqueue')
default_database_file = os.path.join(home_directory, '.tweetqueue.db')
config = {}
config['API_KEY'] = click.prompt('API Key')
config['API_SECRET'] = click.prompt('API Secret')
config['ACCESS_TOKEN'] = click.prompt('Access Token')
config['ACCESS_TOKEN_SECRET'] = click.prompt('Access Token Secret')
config['DATABASE_LOCATION'] = click.prompt('Database', default=default_database_file)
config_file = click.prompt('\nSave to', default=default_config_file)
if click.confirm('Do you want to save this configuration?', abort=True):
f = open(config_file, 'wb')
json.dump(config, f, indent=4, separators=(',',': '))
f.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 delete(ctx,tweet):
"""Deletes a tweet from the queue with a given ID""" |
if not ctx.obj['DRYRUN']:
try:
ctx.obj['TWEETLIST'].delete(tweet)
except ValueError as e:
click.echo("Now tweet was found with that id.")
ctx.exit(1)
else:
click.echo("Not ran due to dry-run.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def make_request(self, model, action, url_params={}, post_data=None):
'''
Send request to API then validate, parse, and return the response
'''
url = self._create_url(model, **url_params)
headers = self._headers(action)
try:
response = requests.request(action, url, headers=headers, data=post_data)
except Exception as e:
raise APIError("There was an error communicating with Union: %s" % e)
if not self._is_valid(response):
raise ValidationError("The Union response returned an error: %s" % response.content)
return self._parse_response(response) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def insert_jobs(jobs, verify_jobs=True, conn=None):
""" insert_jobs function inserts data into Brain.Jobs table jobs must be in Job format :param jobs: <list> of Jobs :param verify_jobs: <bool> :param conn: <rethinkdb.DefaultConnection> :return: <dict> rethinkdb insert response value """ |
assert isinstance(jobs, list)
if verify_jobs \
and not verify({Jobs.DESCRIPTOR.name: jobs}, Jobs()):
raise ValueError("Invalid Jobs")
inserted = RBJ.insert(jobs).run(conn)
return inserted |
<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_job_status(job_id, status, conn=None):
"""Updates a job to a new status :param job_id: <str> the id of the job :param status: <str> new status :param conn: <connection> a database connection (default: {None}) :return: <dict> the update dicts for the job and the output """ |
if status not in VALID_STATES:
raise ValueError("Invalid status")
job_update = RBJ.get(job_id).update({STATUS_FIELD: status}).run(conn)
if job_update["replaced"] == 0 and job_update["unchanged"] == 0:
raise ValueError("Unknown job_id: {}".format(job_id))
output_job_status = {OUTPUTJOB_FIELD: {STATUS_FIELD: status}}
if RBO.index_list().contains(IDX_OUTPUT_JOB_ID).run(conn):
# NEW
output_update = RBO.get_all(job_id, index=IDX_OUTPUT_JOB_ID).update(output_job_status).run(conn)
else:
# OLD
id_filter = (r.row[OUTPUTJOB_FIELD][ID_FIELD] == job_id)
output_update = RBO.filter(id_filter).update(output_job_status).run(conn)
return {str(RBJ): job_update, str(RBO): output_update} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_output(job_id, content, conn=None):
"""writes output to the output table :param job_id: <str> id of the job :param content: <str> output to write :param conn: """ |
output_job = get_job_by_id(job_id, conn)
results = {}
if output_job is not None:
entry = {
OUTPUTJOB_FIELD: output_job,
CONTENT_FIELD: content
}
results = RBO.insert(entry, conflict=RDB_REPLACE).run(conn)
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 generate_words(numberofwords, wordlist, secure=None):
"""Generate a list of random words from wordlist.""" |
if not secure:
chooser = random.choice
else:
chooser = random.SystemRandom().choice
return [chooser(wordlist) for _ in range(numberofwords)] |
<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_stream(filename):
"""Load a file stream from the package resources.""" |
rawfile = pkg_resources.resource_stream(__name__, filename)
if six.PY2:
return rawfile
return io.TextIOWrapper(rawfile, 'utf-8') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli():
"""Run the command line interface.""" |
args = docopt.docopt(__doc__, version=__VERSION__)
secure = args['--secure']
numberofwords = int(args['<numberofwords>'])
dictpath = args['--dict']
if dictpath is not None:
dictfile = open(dictpath)
else:
dictfile = load_stream('words.txt')
with dictfile:
wordlist = read_wordlist(dictfile)
words = generate_words(numberofwords, wordlist, secure=secure)
print(' '.join(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 processor_for(content_model_or_slug, exact_page=False):
""" Decorator that registers the decorated function as a page processor for the given content model or slug. When a page exists that forms the prefix of custom urlpatterns in a project (eg: the blog page and app), the page will be added to the template context. Passing in ``True`` for the ``exact_page`` arg, will ensure that the page processor is not run in this situation, requiring that the loaded page object is for the exact URL currently being viewed. """ |
content_model = None
slug = ""
if isinstance(content_model_or_slug, (str, _str)):
try:
parts = content_model_or_slug.split(".", 1)
content_model = apps.get_model(*parts)
except (TypeError, ValueError, LookupError):
slug = content_model_or_slug
elif issubclass(content_model_or_slug, Page):
content_model = content_model_or_slug
else:
raise TypeError("%s is not a valid argument for page_processor, "
"which should be a model subclass of Page in class "
"or string form (app.model), or a valid slug" %
content_model_or_slug)
def decorator(func):
parts = (func, exact_page)
if content_model:
model_name = content_model._meta.object_name.lower()
processors[model_name].insert(0, parts)
else:
processors["slug:%s" % slug].insert(0, parts)
return func
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def autodiscover():
""" Taken from ``django.contrib.admin.autodiscover`` and used to run any calls to the ``processor_for`` decorator. """ |
global LOADED
if LOADED:
return
LOADED = True
for app in get_app_name_list():
try:
module = import_module(app)
except ImportError:
pass
else:
try:
import_module("%s.page_processors" % app)
except:
if module_has_submodule(module, "page_processors"):
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 can_vote_on_poll(self, request):
"""Based on jmbo.models.can_vote.""" |
# can't vote if liking is closed
if self.votes_closed:
return False, 'closed'
# can't vote if liking is disabled
if not self.votes_enabled:
return False, 'disabled'
# anonymous users can't vote if anonymous votes are disabled
if not request.user.is_authenticated() and not \
self.anonymous_votes:
return False, 'auth_required'
# return false if existing votes are found
votes = Vote.objects.filter(
object_id__in=[o.id for o in self.polloption_set.all()],
token=request.secretballot_token
)
if votes.exists():
return False, 'voted'
else:
return True, 'can_vote' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vote_count(self):
""" Returns the total number of votes cast across all the poll's options. """ |
return Vote.objects.filter(
content_type=ContentType.objects.get(app_label='poll', model='polloption'),
object_id__in=[o.id for o in self.polloption_set.all()]
).aggregate(Sum('vote'))['vote__sum'] or 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 vote_count(self):
""" Returns the total number of votes cast for this poll options. """ |
return Vote.objects.filter(
content_type=ContentType.objects.get_for_model(self),
object_id=self.id
).aggregate(Sum('vote'))['vote__sum'] or 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 percentage(self):
""" Returns the percentage of votes cast for this poll option in relation to all of its poll's other options. """ |
total_vote_count = self.poll.vote_count
if total_vote_count:
return self.vote_count * 100.0 / total_vote_count
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 does_not_mutate(func):
"""Prevents methods from mutating the receiver""" |
def wrapper(self, *args, **kwargs):
new = self.copy()
return func(new, *args, **kwargs)
wrapper.__name__ = func.__name__
wrapper.__doc__ = func.__doc__
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 find_by(self, **kwargs):
""" Find first record subject to restrictions in +kwargs+, raising RecordNotFound if no such record exists. """ |
result = self.where(**kwargs).first()
if result:
return result
else:
raise RecordNotFound(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 where(self, *custom_restrictions, **restrictions):
""" Restricts the records to the query subject to the passed +restrictions+. Analog to "WHERE" in SQL. Can pass multiple restrictions, and can invoke this method multiple times per query. """ |
for attr, value in restrictions.items():
self.where_query[attr] = value
if custom_restrictions:
self.custom_where.append(tuple(custom_restrictions))
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def joins(self, table):
""" Analog to "INNER JOIN" in SQL on the passed +table+. Use only once per query. """ |
def do_join(table, model):
while model is not associations.model_from_name(table):
# ex) Category -> Forum -> Thread -> Post
# Category: {"posts": "forums"}
# Forum: {"posts": "threads"}
# Thread: {"posts": None}
# >>> Category.joins("posts")
# => [
# {'table': 'forums', 'on': ['category_id', 'id']}
# {'table': 'threads', 'on': ['forum_id', 'id']}
# {'table': 'posts', 'on': ['thread_id', 'id']}
# ]
if table in associations.associations_for(model):
# This to next: one-many (they have the fk)
# If associations.associations_for(model)[table] is None, then this is
# terminal (i.e. table is the FINAL association in the
# chain)
next_level = associations.associations_for(model)[table] or table
next_model = associations.model_from_name(next_level)
foreign_key = associations.foreign_keys_for(model).get(
next_level,
inflector.foreignKey(model.__name__))
yield {'table': next_level, 'on': [foreign_key, 'id']}
else:
# One-One or Many-One
# singular table had better be in associations.associations_for(model)
singular = inflector.singularize(table)
next_level = associations.associations_for(model)[singular] or singular
next_model = associations.model_from_name(next_level)
this_table_name = Repo.table_name(model)
foreign_key = associations.foreign_keys_for(model).get(
next_level,
inflector.foreignKey(model.__name__))
if associations.model_has_foreign_key_for_table(table,
model):
# we have the foreign key
order = ['id', foreign_key]
else:
# They have the foreign key
order = [foreign_key, 'id']
yield {'table': inflector.pluralize(next_level), 'on': order}
model = next_model
self.join_args = list(do_join(table, self.model))
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self, **attributes):
""" Creates a new record suject to the restructions in the query and with the passed +attributes+. Operates using `build`. """ |
record = self.build(**attributes)
record.save()
return record |
<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(technical_terms_filename, spellchecker_cache_path):
"""Create a Dictionary at spellchecker_cache_path with technical words.""" |
user_dictionary = os.path.join(os.getcwd(), "DICTIONARY")
user_words = read_dictionary_file(user_dictionary)
technical_terms_set = set(user_words)
if technical_terms_filename:
with open(technical_terms_filename) as tech_tf:
technical_terms_set |= set(tech_tf.read().splitlines())
return Dictionary(technical_terms_set,
"technical_words",
dictionary_sources=[technical_terms_filename,
user_dictionary],
cache=spellchecker_cache_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 connect(self, agent='Python'):
""" Context manager for HTTP Connection state and ensures proper handling of network sockets, sends a GET request. Exception is raised at the yield statement. :yield request: FileIO<Socket> """ |
headers = {'User-Agent': agent}
request = urlopen(Request(self.url, headers=headers))
try:
yield request
finally:
request.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 reader(self):
""" Reads raw text from the connection stream. Ensures proper exception handling. :return bytes: request """ |
request_stream = ''
with self.connect() as request:
if request.msg != 'OK':
raise HTTPError
request_stream = request.read().decode('utf-8')
return request_stream |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def json(self):
""" Serializes json text stream into python dictionary. :return dict: json """ |
_json = json.loads(self.reader)
if _json.get('error', None):
raise HTTPError(_json['error']['errors'])
return _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 import_class(classpath, package=None):
""" Load and return a class """ |
if '.' in classpath:
module, classname = classpath.rsplit('.', 1)
if package and not module.startswith('.'):
module = '.{0}'.format(module)
mod = import_module(module, package)
else:
classname = classpath
mod = import_module(package)
return getattr(mod, classname) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_module(self, module, idx=-1):
""" Register a module. You could indicate position inside inner list. :param module: must be a string or a module object to register. :type module: str :param idx: position where you want to insert new module. By default it is inserted at the end. :type idx: int """ |
if module in self._modules:
raise AlreadyRegisteredError("Module '{0}' is already registered on loader.".format(module))
if idx < 0:
self._modules.append(module)
else:
self._modules.insert(idx, module) |
<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_class(self, classname):
""" Loads a class looking for it in each module registered. :param classname: Class name you want to load. :type classname: str :return: Class object :rtype: type """ |
module_list = self._get_module_list()
for module in module_list:
try:
return import_class(classname, module.__name__)
except (AttributeError, ImportError):
pass
raise ImportError("Class '{0}' could not be loaded.".format(classname)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def factory(self, classname, *args, **kwargs):
""" Creates an instance of class looking for it in each module registered. You can add needed params to instance the class. :param classname: Class name you want to create an instance. :type classname: str :return: An instance of classname :rtype: object """ |
klass = self.load_class(classname)
return self.get_factory_by_class(klass)(*args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_factory_by_class(self, klass):
""" Returns a custom factory for class. By default it will return the class itself. :param klass: Class type :type klass: type :return: Class factory :rtype: callable """ |
for check, factory in self._factories.items():
if klass is check:
return factory(self, klass)
for check, factory in self._factories.items():
if issubclass(klass, check):
return factory(self, klass)
return klass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_module(self, module, namespace=None):
""" Register a module. :param module: must be a string or a module object to register. :type module: str :param namespace: Namespace tag. If it is None module will be used as namespace tag :type namespace: str """ |
namespace = namespace if namespace is not None else module \
if isinstance(module, str) else module.__name__
self.register_namespace(namespace, module) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_namespace(self, namespace, module):
""" Register a namespace. :param namespace: Namespace tag. :type namespace: str :param module: must be a string or a module object to register. :type module: str """ |
if namespace in self._namespaces:
raise AlreadyRegisteredError("Namespace '{0}' is already registered on loader.".format(namespace))
self._namespaces[namespace] = module |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unregister_namespace(self, namespace):
""" Unregister a namespace. :param namespace: Namespace tag. :type namespace: str """ |
if namespace not in self._namespaces:
raise NoRegisteredError("Namespace '{0}' is not registered on loader.".format(namespace))
del self._namespaces[namespace] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close(self):
""" Close service client and its plugins. """ |
self._execute_plugin_hooks_sync(hook='close')
if not self.session.closed:
ensure_future(self.session.close(), loop=self.loop) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def api(f):
"""Decorator for functions and methods that are part of the external module API and that can throw XPathError exceptions. The call stack for these exceptions can be very large, and not very interesting to the user. This decorator rethrows XPathErrors to trim the stack. """ |
def api_function(*args, **kwargs):
try:
return f(*args, **kwargs)
except XPathError, e:
raise e
api_function.__name__ = f.__name__
api_function.__doc__ = f.__doc__
return api_function |
<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(self, path, strict):
""" Gets the item for `path`. If `strict` is true, this method returns `None` when matching path is not found. Otherwise, this returns the result item of prefix searching. :param path: Path to get :param strict: Searching mode :type path: list :type strict: bool """ |
item, pathinfo = self._get(path, strict)
if item is None:
if strict:
return None, pathinfo
else:
return self._item, pathinfo
else:
return item, pathinfo |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set(self, path, item, replace):
""" Sets item for `path` and returns the item. Replaces existing item with `item` when `replace` is true :param path: Path for item :param item: New item :param replace: Updating mode :type path: list :type item: object :type replace: bool """ |
if len(path) == 0:
if self._item is None or replace:
self._item = item
return self._item
else:
head, tail = path[0], path[1:]
if head.startswith(':'):
default = (head[1:], self.__class__())
_, rtree = self._subtrees.setdefault(self._WILDCARD, default)
return rtree.set(tail, item, replace)
else:
rtree = self._subtrees.setdefault(head, self.__class__())
return rtree.set(tail, item, replace) |
<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_ajax_rsvps(event, user_profile):
"""Return link and list strings for a given event.""" |
if user_profile in event.rsvps.all():
link_string = True
else:
link_string = False
if not event.rsvps.all().count():
list_string = 'No RSVPs.'
else:
list_string = 'RSVPs:'
for counter, profile in enumerate(event.rsvps.all()):
if counter > 0:
list_string += ','
list_string += \
' <a class="page_link" title="View Profile" href="{url}">' \
'{name}</a>'.format(
url=reverse(
'member_profile',
kwargs={'targetUsername': profile.user.username}
),
name='You' if profile.user == user_profile.user \
else profile.user.get_full_name(),
)
return (link_string, list_string) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setResponse(self, response):
""" A response has been received by the gateway """ |
self.response = response
self.result = self.response.body
if isinstance(self.result, remoting.ErrorFault):
self.result.raiseException() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addHeader(self, name, value, must_understand=False):
""" Sets a persistent header to send with each request. @param name: Header name. """ |
self.headers[name] = value
self.headers.set_required(name, must_understand) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getRequest(self, id_):
""" Gets a request based on the id. :raise LookupError: Request not found. """ |
for request in self.requests:
if request.id == id_:
return request
raise LookupError("Request %r not found" % (id_,)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addRequest(self, service, *args):
""" Adds a request to be sent to the remoting gateway. """ |
wrapper = RequestWrapper(self, '/%d' % self.request_number,
service, *args)
self.request_number += 1
self.requests.append(wrapper)
if self.logger:
self.logger.debug('Adding request %s%r', wrapper.service, args)
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 removeRequest(self, service, *args):
""" Removes a request from the pending request list. """ |
if isinstance(service, RequestWrapper):
if self.logger:
self.logger.debug('Removing request: %s',
self.requests[self.requests.index(service)])
del self.requests[self.requests.index(service)]
return
for request in self.requests:
if request.service == service and request.args == args:
if self.logger:
self.logger.debug('Removing request: %s',
self.requests[self.requests.index(request)])
del self.requests[self.requests.index(request)]
return
raise LookupError("Request not found") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute_single(self, request):
""" Builds, sends and handles the response to a single request, returning the response. """ |
if self.logger:
self.logger.debug('Executing single request: %s', request)
self.removeRequest(request)
body = remoting.encode(self.getAMFRequest([request]), strict=self.strict)
http_request = urllib2.Request(self._root_url, body.getvalue(),
self._get_execute_headers())
if self.proxy_args:
http_request.set_proxy(*self.proxy_args)
envelope = self._getResponse(http_request)
return envelope[request.id] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _getResponse(self, http_request):
""" Gets and handles the HTTP response from the remote gateway. """ |
if self.logger:
self.logger.debug('Sending POST request to %s', self._root_url)
try:
fbh = self.opener(http_request)
except urllib2.URLError, e:
if self.logger:
self.logger.exception('Failed request for %s',
self._root_url)
raise remoting.RemotingError(str(e))
http_message = fbh.info()
content_encoding = http_message.getheader('Content-Encoding')
content_length = http_message.getheader('Content-Length') or -1
content_type = http_message.getheader('Content-Type')
server = http_message.getheader('Server')
if self.logger:
self.logger.debug('Content-Type: %r', content_type)
self.logger.debug('Content-Encoding: %r', content_encoding)
self.logger.debug('Content-Length: %r', content_length)
self.logger.debug('Server: %r', server)
if content_type != remoting.CONTENT_TYPE:
if self.logger:
self.logger.debug('Body = %s', fbh.read())
raise remoting.RemotingError('Incorrect MIME type received. '
'(got: %s)' % (content_type,))
bytes = fbh.read(int(content_length))
if self.logger:
self.logger.debug('Read %d bytes for the response', len(bytes))
if content_encoding and content_encoding.strip().lower() == 'gzip':
if not GzipFile:
raise remoting.RemotingError(
'Decompression of Content-Encoding: %s not available.' % (
content_encoding,))
compressedstream = StringIO(bytes)
gzipper = GzipFile(fileobj=compressedstream)
bytes = gzipper.read()
gzipper.close()
response = remoting.decode(bytes, strict=self.strict)
if self.logger:
self.logger.debug('Response: %s', response)
if remoting.APPEND_TO_GATEWAY_URL in response.headers:
self.original_url += response.headers[remoting.APPEND_TO_GATEWAY_URL]
self._setUrl(self.original_url)
elif remoting.REPLACE_GATEWAY_URL in response.headers:
self.original_url = response.headers[remoting.REPLACE_GATEWAY_URL]
self._setUrl(self.original_url)
if remoting.REQUEST_PERSISTENT_HEADER in response.headers:
data = response.headers[remoting.REQUEST_PERSISTENT_HEADER]
for k, v in data.iteritems():
self.headers[k] = v
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setCredentials(self, username, password):
""" Sets authentication credentials for accessing the remote gateway. """ |
self.addHeader('Credentials', dict(userid=username.decode('utf-8'),
password=password.decode('utf-8')), True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def patch_gevent_hub():
""" This patches the error handler in the gevent Hub object. """ |
from gevent.hub import Hub
def patched_handle_error(self, context, etype, value, tb):
""" Patched to not print KeyboardInterrupt exceptions. """
if isinstance(value, str):
value = etype(value)
not_error = issubclass(etype, self.NOT_ERROR)
system_error = issubclass(etype, self.SYSTEM_ERROR)
if not not_error and not issubclass(etype, KeyboardInterrupt):
self.print_exception(context, etype, value, tb)
if context is None or system_error:
self.handle_system_error(etype, value)
Hub._original_handle_error = Hub.handle_error
Hub.handle_error = patched_handle_error |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def col2name(col_item):
"helper for SyntheticTable.columns. takes something from SelectX.cols, returns a string column name"
if isinstance(col_item, sqparse2.NameX): return col_item.name
elif isinstance(col_item, sqparse2.AliasX): return col_item.alias
else: raise TypeError(type(col_item), col_item) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def add(self, name, target):
"target should be a Table or SyntheticTable"
if not isinstance(target, (table.Table, SyntheticTable)):
raise TypeError(type(target), target)
if name in self:
# note: this is critical for avoiding cycles
raise ScopeCollisionError('scope already has', name)
self.names[name] = target |
<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_from_upstream(pkg_name, repo_url):
"""Clone a non-existent package using the upstream registry.""" |
msg = "Spawning a cloning task for %s from upstream due to API req."
LOG.info(msg % pkg_name)
upstream_url = settings.UPSTREAM_BOWER_REGISTRY
upstream_pkg = bowerlib.get_package(upstream_url, pkg_name)
if upstream_pkg is None:
raise Http404
task = tasks.clone_repo.delay(pkg_name, upstream_pkg['url'])
try:
result = task.get(timeout=5)
except tasks.TimeoutError:
# Not done yet. What to return?
raise ServiceUnavailable
return result.to_package(repo_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 allocate_port():
"""Allocate an unused port. There is a small race condition here (between the time we allocate the port, and the time it actually gets used), but for the purposes for which this function gets used it isn't a problem in practice. """ |
sock = socket.socket()
try:
sock.bind(("localhost", 0))
return get_port(sock)
finally:
sock.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 spawn(self):
"""Spawn the fake executable using subprocess.Popen.""" |
self._process = subprocess.Popen(
[self.path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
self.addCleanup(self._process_kill) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def listen(self, port=None):
"""Make the fake executable listen to the specified port. Possible values for 'port' are: - None: Allocate immediately a free port and instruct the fake executable to use it when it's invoked. This is subject to a race condition, if that port that was free when listen() was invoked later becomes used before the fake executable had chance to bind to it. However it has the advantage of exposing the free port as FakeExecutable.port instance variable, that can easily be consumed by tests. - An integer: Listen to this specific port. """ |
if port is None:
port = allocate_port()
self.port = port
self.line("import socket")
self.line("sock = socket.socket()")
self.line("sock.bind(('localhost', {}))".format(self.port))
self.log("listening: %d" % self.port)
self.line("sock.listen(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 _process_kill(self):
"""Kill the fake executable process if it's still running.""" |
if self._process.poll() is None: # pragma: no cover
self._process.kill()
self._process.wait(timeout=5) |
<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_info(self):
"""Return details about the fake process.""" |
if not self._process:
return []
output, error = self._process.communicate(timeout=5)
if error is None:
error = b""
output = output.decode("utf-8").strip()
error = error.decode("utf-8").strip()
info = (u"returncode: %r\n"
u"output:\n%s\n"
u"error:\n%s\n" % (self._process.returncode, output, error))
return [info.encode("utf-8")] |
<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_tasks_from_file(self, file_path):
""" Imports specified python module and returns subclasses of BaseTask from it :param file_path: a fully qualified file path for a python module to import CustomTasks from :type file_path: `str` :return: a dict of CustomTasks, where key is CustomTask.name, and value is a CustomClass task itself :rtype: `dict` """ |
file_name, module_path, objects = Loader.import_custom_python_file(file_path)
result = {}
for entry in objects:
try:
if issubclass(entry, BaseTask):
if entry.__name__ != BaseTask.__name__ and entry.name == BaseTask.name:
raise GOSTaskException("Class {class_name} form file {file_name} does not have a unique `name` class field. "
"All custom tasks must have a unique `name` class field for them, tat is used for future reference"
"".format(class_name=entry.name, file_name=os.path.join(module_path, file_name)))
result[entry.name] = entry
except TypeError:
continue
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_tasks_from_dir(self, dir_path, propagate_exceptions=False):
""" Imports all python modules in specified directories and returns subclasses of BaseTask from them :param propagate_exceptions: a flag that indicates if exceptions from single file import shall be raised during the whole directory lookup :param dir_path: fully qualified directory path, where all python modules will be search for subclasses of BaseTask :type dir_path: `str` :return: a dict of CustomTasks, where key is CustomTask.name, and value is a CustomClass task itself :rtype: `dict` """ |
if not os.path.exists(dir_path):
raise GOSTaskException()
if os.path.isfile(dir_path):
raise GOSTaskException()
result = {}
for file_basename in os.listdir(dir_path):
full_file_path = os.path.join(dir_path, file_basename)
try:
result.update(self.load_tasks_from_file(full_file_path))
except (GOSTaskException, GOSIOException):
if propagate_exceptions:
raise
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_tasks(self, paths, propagate_exception=False):
""" Loads all subclasses of BaseTask from modules that are contained in supplied directory paths or direct module paths :param propagate_exception: a flag that indicates if exceptions from single file import shall be raised during the whole directory lookup :param paths: an iterable of fully qualified paths to python modules / directories, from where we import subclasses of BaseClass :type paths: `iterable`(`str`) :return: a dict of CustomTasks, where key is CustomTask.name, and value is a CustomClass task itself :rtype: `dict` """ |
try:
result = {}
for path in paths:
try:
if os.path.isdir(path):
result.update(self.load_tasks_from_dir(dir_path=path, propagate_exceptions=propagate_exception))
elif os.path.isfile(path):
result.update(self.load_tasks_from_file(file_path=path))
except (GOSTaskException, GOSIOException):
if propagate_exception:
raise
return result
except TypeError:
raise GOSTaskException("Argument for `load_tasks` method must be iterable") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.