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 pages_to_show(paginator, page, page_labels=None):
"""Generate a dictionary of pages to show around the current page. Show 3 numbers on either side of the spe... |
show_pages = {} # FIXME; do we need OrderedDict here ?
if page_labels is None:
page_labels = {}
def get_page_label(index):
if index in page_labels:
return page_labels[index]
else:
return unicode(index)
if page != 1:
before = 3 # default nu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Indentation( logical_line, previous_logical, indent_level, previous_indent_level ):
"""Use two spaces per indentation level.""" |
comment = '' if logical_line else ' (comment)'
if indent_level % 2:
code = 'YCM111' if logical_line else 'YCM114'
message = ' indentation is not a multiple of two spaces' + comment
yield 0, code + message
if ( previous_logical.endswith( ':' ) and
( indent_level - previous_indent_level != 2 ) )... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def SpacesInsideBrackets( logical_line, tokens ):
"""Require spaces inside parentheses, square brackets, and braces for non-empty content.""" |
for index in range( len( tokens ) ):
_, prev_text, _, prev_end, _ = ( tokens[ index - 1 ] if index - 1 >= 0 else
( None, None, None, None, None ) )
token_type, text, start, end, _ = tokens[ index ]
next_token_type, next_text, next_start, _, _ = (
tokens[ index +... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def buy(self, player, cost):
""" indicate that the player was bought at the specified cost :param Player player: player to buy :param int cost: cost to pay :rais... |
if cost > self.max_bid():
raise InsufficientFundsError()
elif not any(roster_slot.accepts(player) and roster_slot.occupant is None for roster_slot in self.roster):
raise NoValidRosterSlotError()
elif self.owns(player):
raise AlreadyPurchasedError()
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 run(self):
"""Keep running this thread until it's stopped""" |
while not self._finished.isSet():
self._func(self._reference)
self._finished.wait(self._func._interval / 1000.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 subscribe(self, clock_name: str=None, clock_slots: Iterable[str]=None, subscriptions: Dict[str, Any]={}):
"""Subscribes this Area to the given Areas and op... |
for area in subscriptions: # type: str
init_full(self, area, subscriptions[area])
subscriptions[area] = {'slots': subscriptions[area]}
if clock_name is not None:
self.clock_name = clock_name
self.clock_slots = clock_slots
subscriptions[clock_name] = {'slots': clock_slots, 'buffer-length': 1}
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 logger(ref=0):
"""Finds a module logger. If the argument passed is a module, find the logger for that module using the modules' name; if it's a string, finds... |
if inspect.ismodule(ref):
return extend(logging.getLogger(ref.__name__))
if isinstance(ref, basestring):
return extend(logging.getLogger(ref))
return extend(logging.getLogger(stackclimber(ref+1))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def auto(cls, syslog=None, stderr=None, level=None, extended=None, server=None):
"""Tries to guess a sound logging configuration. """ |
level = norm_level(level) or logging.INFO
if syslog is None and stderr is None:
if sys.stderr.isatty() or syslog_path() is None:
log.info('Defaulting to STDERR logging.')
syslog, stderr = None, level
if extended is None:
ex... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_file(fd, filename=None, size=None, timestamp=None, ctype=None, charset=CHARSET, attachment=False, wrapper=DEFAULT_WRAPPER):
""" Send a file represented ... |
if not hasattr(fd, 'read'):
raise ValueError("Object '{}' has no read() method".format(fd))
headers = {}
status = 200
if not ctype and filename is not None:
ctype, enc = mimetypes.guess_type(filename)
if enc:
headers['Content-Encoding'] = enc
if ctype:
... |
<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(self, element):
"""Convert an element to a chainlink""" |
if isinstance(element, self.base_link_type):
return element
for converter in self.converters:
link = converter(element)
if link is not NotImplemented:
return link
raise TypeError('%r cannot be converted to a chainlink' % element) |
<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_view_name(view_cls, suffix=None):
""" Given a view class, return a textual name to represent the view. This name is used in the browsable API, and in OPT... |
name = view_cls.__name__
name = formatting.remove_trailing_string(name, 'View')
name = formatting.remove_trailing_string(name, 'ViewSet')
name = formatting.camelcase_to_spaces(name)
if suffix:
name += ' ' + suffix
return 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 get_view_description(view_cls, html=False):
""" Given a view class, return a textual description to represent the view. This name is used in the browsable AP... |
description = view_cls.__doc__ or ''
description = formatting.dedent(smart_text(description))
if html:
return formatting.markup_description(description)
return description |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exception_handler(exc, context):
""" Returns the response that should be used for any given exception. By default we handle the REST framework `APIException`... |
if isinstance(exc, exceptions.APIException):
headers = {}
if getattr(exc, 'auth_header', None):
headers['WWW-Authenticate'] = exc.auth_header
if getattr(exc, 'wait', None):
headers['Retry-After'] = '%d' % exc.wait
if isinstance(exc.detail, (list, dict)):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def as_view(cls, **initkwargs):
""" Store the original class on the view function. This allows us to discover information about the view when we do URL reverse l... |
if isinstance(getattr(cls, 'queryset', None), models.query.QuerySet):
def force_evaluation():
raise RuntimeError(
'Do not evaluate the `.queryset` attribute directly, '
'as the result will be cached and reused between 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 permission_denied(self, request, message=None):
""" If request is not permitted, determine what kind of exception to raise. """ |
if not request.successful_authenticator:
raise exceptions.NotAuthenticated()
raise exceptions.PermissionDenied(detail=message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_view_name(self):
""" Return the view name, as used in OPTIONS responses and in the browsable API. """ |
func = self.settings.VIEW_NAME_FUNCTION
return func(self.__class__, getattr(self, 'suffix', 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 get_view_description(self, html=False):
""" Return some descriptive text for the view, as used in OPTIONS responses and in the browsable API. """ |
func = self.settings.VIEW_DESCRIPTION_FUNCTION
return func(self.__class__, 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_format_suffix(self, **kwargs):
""" Determine if the request includes a '.json' style format suffix """ |
if self.settings.FORMAT_SUFFIX_KWARG:
return kwargs.get(self.settings.FORMAT_SUFFIX_KWARG) |
<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_content_negotiator(self):
""" Instantiate and return the content negotiation class to use. """ |
if not getattr(self, '_negotiator', None):
self._negotiator = self.content_negotiation_class()
return self._negotiator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def perform_content_negotiation(self, request, force=False):
""" Determine which renderer and media type to use render the response. """ |
renderers = self.get_renderers()
conneg = self.get_content_negotiator()
try:
return conneg.select_renderer(request, renderers, self.format_kwarg)
except Exception:
if force:
return (renderers[0], renderers[0].media_type)
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 check_throttles(self, request):
""" Check if request should be throttled. Raises an appropriate exception if the request is throttled. """ |
for throttle in self.get_throttles():
if not throttle.allow_request(request, self):
self.throttled(request, throttle.wait()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def initialize_request(self, request, *args, **kwargs):
""" Returns the initial request object. """ |
parser_context = self.get_parser_context(request)
return Request(
request,
parsers=self.get_parsers(),
authenticators=self.get_authenticators(),
negotiator=self.get_content_negotiator(),
parser_context=parser_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 initial(self, request, *args, **kwargs):
""" Runs anything that needs to occur prior to calling the method handler. """ |
self.format_kwarg = self.get_format_suffix(**kwargs)
# Ensure that the incoming request is permitted
self.perform_authentication(request)
self.check_permissions(request)
self.check_throttles(request)
# Perform content negotiation and store the accepted info on the requ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def finalize_response(self, request, response, *args, **kwargs):
""" Returns the final response object. """ |
# Make the error obvious if a proper response is not returned
assert isinstance(response, HttpResponseBase), (
'Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` '
'to be returned from the view, but received a `%s`'
% type(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 handle_exception(self, exc):
""" Handle any exception that occurs, by returning an appropriate response, or re-raising the error. """ |
if isinstance(exc, (exceptions.NotAuthenticated,
exceptions.AuthenticationFailed)):
# WWW-Authenticate header for 401 responses, else coerce to 403
auth_header = self.get_authenticate_header(self.request)
if auth_header:
exc.auth_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def options(self, request, *args, **kwargs):
""" Handler method for HTTP 'OPTIONS' request. """ |
if self.metadata_class is None:
return self.http_method_not_allowed(request, *args, **kwargs)
data = self.metadata_class().determine_metadata(request, self)
return Response(data, status=status.HTTP_200_OK) |
<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_subkey(self,name):
"""Retreive the subkey with the specified name. If the named subkey is not found, AttributeError is raised; this is for consistency wi... |
subkey = Key(name,self)
try:
hkey = subkey.hkey
except WindowsError:
raise AttributeError("subkey '%s' does not exist" % (name,))
return subkey |
<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_subkey(self,name,value=None):
"""Create the named subkey and set its value. There are several different ways to specify the new contents of the named sub... |
self.sam |= KEY_CREATE_SUB_KEY
subkey = Key(name,self)
try:
subkey = self.get_subkey(name)
except AttributeError:
_winreg.CreateKey(self.hkey,name)
subkey = self.get_subkey(name)
if value is None:
pass
elif issubclass(type(... |
<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_subkey(self,name):
"""Delete the named subkey, and any values or keys it contains.""" |
self.sam |= KEY_WRITE
subkey = self.get_subkey(name)
subkey.clear()
_winreg.DeleteKey(subkey.parent.hkey,subkey.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 clear(self):
"""Remove all subkeys and values from this key.""" |
self.sam |= KEY_WRITE
for v in list(self.values()):
del self[v.name]
for k in list(self.subkeys()):
self.del_subkey(k.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 publish(self):
""" Iterate over the scheduler collections and apply any actions found """ |
try:
for collection in self.settings.get("scheduler").get("collections"):
yield self.publish_for_collection(collection)
except Exception as ex:
self.logger.error(ex) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_all_revisions_to_in_process(self, ids):
""" Set all revisions found to in process, so that other threads will not pick them up. :param list ids: """ |
predicate = {
"_id" : {
"$in" : [ ObjectId(id) for id in ids ]
}
}
set = {"$set": { "inProcess": True }}
yield self.revisions.collection.update(predicate, set, multi=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_pending_revisions(self):
""" Get all the pending revisions after the current time :return: A list of revisions :rtype: list """ |
dttime = time.mktime(datetime.datetime.now().timetuple())
changes = yield self.revisions.find({
"toa" : {
"$lt" : dttime,
},
"processed": False,
"inProcess": None
})
if len(changes) > 0:
yield self.set_all_revis... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def publish_for_collection(self, collection_name):
""" Run the publishing operations for a given collection :param str collection_name: """ |
self.revisions = BaseAsyncMotorDocument("%s_revisions" % collection_name, self.settings)
changes = yield self.__get_pending_revisions()
if len(changes) > 0:
self.logger.info("%s revisions will be actioned" % len(changes))
for change in changes:
try:
... |
<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_action(self, revision):
"""Update a master document and revision history document :param dict revision: The revision dictionary """ |
patch = revision.get("patch")
if patch.get("_id"):
del patch["_id"]
update_response = yield self.collection.patch(revision.get("master_id"), self.__make_storeable_patch_patchable(patch))
if update_response.get("n") == 0:
raise RevisionNotFoundException() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __insert_action(self, revision):
""" Handle the insert action type. Creates new document to be created in this collection. This allows you to stage a creatio... |
revision["patch"]["_id"] = ObjectId(revision.get("master_id"))
insert_response = yield self.collection.insert(revision.get("patch"))
if not isinstance(insert_response, str):
raise DocumentRevisionInsertFailed() |
<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_action(self, revision):
""" Handle a delete action to a partiular master id via the revision. :param dict revision: :return: """ |
delete_response = yield self.collection.delete(revision.get("master_id"))
if delete_response.get("n") == 0:
raise DocumentRevisionDeleteFailed() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pop(self):
"""Pop the top revision off the stack back onto the collection at the given id. This method applies the action. Note: This assumes you don't have ... |
revisions = yield self.list()
if len(revisions) > 0:
revision = revisions[0]
# Update type action
if revision.get("action") == self.UPDATE_ACTION:
try:
yield self.__update_action(revision)
except Exception as ex:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __make_patch_storeable(self, patch):
"""Replace all dots with pipes in key names, mongo doesn't like to store keys with dots. :param dict patch: The patch th... |
new_patch = {}
for key in patch:
new_patch[key.replace(".", "|")] = patch[key]
return new_patch |
<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, patch=None, toa=None, meta=None):
"""Push a change on to the revision stack for this ObjectId. Pushing onto the stack is how you get revisions to ... |
if not meta:
meta = {}
if not toa:
toa = time.mktime(datetime.datetime.now().timetuple())
if not isinstance(toa, int):
toa = int(toa)
#Documents should be stored in bson formats
if isinstance(patch, dict):
patch = self.revision... |
<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(self, toa=None, show_history=False):
"""Return all revisions for this stack :param int toa: The time of action as a UTC timestamp :param bool show_histo... |
if not toa:
toa = time.mktime(datetime.datetime.now().timetuple())
query = {
"$query": {
"master_id": self.master_id,
"processed": show_history,
"toa" : {"$lte" : toa}
},
"$orderby": {
"toa"... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _lazy_migration(self, patch=None, meta=None, toa=None):
""" Handle when a revision scheduling is turned onto a collection that was previously not scheduleabl... |
objects = yield self.revisions.find({"master_id": self.master_id}, limit=1)
if len(objects) > 0:
raise Return(objects)
if not patch:
patch = yield self.collection.find_one_by_id(self.master_id)
if not toa:
toa = long(time.mktime(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 __create_preview_object_base(self, dct):
""" The starting point for a preview of a future object. This is the object which will have future revisions iterate... |
if dct.get("_id"):
del dct["_id"]
preview_object_id = yield self.previews.insert(dct)
raise Return(preview_object_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 preview(self, revision_id):
"""Get an ephemeral preview of a revision with all revisions applied between it and the current state :param str revision_id: The... |
target_revision = yield self.revisions.find_one_by_id(revision_id)
if isinstance(target_revision.get("snapshot"), dict):
raise Return(target_revision)
preview_object = None
if not isinstance(target_revision, dict):
raise RevisionNotFound()
revision_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 insert(self, dct, toa=None, comment=""):
"""Create a document :param dict dct: :param toa toa: Optional time of action, triggers this to be handled as a futu... |
if self.schema:
jsonschema.validate(dct, self.schema)
bson_obj = yield self.collection.insert(dct)
raise Return(bson_obj.__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 upsert(self, _id, dct, attribute="_id"):
"""Update or Insert a new document :param str _id: The document id :param dict dct: The dictionary to set on the doc... |
mongo_response = yield self.update(_id, dct, upsert=True, attribute=attribute)
raise Return(mongo_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 update(self, predicate_value, dct, upsert=False, attribute="_id"):
"""Update an existing document :param predicate_value: The value of the predicate :param d... |
if self.schema:
jsonschema.validate(dct, self.schema)
if attribute=="_id" and not isinstance(predicate_value, ObjectId):
predicate_value = ObjectId(predicate_value)
predicate = {attribute: predicate_value}
dct = self._dictionary_to_cursor(dct)
mongo_... |
<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, _id):
"""Delete a document or create a DELETE revision :param str _id: The ID of the document to be deleted :returns: JSON Mongo client response... |
mongo_response = yield self.collection.remove({"_id": ObjectId(_id)})
raise Return(mongo_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 find_one(self, query):
"""Find one wrapper with conversion to dictionary :param dict query: A Mongo query """ |
mongo_response = yield self.collection.find_one(query)
raise Return(self._obj_cursor_to_dictionary(mongo_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 find(self, query, orderby=None, order_by_direction=1, page=0, limit=0):
"""Find a document by any criteria :param dict query: The query to perform :param str... |
cursor = self.collection.find(query)
if orderby:
cursor.sort(orderby, order_by_direction)
cursor.skip(page*limit).limit(limit)
results = []
while (yield cursor.fetch_next):
results.append(self._obj_cursor_to_dictionary(cursor.next_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 find_one_by_id(self, _id):
""" Find a single document by id :param str _id: BSON string repreentation of the Id :return: a signle object :rtype: dict """ |
document = (yield self.collection.find_one({"_id": ObjectId(_id)}))
raise Return(self._obj_cursor_to_dictionary(document)) |
<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_index(self, index, index_type=GEO2D):
"""Create an index on a given attribute :param str index: Attribute to set index on :param str index_type: See P... |
self.logger.info("Adding %s index to stores on attribute: %s" % (index_type, index))
yield self.collection.create_index([(index, index_type)]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def location_based_search(self, lng, lat, distance, unit="miles", attribute_map=None, page=0, limit=50):
"""Search based on location and other attribute filters ... |
#Determine what type of radian conversion you want base on a unit of measure
if unit == "miles":
distance = float(distance/69)
else:
distance = float(distance/111.045)
#Start with geospatial query
query = {
"loc" : {
"$within... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def default(self, obj, **kwargs):
"""Handles the adapting of special types from mongo""" |
if isinstance(obj, datetime.datetime):
return time.mktime(obj.timetuple())
if isinstance(obj, Timestamp):
return obj.time
if isinstance(obj, ObjectId):
return obj.__str__()
return JSONEncoder.default(self, 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 _tdec(code: str, unit: str = 'C') -> str: """ Translates a 4-digit decimal temperature representation Ex: 1045 -> -4.5°C 0237 -> 23.7°C """ |
ret = f"{'-' if code[0] == '1' else ''}{int(code[1:3])}.{code[3]}"
if unit:
ret += f'°{unit}'
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pressure_tendency(code: str, unit: str = 'mb') -> str: """ Translates a 5-digit pressure outlook code Ex: 50123 -> 12.3 mb: Increasing, then decreasing """ |
width, precision = int(code[2:4]), code[4]
return ('3-hour pressure difference: +/- '
f'{width}.{precision} {unit} - {PRESSURE_TENDENCIES[code[1]]}') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(rmk: str) -> RemarksData: """ Finds temperature and dewpoint decimal values from the remarks """ |
rmkdata = {}
for item in rmk.split(' '):
if len(item) in [5, 9] and item[0] == 'T' and item[1:].isdigit():
rmkdata['temperature_decimal'] = core.make_number(_tdec(item[1:5], None)) # type: ignore
rmkdata['dewpoint_decimal'] = core.make_number(_tdec(item[5:], None)) # type: ign... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def translate(remarks: str) -> typing.Dict[str, str]: # noqa """ Translates elements in the remarks string """ |
ret = {}
# Add and replace static multi-word elements
for key in REMARKS_GROUPS:
if key in remarks:
ret[key.strip()] = REMARKS_GROUPS[key]
remarks.replace(key, ' ')
# For each remaining element
for rmk in remarks.split()[1:]:
rlen = len(rmk)
# Static ... |
<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_row(self):
""" Parses a row, cell-by-cell, returning a dict of field names to the cleaned field values. """ |
fields = self.mapping
for i, cell in enumerate(self.row[0:len(fields)]):
field_name, field_type = fields[str(i)]
parsed_cell = self.clean_cell(cell, field_type)
self.parsed_row[field_name] = parsed_cell |
<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_mappings(self):
""" Uses CSV files of field names and positions for different filing types to load mappings into memory, for use in parsing different t... |
self.mappings = {}
for record_type in ('sa', 'sb', 'F8872'):
path = os.path.join(
os.path.dirname(
os.path.dirname(
os.path.dirname(__file__))),
'mappings',
'{}.csv'.format(record_type))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def diff(full, dataset_uri, reference_dataset_uri):
"""Report the difference between two datasets. 1. Checks that the identifiers are identicial 2. Checks that t... |
def echo_header(desc, ds_name, ref_ds_name, prop):
click.secho("Different {}".format(desc), fg="red")
click.secho("ID, {} in '{}', {} in '{}'".format(
prop, ds_name, prop, ref_ds_name))
def echo_diff(diff):
for d in diff:
line = "{}, {}, {}".format(d[0], d[1], ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def identifiers(dataset_uri):
"""List the item identifiers in the dataset.""" |
dataset = dtoolcore.DataSet.from_uri(dataset_uri)
for i in dataset.identifiers:
click.secho(i) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def summary(dataset_uri, format):
"""Report summary information about a dataset.""" |
dataset = dtoolcore.DataSet.from_uri(dataset_uri)
creator_username = dataset._admin_metadata["creator_username"]
frozen_at = dataset._admin_metadata["frozen_at"]
num_items = len(dataset.identifiers)
tot_size = sum([dataset.item_properties(i)["size_in_bytes"]
for i in dataset.ide... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def properties(dataset_uri, item_identifier):
"""Report item properties.""" |
dataset = dtoolcore.DataSet.from_uri(dataset_uri)
try:
props = dataset.item_properties(item_identifier)
except KeyError:
click.secho(
"No such item in dataset: {}".format(item_identifier),
fg="red",
err=True
)
sys.exit(20)
json_lines ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def relpath(dataset_uri, item_identifier):
"""Return relpath associated with the item. """ |
dataset = dtoolcore.DataSet.from_uri(dataset_uri)
try:
props = dataset.item_properties(item_identifier)
except KeyError:
click.secho(
"No such item in dataset: {}".format(item_identifier),
fg="red",
err=True
)
sys.exit(21)
click.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 verify(full, dataset_uri):
"""Verify the integrity of a dataset. """ |
dataset = dtoolcore.DataSet.from_uri(dataset_uri)
all_okay = True
generated_manifest = dataset.generate_manifest()
generated_identifiers = set(generated_manifest["items"].keys())
manifest_identifiers = set(dataset.identifiers)
for i in generated_identifiers.difference(manifest_identifiers):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uuid(dataset_uri):
"""Return the UUID of the dataset.""" |
dataset = dtoolcore.DataSet.from_uri(dataset_uri)
click.secho(dataset.uuid) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split_data(self):
"""Splits the list of SeqRecordExpanded objects into lists, which are kept into a bigger list. If the file_format is Nexus, then it is only... |
this_gene_code = None
for seq_record in self.data.seq_records:
if this_gene_code is None or this_gene_code != seq_record.gene_code:
this_gene_code = seq_record.gene_code
self._blocks.append([])
list_length = len(self._blocks)
self._blo... |
<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(self, block):
"""Makes gene_block as str from list of SeqRecordExpanded objects of a gene_code. Override this function if the dataset block... |
if self.partitioning != '1st-2nd, 3rd':
return self.make_datablock_by_gene(block)
else:
if self.format == 'FASTA':
return self.make_datablock_considering_codon_positions_as_fasta_format(block)
else:
return self.make_datablock_by_gene(b... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_block_dicts_to_string(self, block_1st2nd, block_1st, block_2nd, block_3rd):
"""Takes into account whether we need to output all codon positions.""" |
out = ""
# We need 1st and 2nd positions
if self.codon_positions in ['ALL', '1st-2nd']:
for gene_code, seqs in block_1st2nd.items():
out += '>{0}_1st-2nd\n----\n'.format(gene_code)
for seq in seqs:
out += seq
elif self.codo... |
<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_charsets(self):
""" Override this function for Phylip dataset as the content is different and goes into a separate file. """ |
count_start = 1
out = ''
for gene_code, lengths in self.data.gene_codes_and_lengths.items():
count_end = lengths[0] + count_start - 1
out += self.format_charset_line(gene_code, count_start, count_end)
count_start = count_end + 1
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_slash_number(self):
""" Charset lines have \2 or \3 depending on type of partitioning and codon positions requested for our dataset. :return: """ |
if self.partitioning == 'by codon position' and self.codon_positions == '1st-2nd':
return '\\2'
elif self.partitioning in ['by codon position', '1st-2nd, 3rd'] and self.codon_positions in ['ALL', None]:
return '\\3'
else:
return '' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_suffixes_to_gene_codes(self):
"""Appends pos1, pos2, etc to the gene_code if needed.""" |
out = []
for gene_code in self.data.gene_codes:
for sufix in self.make_gene_code_suffixes():
out.append('{0}{1}'.format(gene_code, sufix))
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_outgroup(self):
"""Generates the outgroup line from the voucher code specified by the user. """ |
if self.outgroup is not None:
outgroup_taxonomy = ''
for i in self.data.seq_records:
if self.outgroup == i.voucher_code:
outgroup_taxonomy = '{0}_{1}'.format(i.taxonomy['genus'],
i.taxonomy['spe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_string(input_str) -> 'MissionTime': # noinspection SpellCheckingInspection """ Creates a MissionTime instance from a string Format: YYYYMMDDHHMMSS Args: ... |
match = RE_INPUT_STRING.match(input_str)
if not match:
raise ValueError(f'badly formatted date/time: {input_str}')
return MissionTime(
datetime.datetime(
int(match.group('year')),
int(match.group('month')),
int(match.group... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def run(self, output):
'''Generate the report to the given output.
:param output: writable file-like object or file path
'''
# Ensure folder exists.
if self.folder_id not in self.folders.folders(self.user):
print("E: folder not found: %s" % self.folder_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 _generate_report_all(self):
'''Generate report for all subfolders contained by self.folder_id.'''
assert self.workbook is not None
count = 0
# Do all subfolders
for sid in self.folders.subfolders(self.folder_id, self.user):
count += 1
self._generate_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 _generate_report_single(self, sid):
'''Generate report for subfolder given by sid .
The main purpose of this method is to make sure the subfolder given by
sid does indeed exist. All real work is delegated to
_generate_for_subfolder.
:param sid: The subfolder id
Pr... |
<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_for_subfolder(self, sid):
''' Generate report for a subfolder.
:param sid: The subfolder id; assumed valid
'''
# TODO: the following assumes subfolder names can be constructed from a
# subfolder id, which might not be the case in the future.
name = self._sa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def construct(generator, subtopic):
'''Method constructor of Item-derived classes.
Given a subtopic tuple, this method attempts to construct an
Item-derived class, currently either ItemText or ItemImage, from the
subtopic's type, found in its 4th element.
:param generator: Refe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def resize_image(self, data):
'''Resize image if height over 50 pixels and convert to JPEG.
Given a ByteIO or StringIO data input, this method ensures that the
image is not over 50 pixels high. If it is over 50 pixels high, the
image is resized to precisely 50 pixels in height and 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 desc(self):
""" A textual description of this course """ |
if 'ects' in self:
fmt = '%s (%s, S%d) [%s, %.2f ECTS]'
fields = ('title', 'code', 'semester', 'status', 'ects')
else:
fmt = '%s'
fields = ('title',)
s = fmt % tuple([self[f] for f in fields])
if self['followed'] and self['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 _populate(self, soup):
""" Populate the list, assuming ``soup`` is a ``BeautifulSoup`` object. """ |
tables = soup.select('table[rules=all]')
if not tables:
return
trs = tables[0].select('tr')[1:]
if len(trs[0]) == 5:
# M1
self._populate_small_table(trs)
else:
# M2
self._populate_large_table(trs) |
<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_host(self):
""" Gets the host name or IP address. :return: the host name or IP address. """ |
host = self.get_as_nullable_string("host")
host = host if host != None else self.get_as_nullable_string("ip")
return host |
<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_icao(icao: str):
""" Queries AWC for the METAR of a given station Args: icao: station ID as a four letters-digits ICAO code Returns: AWC result for the... |
params = {
'dataSource': 'metars',
'requestType': 'retrieve',
'format': 'csv',
'hoursBeforeNow': 24,
}
AWC._validate_icao(icao)
params['stationString'] = icao
try:
return AWC._query(params)
except RequestsConnec... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self, asset_content, friendly_name, tags='', optimize=False):
""" Create an asset on the server You must provide the asset with a friendly name for th... |
return self._create_asset({
'asset': b64encode(asset_content),
'friendly-name': friendly_name,
'tags': tags,
'optimize': optimize,
'type': 'base64'
}) |
<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_at_path(self, asset_content, url_path, tags=''):
""" Create asset at a specific URL path on the server """ |
return self._create_asset({
'asset': b64encode(asset_content),
'url-path': url_path,
'tags': tags,
'type': 'base64'
}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _matrix_integration(q, h, t):
''' Returns the dp metric for a single horsetail
curve at a given value of the epistemic uncertainties'''
N = len(q)
# correction if CDF has gone out of trapezium range
if h[-1] < 0.9: h[-1] = 1.0
W = np.zeros([N, N])
for i in range(N):
W[i, i] = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _matrix_grad(q, h, h_dx, t, t_prime):
''' Returns the gradient with respect to a single variable'''
N = len(q)
W = np.zeros([N, N])
Wprime = np.zeros([N, N])
for i in range(N):
W[i, i] = 0.5*(h[min(i+1, N-1)] - h[max(i-1, 0)])
Wprime[i, i] = \
0.5*(h_dx[min(i+1, N-1)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def evalMetric(self, x, method=None):
'''Evaluates the horsetail matching metric at given values of the
design variables.
:param iterable x: values of the design variables, this is passed as
the first argument to the function fqoi
:param str method: method to use to evaluate... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def evalMetricFromSamples(self, q_samples, grad_samples=None, method=None):
'''Evaluates the horsetail matching metric from given samples of the quantity
of interest and gradient instead of evaluating them at a design.
:param np.ndarray q_samples: samples of the quantity of interest,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getHorsetail(self):
'''Function that gets vectors of the horsetail plot at the last design
evaluated.
:return: upper_curve, lower_curve, CDFs - returns three parameters,
the first two are tuples containing pairs of x/y vectors of the
upper and lower bounds on the CDF... |
<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):
'''
If MultiTenantMiddleware is used, filter queryset by request.site_id
'''
queryset = super(PageList, self).get_queryset()
if hasattr(self.request, 'site_id'):
queryset = queryset.filter(site_id=self.request.site_id)
return queryset |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def retrieve_taf(station_icao) -> typing.Tuple[typing.Union[str, None], typing.Union[str, None]]: """ Retrieves a TAF string from an online database Args: station... |
url = _BASE_TAF_URL.format(station=station_icao)
with requests.get(url) as resp:
if not resp.ok:
return f'unable to obtain TAF for station {station_icao}\n' \
f'Got to "http://tgftp.nws.noaa.gov/data/observations/metar/stations" ' \
f'for a list of vali... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def retrieve_metar(station_icao) -> typing.Tuple[typing.Optional[str], typing.Optional[str]]: """ Retrieves a METAR string from an online database Args: station_i... |
url = _BASE_METAR_URL.format(station=station_icao)
with requests.get(url) as resp:
if not resp.ok:
return f'unable to obtain METAR for station {station_icao}\n' \
f'Got to "http://tgftp.nws.noaa.gov/data/observations/metar/stations" ' \
f'for a list of ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def value(self, units=None):
"""Return the pressure in the specified units.""" |
if units is None:
return self._value
if not units.upper() in CustomPressure.legal_units:
raise UnitsError("unrecognized pressure unit: '" + units + "'")
units = units.upper()
if units == self._units:
return self._value
if self._units == "IN":... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def string(self, units: typing.Optional[str] = None) -> str: """Return a string representation of the pressure, using the given units.""" |
if not units:
_units: str = self._units
else:
if not units.upper() in CustomPressure.legal_units:
raise UnitsError("unrecognized pressure unit: '" + units + "'")
_units = units.upper()
val = self.value(units)
if _units == "MB":
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def determine_name(func):
""" Given a function, returns the name of the function. Ex:: from random import choice determine_name(choice) # Returns 'choice' :param... |
if hasattr(func, '__name__'):
return func.__name__
elif hasattr(func, '__class__'):
return func.__class__.__name__
# This shouldn't be possible, but blow up if so.
raise AttributeError("Provided callable '{}' has no name.".format(
func
)) |
<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_module(module_name):
""" Given a dotted Python path, imports & returns the module. If not found, raises ``UnknownModuleError``. Ex:: mod = import_modu... |
try:
return importlib.import_module(module_name)
except ImportError as err:
raise UnknownModuleError(str(err)) |
<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_attr(module_name, attr_name):
""" Given a dotted Python path & an attribute name, imports the module & returns the attribute. If not found, raises ``U... |
module = import_module(module_name)
try:
return getattr(module, attr_name)
except AttributeError as err:
raise UnknownCallableError(str(err)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.