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 set_cache_policy(self, func):
"""Set the context cache policy function. Args: func: A function that accepts a Key instance as argument and returns a bool ind... |
if func is None:
func = self.default_cache_policy
elif isinstance(func, bool):
func = lambda unused_key, flag=func: flag
self._cache_policy = 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 _use_cache(self, key, options=None):
"""Return whether to use the context cache for this key. Args: key: Key instance. options: ContextOptions instance, or N... |
flag = ContextOptions.use_cache(options)
if flag is None:
flag = self._cache_policy(key)
if flag is None:
flag = ContextOptions.use_cache(self._conn.config)
if flag is None:
flag = True
return flag |
<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_memcache_policy(self, func):
"""Set the memcache policy function. Args: func: A function that accepts a Key instance as argument and returns a bool indic... |
if func is None:
func = self.default_memcache_policy
elif isinstance(func, bool):
func = lambda unused_key, flag=func: flag
self._memcache_policy = 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 _use_memcache(self, key, options=None):
"""Return whether to use memcache for this key. Args: key: Key instance. options: ContextOptions instance, or None. R... |
flag = ContextOptions.use_memcache(options)
if flag is None:
flag = self._memcache_policy(key)
if flag is None:
flag = ContextOptions.use_memcache(self._conn.config)
if flag is None:
flag = True
return flag |
<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_datastore_policy(key):
"""Default datastore policy. This defers to _use_datastore on the Model class. Args: key: Key instance. Returns: A bool or Non... |
flag = None
if key is not None:
modelclass = model.Model._kind_map.get(key.kind())
if modelclass is not None:
policy = getattr(modelclass, '_use_datastore', None)
if policy is not None:
if isinstance(policy, bool):
flag = policy
else:
flag... |
<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_datastore_policy(self, func):
"""Set the context datastore policy function. Args: func: A function that accepts a Key instance as argument and returns a ... |
if func is None:
func = self.default_datastore_policy
elif isinstance(func, bool):
func = lambda unused_key, flag=func: flag
self._datastore_policy = 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 _use_datastore(self, key, options=None):
"""Return whether to use the datastore for this key. Args: key: Key instance. options: ContextOptions instance, or N... |
flag = ContextOptions.use_datastore(options)
if flag is None:
flag = self._datastore_policy(key)
if flag is None:
flag = ContextOptions.use_datastore(self._conn.config)
if flag is None:
flag = True
return flag |
<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_memcache_timeout_policy(key):
"""Default memcache timeout policy. This defers to _memcache_timeout on the Model class. Args: key: Key instance. Retur... |
timeout = None
if key is not None and isinstance(key, model.Key):
modelclass = model.Model._kind_map.get(key.kind())
if modelclass is not None:
policy = getattr(modelclass, '_memcache_timeout', None)
if policy is not None:
if isinstance(policy, (int, long)):
ti... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load_from_cache_if_available(self, key):
"""Returns a cached Model instance given the entity key if available. Args: key: Key instance. Returns: A Model ins... |
if key in self._cache:
entity = self._cache[key] # May be None, meaning "doesn't exist".
if entity is None or entity._key == key:
# If entity's key didn't change later, it is ok.
# See issue 13. http://goo.gl/jxjOP
raise tasklets.Return(entity) |
<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, key, **ctx_options):
"""Return a Model instance given the entity key. It will use the context cache if the cache policy for the given key is enable... |
options = _make_ctx_options(ctx_options)
use_cache = self._use_cache(key, options)
if use_cache:
self._load_from_cache_if_available(key)
use_datastore = self._use_datastore(key, options)
if (use_datastore and
isinstance(self._conn, datastore_rpc.TransactionalConnection)):
use_m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call_on_commit(self, callback):
"""Call a callback upon successful commit of a transaction. If not in a transaction, the callback is called immediately. In a... |
if not self.in_transaction():
callback()
else:
self._on_commit_queue.append(callback) |
<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_nickname(userid):
"""Return a Future for a nickname from an account.""" |
account = yield get_account(userid)
if not account:
nickname = 'Unregistered'
else:
nickname = account.nickname or account.email
raise ndb.Return(nickname) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mark_done(task_id):
"""Marks a task as done. Args: task_id: The integer id of the task to update. Raises: ValueError: if the requested task doesn't exist. ""... |
task = Task.get_by_id(task_id)
if task is None:
raise ValueError('Task with id %d does not exist' % task_id)
task.done = True
task.put() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_tasks(tasks):
"""Converts a list of tasks to a list of string representations. Args: tasks: A list of the tasks to convert. Returns: A list of string ... |
return ['%d : %s (%s)' % (task.key.id(),
task.description,
('done' if task.done
else 'created %s' % task.created))
for task in tasks] |
<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_command(command):
"""Accepts a string command and performs an action. Args: command: the command to run as a string. """ |
try:
cmds = command.split(None, 1)
cmd = cmds[0]
if cmd == 'new':
add_task(get_arg(cmds))
elif cmd == 'done':
mark_done(int(get_arg(cmds)))
elif cmd == 'list':
for task in format_tasks(list_tasks()):
print task
elif cmd == 'delete':
delete_task(int(get_arg(cmds... |
<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_upload_url(success_path, max_bytes_per_blob=None, max_bytes_total=None, **options):
"""Create upload URL for POST form. Args: success_path: Path withi... |
fut = create_upload_url_async(success_path,
max_bytes_per_blob=max_bytes_per_blob,
max_bytes_total=max_bytes_total,
**options)
return fut.get_result() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_blob_info(field_storage):
"""Parse a BlobInfo record from file upload field_storage. Args: field_storage: cgi.FieldStorage that represents uploaded blo... |
if field_storage is None:
return None
field_name = field_storage.name
def get_value(dct, name):
value = dct.get(name, None)
if value is None:
raise BlobInfoParseError(
'Field %s has no %s.' % (field_name, name))
return value
filename = get_value(field_storage.disposition_opti... |
<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(blob, start_index, end_index, **options):
"""Fetch data for blob. Fetches a fragment of a blob up to MAX_BLOB_FETCH_SIZE in length. Attempting to ... |
fut = fetch_data_async(blob, start_index, end_index, **options)
return fut.get_result() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(cls, blob_key, **ctx_options):
"""Retrieve a BlobInfo by key. Args: blob_key: A blob key. This may be a str, unicode or BlobKey instance. **ctx_options: ... |
fut = cls.get_async(blob_key, **ctx_options)
return fut.get_result() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, **options):
"""Permanently delete this blob from Blobstore. Args: **options: Options for create_rpc(). """ |
fut = delete_async(self.key(), **options)
fut.get_result() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __fill_buffer(self, size=0):
"""Fills the internal buffer. Args: size: Number of bytes to read. Will be clamped to [self.__buffer_size, MAX_BLOB_FETCH_SIZE].... |
read_size = min(max(size, self.__buffer_size), MAX_BLOB_FETCH_SIZE)
self.__buffer = fetch_data(self.__blob_key, self.__position,
self.__position + read_size - 1)
self.__buffer_position = 0
self.__eof = len(self.__buffer) < read_size |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def blob_info(self):
"""Returns the BlobInfo for this file.""" |
if not self.__blob_info:
self.__blob_info = BlobInfo.get(self.__blob_key)
return self.__blob_info |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_connection(config=None, default_model=None, _api_version=datastore_rpc._DATASTORE_V3, _id_resolver=None):
"""Create a new Connection object with the rig... |
return datastore_rpc.Connection(
adapter=ModelAdapter(default_model, id_resolver=_id_resolver),
config=config,
_api_version=_api_version) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _unpack_user(v):
"""Internal helper to unpack a User value from a protocol buffer.""" |
uv = v.uservalue()
email = unicode(uv.email().decode('utf-8'))
auth_domain = unicode(uv.auth_domain().decode('utf-8'))
obfuscated_gaiaid = uv.obfuscated_gaiaid().decode('utf-8')
obfuscated_gaiaid = unicode(obfuscated_gaiaid)
federated_identity = None
if uv.has_federated_identity():
federated_identit... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _date_to_datetime(value):
"""Convert a date to a datetime for Cloud Datastore storage. Args: value: A datetime.date object. Returns: A datetime object with t... |
if not isinstance(value, datetime.date):
raise TypeError('Cannot convert to datetime expected date value; '
'received %s' % value)
return datetime.datetime(value.year, value.month, value.day) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _time_to_datetime(value):
"""Convert a time to a datetime for Cloud Datastore storage. Args: value: A datetime.time object. Returns: A datetime object with d... |
if not isinstance(value, datetime.time):
raise TypeError('Cannot convert to datetime expected time value; '
'received %s' % value)
return datetime.datetime(1970, 1, 1,
value.hour, value.minute, value.second,
value.microsecond) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transactional(func, args, kwds, **options):
"""Decorator to make a function automatically run in a transaction. Args: **ctx_options: Transaction options (see... |
return transactional_async.wrapped_decorator(
func, args, kwds, **options).get_result() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transactional_async(func, args, kwds, **options):
"""The async version of @ndb.transaction.""" |
options.setdefault('propagation', datastore_rpc.TransactionOptions.ALLOWED)
if args or kwds:
return transaction_async(lambda: func(*args, **kwds), **options)
return transaction_async(func, **options) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def non_transactional(func, args, kwds, allow_existing=True):
"""A decorator that ensures a function is run outside a transaction. If there is an existing transa... |
from . import tasklets
ctx = tasklets.get_context()
if not ctx.in_transaction():
return func(*args, **kwds)
if not allow_existing:
raise datastore_errors.BadRequestError(
'%s cannot be called within a transaction.' % func.__name__)
save_ctx = ctx
while ctx.in_transaction():
ctx = ctx._p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set(self, value):
"""Updates all descendants to a specified value.""" |
if self.__is_parent_node():
for child in self.__sub_counters.itervalues():
child._set(value)
else:
self.__counter = value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _comparison(self, op, value):
"""Internal helper for comparison operators. Args: op: The operator ('=', '<' etc.). Returns: A FilterNode instance representin... |
# NOTE: This is also used by query.gql().
if not self._indexed:
raise datastore_errors.BadFilterError(
'Cannot query for unindexed property %s' % self._name)
from .query import FilterNode # Import late to avoid circular imports.
if value is not None:
value = self._do_validate(val... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _IN(self, value):
"""Comparison operator for the 'in' comparison operator. The Python 'in' operator cannot be overloaded in the way we want to, so we define ... |
if not self._indexed:
raise datastore_errors.BadFilterError(
'Cannot query for unindexed property %s' % self._name)
from .query import FilterNode # Import late to avoid circular imports.
if not isinstance(value, (list, tuple, set, frozenset)):
raise datastore_errors.BadArgumentError(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _do_validate(self, value):
"""Call all validations on the value. This calls the most derived _validate() method(s), then the custom validator function, and t... |
if isinstance(value, _BaseValue):
return value
value = self._call_shallow_validation(value)
if self._validator is not None:
newvalue = self._validator(self, value)
if newvalue is not None:
value = newvalue
if self._choices is not None:
if value not in self._choices:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fix_up(self, cls, code_name):
"""Internal helper called to tell the property its name. This is called by _fix_up_properties() which is called by MetaModel w... |
self._code_name = code_name
if self._name is None:
self._name = code_name |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set_value(self, entity, value):
"""Internal helper to set a value in an entity for a Property. This performs validation first. For a repeated Property the v... |
if entity._projection:
raise ReadonlyPropertyError(
'You cannot set property values of a projection entity')
if self._repeated:
if not isinstance(value, (list, tuple, set, frozenset)):
raise datastore_errors.BadValueError('Expected list or tuple, got %r' %
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _retrieve_value(self, entity, default=None):
"""Internal helper to retrieve the value for this Property from an entity. This returns None if no value is set,... |
return entity._values.get(self._name, default) |
<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_methods(cls, *names, **kwds):
"""Compute a list of composable methods. Because this is a common operation and the class hierarchy is static, the outcom... |
reverse = kwds.pop('reverse', False)
assert not kwds, repr(kwds)
cache = cls.__dict__.get('_find_methods_cache')
if cache:
hit = cache.get(names)
if hit is not None:
return hit
else:
cls._find_methods_cache = cache = {}
methods = []
for c in cls.__mro__:
for ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _apply_list(self, methods):
"""Return a single callable that applies a list of methods to a value. If a method returns None, the last value is kept; if it re... |
def call(value):
for method in methods:
newvalue = method(self, value)
if newvalue is not None:
value = newvalue
return value
return call |
<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_value(self, entity):
"""Internal helper to get the value for this Property from an entity. For a repeated Property this initializes the value to an empt... |
if entity._projection:
if self._name not in entity._projection:
raise UnprojectedPropertyError(
'Property %s is not in the projection' % (self._name,))
return self._get_user_value(entity) |
<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_value(self, entity):
"""Internal helper to delete the value for this Property from an entity. Note that if no value exists this is a no-op; deleted v... |
if self._name in entity._values:
del entity._values[self._name] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _is_initialized(self, entity):
"""Internal helper to ask if the entity has a value for this Property. This returns False if a value is stored but it is None.... |
return (not self._required or
((self._has_value(entity) or self._default is not None) and
self._get_value(entity) is not 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 _serialize(self, entity, pb, prefix='', parent_repeated=False, projection=None):
"""Internal helper to serialize this property to a protocol buffer. Subclass... |
values = self._get_base_value_unwrapped_as_list(entity)
name = prefix + self._name
if projection and name not in projection:
return
if self._indexed:
create_prop = lambda: pb.add_property()
else:
create_prop = lambda: pb.add_raw_property()
if self._repeated and not values an... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _deserialize(self, entity, p, unused_depth=1):
"""Internal helper to deserialize this property from a protocol buffer. Subclasses may override this method. A... |
if p.meaning() == entity_pb.Property.EMPTY_LIST:
self._store_value(entity, [])
return
val = self._db_get_value(p.value(), p)
if val is not None:
val = _BaseValue(val)
# TODO: replace the remainder of the function with the following commented
# out code once its feasible to make ... |
<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_property(self, rest=None, require_indexed=True):
"""Internal helper to check this property for specific requirements. Called by Model._check_propertie... |
if require_indexed and not self._indexed:
raise InvalidPropertyError('Property is unindexed %s' % self._name)
if rest:
raise InvalidPropertyError('Referencing subproperty %s.%s '
'but %s is not a structured property' %
(self._name, r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set_value(self, entity, value):
"""Setter for key attribute.""" |
if value is not None:
value = _validate_key(value, entity=entity)
value = entity._validate_key(value)
entity._entity_key = value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __get_arg(cls, kwds, kwd):
"""Internal helper method to parse keywords that may be property names.""" |
alt_kwd = '_' + kwd
if alt_kwd in kwds:
return kwds.pop(alt_kwd)
if kwd in kwds:
obj = getattr(cls, kwd, None)
if not isinstance(obj, Property) or isinstance(obj, ModelKey):
return kwds.pop(kwd)
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set_attributes(self, kwds):
"""Internal helper to set attributes from keyword arguments. Expando overrides this. """ |
cls = self.__class__
for name, value in kwds.iteritems():
prop = getattr(cls, name) # Raises AttributeError for unknown properties.
if not isinstance(prop, Property):
raise TypeError('Cannot set non-property %s' % name)
prop._set_value(self, value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_uninitialized(self):
"""Internal helper to find uninitialized properties. Returns: A set of property names. """ |
return set(name
for name, prop in self._properties.iteritems()
if not prop._is_initialized(self)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _check_initialized(self):
"""Internal helper to check for uninitialized properties. Raises: BadValueError if it finds any. """ |
baddies = self._find_uninitialized()
if baddies:
raise datastore_errors.BadValueError(
'Entity has uninitialized properties: %s' % ', '.join(baddies)) |
<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_kind_map(cls):
"""Clear the kind map. Useful for testing.""" |
# Preserve "system" kinds, like __namespace__
keep = {}
for name, value in cls._kind_map.iteritems():
if name.startswith('__') and name.endswith('__'):
keep[name] = value
cls._kind_map.clear()
cls._kind_map.update(keep) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _lookup_model(cls, kind, default_model=None):
"""Get the model class for the kind. Args: kind: A string representing the name of the kind to lookup. default_... |
modelclass = cls._kind_map.get(kind, default_model)
if modelclass is None:
raise KindError(
"No model class found for kind '%s'. Did you forget to import it?" %
kind)
return modelclass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _equivalent(self, other):
"""Compare two entities of the same class, excluding keys.""" |
if other.__class__ is not self.__class__: # TODO: What about subclasses?
raise NotImplementedError('Cannot compare different model classes. '
'%s is not %s' % (self.__class__.__name__,
other.__class_.__name__))
if set(self... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _to_pb(self, pb=None, allow_partial=False, set_key=True):
"""Internal helper to turn an entity into an EntityProto protobuf.""" |
if not allow_partial:
self._check_initialized()
if pb is None:
pb = entity_pb.EntityProto()
if set_key:
# TODO: Move the key stuff into ModelAdapter.entity_to_pb()?
self._key_to_pb(pb)
for unused_name, prop in sorted(self._properties.iteritems()):
prop._serialize(self, p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _key_to_pb(self, pb):
"""Internal helper to copy the key into a protobuf.""" |
key = self._key
if key is None:
pairs = [(self._get_kind(), None)]
ref = key_module._ReferenceFromPairs(pairs, reference=pb.mutable_key())
else:
ref = key.reference()
pb.mutable_key().CopyFrom(ref)
group = pb.mutable_entity_group() # Must initialize this.
# To work around 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 _from_pb(cls, pb, set_key=True, ent=None, key=None):
"""Internal helper to create an entity from an EntityProto protobuf.""" |
if not isinstance(pb, entity_pb.EntityProto):
raise TypeError('pb must be a EntityProto; received %r' % pb)
if ent is None:
ent = cls()
# A key passed in overrides a key in the pb.
if key is None and pb.key().path().element_size():
key = Key(reference=pb.key())
# If set_key is no... |
<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_property_for(self, p, indexed=True, depth=0):
"""Internal helper to get the Property for a protobuf-level property.""" |
parts = p.name().split('.')
if len(parts) <= depth:
# Apparently there's an unstructured value here.
# Assume it is a None written for a missing value.
# (It could also be that a schema change turned an unstructured
# value into a structured one. In that case, too, it seems
# bet... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _clone_properties(self):
"""Internal helper to clone self._properties if necessary.""" |
cls = self.__class__
if self._properties is cls._properties:
self._properties = dict(cls._properties) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fake_property(self, p, next, indexed=True):
"""Internal helper to create a fake Property.""" |
self._clone_properties()
if p.name() != next and not p.name().endswith('.' + next):
prop = StructuredProperty(Expando, next)
prop._store_value(self, _BaseValue(Expando()))
else:
compressed = p.meaning_uri() == _MEANING_URI_COMPRESSED
prop = GenericProperty(next,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _to_dict(self, include=None, exclude=None):
"""Return a dict containing the entity's property values. Args: include: Optional set of property names to includ... |
if (include is not None and
not isinstance(include, (list, tuple, set, frozenset))):
raise TypeError('include should be a list, tuple or set')
if (exclude is not None and
not isinstance(exclude, (list, tuple, set, frozenset))):
raise TypeError('exclude should be a list, tuple or set... |
<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_properties(cls, property_names, require_indexed=True):
"""Internal helper to check the given properties exist and meet specified requirements. Called ... |
assert isinstance(property_names, (list, tuple)), repr(property_names)
for name in property_names:
assert isinstance(name, basestring), repr(name)
if '.' in name:
name, rest = name.split('.', 1)
else:
rest = None
prop = cls._properties.get(name)
if prop is 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 _query(cls, *args, **kwds):
"""Create a Query object for this class. Args: distinct: Optional bool, short hand for group_by = projection. *args: Used to appl... |
# Validating distinct.
if 'distinct' in kwds:
if 'group_by' in kwds:
raise TypeError(
'cannot use distinct= and group_by= at the same time')
projection = kwds.get('projection')
if not projection:
raise TypeError(
'cannot use distinct= without projection... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _gql(cls, query_string, *args, **kwds):
"""Run a GQL query.""" |
from .query import gql # Import late to avoid circular imports.
return gql('SELECT * FROM %s %s' % (cls._class_name(), query_string),
*args, **kwds) |
<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_async(self, **ctx_options):
"""Write this entity to Cloud Datastore. This is the asynchronous version of Model._put(). """ |
if self._projection:
raise datastore_errors.BadRequestError('Cannot put a partial entity')
from . import tasklets
ctx = tasklets.get_context()
self._prepare_for_put()
if self._key is None:
self._key = Key(self._get_kind(), None)
self._pre_put_hook()
fut = ctx.put(self, **ctx_opt... |
<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_by_id(cls, id, parent=None, **ctx_options):
"""Returns an instance of Model class by ID. Args: id: A string or integer key ID. parent: Optional parent k... |
return cls._get_by_id_async(id, parent=parent, **ctx_options).get_result() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _is_default_hook(default_hook, hook):
"""Checks whether a specific hook is in its default state. Args: cls: A ndb.model.Model class. default_hook: Callable s... |
if not hasattr(default_hook, '__call__'):
raise TypeError('Default hooks for ndb.model.Model must be callable')
if not hasattr(hook, '__call__'):
raise TypeError('Hooks must be callable')
return default_hook.im_func is hook.im_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 _ReferenceFromSerialized(serialized):
"""Construct a Reference from a serialized Reference.""" |
if not isinstance(serialized, basestring):
raise TypeError('serialized must be a string; received %r' % serialized)
elif isinstance(serialized, unicode):
serialized = serialized.encode('utf8')
return entity_pb.Reference(serialized) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _DecodeUrlSafe(urlsafe):
"""Decode a url-safe base64-encoded string. This returns the decoded string. """ |
if not isinstance(urlsafe, basestring):
raise TypeError('urlsafe must be a string; received %r' % urlsafe)
if isinstance(urlsafe, unicode):
urlsafe = urlsafe.encode('utf8')
mod = len(urlsafe) % 4
if mod:
urlsafe += '=' * (4 - mod)
# This is 3-4x faster than urlsafe_b64decode()
return base64.b64... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flat(self):
"""Return a tuple of alternating kind and id values.""" |
flat = []
for kind, id in self.__pairs:
flat.append(kind)
flat.append(id)
return tuple(flat) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reference(self):
"""Return the Reference object for this Key. This is a entity_pb.Reference instance -- a protocol buffer class used by the lower-level API t... |
if self.__reference is None:
self.__reference = _ConstructReference(self.__class__,
pairs=self.__pairs,
app=self.__app,
namespace=self.__namespace)
return self.__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 urlsafe(self):
"""Return a url-safe string encoding this Key's Reference. This string is compatible with other APIs and languages and with the strings used t... |
# This is 3-4x faster than urlsafe_b64decode()
urlsafe = base64.b64encode(self.reference().Encode())
return urlsafe.rstrip('=').replace('+', '-').replace('/', '_') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_async(self, **ctx_options):
"""Return a Future whose result is the entity for this Key. If no such entity exists, a Future is still returned, and the Fut... |
from . import model, tasklets
ctx = tasklets.get_context()
cls = model.Model._kind_map.get(self.kind())
if cls:
cls._pre_get_hook(self)
fut = ctx.get(self, **ctx_options)
if cls:
post_hook = cls._post_get_hook
if not cls._is_default_hook(model.Model._default_post_get_hook,
... |
<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_async(self, **ctx_options):
"""Schedule deletion of the entity for this Key. This returns a Future, whose result becomes available once the deletion i... |
from . import tasklets, model
ctx = tasklets.get_context()
cls = model.Model._kind_map.get(self.kind())
if cls:
cls._pre_delete_hook(self)
fut = ctx.delete(self, **ctx_options)
if cls:
post_hook = cls._post_delete_hook
if not cls._is_default_hook(model.Model._default_post_dele... |
<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_flow_exception(exc):
"""Add an exception that should not be logged. The argument must be a subclass of Exception. """ |
global _flow_exceptions
if not isinstance(exc, type) or not issubclass(exc, Exception):
raise TypeError('Expected an Exception subclass, got %r' % (exc,))
as_set = set(_flow_exceptions)
as_set.add(exc)
_flow_exceptions = tuple(as_set) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_flow_exceptions():
"""Internal helper to initialize _flow_exceptions. This automatically adds webob.exc.HTTPException, if it can be imported. """ |
global _flow_exceptions
_flow_exceptions = ()
add_flow_exception(datastore_errors.Rollback)
try:
from webob import exc
except ImportError:
pass
else:
add_flow_exception(exc.HTTPException) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sleep(dt):
"""Public function to sleep some time. Example: yield tasklets.sleep(0.5) # Sleep for half a sec. """ |
fut = Future('sleep(%.3f)' % dt)
eventloop.queue_call(dt, fut.set_result, None)
return fut |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _transfer_result(fut1, fut2):
"""Helper to transfer result or errors from one Future to another.""" |
exc = fut1.get_exception()
if exc is not None:
tb = fut1.get_traceback()
fut2.set_exception(exc, tb)
else:
val = fut1.get_result()
fut2.set_result(val) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def synctasklet(func):
"""Decorator to run a function as a tasklet when called. Use this to wrap a request handler function that will be called by some web appli... |
taskletfunc = tasklet(func) # wrap at declaration time.
@utils.wrapping(func)
def synctasklet_wrapper(*args, **kwds):
# pylint: disable=invalid-name
__ndb_debug__ = utils.func_info(func)
return taskletfunc(*args, **kwds).get_result()
return synctasklet_wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def toplevel(func):
"""A sync tasklet that sets a fresh default Context. Use this for toplevel view functions such as webapp.RequestHandler.get() or Django view ... |
synctaskletfunc = synctasklet(func) # wrap at declaration time.
@utils.wrapping(func)
def add_context_wrapper(*args, **kwds):
# pylint: disable=invalid-name
__ndb_debug__ = utils.func_info(func)
_state.clear_all_pending()
# Create and install a new context.
ctx = make_default_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 _make_cloud_datastore_context(app_id, external_app_ids=()):
"""Creates a new context to connect to a remote Cloud Datastore instance. This should only be use... |
from . import model # Late import to deal with circular imports.
# Late import since it might not exist.
if not datastore_pbs._CLOUD_DATASTORE_ENABLED:
raise datastore_errors.BadArgumentError(
datastore_pbs.MISSING_CLOUD_DATASTORE_MESSAGE)
import googledatastore
try:
from google.appengine.da... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _analyze_indexed_fields(indexed_fields):
"""Internal helper to check a list of indexed fields. Args: indexed_fields: A list of names, possibly dotted names. ... |
result = {}
for field_name in indexed_fields:
if not isinstance(field_name, basestring):
raise TypeError('Field names must be strings; got %r' % (field_name,))
if '.' not in field_name:
if field_name in result:
raise ValueError('Duplicate field name %s' % field_name)
result[field_... |
<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_model_class(message_type, indexed_fields, **props):
"""Construct a Model subclass corresponding to a Message subclass. Args: message_type: A Message su... |
analyzed = _analyze_indexed_fields(indexed_fields)
for field_name, sub_fields in analyzed.iteritems():
if field_name in props:
raise ValueError('field name %s is reserved' % field_name)
try:
field = message_type.field_by_name(field_name)
except KeyError:
raise ValueError('Message 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 _get_value(self, entity):
"""Compute and store a default value if necessary.""" |
value = super(_ClassKeyProperty, self)._get_value(entity)
if not value:
value = entity._class_key()
self._store_value(entity, value)
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_hierarchy(cls):
"""Internal helper to return the list of polymorphic base classes. This returns a list of class objects, e.g. [Animal, Feline, Cat]. """ |
bases = []
for base in cls.mro(): # pragma: no branch
if hasattr(base, '_get_hierarchy'):
bases.append(base)
del bases[-1] # Delete PolyModel itself
bases.reverse()
return bases |
<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_env_paths_in_basedirs(base_dirs):
"""Returns all potential envs in a basedir""" |
# get potential env path in the base_dirs
env_path = []
for base_dir in base_dirs:
env_path.extend(glob.glob(os.path.join(
os.path.expanduser(base_dir), '*', '')))
# self.log.info("Found the following kernels from config: %s", ", ".join(venvs))
return env_path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_to_env_data(mgr, env_paths, validator_func, activate_func, name_template, display_name_template, name_prefix):
"""Converts a list of paths to environ... |
env_data = {}
for venv_dir in env_paths:
venv_name = os.path.split(os.path.abspath(venv_dir))[1]
kernel_name = name_template.format(name_prefix + venv_name)
kernel_name = kernel_name.lower()
if kernel_name in env_data:
mgr.log.debug(
"Found duplicate ... |
<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_IPykernel(venv_dir):
"""Validates that this env contains an IPython kernel and returns info to start it Returns: tuple (ARGV, language, resource_dir... |
python_exe_name = find_exe(venv_dir, "python")
if python_exe_name is None:
python_exe_name = find_exe(venv_dir, "python2")
if python_exe_name is None:
python_exe_name = find_exe(venv_dir, "python3")
if python_exe_name is None:
return [], None, None
# Make some checks for ip... |
<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_IRkernel(venv_dir):
"""Validates that this env contains an IRkernel kernel and returns info to start it Returns: tuple (ARGV, language, resource_dir... |
r_exe_name = find_exe(venv_dir, "R")
if r_exe_name is None:
return [], None, None
# check if this is really an IRkernel **kernel**
import subprocess
ressources_dir = None
try:
print_resources = 'cat(as.character(system.file("kernelspec", package = "IRkernel")))'
resourc... |
<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_exe(env_dir, name):
"""Finds a exe with that name in the environment path""" |
if platform.system() == "Windows":
name = name + ".exe"
# find the binary
exe_name = os.path.join(env_dir, name)
if not os.path.exists(exe_name):
exe_name = os.path.join(env_dir, "bin", name)
if not os.path.exists(exe_name):
exe_name = os.path.join(env_dir, "Script... |
<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_virtualenv_env_data(mgr):
"""Finds kernel specs from virtualenv environments env_data is a structure {name -> (resourcedir, kernel spec)} """ |
if not mgr.find_virtualenv_envs:
return {}
mgr.log.debug("Looking for virtualenv environments in %s...", mgr.virtualenv_env_dirs)
# find all potential env paths
env_paths = find_env_paths_in_basedirs(mgr.virtualenv_env_dirs)
mgr.log.debug("Scanning virtualenv environments for python ker... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def source_bash(args, stdin=None):
"""Simply bash-specific wrapper around source-foreign Returns a dict to be used as a new environment""" |
args = list(args)
new_args = ['bash', '--sourcer=source']
new_args.extend(args)
return source_foreign(new_args, stdin=stdin) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def source_zsh(args, stdin=None):
"""Simply zsh-specific wrapper around source-foreign Returns a dict to be used as a new environment""" |
args = list(args)
new_args = ['zsh', '--sourcer=source']
new_args.extend(args)
return source_foreign(new_args, stdin=stdin) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def source_cmd(args, stdin=None):
"""Simple cmd.exe-specific wrapper around source-foreign. returns a dict to be used as a new environment """ |
args = list(args)
fpath = locate_binary(args[0])
args[0] = fpath if fpath else args[0]
if not os.path.isfile(args[0]):
raise RuntimeError("Command not found: %s" % args[0])
prevcmd = 'call '
prevcmd += ' '.join([argvquote(arg, force=True) for arg in args])
prevcmd = escape_windows_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 source_foreign(args, stdin=None):
"""Sources a file written in a foreign shell language.""" |
parser = _ensure_source_foreign_parser()
ns = parser.parse_args(args)
if ns.prevcmd is not None:
pass # don't change prevcmd if given explicitly
elif os.path.isfile(ns.files_or_code[0]):
# we have filename to source
ns.prevcmd = '{} "{}"'.format(ns.sourcer, '" "'.join(ns.files_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_bool(x):
""""Converts to a boolean in a semantically meaningful way.""" |
if isinstance(x, bool):
return x
elif isinstance(x, str):
return False if x.lower() in _FALSES else True
else:
return bool(x) |
<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_env(s):
"""Parses the environment portion of string into a dict.""" |
m = ENV_RE.search(s)
if m is None:
return {}
g1 = m.group(1)
env = dict(ENV_SPLIT_RE.findall(g1))
return env |
<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_conda_env_data(mgr):
"""Finds kernel specs from conda environments env_data is a structure {name -> (resourcedir, kernel spec)} """ |
if not mgr.find_conda_envs:
return {}
mgr.log.debug("Looking for conda environments in %s...", mgr.conda_env_dirs)
# find all potential env paths
env_paths = find_env_paths_in_basedirs(mgr.conda_env_dirs)
env_paths.extend(_find_conda_env_paths_from_conda(mgr))
env_paths = list(set(env... |
<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_env(self, envname):
""" Check the name of the environment against the black list and the whitelist. If a whitelist is specified only it is checked. ... |
if self.whitelist_envs and envname in self.whitelist_envs:
return True
elif self.whitelist_envs:
return False
if self.blacklist_envs and envname not in self.blacklist_envs:
return True
elif self.blacklist_envs:
# If there is just a 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_env_data(self, reload=False):
"""Get the data about the available environments. env_data is a structure {name -> (resourcedir, kernel spec)} """ |
# This is called much too often and finding-process is really expensive :-(
if not reload and getattr(self, "_env_data_cache", {}):
return getattr(self, "_env_data_cache")
env_data = {}
for supplyer in ENV_SUPPLYER:
env_data.update(supplyer(self))
env_... |
<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_all_kernel_specs_for_envs(self):
"""Returns the dict of name -> kernel_spec for all environments""" |
data = self._get_env_data()
return {name: data[name][1] for name in 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 get_all_specs(self):
"""Returns a dict mapping kernel names and resource directories. """ |
# This is new in 4.1 -> https://github.com/jupyter/jupyter_client/pull/93
specs = self.get_all_kernel_specs_for_envs()
specs.update(super(EnvironmentKernelSpecManager, self).get_all_specs())
return specs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.