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 get_check_and_report(client_site_url, apikey, get_resource_ids_to_check, get_url_for_id, check_url, upsert_result):
"""Get links from the client site, check ... |
logger = _get_logger()
resource_ids = get_resource_ids_to_check(client_site_url, apikey)
for resource_id in resource_ids:
try:
url = get_url_for_id(client_site_url, apikey, resource_id)
except CouldNotGetURLError:
logger.info(u"This link checker was not authorized 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 remove(self, member):
"""Remove a member from the archive.""" |
# Make sure we have an info object
if isinstance(member, ZipInfo):
# 'member' is already an info object
zinfo = member
else:
# Get info object for name
zinfo = self.getinfo(member)
# compute the location of the file data in the local file... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def import_class(class_path):
'''
Imports the class for the given class name.
'''
module_name, class_name = class_path.rsplit(".", 1)
module = import_module(module_name)
claz = getattr(module, class_name)
return claz |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _executor(self):
'''
Creating an ExecutorPool is a costly operation. Executor needs to be instantiated only once.
'''
if self.EXECUTE_PARALLEL is False:
executor_path = "batch_requests.concurrent.executor.SequentialExecutor"
executor_class = import_class(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 make_label(self, path):
""" this borrows too much from the internals of ofs maybe expose different parts of the api? """ |
from datetime import datetime
from StringIO import StringIO
path = path.lstrip("/")
bucket, label = path.split("/", 1)
bucket = self.ofs._require_bucket(bucket)
key = self.ofs._get_key(bucket, label)
if key is None:
key = bucket.new_key(label)
... |
<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_proxy_config(self, headers, path):
""" stub. this really needs to be a call to the remote restful interface to get the appropriate host and headers to us... |
self.ofs.conn.add_aws_auth_header(headers, 'PUT', path)
from pprint import pprint
pprint(headers)
host = self.ofs.conn.server_name()
return host, 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 fetch_all_mood_stations(self, terr=KKBOXTerritory.TAIWAN):
'''
Fetches all mood stations.
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#moodstations`.
'''
url = 'https://api.kk... |
<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_mood_station(self, station_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches a mood station by given ID.
:param station_id: the station ID
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/referenc... |
<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_data(self, url):
'''
Fetches data from specific url.
:return: The response.
:rtype: dict
'''
return self.http._post_data(url, None, self.http._headers_with_access_token()) |
<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_shared_playlist(self, playlist_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches a shared playlist by given ID.
:param playlist_id: the playlist ID.
:type playlist_id: str
:param terr: the current territory.
:return: API response.
:rtype: dictcd
See... |
<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_firewall_rule(self, server_uuid, firewall_rule_position, server_instance=None):
""" Return a FirewallRule object based on server uuid and rule position. ... |
url = '/server/{0}/firewall_rule/{1}'.format(server_uuid, firewall_rule_position)
res = self.get_request(url)
return FirewallRule(**res['firewall_rule']) |
<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_firewall_rules(self, server):
""" Return all FirewallRule objects based on a server instance or uuid. """ |
server_uuid, server_instance = uuid_and_instance(server)
url = '/server/{0}/firewall_rule'.format(server_uuid)
res = self.get_request(url)
return [
FirewallRule(server=server_instance, **firewall_rule)
for firewall_rule in res['firewall_rules']['firewall_rule']... |
<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_firewall_rule(self, server, firewall_rule_body):
""" Create a new firewall rule for a given server uuid. The rule can begiven as a dict or with Firewa... |
server_uuid, server_instance = uuid_and_instance(server)
url = '/server/{0}/firewall_rule'.format(server_uuid)
body = {'firewall_rule': firewall_rule_body}
res = self.post_request(url, body)
return FirewallRule(server=server_instance, **res['firewall_rule']) |
<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_firewall_rule(self, server_uuid, firewall_rule_position):
""" Delete a firewall rule based on a server uuid and rule position. """ |
url = '/server/{0}/firewall_rule/{1}'.format(server_uuid, firewall_rule_position)
return self.request('DELETE', 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 configure_firewall(self, server, firewall_rule_bodies):
""" Helper for calling create_firewall_rule in series for a list of firewall_rule_bodies. """ |
server_uuid, server_instance = uuid_and_instance(server)
return [
self.create_firewall_rule(server_uuid, rule)
for rule in firewall_rule_bodies
] |
<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, data):
""" POSTs a raw SMTP message to the Sinkhole API :param data: raw content to be submitted [STRING] :return: { list of predictions } """ |
uri = '{}/sinkhole'.format(self.client.remote)
self.logger.debug(uri)
if PYVERSION == 2:
try:
data = data.decode('utf-8')
except Exception:
data = data.decode('latin-1')
data = {
'message': data
}
bod... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def pre_process_method_headers(method, headers):
'''
Returns the lowered method.
Capitalize headers, prepend HTTP_ and change - to _.
'''
method = method.lower()
# Standard WSGI supported headers
_wsgi_headers = ["content_length", "content_type", "query_string",
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def headers_to_include_from_request(curr_request):
'''
Define headers that needs to be included from the current request.
'''
return {
h: v for h, v in curr_request.META.items() if h in _settings.HEADERS_TO_INCLUDE} |
<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_wsgi_request_object(curr_request, method, url, headers, body):
'''
Based on the given request parameters, constructs and returns the WSGI request object.
'''
x_headers = headers_to_include_from_request(curr_request)
method, t_headers = pre_process_method_headers(method, headers)
# A... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _base_environ(self, **request):
'''
Override the default values for the wsgi environment variables.
'''
# This is a minimal valid WSGI environ dictionary, plus:
# - HTTP_COOKIE: for cookie support,
# - REMOTE_ADDR: often useful, see #8551.
# See http://www... |
<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(self, method, endpoint, body=None, timeout=-1):
""" Perform a request with a given body to a given endpoint in UpCloud's API. Handles errors with __e... |
if method not in set(['GET', 'POST', 'PUT', 'DELETE']):
raise Exception('Invalid/Forbidden HTTP method')
url = '/' + self.api_v + endpoint
headers = {
'Authorization': self.token,
'Content-Type': 'application/json'
}
if body:
jso... |
<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_request(self, endpoint, body=None, timeout=-1):
""" Perform a POST request to a given endpoint in UpCloud's API. """ |
return self.request('POST', endpoint, body, timeout) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __error_middleware(self, res, res_json):
""" Middleware that raises an exception when HTTP statuscode is an error code. """ |
if(res.status_code in [400, 401, 402, 403, 404, 405, 406, 409]):
err_dict = res_json.get('error', {})
raise UpCloudAPIError(error_code=err_dict.get('error_code'),
error_message=err_dict.get('error_message'))
return res_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 put_stream(self, bucket, label, stream_object, params={}):
''' Create a new file to swift object storage. '''
self.claim_bucket(bucket)
self.connection.put_object(bucket, label, stream_object,
headers=self._convert_to_meta(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 get(self, q, limit=None):
""" Performs a search against the predict endpoint :param q: query to be searched for [STRING] :return: { score: [0|1] } """ |
uri = '{}/predict?q={}'.format(self.client.remote, q)
self.logger.debug(uri)
body = self.client.get(uri)
return body['score'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def list_labels(self, bucket):
'''List labels for the given bucket. Due to zipfiles inherent arbitrary ordering,
this is an expensive operation, as it walks the entire archive searching for individual
'buckets'
:param bucket: bucket to list labels for.
:return: iterator for the ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def list_buckets(self):
'''List all buckets managed by this OFS instance. Like list_labels, this also
walks the entire archive, yielding the bucketnames. A local set is retained so that
duplicates aren't returned so this will temporarily pull the entire list into memory
even though this ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def del_stream(self, bucket, label):
'''Delete a bitstream. This needs more testing - file deletion in a zipfile
is problematic. Alternate method is to create second zipfile without the files
in question, which is not a nice method for large zip archives.
'''
if self.exists(bucke... |
<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_metadata(self, bucket, label, params):
'''Update the metadata with the provided dictionary of params.
:param parmams: dictionary of key values (json serializable).
'''
if self.mode !="r":
try:
payload = self._get_bucket_md(bucket)
excep... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def del_metadata_keys(self, bucket, label, keys):
'''Delete the metadata corresponding to the specified keys.
'''
if self.mode !="r":
try:
payload = self._get_bucket_md(bucket)
except OFSFileNotFound:
# No MD found...
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_response(wsgi_request):
'''
Given a WSGI request, makes a call to a corresponding view
function and returns the response.
'''
service_start_time = datetime.now()
# Get the view / handler for this request
view, args, kwargs = resolve(wsgi_request.path_info)
kwargs.update(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_wsgi_requests(request):
'''
For the given batch request, extract the individual requests and create
WSGIRequest object for each.
'''
valid_http_methods = ["get", "post", "put", "patch", "delete", "head", "options", "connect", "trace"]
requests = json.loads(request.body)
if t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def handle_batch_requests(request, *args, **kwargs):
'''
A view function to handle the overall processing of batch requests.
'''
batch_start_time = datetime.now()
try:
# Get the Individual WSGI requests.
wsgi_requests = get_wsgi_requests(request)
except BadBatchRequest as brx... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def search(self, keyword, types=[], terr=KKBOXTerritory.TAIWAN):
'''
Searches within KKBOX's database.
:param keyword: the keyword.
:type keyword: str
:param types: the search types.
:return: list
:param terr: the current territory.
:return: API response.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create_ip_address_objs(ip_addresses, cloud_manager):
""" Create IPAddress objects from API response data. Also associates CloudManager with the objects. """ |
# ip-addresses might be provided as a flat array or as a following dict:
# {'ip_addresses': {'ip_address': [...]}} || {'ip_address': [...]}
if 'ip_addresses' in ip_addresses:
ip_addresses = ip_addresses['ip_addresses']
if 'ip_address' in ip_addresses:
ip_addres... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _reset(self, **kwargs):
""" Reset the objects attributes. Accepts servers as either unflattened or flattened UUID strings or Server objects. """ |
super(Tag, self)._reset(**kwargs)
# backup name for changing it (look: Tag.save)
self._api_name = self.name
# flatten { servers: { server: [] } }
if 'server' in self.servers:
self.servers = kwargs['servers']['server']
# convert UUIDs into server objects
... |
<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, uri, params={}):
""" HTTP GET function :param uri: REST endpoint :param params: optional HTTP params to pass to the endpoint :return: list of resu... |
if not uri.startswith(self.remote):
uri = '{}{}'.format(self.remote, uri)
return self._make_request(uri, 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 _post(self, uri, data):
""" HTTP POST function :param uri: REST endpoint to POST to :param data: list of dicts to be passed to the endpoint :return: list of ... |
if not uri.startswith(self.remote):
uri = '{}/{}'.format(self.remote, uri)
self.logger.debug(uri)
return self._make_request(uri, data=data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modify_server(self, UUID, **kwargs):
""" modify_server allows updating the server's updateable_fields. Note: Server's IP-addresses and Storages are managed b... |
body = dict()
body['server'] = {}
for arg in kwargs:
if arg not in Server.updateable_fields:
Exception('{0} is not an updateable field'.format(arg))
body['server'][arg] = kwargs[arg]
res = self.request('PUT', '/server/{0}'.format(UUID), body)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _internal_convert(inp):
""" Converts file in IDX format provided by file-like input into numpy.ndarray and returns it. """ |
'''
Converts file in IDX format provided by file-like input into numpy.ndarray
and returns it.
'''
# Read the "magic number" - 4 bytes.
try:
mn = struct.unpack('>BBBB', inp.read(4))
except struct.error:
raise FormatError(struct.error)
# First two bytes are always zero,... |
<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_to_string(ndarr):
""" Writes the contents of the numpy.ndarray ndarr to bytes in IDX format and returns it. """ |
with contextlib.closing(BytesIO()) as bytesio:
_internal_write(bytesio, ndarr)
return bytesio.getvalue() |
<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_OS_UUID(cls, os):
""" Validate Storage OS and its UUID. If the OS is a custom OS UUID, don't validate against templates. """ |
if os in cls.templates:
return cls.templates[os]
uuid_regexp = '^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$'
if re.search(uuid_regexp, os):
return os
raise Exception((
"Invalid OS -- valid options are: 'CentOS 6.5', 'CentOS 7.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 execute(self, requests, resp_generator, *args, **kwargs):
'''
Calls the resp_generator for all the requests in parallel in an asynchronous way.
'''
result_futures = [self.executor_pool.submit(resp_generator, req, *args, **kwargs) for req in requests]
resp = [res_future.re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def execute(self, requests, resp_generator, *args, **kwargs):
'''
Calls the resp_generator for all the requests in sequential order.
'''
return [resp_generator(request) for request in requests] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup_logging(args):
""" Sets up basic logging :param args: ArgParse arguments :return: nothing. sets logger up globally """ |
loglevel = logging.WARNING
if args.verbose:
loglevel = logging.INFO
if args.debug:
loglevel = logging.DEBUG
console = logging.StreamHandler()
logging.getLogger('').setLevel(loglevel)
console.setFormatter(logging.Formatter(LOG_FORMAT))
logging.getLogger('').addHandler(consol... |
<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_ips(self):
""" Get all IPAddress objects from the API. """ |
res = self.get_request('/ip_address')
IPs = IPAddress._create_ip_address_objs(res['ip_addresses'], cloud_manager=self)
return IPs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new(self, user, name, description=None):
""" Creates a new Feed object :param user: feed username :param name: feed name :param description: feed description... |
uri = self.client.remote + '/users/{0}/feeds'.format(user)
data = {
'feed': {
'name': name,
'description': description
}
}
resp = self.client.post(uri, data)
return resp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, user, name):
""" Removes a feed :param user: feed username :param name: feed name :return: true/false """ |
uri = self.client.remote + '/users/{}/feeds/{}'.format(user, name)
resp = self.client.session.delete(uri)
return resp.status_code |
<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(self, user):
""" Returns a list of Feeds from the API :param user: feed username :return: list Example: ret = feed.index('csirtgadgets') """ |
uri = self.client.remote + '/users/{0}/feeds'.format(user)
return self.client.get(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 show(self, user, name, limit=None, lasttime=None):
""" Returns a specific Feed from the API :param user: feed username :param name: feed name :param limit: l... |
uri = self.client.remote + '/users/{0}/feeds/{1}'.format(user, name)
return self.client.get(uri, params={'limit': limit, 'lasttime': lasttime}) |
<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_object(self, obj):
"""Override django-bakery to skip profiles that raise 404""" |
try:
build_path = self.get_build_path(obj)
self.request = self.create_request(build_path)
self.request.user = AnonymousUser()
self.set_kwargs(obj)
self.build_file(build_path, self.get_content())
except Http404:
# cleanup directory
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_schedule_row(schedule_day, slot, seen_items):
"""Create a row for the schedule table.""" |
row = ScheduleRow(schedule_day, slot)
skip = {}
expanding = {}
all_items = list(slot.scheduleitem_set
.select_related('talk', 'page', 'venue')
.all())
for item in all_items:
if item in seen_items:
# Inc rowspan
seen_items[it... |
<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_schedule(today=None):
"""Helper function which creates an ordered list of schedule days""" |
# We create a list of slots and schedule items
schedule_days = {}
seen_items = {}
for slot in Slot.objects.all().order_by('end_time', 'start_time', 'day'):
day = slot.get_day()
if today and day != today:
# Restrict ourselves to only today
continue
schedul... |
<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_context_data(self, **kwargs):
"""Allow adding a 'render_description' parameter""" |
context = super(ScheduleXmlView, self).get_context_data(**kwargs)
if self.request.GET.get('render_description', None) == '1':
context['render_description'] = True
else:
context['render_description'] = False
return 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 get(self, request):
"""Create a iCal file from the schedule""" |
# Heavily inspired by https://djangosnippets.org/snippets/2223/ and
# the icalendar documentation
calendar = Calendar()
site = get_current_site(request)
calendar.add('prodid', '-//%s Schedule//%s//' % (site.name, site.domain))
calendar.add('version', '2.0')
# Si... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_object(self, obj):
"""Override django-bakery to skip pages marked exclude_from_static""" |
if not obj.exclude_from_static:
super(ShowPage, self).build_object(obj) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_object(self, obj):
"""Override django-bakery to skip talks that raise 403""" |
try:
super(TalkView, self).build_object(obj)
except PermissionDenied:
# We cleanup the directory created
self.unbuild_object(obj) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_object(self, *args, **kwargs):
'''Only talk owners can see talks, unless they've been accepted'''
object_ = super(TalkView, self).get_object(*args, **kwargs)
if not object_.can_view(self.request.user):
raise PermissionDenied
return object_ |
<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, *args, **kwargs):
'''Canonicalize the URL if the slug changed'''
if self.request.path != self.object.get_absolute_url():
return HttpResponseRedirect(self.object.get_absolute_url())
return super(TalkView, self).render_to_response(*args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, request, *args, **kwargs):
"""Override delete to only withdraw""" |
talk = self.get_object()
talk.status = WITHDRAWN
talk.save()
revisions.set_user(self.request.user)
revisions.set_comment("Talk Withdrawn")
return HttpResponseRedirect(self.success_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 order_results_by(*fields):
"""A decorator that applies an ordering to the QuerySet returned by a function. """ |
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kw):
result = f(*args, **kw)
return result.order_by(*fields)
return wrapper
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cache_result(cache_key, timeout):
"""A decorator for caching the result of a function.""" |
def decorator(f):
cache_name = settings.WAFER_CACHE
@functools.wraps(f)
def wrapper(*args, **kw):
cache = caches[cache_name]
result = cache.get(cache_key)
if result is None:
result = f(*args, **kw)
cache.set(cache_key, res... |
<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_queryset(self):
"""Override django-bakery's build logic to fake pagination.""" |
paths = [(os.path.join(self.build_prefix, 'index.html'), {})]
self.request = None
queryset = self.get_queryset()
paginator = self.get_paginator(queryset, self.get_paginate_by(queryset))
for page in paginator.page_range:
paths.append(
(os.path.join(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 site_info(request):
'''Expose the site's info to templates'''
site = get_current_site(request)
context = {
'WAFER_CONFERENCE_NAME': site.name,
'WAFER_CONFERENCE_DOMAIN': site.domain,
}
return 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 navigation_info(request):
'''Expose whether to display the navigation header and footer'''
if request.GET.get('wafer_hide_navigation') == "1":
nav_class = "wafer-invisible"
else:
nav_class = "wafer-visible"
context = {
'WAFER_NAVIGATION_VISIBILITY': nav_class,
}
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 registration_settings(request):
'''Expose selected settings to templates'''
context = {}
for setting in (
'WAFER_SSO',
'WAFER_HIDE_LOGIN',
'WAFER_REGISTRATION_OPEN',
'WAFER_REGISTRATION_MODE',
'WAFER_TALKS_OPEN',
'WAFER_VIDEO_LICENS... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def profiles(self):
'''
return the rolls this people is related with
'''
limit = []
if self.is_admin():
limit.append(_("Administrator"))
limit.sort()
return limit |
<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_logging_level(args):
"Computes and sets the logging level from the parsed arguments."
root_logger = logging.getLogger()
level = logging.INFO
logging.getLogger('requests.packages.urllib3').setLevel(logging.WARNING)
if "verbose" in args and args.verbose is not None:
logging.getLogger('... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def debug(self, msg):
'''
Handle the debugging to a file
'''
# If debug is not disabled
if self.__debug is not False:
# If never was set, try to set it up
if self.__debug is None:
# Check what do we have inside settings
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 authenticate(self, *args, **kwargs):
'''
Authenticate the user agains LDAP
'''
# Get config
username = kwargs.get("username", None)
password = kwargs.get("password", None)
# Check user in Active Directory (authorization == None if can not connect to Active D... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_or_create_user(self, username, password):
'''
Get or create the given user
'''
# Get the groups for this user
info = self.get_ad_info(username, password)
self.debug("INFO found: {}".format(info))
# Find the user
try:
user = User.objec... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def synchronize(self, user, info):
'''
It tries to do a group synchronization if possible
This methods should be redeclared by the developer
'''
self.debug("Synchronize!")
# Remove all groups from this user
user.groups.clear()
# For all domains found fo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_schedule_items(*args, **kw):
"""We save all the schedule items associated with this slot, so the last_update time is updated to reflect any changes to... |
slot = kw.pop('instance', None)
if not slot:
return
for item in slot.scheduleitem_set.all():
item.save(update_fields=['last_updated'])
# We also need to update the next slot, in case we changed it's
# times as well
next_slot = slot.slot_set.all()
if next_slot.count():
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_diff(current, revision):
"""Create the difference between the current revision and a previous version""" |
the_diff = []
dmp = diff_match_patch()
for field in (set(current.field_dict.keys()) | set(revision.field_dict.keys())):
# These exclusions really should be configurable
if field == 'id' or field.endswith('_rendered'):
continue
# KeyError's may happen if the database str... |
<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_view(self, request, object_id, version_id, extra_context=None):
"""Actually compare two versions.""" |
opts = self.model._meta
object_id = unquote(object_id)
# get_for_object's ordering means this is always the latest revision.
# The reversion we want to compare to
current = Version.objects.get_for_object_reference(self.model, object_id)[0]
revision = Version.objects.get_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def comparelist_view(self, request, object_id, extra_context=None):
"""Allow selecting versions to compare.""" |
opts = self.model._meta
object_id = unquote(object_id)
current = get_object_or_404(self.model, pk=object_id)
# As done by reversion's history_view
action_list = [
{
"revision": version.revision,
"url": reverse("%s:%s_%s_compare" % (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 grv(struct, position):
'''
This function helps to convert date information for showing proper filtering
'''
if position == 'year':
size = 4
else:
size = 2
if (struct[position][2]):
rightnow = str(struct[position][0]).zfill(size)
else:
if position == 'year... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_template_names(self):
'''
Build the list of templates related to this user
'''
# Get user template
template_model = getattr(self, 'template_model', "{0}/{1}_{2}".format(self._appname.lower(), self._modelname.lower(), self.get_template_names_key))
template_model_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 get_context_data(self, **kwargs):
'''
Set a base context
'''
# Call the base implementation first to get a context
context = super(GenBase, self).get_context_data(**kwargs)
# Update general context with the stuff we already calculated
if hasattr(self, 'html_... |
<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_context_data(self, **kwargs):
'''
Generic list view with validation included and object transfering support
'''
# Call the base implementation first to get a context
context = super(GenList, self).get_context_data(**kwargs)
# Update general context with the stuff... |
<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_context_json(self, context):
'''
Return a base answer for a json answer
'''
# Initialize answer
answer = {}
# Metadata builder
answer['meta'] = self.__jcontext_metadata(context)
# Filter builder
answer['filter'] = self.__jcontext_filter(c... |
<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(self, form_class=None):
'''
Set form groups to the groups specified in the view if defined
'''
formobj = super(GenModify, self).get_form(form_class)
# Set requested group to this form
selfgroups = getattr(self, "form_groups", None)
if selfgroups:
... |
<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_parent(self, directory):
""" Given a directory name, return the Page representing it in the menu heirarchy. """ |
assert settings.PAGE_DIR.startswith('/')
assert settings.PAGE_DIR.endswith('/')
parents = directory[len(settings.PAGE_DIR):]
page = None
if parents:
for slug in parents.split('/'):
page = Page.objects.get(parent=page, slug=slug)
return 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 wafer_sso_url(context, sso_method):
'''
Return the correct URL to SSO with the given method.
'''
request = context.request
url = reverse(getattr(views, '%s_login' % sso_method))
if 'next' in request.GET:
url += '?' + urlencode({'next': request.GET['next']})
return url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authorize(args):
""" Authorizes Coursera's OAuth2 client for using coursera.org API servers for a specific application """ |
oauth2_instance = oauth2.build_oauth2(args.app, args)
oauth2_instance.build_authorizer()
logging.info('Application "%s" authorized!', args.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 check_auth(args):
""" Checks courseraoauth2client's connectivity to the coursera.org API servers for a specific application """ |
oauth2_instance = oauth2.build_oauth2(args.app, args)
auth = oauth2_instance.build_authorizer()
my_profile_url = (
'https://api.coursera.org/api/externalBasicProfiles.v1?'
'q=me&fields=name'
)
r = requests.get(my_profile_url, auth=auth)
if r.status_code != 200:
logging.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 quintic_bucket_warp(x, n, l1, l2, l3, x0, w1, w2, w3):
"""Warps the length scale with a piecewise quintic "bucket" shape. Parameters x : float or array-like ... |
x1 = x0 - w2 / 2.0 - w1 / 2.0
x2 = x0 + w2 / 2.0 + w3 / 2.0
x_shift_1 = 2.0 * (x - x1) / w1
x_shift_3 = 2.0 * (x - x2) / w3
if n == 0:
return (
l1 * (x <= (x1 - w1 / 2.0)) + (
0.5 * (l2 - l1) * (
3.0 / 8.0 * x_shift_1**5 -
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sso(user, desired_username, name, email, profile_fields=None):
""" Create a user, if the provided `user` is None, from the parameters. Then log the user in, ... |
if not user:
if not settings.REGISTRATION_OPEN:
raise SSOError('Account registration is closed')
user = _create_desired_user(desired_username)
_configure_user(user, name, email, profile_fields)
if not user.is_active:
raise SSOError('Account disabled')
# login()... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def debit(self, amount, credit_account, description, debit_memo="", credit_memo="", datetime=None):
""" Post a debit of 'amount' and a credit of -amount against ... |
assert amount >= 0
return self.post(amount, credit_account, description, self_memo=debit_memo, other_memo=credit_memo, datetime=datetime) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def credit(self, amount, debit_account, description, debit_memo="", credit_memo="", datetime=None):
""" Post a credit of 'amount' and a debit of -amount against ... |
assert amount >= 0
return self.post(-amount, debit_account, description, self_memo=credit_memo, other_memo=debit_memo, datetime=datetime) |
<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, amount, other_account, description, self_memo="", other_memo="", datetime=None):
""" Post a transaction of 'amount' against this account and the n... |
#Note: debits are always positive, credits are always negative. They should be negated before displaying
#(expense and liability?) accounts
tx = self._new_transaction()
if datetime:
tx.t_stamp = datetime
#else now()
tx.description = description
tx... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def totals(self, start=None, end=None):
"""Returns a Totals object containing the sum of all debits, credits and net change over the period of time from start to... |
qs = self._entries_range(start=start, end=end)
qs_positive = qs.filter(amount__gt=Decimal("0.00")).all().aggregate(Sum('amount'))
qs_negative = qs.filter(amount__lt=Decimal("0.00")).all().aggregate(Sum('amount'))
#Is there a cleaner way of saying this? Should the sum of 0 things be 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 ledger(self, start=None, end=None):
"""Returns a list of entries for this account. Ledger returns a sequence of LedgerEntry's matching the criteria in chrono... |
DEBIT_IN_DB = self._DEBIT_IN_DB()
flip = 1
if self._positive_credit():
flip *= -1
qs = self._entries_range(start=start, end=end)
qs = qs.order_by("transaction__t_stamp", "transaction__tid")
balance = Decimal("0.00")
if start:
balance =... |
<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_overlapping_slots(all_slots):
"""Find any slots that overlap""" |
overlaps = set([])
for slot in all_slots:
# Because slots are ordered, we can be more efficient than this
# N^2 loop, but this is simple and, since the number of slots
# should be low, this should be "fast enough"
start = slot.get_start_time()
end = slot.end_time
... |
<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_non_contiguous(all_items):
"""Find any items that have slots that aren't contiguous""" |
non_contiguous = []
for item in all_items:
if item.slots.count() < 2:
# No point in checking
continue
last_slot = None
for slot in item.slots.all().order_by('end_time'):
if last_slot:
if last_slot.end_time != slot.get_start_time():
... |
<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_invalid_venues(all_items):
"""Find venues assigned slots that aren't on the allowed list of days.""" |
venues = {}
for item in all_items:
valid = False
item_days = list(item.venue.days.all())
for slot in item.slots.all():
for day in item_days:
if day == slot.get_day():
valid = True
break
if not valid:
... |
<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_schedule():
"""Helper routine to easily test if the schedule is valid""" |
all_items = prefetch_schedule_items()
for validator, _type, _msg in SCHEDULE_ITEM_VALIDATORS:
if validator(all_items):
return False
all_slots = prefetch_slots()
for validator, _type, _msg in SLOT_VALIDATORS:
if validator(all_slots):
return False
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 validate_schedule():
"""Helper routine to report issues with the schedule""" |
all_items = prefetch_schedule_items()
errors = []
for validator, _type, msg in SCHEDULE_ITEM_VALIDATORS:
if validator(all_items):
errors.append(msg)
all_slots = prefetch_slots()
for validator, _type, msg in SLOT_VALIDATORS:
if validator(all_slots):
errors.ap... |
<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(self, request, obj=None, **kwargs):
"""Change the form depending on whether we're adding or editing the slot.""" |
if obj is None:
# Adding a new Slot
kwargs['form'] = SlotAdminAddForm
return super(SlotAdmin, self).get_form(request, obj, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_cached_menus():
"""Return the menus from the cache or generate them if needed.""" |
items = cache.get(CACHE_KEY)
if items is None:
menu = generate_menu()
cache.set(CACHE_KEY, menu.items)
else:
menu = Menu(items)
return menu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.