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 post(self, request, *args, **kwargs):
""" Returns POST response. :param request: the request instance. :rtype: django.http.HttpResponse. """ |
form = None
link_type = int(request.POST.get('link_type', 0))
if link_type == Link.LINK_TYPE_EMAIL:
form = EmailLinkForm(**self.get_form_kwargs())
elif link_type == Link.LINK_TYPE_EXTERNAL:
form = ExternalLinkForm(**self.get_form_kwargs())
if f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_form_class(self):
""" Returns form class to use in the view. :rtype: django.forms.ModelForm. """ |
if self.object.link_type == Link.LINK_TYPE_EMAIL:
return EmailLinkForm
elif self.object.link_type == Link.LINK_TYPE_EXTERNAL:
return ExternalLinkForm
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 set_password(self, service, username, password):
"""Write the password to the registry """ |
# encrypt the password
password_encrypted = _win_crypto.encrypt(password.encode('utf-8'))
# encode with base64
password_base64 = base64.encodestring(password_encrypted)
# encode again to unicode
password_saved = password_base64.decode('ascii')
# store the passwo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encrypt(self, password):
"""Encrypt the password. """ |
if not password or not self._crypter:
return password or b''
return self._crypter.encrypt(password) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decrypt(self, password_encrypted):
"""Decrypt the password. """ |
if not password_encrypted or not self._crypter:
return password_encrypted or b''
return self._crypter.decrypt(password_encrypted) |
<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, mode='r'):
"""Open the password file in the specified mode """ |
open_file = None
writeable = 'w' in mode or 'a' in mode or '+' in mode
try:
# NOTE: currently the MemOpener does not split off any filename
# which causes errors on close()
# so we add a dummy name and open it separately
if (self.filen... |
<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(self):
"""load the passwords from the config file """ |
if not hasattr(self, '_config'):
raw_config = configparser.RawConfigParser()
f = self._open()
if f:
raw_config.readfp(f)
f.close()
self._config = raw_config
return self._config |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_queryset(self):
""" Returns queryset limited to categories with live Entry instances. :rtype: django.db.models.query.QuerySet. """ |
queryset = super(LiveEntryCategoryManager, self).get_queryset()
return queryset.filter(tag__in=[
entry_tag.tag
for entry_tag
in EntryTag.objects.filter(entry__live=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 get_for_tag(self, tag):
""" Returns queryset of Entry instances assigned to specified tag, which can be a PK value, a slug value, or a Tag instance. :param t... |
tag_filter = {'tag': tag}
if isinstance(tag, six.integer_types):
tag_filter = {'tag_id': tag}
elif isinstance(tag, str):
tag_filter = {'tag__slug': tag}
return self.filter(id__in=[
entry_tag.entry_id
for entry_tag
in EntryTag... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def for_category(self, category, live_only=False):
""" Returns queryset of EntryTag instances for specified category. :param category: the Category instance. :pa... |
filters = {'tag': category.tag}
if live_only:
filters.update({'entry__live': True})
return self.filter(**filters) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def related_to(self, entry, live_only=False):
""" Returns queryset of Entry instances related to specified Entry instance. :param entry: the Entry instance. :par... |
filters = {'tag__in': entry.tags}
if live_only:
filters.update({'entry__live': True})
return self.filter(**filters).exclude(entry=entry) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chosen_view_factory(chooser_cls):
""" Returns a ChosenView class that extends specified chooser class. :param chooser_cls: the class to extend. :rtype: class... |
class ChosenView(chooser_cls):
#noinspection PyUnusedLocal
def get(self, request, *args, **kwargs):
"""
Returns GET response.
:param request: the request instance.
:rtype: django.http.HttpResponse.
"""
#noinspection PyAttribut... |
<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, request, *args, **kwargs):
""" Returns GET response. :param request: the request instance. :rtype: django.http.HttpResponse. """ |
#noinspection PyAttributeOutsideInit
self.object_list = self.get_queryset()
context = self.get_context_data(force_search=True)
if self.form_class:
context.update({'form': self.get_form()})
if 'q' in request.GET or 'p' in request.GET:
retu... |
<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_entry_tag(sender, instance, created, **kwargs):
""" Creates EntryTag for Entry corresponding to specified ItemBase instance. :param sender: the sendin... |
from ..models import (
Entry,
EntryTag
)
entry = Entry.objects.get_for_model(instance.content_object)[0]
tag = instance.tag
if not EntryTag.objects.filter(tag=tag, entry=entry).exists():
EntryTag.objects.create(tag=tag, entry=entry) |
<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_entry_tag(sender, instance, **kwargs):
""" Deletes EntryTag for Entry corresponding to specified TaggedItemBase instance. :param sender: the sending T... |
from ..models import (
Entry,
EntryTag
)
entry = Entry.objects.get_for_model(instance.content_object)[0]
tag = instance.tag
EntryTag.objects.filter(tag=tag, entry=entry).delete() |
<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_entry(sender, instance, **kwargs):
""" Deletes Entry instance corresponding to specified instance. :param sender: the sending class. :param instance: ... |
from ..models import Entry
Entry.objects.get_for_model(instance)[0].delete() |
<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_entry_attributes(sender, instance, **kwargs):
""" Updates attributes for Entry instance corresponding to specified instance. :param sender: the sendin... |
from ..models import Entry
entry = Entry.objects.get_for_model(instance)[0]
default_url = getattr(instance, 'get_absolute_url', '')
entry.title = getattr(instance, 'title', str(instance))
entry.url = getattr(instance, 'url', default_url)
entry.live = bool(getattr(instance, 'live', 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 get_revisions(page, page_num=1):
""" Returns paginated queryset of PageRevision instances for specified Page instance. :param page: the page instance. :param... |
revisions = page.revisions.order_by('-created_at')
current = page.get_latest_revision()
if current:
revisions.exclude(id=current.id)
paginator = Paginator(revisions, 5)
try:
revisions = paginator.page(page_num)
except PageNotAnInteger:
revisions = paginator.page... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def page_revisions(request, page_id, template_name='wagtailrollbacks/edit_handlers/revisions.html'):
""" Returns GET response for specified page revisions. :para... |
page = get_object_or_404(Page, pk=page_id)
page_perms = page.permissions_for_user(request.user)
if not page_perms.can_edit():
raise PermissionDenied
page_num = request.GET.get('p', 1)
revisions = get_revisions(page, page_num)
return render(
request,
templ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def preview_page_version(request, revision_id):
""" Returns GET response for specified page preview. :param request: the request instance. :param reversion_pk: t... |
revision = get_object_or_404(PageRevision, pk=revision_id)
if not revision.page.permissions_for_user(request.user).can_publish():
raise PermissionDenied
page = revision.as_page_object()
request.revision_id = revision_id
return page.serve_preview(request, page.default_previ... |
<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_keyring(self, keyring_dict):
"""Helper to actually write the keyring to Google""" |
import gdata
result = self.OK
file_contents = base64.urlsafe_b64encode(pickle.dumps(keyring_dict))
try:
if self.docs_entry:
extra_headers = {'Content-Type': 'text/plain',
'Content-Length': len(file_contents)}
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 _request(method, url, session=None, **kwargs):
"""Make HTTP request, raising an exception if it fails. """ |
url = BASE_URL + url
if session:
request_func = getattr(session, method)
else:
request_func = getattr(requests, method)
response = request_func(url, **kwargs)
# raise an exception if request is not successful
if not response.status_code == requests.codes.ok:
raise Dweep... |
<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_dweet(payload, url, params=None, session=None):
"""Send a dweet to dweet.io """ |
data = json.dumps(payload)
headers = {'Content-type': 'application/json'}
return _request('post', url, data=data, headers=headers, params=params, session=session) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dweet_for(thing_name, payload, key=None, session=None):
"""Send a dweet to dweet.io for a thing with a known name """ |
if key is not None:
params = {'key': key}
else:
params = None
return _send_dweet(payload, '/dweet/for/{0}'.format(thing_name), params=params, session=session) |
<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_dweets_for(thing_name, key=None, session=None):
"""Read all the dweets for a dweeter """ |
if key is not None:
params = {'key': key}
else:
params = None
return _request('get', '/get/dweets/for/{0}'.format(thing_name), params=params, session=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 unlock(thing_name, key, session=None):
"""Unlock a thing """ |
return _request('get', '/unlock/{0}'.format(thing_name), params={'key': key}, session=session) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_alert(thing_name, key, session=None):
"""Remove an alert for the given thing """ |
return _request('get', '/remove/alert/for/{0}'.format(thing_name), params={'key': key}, session=session) |
<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_product_sets(self):
""" list all product sets for current user """ |
# ensure we are using api url without a specific product set id
api_url = super(ProductSetAPI, self).base_url
return self.client.get(api_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 _check_stream_timeout(started, timeout):
"""Check if the timeout has been reached and raise a `StopIteration` if so. """ |
if timeout:
elapsed = datetime.datetime.utcnow() - started
if elapsed.seconds > timeout:
raise StopIteration |
<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_for_dweets_from_response(response):
"""Yields dweets as received from dweet.io's streaming API """ |
streambuffer = ''
for byte in response.iter_content():
if byte:
streambuffer += byte.decode('ascii')
try:
dweet = json.loads(streambuffer.splitlines()[1])
except (IndexError, ValueError):
continue
if isstr(dweet):
... |
<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_for_dweets_from(thing_name, timeout=900, key=None, session=None):
"""Create a real-time subscription to dweets """ |
url = BASE_URL + '/listen/for/dweets/from/{0}'.format(thing_name)
session = session or requests.Session()
if key is not None:
params = {'key': key}
else:
params = None
start = datetime.datetime.utcnow()
while True:
request = requests.Request("GET", url, params=params).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 build(self, parallel=True, debug=False, force=False, machine_readable=False):
"""Executes a `packer build` :param bool parallel: Run builders in parallel :pa... |
self.packer_cmd = self.packer.build
self._add_opt('-parallel=true' if parallel else None)
self._add_opt('-debug' if debug else None)
self._add_opt('-force' if force else None)
self._add_opt('-machine-readable' if machine_readable else None)
self._append_base_arguments()... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fix(self, to_file=None):
"""Implements the `packer fix` function :param string to_file: File to output fixed template to """ |
self.packer_cmd = self.packer.fix
self._add_opt(self.packerfile)
result = self.packer_cmd()
if to_file:
with open(to_file, 'w') as f:
f.write(result.stdout.decode())
result.fixed = json.loads(result.stdout.decode())
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 push(self, create=True, token=False):
"""Implmenets the `packer push` function UNTESTED! Must be used alongside an Atlas account """ |
self.packer_cmd = self.packer.push
self._add_opt('-create=true' if create else None)
self._add_opt('-tokn={0}'.format(token) if token else None)
self._add_opt(self.packerfile)
return self.packer_cmd() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _append_base_arguments(self):
"""Appends base arguments to packer commands. -except, -only, -var and -var-file are appeneded to almost all subcommands in pac... |
if self.exc and self.only:
raise PackerException('Cannot provide both "except" and "only"')
elif self.exc:
self._add_opt('-except={0}'.format(self._join_comma(self.exc)))
elif self.only:
self._add_opt('-only={0}'.format(self._join_comma(self.only)))
f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_inspection_output(self, output):
"""Parses the machine-readable output `packer inspect` provides. See the inspect method for more info. This has been ... |
parts = {'variables': [], 'builders': [], 'provisioners': []}
for line in output.splitlines():
line = line.split(',')
if line[2].startswith('template'):
del line[0:2]
component = line[0]
if component == 'template-variable':
... |
<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(self, url, data, headers=None):
""" Perform an HTTP POST request for a given url. Returns the response object. """ |
return self._request('POST', url, data, headers=headers) |
<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, data, headers=None):
""" Perform an HTTP PUT request for a given url. Returns the response object. """ |
return self._request('PUT', url, data, headers=headers) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query(self, *args):
""" Query a fulltext index by key and query or just a plain Lucene query, i1 = gdb.nodes.indexes.get('people',type='fulltext', provider='... |
if not args or len(args) > 2:
raise TypeError('query() takes 2 or 3 arguments (a query or a key '
'and a query) (%d given)' % (len(args) + 1))
elif len(args) == 1:
query, = args
return self.get('text').query(text_type(query))
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 do_call(self, path, method, body=None, headers=None):
""" Send an HTTP request to the REST API. :param string path: A URL :param string method: The HTTP meth... |
url = urljoin(self.base_url, path)
try:
resp = requests.request(method, url, data=body, headers=headers,
auth=self.auth, timeout=self.timeout)
except requests.exceptions.Timeout as out:
raise NetworkError("Timeout while trying to conne... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _call(self, path, method, body=None, headers=None):
""" Wrapper around http.do_call that transforms some HTTPError into our own exceptions """ |
try:
resp = self.http.do_call(path, method, body, headers)
except http.HTTPError as err:
if err.status == 401:
raise PermissionError('Insufficient permissions to query ' +
'%s with user %s :%s' % (path, self.user, err))
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 get_whoami(self):
""" A convenience function used in the event that you need to confirm that the broker thinks you are who you think you are. :returns dict w... |
path = Client.urls['whoami']
whoami = self._call(path, 'GET')
return whoami |
<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_vhost_names(self):
""" A convenience function for getting back only the vhost names instead of the larger vhost dicts. :returns list vhost_names: A list ... |
vhosts = self.get_all_vhosts()
vhost_names = [i['name'] for i in vhosts]
return vhost_names |
<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_vhost(self, vname):
""" Returns the attributes of a single named vhost in a dict. :param string vname: Name of the vhost to get. :returns dict vhost: Att... |
vname = quote(vname, '')
path = Client.urls['vhosts_by_name'] % vname
vhost = self._call(path, 'GET', headers=Client.json_headers)
return vhost |
<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_vhost(self, vname):
""" Creates a vhost on the server to house exchanges. :param string vname: The name to give to the vhost on the server :returns: b... |
vname = quote(vname, '')
path = Client.urls['vhosts_by_name'] % vname
return self._call(path, 'PUT',
headers=Client.json_headers) |
<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_vhost(self, vname):
""" Deletes a vhost from the server. Note that this also deletes any exchanges or queues that belong to this vhost. :param string ... |
vname = quote(vname, '')
path = Client.urls['vhosts_by_name'] % vname
return self._call(path, 'DELETE') |
<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_vhost_permissions(self, vname, username, config, rd, wr):
""" Set permissions for a given username on a given vhost. Both must already exist. :param stri... |
vname = quote(vname, '')
body = json.dumps({"configure": config, "read": rd, "write": wr})
path = Client.urls['vhost_permissions'] % (vname, username)
return self._call(path, 'PUT', body,
headers=Client.json_headers) |
<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_permission(self, vname, username):
""" Delete permission for a given username on a given vhost. Both must already exist. :param string vname: Name of ... |
vname = quote(vname, '')
path = Client.urls['vhost_permissions'] % (vname, username)
return self._call(path, 'DELETE') |
<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_exchange(self, vhost, name):
""" Gets a single exchange which requires a vhost and name. :param string vhost: The vhost containing the target exchange :p... |
vhost = quote(vhost, '')
name = quote(name, '')
path = Client.urls['exchange_by_name'] % (vhost, name)
exch = self._call(path, 'GET')
return exch |
<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_exchange(self, vhost, name):
""" Delete the named exchange from the named vhost. The API returns a 204 on success, in which case this method returns T... |
vhost = quote(vhost, '')
name = quote(name, '')
path = Client.urls['exchange_by_name'] % (vhost, name)
self._call(path, 'DELETE')
return 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 get_queues(self, vhost=None):
""" Get all queues, or all queues in a vhost if vhost is not None. Returns a list. :param string vhost: The virtual host to lis... |
if vhost:
vhost = quote(vhost, '')
path = Client.urls['queues_by_vhost'] % vhost
else:
path = Client.urls['all_queues']
queues = self._call(path, 'GET')
return queues or list() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_queue(self, vhost, name):
""" Get a single queue, which requires both vhost and name. :param string vhost: The virtual host for the queue being requested... |
vhost = quote(vhost, '')
name = quote(name, '')
path = Client.urls['queues_by_name'] % (vhost, name)
queue = self._call(path, 'GET')
return queue |
<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_queue_depths(self, vhost, names=None):
""" Get the number of messages currently sitting in either the queue names listed in 'names', or all queues in 'vh... |
vhost = quote(vhost, '')
if not names:
# get all queues in vhost
path = Client.urls['queues_by_vhost'] % vhost
queues = self._call(path, 'GET')
for queue in queues:
depth = queue['messages']
print("\t%s: %s" % (queue, dept... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def purge_queues(self, queues):
""" Purge all messages from one or more queues. :param list queues: A list of ('qname', 'vhost') tuples. :returns: True on succes... |
for name, vhost in queues:
vhost = quote(vhost, '')
name = quote(name, '')
path = Client.urls['purge_queue'] % (vhost, name)
self._call(path, 'DELETE')
return 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 purge_queue(self, vhost, name):
""" Purge all messages from a single queue. This is a convenience method so you aren't forced to supply a list containing a s... |
vhost = quote(vhost, '')
name = quote(name, '')
path = Client.urls['purge_queue'] % (vhost, name)
return self._call(path, 'DELETE') |
<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_queue(self, vhost, name, **kwargs):
""" Create a queue. The API documentation specifies that all of the body elements are optional, so this method onl... |
vhost = quote(vhost, '')
name = quote(name, '')
path = Client.urls['queues_by_name'] % (vhost, name)
body = json.dumps(kwargs)
return self._call(path,
'PUT',
body,
headers=Clien... |
<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_queue(self, vhost, qname):
""" Deletes the named queue from the named vhost. :param string vhost: Vhost housing the queue to be deleted. :param string... |
vhost = quote(vhost, '')
qname = quote(qname, '')
path = Client.urls['queues_by_name'] % (vhost, qname)
return self._call(path, 'DELETE', headers=Client.json_headers) |
<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_connection(self, name):
""" Get a connection by name. To get the names, use get_connections. :param string name: Name of connection to get :returns dict ... |
name = quote(name, '')
path = Client.urls['connections_by_name'] % name
conn = self._call(path, 'GET')
return conn |
<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_connection(self, name):
""" Close the named connection. The API returns a 204 on success, in which case this method returns True, otherwise the error ... |
name = quote(name, '')
path = Client.urls['connections_by_name'] % name
self._call(path, 'DELETE')
return 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 get_channel(self, name):
""" Get a channel by name. To get the names, use get_channels. :param string name: Name of channel to get :returns dict conn: A chan... |
name = quote(name, '')
path = Client.urls['channels_by_name'] % name
chan = self._call(path, 'GET')
return chan |
<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_binding(self, vhost, exchange, queue, rt_key=None, args=None):
""" Creates a binding between an exchange and a queue on a given vhost. :param string v... |
vhost = quote(vhost, '')
exchange = quote(exchange, '')
queue = quote(queue, '')
body = json.dumps({'routing_key': rt_key, 'arguments': args or []})
path = Client.urls['bindings_between_exch_queue'] % (vhost,
exchange... |
<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_binding(self, vhost, exchange, queue, rt_key):
""" Deletes a binding between an exchange and a queue on a given vhost. :param string vhost: vhost hous... |
vhost = quote(vhost, '')
exchange = quote(exchange, '')
queue = quote(queue, '')
body = ''
path = Client.urls['rt_bindings_between_exch_queue'] % (vhost,
exchange,
... |
<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_user(self, username):
""" Deletes a user from the server. :param string username: Name of the user to delete from the server. """ |
path = Client.urls['users_by_name'] % username
return self._call(path, 'DELETE') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def index(request):
""" Redirects to the default wiki index name. """ |
kwargs = {'slug': getattr(settings, 'WAKAWAKA_DEFAULT_INDEX', 'WikiIndex')}
redirect_to = reverse('wakawaka_page', kwargs=kwargs)
return HttpResponseRedirect(redirect_to) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def page( request, slug, rev_id=None, template_name='wakawaka/page.html', extra_context=None, ):
""" Displays a wiki page. Redirects to the edit view if the page... |
try:
queryset = WikiPage.objects.all()
page = queryset.get(slug=slug)
rev = page.current
# Display an older revision if rev_id is given
if rev_id:
revision_queryset = Revision.objects.all()
rev_specific = revision_queryset.get(pk=rev_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 edit( request, slug, rev_id=None, template_name='wakawaka/edit.html', extra_context=None, wiki_page_form=WikiPageForm, wiki_delete_form=DeleteWikiPageForm, ):... |
# Get the page for slug and get a specific revision, if given
try:
queryset = WikiPage.objects.all()
page = queryset.get(slug=slug)
rev = page.current
initial = {'content': page.current.content}
# Do not allow editing wiki pages if the user has no permission
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 revisions( request, slug, template_name='wakawaka/revisions.html', extra_context=None ):
""" Displays the list of all revisions for a specific WikiPage """ |
queryset = WikiPage.objects.all()
page = get_object_or_404(queryset, slug=slug)
template_context = {'page': page}
template_context.update(extra_context or {})
return render(request, template_name, template_context) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def changes( request, slug, template_name='wakawaka/changes.html', extra_context=None ):
""" Displays the changes between two revisions. """ |
rev_a_id = request.GET.get('a', None)
rev_b_id = request.GET.get('b', None)
# Some stinky fingers manipulated the url
if not rev_a_id or not rev_b_id:
return HttpResponseBadRequest('Bad Request')
try:
revision_queryset = Revision.objects.all()
wikipage_queryset = WikiPage.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def revision_list( request, template_name='wakawaka/revision_list.html', extra_context=None ):
""" Displays a list of all recent revisions. """ |
revision_list = Revision.objects.all()
template_context = {'revision_list': revision_list}
template_context.update(extra_context or {})
return render(request, template_name, template_context) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def page_list( request, template_name='wakawaka/page_list.html', extra_context=None ):
""" Displays all Pages """ |
page_list = WikiPage.objects.all()
page_list = page_list.order_by('slug')
template_context = {
'page_list': page_list,
'index_slug': getattr(settings, 'WAKAWAKA_DEFAULT_INDEX', 'WikiIndex'),
}
template_context.update(extra_context or {})
return render(request, template_name, te... |
<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_wiki(self, request, page, rev):
""" Deletes the page with all revisions or the revision, based on the users choice. Returns a HttpResponseRedirect. ""... |
# Delete the page
if (
self.cleaned_data.get('delete') == 'page'
and request.user.has_perm('wakawaka.delete_revision')
and request.user.has_perm('wakawaka.delete_wikipage')
):
self._delete_page(page)
messages.success(
... |
<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_real_field(model, field_name):
'''
Get the real field from a model given its name.
Handle nested models recursively (aka. ``__`` lookups)
'''
parts = field_name.split('__')
field = model._meta.get_field(parts[0])
if len(parts) == 1:
return model._meta.get_field(field_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 can_regex(self, field):
'''Test if a given field supports regex lookups'''
from django.conf import settings
if settings.DATABASES['default']['ENGINE'].endswith('sqlite3'):
return not isinstance(get_real_field(self.model, field), UNSUPPORTED_REGEX_FIELDS)
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 get_orders(self):
'''Get ordering fields for ``QuerySet.order_by``'''
orders = []
iSortingCols = self.dt_data['iSortingCols']
dt_orders = [(self.dt_data['iSortCol_%s' % i], self.dt_data['sSortDir_%s' % i]) for i in xrange(iSortingCols)]
for field_idx, field_dir in dt_orders:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def global_search(self, queryset):
'''Filter a queryset with global search'''
search = self.dt_data['sSearch']
if search:
if self.dt_data['bRegex']:
criterions = [
Q(**{'%s__iregex' % field: search})
for field in self.get_db_fie... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def column_search(self, queryset):
'''Filter a queryset with column search'''
for idx in xrange(self.dt_data['iColumns']):
search = self.dt_data['sSearch_%s' % idx]
if search:
if hasattr(self, 'search_col_%s' % idx):
custom_search = getattr(sel... |
<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_queryset(self):
'''Apply Datatables sort and search criterion to QuerySet'''
qs = super(DatatablesView, self).get_queryset()
# Perform global search
qs = self.global_search(qs)
# Perform column search
qs = self.column_search(qs)
# Return the ordered querys... |
<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_page(self, form):
'''Get the requested page'''
page_size = form.cleaned_data['iDisplayLength']
start_index = form.cleaned_data['iDisplayStart']
paginator = Paginator(self.object_list, page_size)
num_page = (start_index / page_size) + 1
return paginator.page(num_pa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def render_to_response(self, form, **kwargs):
'''Render Datatables expected JSON format'''
page = self.get_page(form)
data = {
'iTotalRecords': page.paginator.count,
'iTotalDisplayRecords': page.paginator.count,
'sEcho': form.cleaned_data['sEcho'],
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authenticated(func):
""" Decorator to check if Smappee's access token has expired. If it has, use the refresh token to request a new access token """ |
@wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
if self.refresh_token is not None and \
self.token_expiration_time <= dt.datetime.utcnow():
self.re_authenticate()
return func(*args, **kwargs)
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 urljoin(*parts):
""" Join terms together with forward slashes Parameters parts Returns ------- str """ |
# first strip extra forward slashes (except http:// and the likes) and
# create list
part_list = []
for part in parts:
p = str(part)
if p.endswith('//'):
p = p[0:-1]
else:
p = p.strip('/')
part_list.append(p)
# join everything together
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 authenticate(self, username, password):
""" Uses a Smappee username and password to request an access token, refresh token and expiry date. Parameters userna... |
url = URLS['token']
data = {
"grant_type": "password",
"client_id": self.client_id,
"client_secret": self.client_secret,
"username": username,
"password": password
}
r = requests.post(url, data=data)
r.raise_for_status(... |
<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_service_location_info(self, service_location_id):
""" Request service location info Parameters service_location_id : int Returns ------- dict """ |
url = urljoin(URLS['servicelocation'], service_location_id, "info")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
r = requests.get(url, headers=headers)
r.raise_for_status()
return r.json() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_consumption(self, service_location_id, start, end, aggregation, raw=False):
""" Request Elektricity consumption and Solar production for a given service ... |
url = urljoin(URLS['servicelocation'], service_location_id,
"consumption")
d = self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation)
if not raw:
for block in d['consumptions']:
if 'always... |
<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_sensor_consumption(self, service_location_id, sensor_id, start, end, aggregation):
""" Request consumption for a given sensor in a given service location... |
url = urljoin(URLS['servicelocation'], service_location_id, "sensor",
sensor_id, "consumption")
return self._get_consumption(url=url, start=start, end=end,
aggregation=aggregation) |
<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_consumption(self, url, start, end, aggregation):
""" Request for both the get_consumption and get_sensor_consumption methods. Parameters url : str start... |
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"aggregation": aggregation,
"from": start,
"to": end
}
r = requests.get(url, headers=h... |
<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_events(self, service_location_id, appliance_id, start, end, max_number=None):
""" Request events for a given appliance Parameters service_location_id : i... |
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
url = urljoin(URLS['servicelocation'], service_location_id, "events")
headers = {"Authorization": "Bearer {}".format(self.access_token)}
params = {
"from": start,
"to": end,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def actuator_on(self, service_location_id, actuator_id, duration=None):
""" Turn actuator on Parameters service_location_id : int actuator_id : int duration : in... |
return self._actuator_on_off(
on_off='on', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def actuator_off(self, service_location_id, actuator_id, duration=None):
""" Turn actuator off Parameters service_location_id : int actuator_id : int duration : ... |
return self._actuator_on_off(
on_off='off', service_location_id=service_location_id,
actuator_id=actuator_id, duration=duration) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _actuator_on_off(self, on_off, service_location_id, actuator_id, duration=None):
""" Turn actuator on or off Parameters on_off : str 'on' or 'off' service_lo... |
url = urljoin(URLS['servicelocation'], service_location_id,
"actuator", actuator_id, on_off)
headers = {"Authorization": "Bearer {}".format(self.access_token)}
if duration is not None:
data = {"duration": duration}
else:
data = {}
r ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _to_milliseconds(self, time):
""" Converts a datetime-like object to epoch, in milliseconds Timezone-naive datetime objects are assumed to be in UTC Paramete... |
if isinstance(time, dt.datetime):
if time.tzinfo is None:
time = time.replace(tzinfo=pytz.UTC)
return int(time.timestamp() * 1e3)
elif isinstance(time, numbers.Number):
return time
else:
raise NotImplementedError("Time format not 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 _basic_post(self, url, data=None):
""" Because basically every post request is the same Parameters url : str data : str, optional Returns ------- requests.Re... |
_url = urljoin(self.base_url, url)
r = self.session.post(_url, data=data, headers=self.headers, timeout=5)
r.raise_for_status()
return r |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def active_power(self):
""" Takes the sum of all instantaneous active power values Returns them in kWh Returns ------- float """ |
inst = self.load_instantaneous()
values = [float(i['value']) for i in inst if i['key'].endswith('ActivePower')]
return sum(values) / 1000 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def active_cosfi(self):
""" Takes the average of all instantaneous cosfi values Returns ------- float """ |
inst = self.load_instantaneous()
values = [float(i['value']) for i in inst if i['key'].endswith('Cosfi')]
return sum(values) / len(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 getInterfaceInAllSpeeds(interface, endpoint_list, class_descriptor_list=()):
""" Produce similar fs, hs and ss interface and endpoints descriptors. Should be... |
interface = getDescriptor(
USBInterfaceDescriptor,
bNumEndpoints=len(endpoint_list),
**interface
)
class_descriptor_list = list(class_descriptor_list)
fs_list = [interface] + class_descriptor_list
hs_list = [interface] + class_descriptor_list
ss_list = [interface] + clas... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getDescriptor(klass, **kw):
""" Automatically fills bLength and bDescriptorType. """ |
# XXX: ctypes Structure.__init__ ignores arguments which do not exist
# as structure fields. So check it.
# This is annoying, but not doing it is a huge waste of time for the
# developer.
empty = klass()
assert hasattr(empty, 'bLength')
assert hasattr(empty, 'bDescriptorType')
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 getRealInterfaceNumber(self, interface):
""" Returns the host-visible interface number, or None if there is no such interface. """ |
try:
return self._ioctl(INTERFACE_REVMAP, interface)
except IOError as exc:
if exc.errno == errno.EDOM:
return None
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 close(self):
""" Close all endpoint file descriptors. """ |
ep_list = self._ep_list
while ep_list:
ep_list.pop().close()
self._closed = 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 onSetup(self, request_type, request, value, index, length):
""" Called when a setup USB transaction was received. Default implementation: - handles USB_REQ_G... |
if (request_type & ch9.USB_TYPE_MASK) == ch9.USB_TYPE_STANDARD:
recipient = request_type & ch9.USB_RECIP_MASK
is_in = (request_type & ch9.USB_DIR_IN) == ch9.USB_DIR_IN
if request == ch9.USB_REQ_GET_STATUS:
if is_in and length == 2:
if reci... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def onEnable(self):
""" The configuration containing this function has been enabled by host. Endpoints become working files, so submit some read operations. """ |
trace('onEnable')
self._disable()
self._aio_context.submit(self._aio_recv_block_list)
self._real_onCanSend()
self._enabled = True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.