INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Override this and do some customer message handler. | def ack(self, msg):
"""Override this and do some customer message handler.
"""
print("Got a message:\n%s\n" % msg['body'])
# do something with the message...
# Generate the ack or not if you subscribed with ack='auto'
return super(Pong, self).ack(msg) |
This is a decorator that will wrap the decorated method in an atomic transaction and retry the transaction a given number of times | def transaction_atomic_with_retry(num_retries=5, backoff=0.1):
"""
This is a decorator that will wrap the decorated method in an atomic transaction and
retry the transaction a given number of times
:param num_retries: How many times should we retry before we give up
:param backoff: How long should ... |
A decorator that can be used to defer the syncing of entities until after the method has been run This is being introduced to help avoid deadlocks in the meantime as we attempt to better understand why they are happening | def defer_entity_syncing(wrapped, instance, args, kwargs):
"""
A decorator that can be used to defer the syncing of entities until after the method has been run
This is being introduced to help avoid deadlocks in the meantime as we attempt to better understand
why they are happening
"""
# Defer... |
Given model objects organized by content type and a dictionary of all model IDs that need to be synced organize all super entity relationships that need to be synced. | def _get_super_entities_by_ctype(model_objs_by_ctype, model_ids_to_sync, sync_all):
"""
Given model objects organized by content type and a dictionary of all model IDs that need
to be synced, organize all super entity relationships that need to be synced.
Ensure that the model_ids_to_sync dict is updat... |
Given the model IDs to sync fetch all model objects to sync | def _get_model_objs_to_sync(model_ids_to_sync, model_objs_map, sync_all):
"""
Given the model IDs to sync, fetch all model objects to sync
"""
model_objs_to_sync = {}
for ctype, model_ids_to_sync_for_ctype in model_ids_to_sync.items():
model_qset = entity_registry.entity_registry.get(ctype.m... |
Syncs entities | def sync_entities(*model_objs):
"""
Syncs entities
Args:
model_objs (List[Model]): The model objects to sync. If empty, all entities will be synced
"""
# Check if we are deferring processing
if sync_entities.defer:
# If we dont have any model objects passed add a none to let us... |
Syncs entities watching changes of a model instance. | def sync_entities_watching(instance):
"""
Syncs entities watching changes of a model instance.
"""
for entity_model, entity_model_getter in entity_registry.entity_watching[instance.__class__]:
model_objs = list(entity_model_getter(instance))
if model_objs:
sync_entities(*mode... |
Given a list of entity kinds ensure they are synced properly to the database. This will ensure that only unchanged entity kinds are synced and will still return all updated entity kinds | def upsert_entity_kinds(self, entity_kinds):
"""
Given a list of entity kinds ensure they are synced properly to the database.
This will ensure that only unchanged entity kinds are synced and will still return all
updated entity kinds
:param entity_kinds: The list of entity kind... |
Upsert a list of entities to the database: param entities: The entities to sync: param sync: Do a sync instead of an upsert | def upsert_entities(self, entities, sync=False):
"""
Upsert a list of entities to the database
:param entities: The entities to sync
:param sync: Do a sync instead of an upsert
"""
# Select the entities we are upserting for update to reduce deadlocks
if entities:... |
Upsert entity relationships to the database: param queryset: The base queryset to use: param entity_relationships: The entity relationships to ensure exist in the database | def upsert_entity_relationships(self, queryset, entity_relationships):
"""
Upsert entity relationships to the database
:param queryset: The base queryset to use
:param entity_relationships: The entity relationships to ensure exist in the database
"""
# Select the relatio... |
Returns a tuple for a kind name and kind display name of an entity. By default uses the app_label and model of the model object s content type as the kind. | def get_entity_kind(self, model_obj):
"""
Returns a tuple for a kind name and kind display name of an entity.
By default, uses the app_label and model of the model object's content
type as the kind.
"""
model_obj_ctype = ContentType.objects.get_for_model(self.queryset.mod... |
Registers an entity config | def register_entity(self, entity_config):
"""
Registers an entity config
"""
if not issubclass(entity_config, EntityConfig):
raise ValueError('Must register entity config class of subclass EntityConfig')
if entity_config.queryset is None:
raise ValueError... |
Start twisted event loop and the fun should begin... | def start(host='localhost', port=61613, username='', password=''):
"""Start twisted event loop and the fun should begin...
"""
StompClientFactory.username = username
StompClientFactory.password = password
reactor.connectTCP(host, port, StompClientFactory())
reactor.run() |
Once I ve connected I want to subscribe to my the message queue. | def connected(self, msg):
"""Once I've connected I want to subscribe to my the message queue.
"""
stomper.Engine.connected(self, msg)
self.log.info("Connected: session %s. Beginning say hello." % msg['headers']['session'])
def setup_looping_call():
lc = Loop... |
Send out a hello message periodically. | def send(self):
"""Send out a hello message periodically.
"""
self.log.info("Saying hello (%d)." % self.counter)
f = stomper.Frame()
f.unpack(stomper.send(DESTINATION, 'hello there (%d)' % self.counter))
self.counter += 1
# ActiveMQ specific headers:
... |
Register with stomp server. | def connectionMade(self):
"""Register with stomp server.
"""
cmd = stomper.connect(self.username, self.password)
self.transport.write(cmd) |
Use stompbuffer to determine when a complete message has been received. | def dataReceived(self, data):
"""Use stompbuffer to determine when a complete message has been received.
"""
self.stompBuffer.appendData(data)
while True:
msg = self.stompBuffer.getOneMessage()
if msg is None:
break
returned = self.react... |
Connection failed | def clientConnectionFailed(self, connector, reason):
"""Connection failed
"""
print('Connection failed. Reason:', reason)
ReconnectingClientFactory.clientConnectionFailed(self, connector, reason) |
Process the message and determine what to do with it. | def ack(self, msg):
"""Process the message and determine what to do with it.
"""
self.log.info("receiverId <%s> Received: <%s> " % (self.receiverId, msg['body']))
#return super(MyStomp, self).ack(msg)
return stomper.NO_REPONSE_NEEDED |
Register with the stomp server. | def connectionMade(self):
"""Register with the stomp server.
"""
cmd = self.sm.connect()
self.transport.write(cmd) |
Data received react to it and respond if needed. | def dataReceived(self, data):
"""Data received, react to it and respond if needed.
"""
# print "receiver dataReceived: <%s>" % data
msg = stomper.unpack_frame(data)
returned = self.sm.react(msg)
# print "receiver returned <%s>" % returned
... |
Find a folder or a file ID from its name inside a given folder. | def find_id_in_folder(self, name, parent_folder_id=0):
"""Find a folder or a file ID from its name, inside a given folder.
Args:
name (str): Name of the folder or the file to find.
parent_folder_id (int): ID of the folder where to search.
Returns:
int. ID o... |
Create a folder | def create_folder(self, name, parent_folder_id=0):
"""Create a folder
If the folder exists, a BoxError will be raised.
Args:
folder_id (int): Name of the folder.
parent_folder_id (int): ID of the folder where to create the new one.
Returns:
dict. R... |
Delete an existing folder | def delete_folder(self, folder_id, recursive=True):
"""Delete an existing folder
Args:
folder_id (int): ID of the folder to delete.
recursive (bool): Delete all subfolder if True.
Returns:
dict. Response from Box.
Raises:
BoxError: An er... |
Get files and folders inside a given folder | def get_folder_items(self, folder_id,
limit=100, offset=0, fields_list=None):
"""Get files and folders inside a given folder
Args:
folder_id (int): Where to get files and folders info.
limit (int): The number of items to return.
offset (... |
Upload a file into a folder. | def upload_file(self, name, folder_id, file_path):
"""Upload a file into a folder.
Use function for small file otherwise there is the chunk_upload_file() function
Args::
name (str): Name of the file on your Box storage.
folder_id (int): ID of the folder where to upload... |
Upload a new version of a file into a folder. | def upload_new_file_version(self, name, folder_id, file_id, file_path):
"""Upload a new version of a file into a folder.
Use function for small file otherwise there is the chunk_upload_file() function.
Args::
name (str): Name of the file on your Box storage.
folder_id ... |
Upload a file chunk by chunk. | def chunk_upload_file(self, name, folder_id, file_path,
progress_callback=None,
chunk_size=1024*1024*1):
"""Upload a file chunk by chunk.
The whole file is never loaded in memory.
Use this function for big file.
The callback(trans... |
Copy file to new destination | def copy_file(self, file_id, dest_folder_id):
"""Copy file to new destination
Args:
file_id (int): ID of the folder.
dest_folder_id (int): ID of parent folder you are copying to.
Returns:
dict. Response from Box.
Raises:
BoxError: An er... |
Download a file. | def download_file(self, file_id, dest_file_path,
progress_callback=None,
chunk_size=1024*1024*1):
"""Download a file.
The whole file is never loaded in memory.
The callback(transferred, total) to let you know the download progress.
... |
Searches for files/ folders | def search(self, **kwargs):
"""Searches for files/folders
Args:
\*\*kwargs (dict): A dictionary containing necessary parameters
(check https://developers.box.com/docs/#search for
list of parameters)
Returns:
dict. ... |
Return a list of values corresponding to the keys in the iterable of * keys *. If a key is not present in the collection its corresponding value will be: obj: None. | def getmany(self, *keys):
"""
Return a list of values corresponding to the keys in the iterable of
*keys*.
If a key is not present in the collection, its corresponding value will
be :obj:`None`.
.. note::
This method is not implemented by standard Python dict... |
Returns a Python dictionary with the same values as this object ( without checking the local cache ). | def _data(self, pipe=None):
"""
Returns a Python dictionary with the same values as this object
(without checking the local cache).
"""
pipe = self.redis if pipe is None else pipe
items = pipe.hgetall(self.key).items()
return {self._unpickle_key(k): self._unpickl... |
Return an iterator over the dictionary s ( key value ) pairs. | def iteritems(self, pipe=None):
"""Return an iterator over the dictionary's ``(key, value)`` pairs."""
pipe = self.redis if pipe is None else pipe
for k, v in self._data(pipe).items():
yield k, self.cache.get(k, v) |
If * key * is in the dictionary remove it and return its value else return * default *. If * default * is not given and * key * is not in the dictionary a: exc: KeyError is raised. | def pop(self, key, default=__marker):
"""If *key* is in the dictionary, remove it and return its value,
else return *default*. If *default* is not given and *key* is not
in the dictionary, a :exc:`KeyError` is raised.
"""
pickled_key = self._pickle_key(key)
if key in sel... |
Remove and return an arbitrary ( key value ) pair from the dictionary. | def popitem(self):
"""Remove and return an arbitrary ``(key, value)`` pair from
the dictionary.
:func:`popitem` is useful to destructively iterate over
a dictionary, as often used in set algorithms. If
the dictionary is empty, calling :func:`popitem` raises
a :exc:`KeyEr... |
If * key * is in the dictionary return its value. If not insert * key * with a value of * default * and return * default *. * default * defaults to: obj: None. | def setdefault(self, key, default=None):
"""If *key* is in the dictionary, return its value.
If not, insert *key* with a value of *default* and
return *default*. *default* defaults to :obj:`None`.
"""
if key in self.cache:
return self.cache[key]
def setdefaul... |
Update the dictionary with the key/ value pairs from * other * overwriting existing keys. Return: obj: None. | def update(self, other=None, **kwargs):
"""Update the dictionary with the key/value pairs from *other*,
overwriting existing keys. Return :obj:`None`.
:func:`update` accepts either another dictionary object or
an iterable of key/value pairs (as tuples or other iterables
of lengt... |
Return a new collection with the same items as this one. If * key * is specified create the new collection with the given Redis key. | def copy(self, key=None):
"""
Return a new collection with the same items as this one.
If *key* is specified, create the new collection with the given
Redis key.
"""
other = self.__class__(redis=self.redis, key=key)
other.update(self)
return other |
Create a new dictionary with keys from * seq * and values set to * value *. | def fromkeys(cls, seq, value=None, **kwargs):
"""Create a new dictionary with keys from *seq* and values set to
*value*.
.. note::
:func:`fromkeys` is a class method that returns a new dictionary.
It is possible to specify additional keyword arguments to be passed
... |
Yield each of the ( key value ) pairs from the collection without pulling them all into memory. | def scan_items(self):
"""
Yield each of the ``(key, value)`` pairs from the collection, without
pulling them all into memory.
.. warning::
This method is not available on the dictionary collections provided
by Python.
This method may return the same ... |
Elements are counted from an * iterable * or added - in from another * mapping * ( or counter ). Like: func: dict. update but adds counts instead of replacing them. Also the * iterable * is expected to be a sequence of elements not a sequence of ( key value ) pairs. | def update(self, other=None, **kwargs):
"""Elements are counted from an *iterable* or added-in from another
*mapping* (or counter). Like :func:`dict.update` but adds counts
instead of replacing them. Also, the *iterable* is expected to be
a sequence of elements, not a sequence of ``(key,... |
Elements are subtracted from an * iterable * or from another * mapping * ( or counter ). Like: func: dict. update but subtracts counts instead of replacing them. | def subtract(self, other=None, **kwargs):
"""Elements are subtracted from an *iterable* or from another
*mapping* (or counter). Like :func:`dict.update` but subtracts
counts instead of replacing them.
"""
if other is not None:
if self._same_redis(other, RedisCollectio... |
Processes the received message. I don t need to generate an ack message. | def ack(self, msg):
"""Processes the received message. I don't need to
generate an ack message.
"""
self.log.info("senderID:%s Received: %s " % (self.senderID, msg['body']))
return stomper.NO_REPONSE_NEEDED |
Helper for clear operations. | def _clear(self, pipe=None):
"""Helper for clear operations.
:param pipe: Redis pipe in case update is performed as a part
of transaction.
:type pipe: :class:`redis.client.StrictPipeline` or
:class:`redis.client.StrictRedis`
"""
redis = s... |
Convert negative indexes into their positive equivalents. | def _normalize_index(self, index, pipe=None):
"""Convert negative indexes into their positive equivalents."""
pipe = self.redis if pipe is None else pipe
len_self = self.__len__(pipe)
positive_index = index if index >= 0 else len_self + index
return len_self, positive_index |
Given a: obj: slice * index * return a 4 - tuple ( start stop step fowrward ). The first three items can be used with the range function to retrieve the values associated with the slice ; the last item indicates the direction. | def _normalize_slice(self, index, pipe=None):
"""Given a :obj:`slice` *index*, return a 4-tuple
``(start, stop, step, fowrward)``. The first three items can be used
with the ``range`` function to retrieve the values associated with the
slice; the last item indicates the direction.
... |
Helper simplifying code within watched transaction. | def _transaction(self, fn, *extra_keys):
"""Helper simplifying code within watched transaction.
Takes *fn*, function treated as a transaction. Returns whatever
*fn* returns. ``self.key`` is watched. *fn* takes *pipe* as the
only argument.
:param fn: Closure treated as a transac... |
Find paths recursively | def recursive_path(pack, path):
"""Find paths recursively"""
matches = []
for root, _, filenames in os.walk(os.path.join(pack, path)):
for filename in filenames:
matches.append(os.path.join(root, filename)[len(pack) + 1:])
return matches |
STOMP negative acknowledge command. | def nack(messageid, subscriptionid, transactionid=None):
"""STOMP negative acknowledge command.
NACK is the opposite of ACK. It is used to tell the server that the client
did not consume the message. The server can then either send the message to
a different client, discard it, or put it in a dead lett... |
STOMP connect command. | def connect(username, password, host, heartbeats=(0,0)):
"""STOMP connect command.
username, password:
These are the needed auth details to connect to the
message server.
After sending this we will receive a CONNECTED
message which will contain our session id.
"""
if len(heart... |
Called when a MESSAGE has been received. | def ack(self, msg):
"""Called when a MESSAGE has been received.
Override this method to handle received messages.
This function will generate an acknowledge message
for the given message and transaction (if present).
"""
message_id = msg['headers']['message-id']
... |
I pull one complete message off the buffer and return it decoded as a dict. If there is no complete message in the buffer I return None. | def getOneMessage ( self ):
"""
I pull one complete message off the buffer and return it decoded
as a dict. If there is no complete message in the buffer, I
return None.
Note that the buffer can contain more than once message. You
should therefore call me in a loop until... |
I examine the data passed to me and return a 2 - tuple of the form: ( message_length header_length ) where message_length is the length in bytes of the first complete message if it contains at least one message or 0 if it contains no message. If message_length is non - zero header_length contains the length in bytes of... | def _findMessageBytes ( self, data ):
"""
I examine the data passed to me and return a 2-tuple of the form:
( message_length, header_length )
where message_length is the length in bytes of the first complete
message, if it contains at least one message, or 0... |
I detect and correct corruption in the buffer. Corruption in the buffer is defined as the following conditions both being true: 1. The buffer contains at least one newline ; 2. The text until the first newline is not a STOMP command. In this case we heuristically try to flush bits of the buffer until one of the followi... | def syncBuffer( self ):
"""
I detect and correct corruption in the buffer.
Corruption in the buffer is defined as the following conditions
both being true:
1. The buffer contains at least one newline;
2. The text until the first newline is not a ... |
Once I ve connected I want to subscribe to my the message queue. | def connected(self, msg):
"""Once I've connected I want to subscribe to my the message queue.
"""
super(MyStomp, self).connected(msg)
self.log.info("connected: session %s" % msg['headers']['session'])
f = stomper.Frame()
f.unpack(stomper.subscribe(DESTINATION))
r... |
Defines a signal handler for syncing an individual entity. Called when an entity is saved or deleted. | def delete_entity_signal_handler(sender, instance, **kwargs):
"""
Defines a signal handler for syncing an individual entity. Called when
an entity is saved or deleted.
"""
if instance.__class__ in entity_registry.entity_registry:
Entity.all_objects.delete_for_obj(instance) |
Defines a signal handler for saving an entity. Syncs the entity to the entity mirror table. | def save_entity_signal_handler(sender, instance, **kwargs):
"""
Defines a signal handler for saving an entity. Syncs the entity to
the entity mirror table.
"""
if instance.__class__ in entity_registry.entity_registry:
sync_entities(instance)
if instance.__class__ in entity_registry.enti... |
Defines a signal handler for a manytomany changed signal. Only listens for the post actions so that entities are synced once ( rather than twice for a pre and post action ). | def m2m_changed_entity_signal_handler(sender, instance, action, **kwargs):
"""
Defines a signal handler for a manytomany changed signal. Only listens for the
post actions so that entities are synced once (rather than twice for a pre and post action).
"""
if action == 'post_add' or action == 'post_re... |
Disables all of the signals for syncing entities. By default everything is turned off. If the user wants to turn off everything but one signal for example the post_save signal they would do: | def turn_off_syncing(for_post_save=True, for_post_delete=True, for_m2m_changed=True, for_post_bulk_operation=True):
"""
Disables all of the signals for syncing entities. By default, everything is turned off. If the user wants
to turn off everything but one signal, for example the post_save signal, they woul... |
Enables all of the signals for syncing entities. Everything is True by default except for the post_bulk_operation signal. The reason for this is because when any bulk operation occurs on any mirrored entity model it will result in every single entity being synced again. This is not a desired behavior by the majority of... | def turn_on_syncing(for_post_save=True, for_post_delete=True, for_m2m_changed=True, for_post_bulk_operation=False):
"""
Enables all of the signals for syncing entities. Everything is True by default, except for the post_bulk_operation
signal. The reason for this is because when any bulk operation occurs on ... |
Add element * value * to the set. | def add(self, value):
"""Add element *value* to the set."""
# Raise TypeError if value is not hashable
hash(value)
self.redis.sadd(self.key, self._pickle(value)) |
Remove element * value * from the set if it is present. | def discard(self, value):
"""Remove element *value* from the set if it is present."""
# Raise TypeError if value is not hashable
hash(value)
self.redis.srem(self.key, self._pickle(value)) |
Return True if the set has no elements in common with * other *. Sets are disjoint if and only if their intersection is the empty set. | def isdisjoint(self, other):
"""
Return ``True`` if the set has no elements in common with *other*.
Sets are disjoint if and only if their intersection is the empty set.
:param other: Any kind of iterable.
:rtype: boolean
"""
def isdisjoint_trans_pure(pipe):
... |
Remove and return an arbitrary element from the set. Raises: exc: KeyError if the set is empty. | def pop(self):
"""
Remove and return an arbitrary element from the set.
Raises :exc:`KeyError` if the set is empty.
"""
result = self.redis.spop(self.key)
if result is None:
raise KeyError
return self._unpickle(result) |
Return a * k * length list of unique elements chosen from the Set. Elements are not removed. Similar to: func: random. sample function from standard library. | def random_sample(self, k=1):
"""
Return a *k* length list of unique elements chosen from the Set.
Elements are not removed. Similar to :func:`random.sample` function
from standard library.
:param k: Size of the sample, defaults to 1.
:rtype: :class:`list`
"""
... |
Remove element * value * from the set. Raises: exc: KeyError if it is not contained in the set. | def remove(self, value):
"""
Remove element *value* from the set. Raises :exc:`KeyError` if it
is not contained in the set.
"""
# Raise TypeError if value is not hashable
hash(value)
result = self.redis.srem(self.key, self._pickle(value))
if not result:
... |
Yield each of the elements from the collection without pulling them all into memory. | def scan_elements(self):
"""
Yield each of the elements from the collection, without pulling them
all into memory.
.. warning::
This method is not available on the set collections provided
by Python.
This method may return the element multiple times.... |
Update the set keeping only elements found in it and all * others *. | def intersection_update(self, *others):
"""
Update the set, keeping only elements found in it and all *others*.
:param others: Iterables, each one as a single positional argument.
:rtype: None
.. note::
The same behavior as at :func:`difference_update` applies.
... |
Update the set adding elements from all * others *. | def update(self, *others):
"""
Update the set, adding elements from all *others*.
:param others: Iterables, each one as a single positional argument.
:rtype: None
.. note::
If all *others* are :class:`Set` instances, the operation
is performed completely... |
Update the set removing elements found in * others *. | def difference_update(self, *others):
"""
Update the set, removing elements found in *others*.
:param others: Iterables, each one as a single positional argument.
:rtype: None
.. note::
The same behavior as at :func:`update` applies.
"""
return self.... |
Remove * member * from the collection unconditionally. | def discard_member(self, member, pipe=None):
"""
Remove *member* from the collection, unconditionally.
"""
pipe = self.redis if pipe is None else pipe
pipe.zrem(self.key, self._pickle(member)) |
Yield each of the ( member score ) tuples from the collection without pulling them all into memory. | def scan_items(self):
"""
Yield each of the ``(member, score)`` tuples from the collection,
without pulling them all into memory.
.. warning::
This method may return the same (member, score) tuple multiple
times.
See the `Redis SCAN documentation
... |
Update the collection with items from * other *. Accepts other: class: SortedSetBase instances dictionaries mapping members to numeric scores or sequences of ( member score ) tuples. | def update(self, other):
"""
Update the collection with items from *other*. Accepts other
:class:`SortedSetBase` instances, dictionaries mapping members to
numeric scores, or sequences of ``(member, score)`` tuples.
"""
def update_trans(pipe):
other_items = me... |
Returns the number of members whose score is between * min_score * and * max_score * ( inclusive ). | def count_between(self, min_score=None, max_score=None):
"""
Returns the number of members whose score is between *min_score* and
*max_score* (inclusive).
"""
min_score = float('-inf') if min_score is None else float(min_score)
max_score = float('inf') if max_score is Non... |
Remove members whose ranking is between * min_rank * and * max_rank * OR whose score is between * min_score * and * max_score * ( both ranges inclusive ). If no bounds are specified no members will be removed. | def discard_between(
self,
min_rank=None,
max_rank=None,
min_score=None,
max_score=None,
):
"""
Remove members whose ranking is between *min_rank* and *max_rank*
OR whose score is between *min_score* and *max_score* (both ranges
inclusive). If ... |
Return the score of * member * or * default * if it is not in the collection. | def get_score(self, member, default=None, pipe=None):
"""
Return the score of *member*, or *default* if it is not in the
collection.
"""
pipe = self.redis if pipe is None else pipe
score = pipe.zscore(self.key, self._pickle(member))
if (score is None) and (defaul... |
If * member * is in the collection return its value. If not store it with a score of * default * and return * default *. * default * defaults to 0. | def get_or_set_score(self, member, default=0):
"""
If *member* is in the collection, return its value. If not, store it
with a score of *default* and return *default*. *default* defaults to
0.
"""
default = float(default)
def get_or_set_score_trans(pipe):
... |
Return the rank of * member * in the collection. By default the member with the lowest score has rank 0. If * reverse * is True the member with the highest score has rank 0. | def get_rank(self, member, reverse=False, pipe=None):
"""
Return the rank of *member* in the collection.
By default, the member with the lowest score has rank 0.
If *reverse* is ``True``, the member with the highest score has rank 0.
"""
pipe = self.redis if pipe is None ... |
Adjust the score of * member * by * amount *. If * member * is not in the collection it will be stored with a score of * amount *. | def increment_score(self, member, amount=1):
"""
Adjust the score of *member* by *amount*. If *member* is not in the
collection it will be stored with a score of *amount*.
"""
return self.redis.zincrby(
self.key, float(amount), self._pickle(member)
) |
Return a list of ( member score ) tuples whose ranking is between * min_rank * and * max_rank * AND whose score is between * min_score * and * max_score * ( both ranges inclusive ). If no bounds are specified all items will be returned. | def items(
self,
min_rank=None,
max_rank=None,
min_score=None,
max_score=None,
reverse=False,
pipe=None,
):
"""
Return a list of ``(member, score)`` tuples whose ranking is between
*min_rank* and *max_rank* AND whose score is between *m... |
Set the score of * member * to * score *. | def set_score(self, member, score, pipe=None):
"""
Set the score of *member* to *score*.
"""
pipe = self.redis if pipe is None else pipe
pipe.zadd(self.key, {self._pickle(member): float(score)}) |
Return the great - circle distance between * place_1 * and * place_2 * in the * unit * specified. | def distance_between(self, place_1, place_2, unit='km'):
"""
Return the great-circle distance between *place_1* and *place_2*,
in the *unit* specified.
The default unit is ``'km'``, but ``'m'``, ``'mi'``, and ``'ft'`` can
also be specified.
"""
pickled_place_1 = ... |
Return the Geohash of * place *. If it s not present in the collection None will be returned instead. | def get_hash(self, place):
"""
Return the Geohash of *place*.
If it's not present in the collection, ``None`` will be returned
instead.
"""
pickled_place = self._pickle(place)
try:
return self.redis.geohash(self.key, pickled_place)[0]
except (A... |
Return a dict with the coordinates * place *. The dict s keys are latitude and longitude. If it s not present in the collection None will be returned instead. | def get_location(self, place):
"""
Return a dict with the coordinates *place*. The dict's keys are
``'latitude'`` and ``'longitude'``.
If it's not present in the collection, ``None`` will be returned
instead.
"""
pickled_place = self._pickle(place)
try:
... |
Return descriptions of the places stored in the collection that are within the circle specified by the given location and radius. A list of dicts will be returned. | def places_within_radius(
self, place=None, latitude=None, longitude=None, radius=0, **kwargs
):
"""
Return descriptions of the places stored in the collection that are
within the circle specified by the given location and radius.
A list of dicts will be returned.
Th... |
Set the location of * place * to the location specified by * latitude * and * longitude *. | def set_location(self, place, latitude, longitude, pipe=None):
"""
Set the location of *place* to the location specified by
*latitude* and *longitude*.
*place* can be any pickle-able Python object.
"""
pipe = self.redis if pipe is None else pipe
pipe.geoadd(self.... |
Update the collection with items from * other *. Accepts other: class: GeoDB instances dictionaries mapping places to { latitude: latitude longitude: longitude } dicts or sequences of ( place latitude longitude ) tuples. | def update(self, other):
"""
Update the collection with items from *other*. Accepts other
:class:`GeoDB` instances, dictionaries mapping places to
``{'latitude': latitude, 'longitude': longitude}`` dicts,
or sequences of ``(place, latitude, longitude)`` tuples.
"""
... |
Creates another collection with the same items and maxsize with the given * key *. | def copy(self, key=None):
"""
Creates another collection with the same items and maxsize with
the given *key*.
"""
other = self.__class__(
maxsize=self.maxsize, redis=self.persistence.redis, key=key
)
other.update(self)
return other |
Create a new collection with keys from * seq * and values set to * value *. The keyword arguments are passed to the persistent Dict. | def fromkeys(cls, seq, value=None, **kwargs):
"""
Create a new collection with keys from *seq* and values set to
*value*. The keyword arguments are passed to the persistent ``Dict``.
"""
other = cls(**kwargs)
other.update(((key, value) for key in seq))
return oth... |
Copy items from the local cache to the persistent Dict. If * clear_cache * is True clear out the local cache after pushing its items to Redis. | def sync(self, clear_cache=False):
"""
Copy items from the local cache to the persistent Dict.
If *clear_cache* is ``True``, clear out the local cache after
pushing its items to Redis.
"""
self.persistence.update(self)
if clear_cache:
self.cache.clear... |
Return a: obj: list of all values from Redis ( without checking the local cache ). | def _data(self, pipe=None):
"""
Return a :obj:`list` of all values from Redis
(without checking the local cache).
"""
pipe = self.redis if pipe is None else pipe
return [self._unpickle(v) for v in pipe.lrange(self.key, 0, -1)] |
Insert * value * at the end of this collection. | def append(self, value):
"""Insert *value* at the end of this collection."""
len_self = self.redis.rpush(self.key, self._pickle(value))
if self.writeback:
self.cache[len_self - 1] = value |
Return a new collection with the same items as this one. If * key * is specified create the new collection with the given Redis key. | def copy(self, key=None):
"""
Return a new collection with the same items as this one.
If *key* is specified, create the new collection with the given
Redis key.
"""
other = self.__class__(
redis=self.redis, key=key, writeback=self.writeback
)
... |
Adds the values from the iterable * other * to the end of this collection. | def extend(self, other):
"""
Adds the values from the iterable *other* to the end of this
collection.
"""
def extend_trans(pipe):
values = list(other.__iter__(pipe)) if use_redis else other
len_self = pipe.rpush(self.key, *(self._pickle(v) for v in values)... |
Return the index of the first occurence of * value *. If * start * or * stop * are provided return the smallest index such that s [ index ] == value and start < = index < stop. | def index(self, value, start=None, stop=None):
"""
Return the index of the first occurence of *value*.
If *start* or *stop* are provided, return the smallest
index such that ``s[index] == value`` and ``start <= index < stop``.
"""
def index_trans(pipe):
len_se... |
Insert * value * into the collection at * index *. | def insert(self, index, value):
"""
Insert *value* into the collection at *index*.
"""
if index == 0:
return self._insert_left(value)
def insert_middle_trans(pipe):
self._insert_middle(index, value, pipe=pipe)
return self._transaction(insert_midd... |
Retrieve the value at * index * remove it from the collection and return it. | def pop(self, index=-1):
"""
Retrieve the value at *index*, remove it from the collection, and
return it.
"""
if index == 0:
return self._pop_left()
elif index == -1:
return self._pop_right()
else:
return self._pop_middle(index) |
Remove the first occurence of * value *. | def remove(self, value):
"""Remove the first occurence of *value*."""
def remove_trans(pipe):
# If we're caching, we'll need to synchronize before removing.
if self.writeback:
self._sync_helper(pipe)
delete_count = pipe.lrem(self.key, 1, self._pickle(... |
Reverses the items of this collection in place ( only two values are retrieved from Redis at a time ). | def reverse(self):
"""
Reverses the items of this collection "in place" (only two values are
retrieved from Redis at a time).
"""
def reverse_trans(pipe):
if self.writeback:
self._sync_helper(pipe)
n = self.__len__(pipe)
for i ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.