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 start(self, *args, **kwargs):
"""Start the task. This is: * not threadsave * assumed to be called in the gtk mainloop """ |
args = (self.counter,) + args
thread = threading.Thread(
target=self._work_callback,
args=args, kwargs=kwargs
)
thread.setDaemon(self.daemon)
thread.start() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_image_to_rgb_mode(image, fill_color=(255, 255, 255)):
""" Convert the specified image instance to RGB mode. @param image: a Python Library Image (PIL... |
if image.mode not in ('RGBA', 'LA'):
return image
# In most cases simply discarding the alpha channel will give
# undesirable result, because transparent pixels also have some
# unpredictable colors. It is much better to fill transparent pixels
# with a specified color.
background_imag... |
<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_multiple_pixel_resolutions(image, pixel_resolutions, filter=Filter.NearestNeighbor, does_crop=False, crop_aligment=CropAlignment.center, match_orient... |
for (logical_size, width, height) in \
sorted(pixel_resolutions, key=lambda (l, w, h): w, reverse=True):
yield (logical_size,
resize_image(image, (width, height),
filter=filter,
does_crop=does_crop,
crop_aligment=crop_aligment,
... |
<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_exposure(image, filters=None):
""" Determine the exposure of a photo, which can be under-exposed, normally exposed or over-exposed. @param image: a Pytho... |
def _get_exposure(histogram):
total = sum(histogram)
range_offset = len(histogram) / 4
dark = float(sum(histogram[0:range_offset])) / total
#normal = float(sum(histogram[range_offset:-range_offset])) / total
light = float(sum(histogram[-range_offset:])) / total
retur... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_image_file_valid(file_path_name):
""" Indicate whether the specified image file is valid or not. @param file_path_name: absolute path and file name of an ... |
# Image.verify is only implemented for PNG images, and it only verifies
# the CRC checksum in the image. The only way to check from within
# Pillow is to load the image in a try/except and check the error. If
# as much info as possible is from the image is needed,
# ``ImageFile.LOAD_TRUNCATED_IMA... |
<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_and_reorient_image(handle):
""" Load the image from the specified file and orient the image accordingly to the Exif tag that the file might embed, which... |
# Retrieve tags from the Exchangeable image file format (Exif)
# included in the picture. If the orientation of the picture is not
# top left side, rotate it accordingly.
# @deprecated
# exif_tags = dict([ (exif_tag.tag, exif_tag)
# for exif_tag in exif.process_file(handle).itervalues()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def realign_image(image, shift_x, shift_y, max_shift_x, max_shift_y, shift_angle=0.0, filter=Filter.NearestNeighbor, stretch_factor=None, cropping_box=None):
"""... |
(width, height) = image.size
# Determine the new size of the image based on the maximal horizontal
# and vertical shifts of all the other images in this series.
new_width = width - max_shift_x * 2
new_height = height - max_shift_y * 2
# Determine the coordinates of the zone to crop to center ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resize_image(image, canvas_size, filter=Filter.NearestNeighbor, does_crop=False, crop_aligment=CropAlignment.center, crop_form=CropForm.rectangle, match_orien... |
(source_width, source_height) = image.size
source_aspect = source_width / float(source_height)
(canvas_width, canvas_height) = canvas_size
canvas_aspect = canvas_width / float(canvas_height)
if match_orientation:
if (source_aspect > 1.0 > canvas_aspect) or (source_aspect < 1.0 < canvas_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 __get_vtt_angles(self, pvals, nvals):
""" Fit the angles to the model Args: pvals (array-like) : positive values nvals (array-like) : negative valu... |
# https://www.khanacademy.org/math/trigonometry/unit-circle-trig-func/inverse_trig_functions/v/inverse-trig-functions--arctan
angles = np.arctan2(pvals, nvals)-np.pi/4
norm = np.maximum(np.minimum(angles, np.pi-angles), -1*np.pi-angles)
norm = csr_matrix(norm)
# Remove any weight from the NER features. These... |
<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_params(self, **params):
""" Set the parameters of the estimator. Args: bias (array-like) : bias of the estimator. Also known as the intercept in a... |
if 'bias' in params.keys():
self.intercept_ = params['bias']
if 'weights' in params.keys():
self.coef_ = params['weights']
for key in params.keys():
if 'b_' == key[:2]:
self.B[int(key[2:])] = params[key]
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 get_params(self, deep=True):
""" Get parameters for the estimator. Args: deep (boolean, optional) : If True, will return the parameters for this estim... |
params = {'weights':self.coef_, 'bias':self.intercept_}
if deep:
for key, value in self.B.items():
params['b_'+str(key)] = value
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 send_email(hostname, username, password, author_name, author_email_address, recipient_email_addresses, subject, content, file_path_names=None, port_number=587... |
# Convert bare string representing only one email address as a list with
# this single email address.
if not isinstance(recipient_email_addresses, (list, set, tuple)):
recipient_email_addresses = [ recipient_email_addresses ]
# Build the message to be sent.
message = MIMEMultipart()
me... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def confirm_send(address, amount, ref_id=None, session=ses):
""" Confirm that a send has completed. Does not actually check confirmations, but instead assumes th... |
debitq = session.query(wm.Debit)
debitq = debitq.filter(wm.Debit.address == address)
debitq = debitq.filter(wm.Debit.amount == amount)
debit = debitq.filter(wm.Debit.transaction_state == 'unconfirmed').first()
if not debit:
raise ValueError("Debit already confirmed or address unknown.")
... |
<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_config(path):
""" Read a configuration from disk. Arguments path -- the loation to deserialize """ |
parser = _make_parser()
if parser.read(path):
return parser
raise Exception("Failed to read {}".format(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 correct_rytov_sc_input(radius_sc, sphere_index_sc, medium_index, radius_sampling):
"""Inverse correction of refractive index and radius for Rytov This method... |
params = get_params(radius_sampling)
# sage script:
# var('sphere_index, sphere_index_sc, na, nb, medium_index')
# x = sphere_index / medium_index - 1
# eq = sphere_index_sc == sphere_index + ( na*x^2 + nb*x) * medium_index
# solve([eq], [sphere_index])
# (take the positive sign solution)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def correct_rytov_output(radius, sphere_index, medium_index, radius_sampling):
r"""Error-correction of refractive index and radius for Rytov This method corrects... |
params = get_params(radius_sampling)
x = sphere_index / medium_index - 1
radius_sc = radius * (params["ra"] * x**2
+ params["rb"] * x
+ params["rc"])
sphere_index_sc = sphere_index + medium_index * (params["na"] * x**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 rytov_sc(radius=5e-6, sphere_index=1.339, medium_index=1.333, wavelength=550e-9, pixel_size=1e-7, grid_size=(80, 80), center=(39.5, 39.5), radius_sampling=42)... |
r_ryt, n_ryt = correct_rytov_sc_input(radius_sc=radius,
sphere_index_sc=sphere_index,
medium_index=medium_index,
radius_sampling=radius_sampling)
qpi = mod_rytov.rytov(radius=r_ryt,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gsignal(name, *args, **kwargs):
"""Add a GObject signal to the current object. It current supports the following types: - str, int, float, long, object, enum... |
frame = sys._getframe(1)
try:
locals = frame.f_locals
finally:
del frame
dict = locals.setdefault('__gsignals__', {})
if args and args[0] == 'override':
dict[name] = 'override'
else:
retval = kwargs.get('retval', None)
if retval is None:
de... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gproperty(name, ptype, default=None, nick='', blurb='', flags=gobject.PARAM_READWRITE, **kwargs):
"""Add a GObject property to the current object. :param nam... |
# General type checking
if default is None:
default = _DEFAULT_VALUES.get(ptype)
elif not isinstance(default, ptype):
raise TypeError("default must be of type %s, not %r" % (
ptype, default))
if not isinstance(nick, str):
raise TypeError('nick for property %s must b... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def refresh_gui(delay=0.0001, wait=0.0001):
"""Use up all the events waiting to be run :param delay: Time to wait before using events :param wait: Time to wait b... |
time.sleep(delay)
while gtk.events_pending():
gtk.main_iteration_do(block=False)
time.sleep(wait) |
<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_in_window(target, on_destroy=gtk.main_quit):
"""Run a widget, or a delegate in a Window """ |
w = _get_in_window(target)
if on_destroy:
w.connect('destroy', on_destroy)
w.resize(500, 400)
w.move(100, 100)
w.show_all()
gtk.main() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def dict_to_form(dict):
'''
Generate a flatland form based on a pandas Series.
'''
from flatland import Boolean, Form, String, Integer, Float
def is_float(v):
try:
return (float(str(v)), True)[1]
except (ValueError, TypeError):
return False
def is_int(v)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _detect_term_type():
""" Detect the type of the terminal. """ |
if os.name == 'nt':
if os.environ.get('TERM') == 'xterm':
# maybe MinTTY
return 'mintty'
else:
return 'nt'
if platform.system().upper().startswith('CYGWIN'):
return 'cygwin'
return 'posix' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear(self):
""" Clear the terminal screen. """ |
if hasattr(self.stdout, 'isatty') and self.stdout.isatty() or self.term_type == 'mintty':
cmd, shell = {
'posix': ('clear', False),
'nt': ('cls', True),
'cygwin': (['echo', '-en', r'\ec'], False),
'mintty': (r'echo -en "\ec', 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 clear_input_buffer(self):
""" Clear the input buffer. """ |
if hasattr(self.stdin, 'isatty') and self.stdin.isatty():
if os.name == 'nt':
while msvcrt.kbhit():
msvcrt.getch()
else:
try:
self.stdin.seek(0, 2) # may fail in some unseekable file object
except I... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getch(self):
""" Read one character from stdin. If stdin is not a tty or set `getch_enabled`=False, read input as one line. :return: unicode: """ |
ch = self._get_one_char()
if self.keep_input_clean:
self.clear_input_buffer()
try:
# accept only unicode characters (for Python 2)
uch = to_unicode(ch, 'ascii')
except UnicodeError:
return ''
return uch if self._check_key_repeat(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gets(self):
""" Read line from stdin. The trailing newline will be omitted. :return: string: """ |
ret = self.stdin.readline()
if ret == '':
raise EOFError # To break out of EOF loop
return ret.rstrip('\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 create_parser(self, subparsers):
""" Creates the subparser for this particular command """ |
self.parser = subparsers.add_parser(self.name, help=self.help, parents=self.parents)
self.add_arguments()
self.parser.set_defaults(func=self.handle)
return self.parser |
<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_arguments(self):
""" Definition and addition of all arguments. """ |
if self.parser is None:
raise TypeError("Parser cannot be None, has create_parser been called?")
for keys, kwargs in self.args.items():
if not isinstance(keys, tuple):
keys = (keys,)
self.parser.add_argument(*keys, **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 allocation(node,format,h):
'''
Allocation provides a snapshot of how shards have located around the
cluster and the state of disk usage
'''
try:
response = base.es.cat.allocation(node_id=node,bytes=format, h=h, format='json')
table = base.draw_table(response)
except Exception... |
<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(index,h):
'''
Gives count of the documents stored in Elasticsearch. If index option is
provided, it will provide document count of that index.
'''
try:
response = base.es.cat.count(index,h=h)
table = base.draw_table(response)
except Exception as e:
click.echo(e)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close(self):
""" Close the connection to the AMQP compliant broker. """ |
if self.channel is not None: self.channel.close()
if self.__connection is not None: self.__connection.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 open(self):
""" Open a connection to the AMQP compliant broker. """ |
self._connection = \
amqp.Connection(host='%s:%s' % (self.hostname, self.port),
userid=self.username, password=self.password,
virtual_host=self.virtual_host, insist=False)
self.channel = self._connection.channel() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def publish(self, message_type, message_payload):
""" Publish the specified object that the function automatically converts into a JSON string representation. Th... |
payload = json.dumps(jsonpickle.Pickler(unpicklable=False).flatten(message_payload))
message = amqp.Message(payload)
message.properties["delivery_mode"] = 2
name = 'majormode.%s.%s.%s' % (settings.ENVIRONMENT_STAGE, self.service_name.lower(), message_type.lower())
self.channel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_py_dtypes(data_frame):
'''
Return a `pandas.DataFrame` containing Python type information for the
columns in `data_frame`.
Args:
data_frame (pandas.DataFrame) : Data frame containing data columns.
Returns:
(pandas.DataFrame) : Data frame indexed by the column names from
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_list_store(data_frame):
'''
Return a `pandas.DataFrame` containing Python type information for the
columns in `data_frame` and a `gtk.ListStore` matching the contents of the
data frame.
Args:
data_frame (pandas.DataFrame) : Data frame containing data columns.
Returns:
... |
<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_columns(tree_view, df_py_dtypes, list_store):
'''
Add columns to a `gtk.TreeView` for the types listed in `df_py_dtypes`.
Args:
tree_view (gtk.TreeView) : Tree view to append columns to.
df_py_dtypes (pandas.DataFrame) : Data frame containing type
information for one or... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def daemonize():
""" Daemonize the program, ie. make it run in the "background", detach it from its controlling terminal and from its controlling process group s... |
try:
pid = os.fork()
if pid > 0:
os._exit(0) # pylint: disable-msg=W0212
except OSError, e:
log.exception("first fork() failed: %d (%s)", e.errno, e.strerror)
sys.exit(1)
os.setsid()
os.umask(0)
os.chdir("/")
try:
pid = os.fork()
if ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def redirect_stream(system_stream, target_stream):
""" Redirect a system stream to a specified file. `system_stream` is a standard system stream such as ``sys.st... |
if target_stream is None:
target_fd = os.open(os.devnull, os.O_RDWR)
else:
target_fd = target_stream.fileno()
os.dup2(target_fd, system_stream.fileno()) |
<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_utf8_streams():
"""Forces UTF-8 on stdout and stderr; in some crazy environments, they use 'ascii' encoding by default """ |
def ensure_utf8_stream(stream):
if not isinstance(stream, io.StringIO):
stream = getwriter("utf-8")(getattr(stream, "buffer", stream))
stream.encoding = "utf-8"
return stream
sys.stdout, sys.stderr = (ensure_utf8_stream(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 configure(name, host, port, auth, current):
'''
Configure is used to add various ES ports you are working on.
The user can add as many es ports as the one wants,
but one will remain active at one point.
'''
Config = ConfigParser.ConfigParser()
if not os.path.exists(os.path.dirname(filena... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compare_parts(list1, list2):
""" if list2 does not start with list1, we can't really check and return 0 """ |
for i, item in enumerate(list1):
if item != list2[i]:
return 0
if len(list2) > len(list1):
return ISDIR
else:
return ISFILE |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_event(urls):
""" This parallel fetcher uses gevent one uses gevent """ |
rs = (grequests.get(u) for u in urls)
return [content.json() for content in grequests.map(rs)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sendTemplate(mailer, sender, recipient, template, context, hook=_nop):
""" Simple case for sending some e-mail using a template. """ |
headers, parts = template.evaluate(context)
headers["From"] = sender
headers["To"] = recipient
hook(headers, parts)
content = mime.buildMessage(headers, parts)
return mailer.send(sender, recipient, content) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def export_cmd(cmd, src_path, dest_dir=None, item_id=None, export_format=None, scale=None):
''' Executes a `sketchtool export` command and returns formatted output
:src_path: File to export. :type <str>
:dest_dir: Items are exported at /dest_dir/name@scale.export_format e.g. `~/Desktop/Page 1@2x.png`
:param ex... |
<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_binaries():
"""Download and return paths of all platform-specific binaries""" |
paths = []
for arp in [False, True]:
paths.append(get_binary(arp=arp))
return paths |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def backward_propagation(parameters, cache, X, Y):
""" Implement the backward propagation using the instructions above. Arguments: parameters -- python dictionar... |
m = X.shape[1]
# First, retrieve W1 and W2 from the dictionary "parameters".
W1 = parameters["W1"]
W2 = parameters["W2"]
# Retrieve also A1 and A2 from dictionary "cache".
A1 = cache["A1"]
A2 = cache["A2"]
# Backward propagation: calculate dW1, db1, dW2, db2.
dZ2 = A2 - Y
dW2... |
<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_parameters(parameters, grads, learning_rate=1.2):
""" Updates parameters using the gradient descent update rule given above Arguments: parameters -- p... |
# Retrieve each parameter from the dictionary "parameters"
W1 = parameters["W1"]
b1 = parameters["b1"]
W2 = parameters["W2"]
b2 = parameters["b2"]
# Retrieve each gradient from the dictionary "grads"
dW1 = grads["dW1"]
db1 = grads["db1"]
dW2 = grads["dW2"]
db2 = grads["db2"]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def predict(parameters, X):
""" Using the learned parameters, predicts a class for each example in X Arguments: parameters -- python dictionary containing your p... |
# Computes probabilities using forward propagation,
# and classifies to 0/1 using 0.5 as the threshold.
A2, cache = forward_propagation(X, parameters)
predictions = np.array([1 if (i > 0.5) else 0 for i in A2[0]])
return predictions |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_email(sender, pw, to, subject, content, files=None, service='163'):
"""send email, recommended use 163 mailbox service, as it is tested. :param sender: ... |
se = EmailSender(from_=sender, pw=pw, service=service)
se.send_email(to=to, subject=subject, content=content, files=files)
se.quit() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def nodes(self, node=None):
'''walks through tree and yields each node'''
if node is None:
for root in self.stack:
yield from self.nodes(root)
else:
yield node
if node.is_container():
for child in node.children:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def context(self, message):
'''
Function decorator which adds "context" around a group of TestCases and may have
a `before` and `after` func.
>>> s = Suite()
>>> @s.context('context 1')
... def _():
... @s.before
... def _(): 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 it(self, message, repeat=None):
'''
Function decorator which adds a TestCase to the Suite
>>> s = Suite()
>>> @s.it('always passes')
... def _(): pass
>>> list(s.nodes())
[<Container: root>, <TestCase: always passes>]
`repeat` w... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spammer_view(request):
"""View for setting cookies on spammers.""" |
# Permits use of CSRF middleware
context = RequestContext(request, {})
template = Template("")
response = HttpResponse(template.render(context))
# Sets a cookie with a 10 years lifetime, accessible only via HTTP:
response.set_cookie(COOKIE_KEY, value=COOKIE_SPAM, httponly=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 load_object_by_name(object_name):
"""Load an object from a module by name""" |
mod_name, attr = object_name.rsplit('.', 1)
mod = import_module(mod_name)
return getattr(mod, attr) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bench_serpy():
"""Beanchmark for 1000 objects with 2 fields. """ |
class FooSerializer(serpy.DictSerializer):
"""The serializer schema definition."""
# Use a Field subclass like IntField if you need more validation.
attr_2 = serpy.IntField()
attr_1 = serpy.StrField()
return [FooSerializer(obj).data for obj in object_loader()] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decompose_locale(locale, strict=True):
""" Return the decomposition of the specified locale into a language code and a country code. @param locale: a string ... |
if locale is None:
return ('eng', None)
match = REGEX_LOCALE.match(locale)
if match is None:
if strict == True:
raise Locale.MalformedLocaleException()
match = REGEX_JAVA_LOCALE.match(locale)
if match is None:
rais... |
<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_drops(self, dropin):
"""Load `drops` from the given dropin. Args: dropin (string):
path of a dropin, e.g. dropin.auth Returns: An iterable contains the... |
obj = load_object(dropin)
try:
drops = getattr(obj, self.drops_type)
except AttributeError:
try:
drops = load_object('%s.%s' % (dropin, self.drops_type))
except ImportError:
drops = None
if hasattr(drops, '__drops__'):
... |
<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_drops(self, dropin):
"""Register the `drops` in given `dropin` to a flask app. Args: app (Flask):
the flask app to be initialized dropin (string):
... |
drops = self.app.extensions['dropin'].setdefault(self.drops_type, [])
drops.extend(self.load_drops(dropin)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge(cls, *others):
""" Merge the `others` schema into this instance. The values will all be read from the provider of the original object. """ |
for other in others:
for k, v in other:
setattr(cls, k, BoundValue(cls, k, v.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 field_value(self, value):
"""Validate against NodeType. """ |
if not self.is_array:
return self.field_type(value)
if isinstance(value, (list, tuple, set)):
return [self.field_type(item) for item in value]
return self.field_type(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 is_valid(self, value):
"""Validate value before actual instance setting based on type. Args: value (object):
The value object for validation. Returns: True ... |
if not self.is_array:
return self._valid(value)
if isinstance(value, (list, set, tuple)):
return all([self._valid(item) for item in value])
return self._valid(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 _attr_data_(self):
"Special property containing the memoized data."
try:
return self.__attr_data
except AttributeError:
self.__attr_data = type(
''.join([type(self).__name__, 'EmptyData']),
(),
{
'__... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _attr_func_(self):
"Special property containing functions to be lazily-evaluated."
try:
return self.__attr_func
except AttributeError:
self.__attr_func = type(
''.join([type(self).__name__, 'EmptyFuncs']),
(),
{
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _loadable_get_(name, self):
"Used to lazily-evaluate & memoize an attribute."
func = getattr(self._attr_func_, name)
ret = func()
setattr(self._attr_data_, name, ret)
setattr(
type(self),
name,
property(
functools.partial(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 _setable_get_(name, self):
"Used to raise an exception for attributes unable to be evaluated yet."
raise AttributeError(
"'{typename}' object has no attribute '{name}'".format(
typename=type(self).__name__,
name=name
)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _setable_set_(name, self, func):
"Used to set the attribute a single time using the given function."
setattr(self._attr_data_, name, func())
if hasattr(self._attr_func_, name):
delattr(self._attr_func_, name)
setattr(
type(self),
name,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _set_attr(self, name, doc=None, preload=False):
"Initially sets up an attribute."
if doc is None:
doc = 'The {name} attribute.'.format(name=name)
if not hasattr(self._attr_func_, name):
attr_prop = property(
functools.partial(self._setable_get_, name... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def simple(type, short, long=None, parent=None, buttons=gtk.BUTTONS_OK, default=None, **kw):
"""A simple dialog :param type: The type of dialog :param short: The... |
if buttons == gtk.BUTTONS_OK:
default = gtk.RESPONSE_OK
return _message_dialog(type, short, long, parent=parent, buttons=buttons,
default=default, **kw) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open_filechooser(title, parent=None, patterns=None, folder=None, filter=None, multiple=False, _before_run=None, action=None):
"""An open dialog. :param paren... |
assert not (patterns and filter)
if multiple:
if action is not None and action != gtk.FILE_CHOOSER_ACTION_OPEN:
raise ValueError('`multiple` is only valid for the action '
'`gtk.FILE_CHOOSER_ACTION_OPEN`.')
action = gtk.FILE_CHOOSER_ACTION_OPEN
else... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(title='Save', parent=None, current_name='', folder=None, _before_run=None, _before_overwrite=None):
"""Displays a save dialog.""" |
filechooser = gtk.FileChooserDialog(title, parent,
gtk.FILE_CHOOSER_ACTION_SAVE,
(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
gtk.STOCK_SAVE, gtk.RESPONSE_OK))
if current_name:
filechoose... |
<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_nans(df):
""" Count the total number of NaNs in every column Parameters df pd.DataFrame Returns nas_df pd.DataFrame """ |
cols = df.columns
res = []
for col in cols:
length = len(df[col])
not_nas = len(df[col].dropna())
nas = length - not_nas
rate = round(nas/length, 4)
# add unique value
uv = len(df[col].unique())
res_ = (col, nas, not_nas, rate, uv)
res.append(... |
<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_project_dir(path=os.getcwd()):
"""Attempt to find the project root, returns None if not found""" |
path_split = os.path.split(path)
while path_split[1]:
if in_armstrong_project(path):
return path
path = path_split[0]
path_split = os.path.split(path)
# we ran out of parents
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 _commonprefix(m):
"Given a list of pathnames, returns the longest common leading component"
if not m:
return ''
prefix = m[0]
for item in m:
for i in range(len(prefix)):
if prefix[:i+1] != item[:i+1]:
prefix = prefix[:i]
if i == 0:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_headers(self, headers, cache_info=None):
""" Prepare headers object for request (add cache information :param headers: Headers object :type headers: ... |
if self.use_advanced and cache_info:
hkeys = headers.keys()
if cache_info.access_time and "If-Modified-Since" not in hkeys:
headers['If-Modified-Since'] = cache_info.access_time.strftime(
"%a, %d %b %Y %H:%M:%S GMT"
)
if ca... |
<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, url, ignore_access_time=False):
""" Try to retrieve url from cache if available :param url: Url to retrieve :type url: str | unicode :param ignore_... |
key = hashlib.md5(url).hexdigest()
accessed = self._cache_meta_get(key)
if not accessed:
# not previously cached
self.debug("From inet {}".format(url))
return None, None
if isinstance(accessed, dict):
cached = CacheInfo.from_dict(accesse... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, url, cache_info=None):
""" Update cache information for url :param url: Update for this url :type url: str | unicode :param cache_info: Cache in... |
key = hashlib.md5(url).hexdigest()
access_time = None
if not cache_info:
cache_info = CacheInfo()
if not access_time:
cache_info.access_time = now_utc()
self._cache_meta_set(key, cache_info.to_dict()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put(self, url, html, cache_info=None):
""" Put response into cache :param url: Url to cache :type url: str | unicode :param html: HTML content of url :type h... |
key = hashlib.md5(url).hexdigest()
try:
self._cache_set(key, html)
except:
self.exception("Failed to write cache")
return
self.update(url, cache_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 urisplit(uri):
""" Basic URI Parser according to STD66 aka RFC3986 ('scheme', 'authority', 'path', 'query', 'fragment') """ |
inner_part = re.compile(r'\(\(.*?\)\)')
m = inner_part.search(uri)
inner_value = ''
if m is not None:
inner_value = uri[m.start():m.end()]
uri = uri[:m.start()]+'__inner_part__'+uri[m.end():]
# regex straight from STD 66 section B
regex = '^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split_authority(authority):
""" Basic authority parser that splits authority into component parts ('user', 'password', 'host', 'port') """ |
if '@' in authority:
userinfo, hostport = authority.split('@', 1)
else:
userinfo, hostport = None, authority
if userinfo and ':' in userinfo:
user, passwd = userinfo.split(':', 1)
else:
user, passwd = userinfo, None
if hostport and ':' in hostport:
host, port... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(self, uri, defaults=None):
"""Parse the URI. uri is the uri to parse. defaults is a scheme-dependent list of values to use if there is no value for tha... |
return tuple([self.scheme_of(uri)] + list(self.parser_for(uri)(defaults).parse(uri))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unparse(self, pieces, defaults=None):
"""Join the parts of a URI back together to form a valid URI. pieces is a tuble of URI pieces. The scheme must be in pi... |
return self.parser_for(pieces[0])(defaults).unparse(pieces) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parser_for(self, uri):
"""Return the Parser object used to parse a particular URI. Parser objects are required to have only 'parse' and 'unparse' methods. ""... |
return self._parsers.get(self.scheme_of(uri), DefaultURIParser) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear_temp(wdir, rmdir=True):
"""Remove all files in wdir""" |
wdir = pathlib.Path(wdir)
extensions = ["*.log", "*.dat", "*.txt"]
for ext in extensions:
for ff in wdir.glob(ext):
ff.unlink()
if rmdir:
wdir.rmdir() |
<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_field(wdir, shape_grid):
"""Extract electric field from simulation file "V_0Ereim.dat" Parameters wdir: str or pathlib.Path path to the working director... |
wdir = pathlib.Path(wdir)
check_simulation(wdir)
field_file = wdir / "V_0Ereim.dat"
a = np.loadtxt(field_file)
assert shape_grid[0] == int(
shape_grid[0]), "resulting x-size is not an integer"
assert shape_grid[1] == int(
shape_grid[1]), "resulting y-size is not an integer"
... |
<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_simulation(wdir):
""" Check bhdebug.txt to make sure that you specify enough digits to overcome roundoff errors. """ |
wdir = pathlib.Path(wdir)
field = wdir / "V_0Ereim.dat"
if not (field.exists() and
field.stat().st_size > 130):
msg = "Output {} does not exist or is too small!".format(field)
raise BHFIELDExecutionError(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 slices(src_path):
''' Return slices as a flat list '''
pages = list_slices(src_path)
slices = []
for page in pages:
slices.extend(page.slices)
return slices |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def artboards(src_path):
''' Return artboards as a flat list '''
pages = list_artboards(src_path)
artboards = []
for page in pages:
artboards.extend(page.artboards)
return artboards |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verify_response(self, response_json, signed_id_name='transactionid'):
""" Verify the response message. :param response_json: :param signed_id_name: :return: ... |
auth_json = response_json.get('auth', {})
nonce = auth_json.get('nonce', '')
timestamp = auth_json.get('timestamp', '')
signature = binascii.unhexlify(auth_json.get('signature', ''))
signed_id = response_json.get(signed_id_name, '')
return self.verify_signature(signat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def soup(self):
'''
Returns HTML as a BeautifulSoup element.
'''
components_soup = Tag(name=self.tagname, builder=BUILDER)
components_soup.attrs = self.attributes
for c in flatten(self.components):
if hasattr(c, 'soup'):
components_soup.app... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def plugins(self, deduplicate=False):
'''
Returns a flattened list of all plugins used by page components.
'''
plugins = []
for c in self.components:
if hasattr(c, 'plugins'):
plugins += c.plugins()
elif isinstance(c, Lib):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def soup(self):
'''
Running plugins and adding an HTML doctype to the
generated Tag HTML.
'''
dom = BeautifulSoup('<!DOCTYPE html>')
# BeautifulSoup behaves differently if lxml is installed or not,
# and will create a basic HTML structure if lxml is insta... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _eq__(self, other):
""" Compare the current place object to another passed to the comparison method. The two place objects must have the same identification,... |
return self.place_id and other.place_id \
and self.place_id == other.place_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 from_json(payload):
""" Build a ``Place`` instance from the specified JSON object. @param payload: JSON representation of a place:: { "area_id": string, "add... |
return payload and \
Place([ (float(lon), float(lat), float(alt)) for (lon, lat, alt) in payload['boundaries']]
if payload.get('boundaries') else GeoPoint.from_json(payload['location']),
address=payload.get('address') and (
Place.__parse_ad... |
<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_classes(package_str):
'''Load all classes from modules of a given `package_str`. All class instances are stored in a case-insensitive `dict`
and returned. If a package doesn't contain any class `None` is returned'''
_logger.debug('Loading all modules from %s', package_str)
package = importlib.... |
<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(package_str, classname):
'''Retrieve from the internal cache a class instance. All arguments are case-insensitive'''
if (package_str in _dynamo_cache) and (classname in _dynamo_cache[package_str]):
return _dynamo_cache[package_str][classname]
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 ex_literal(val):
"""An int, float, long, bool, string, or None literal with the given value. """ |
if val is None:
return ast.Name('None', ast.Load())
elif isinstance(val, int):
return ast.Num(val)
elif isinstance(val, bool):
return ast.Name(bytes(val), ast.Load())
elif isinstance(val, str):
return ast.Str(val)
raise TypeError(u'no literal for {0}'.format(type(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 ex_varassign(name, expr):
"""Assign an expression into a single variable. The expression may either be an `ast.expr` object or a value to be used as a litera... |
if not isinstance(expr, ast.expr):
expr = ex_literal(expr)
return ast.Assign([ex_lvalue(name)], expr) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ex_call(func, args):
"""A function-call expression with only positional parameters. The function may be an expression or the name of a function. Each argumen... |
if isinstance(func, str):
func = ex_rvalue(func)
args = list(args)
for i in range(len(args)):
if not isinstance(args[i], ast.expr):
args[i] = ex_literal(args[i])
if sys.version_info[:2] < (3, 5):
return ast.Call(func, args, [], None, None)
else:
return ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compile_func(arg_names, statements, name='_the_func', debug=False):
"""Compile a list of statements as the body of a function and return the resulting Python... |
func_def = ast.FunctionDef(
name=name,
args=ast.arguments(
args=[ast.arg(arg=n, annotation=None) for n in arg_names],
kwonlyargs=[],
kw_defaults=[],
defaults=[ex_literal(None) for _ in arg_names],
),
body=statements,
decorator_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.