text
stringlengths
81
112k
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 =...
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 *...
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. ...
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 *a...
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...
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. The default unit is ``'km'``, but ``'m'``, ``'mi'``, and ``'ft'`` can also be specified. def distance_between(self, place_1, place_2, unit='km'): """ Return the great-circle distance betw...
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_pl...
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 ...
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. The center of the circle can be specified by the identifier of another place in the collection with the *place* keyword arg...
Set the location of *place* to the location specified by *latitude* and *longitude*. *place* can be any pickle-able Python object. def set_location(self, place, latitude, longitude, pipe=None): """ Set the location of *place* to the location specified by *latitude* and *longitu...
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 collec...
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.persis...
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...
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 ou...
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._unpic...
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 gi...
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 ot...
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*. ...
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=pip...
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: ...
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_coun...
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): i...
Sort the items of this collection according to the optional callable *key*. If *reverse* is set then the sort order is reversed. .. note:: This sort requires all items to be retrieved from Redis and stored in memory. def sort(self, key=None, reverse=False): """ ...
Add *value* to the right side of the collection. def append(self, value): """Add *value* to the right side of the collection.""" def append_trans(pipe): self._append_helper(value, pipe) self._transaction(append_trans)
Add *value* to the left side of the collection. def appendleft(self, value): """Add *value* to the left side of the collection.""" def appendleft_trans(pipe): self._appendleft_helper(value, pipe) self._transaction(appendleft_trans)
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 gi...
Extend the right side of the the collection by appending values from the iterable *other*. def extend(self, other): """ Extend the right side of the the collection by appending values from the iterable *other*. """ def extend_trans(pipe): values = list(other....
Extend the left side of the the collection by appending values from the iterable *other*. Note that the appends will reverse the order of the given values. def extendleft(self, other): """ Extend the left side of the the collection by appending values from the iterable *other*. ...
Insert *value* into the collection at *index*. If the insertion would the collection to grow beyond ``maxlen``, raise ``IndexError``. def insert(self, index, value): """ Insert *value* into the collection at *index*. If the insertion would the collection to grow beyond ``maxlen`...
Rotate the deque n steps to the right. If n is negative, rotate to the left. def rotate(self, n=1): """ Rotate the deque n steps to the right. If n is negative, rotate to the left. """ # No work to do for a 0-step rotate if n == 0: return def...
Builds a dict with keys of entity kinds if and values are another dict. Each of these dicts are keyed off of a super entity id and optional have an 'all' key for any group that has a null super entity. Example structure: { entity_kind_id: { entity1_id: [1, 2, 3], entity2_id: ...
Given a list of super entities, return the entities that have those as a subset of their super entities. def is_sub_to_all(self, *super_entities): """ Given a list of super entities, return the entities that have those as a subset of their super entities. """ if super_entities: ...
Given a list of super entities, return the entities that have super entities that interset with those provided. def is_sub_to_any(self, *super_entities): """ Given a list of super entities, return the entities that have super entities that interset with those provided. """ if super_enti...
Each returned entity will have superentites whos combined entity_kinds included *super_entity_kinds def is_sub_to_all_kinds(self, *super_entity_kinds): """ Each returned entity will have superentites whos combined entity_kinds included *super_entity_kinds """ if super_entity_kinds: ...
Find all entities that have super_entities of any of the specified kinds def is_sub_to_any_kind(self, *super_entity_kinds): """ Find all entities that have super_entities of any of the specified kinds """ if super_entity_kinds: # get the pks of the desired subs from the rela...
Caches the super and sub relationships by doing a prefetch_related. def cache_relationships(self, cache_super=True, cache_sub=True): """ Caches the super and sub relationships by doing a prefetch_related. """ relationships_to_cache = compress( ['super_relationships__super_en...
Given a saved entity model object, return the associated entity. def get_for_obj(self, entity_model_obj): """ Given a saved entity model object, return the associated entity. """ return self.get(entity_type=ContentType.objects.get_for_model( entity_model_obj, for_concrete_mo...
Delete the entities associated with a model object. def delete_for_obj(self, entity_model_obj): """ Delete the entities associated with a model object. """ return self.filter( entity_type=ContentType.objects.get_for_model( entity_model_obj, for_concrete_model...
Caches the super and sub relationships by doing a prefetch_related. def cache_relationships(self, cache_super=True, cache_sub=True): """ Caches the super and sub relationships by doing a prefetch_related. """ return self.get_queryset().cache_relationships(cache_super=cache_super, cache_...
Build a dict cache with the group membership info. Keyed off the group id and the values are a 2 element list of entity id and entity kind id (same values as the membership model). If no group ids are passed, then all groups will be fetched :param is_active: Flag indicating whether to filter on...
Return all the entities in the group. Because groups can contain both individual entities, as well as whole groups of entities, this method acts as a convenient way to get a queryset of all the entities in the group. def all_entities(self, is_active=True): """ Return all the en...
Returns a list of all entity ids in this group or optionally returns a queryset for all entity models. In order to reduce queries for multiple group lookups, it is expected that the membership_cache and entities_by_kind are built outside of this method and passed in as arguments. :param membersh...
Add an entity, or sub-entity group to this EntityGroup. :type entity: Entity :param entity: The entity to add. :type sub_entity_kind: Optional EntityKind :param sub_entity_kind: If a sub_entity_kind is given, all sub_entities of the entity will be added to this ...
Add many entities and sub-entity groups to this EntityGroup. :type entities_and_kinds: List of (Entity, EntityKind) pairs. :param entities_and_kinds: A list of entity, entity-kind pairs to add to the group. In the pairs the entity-kind can be ``None``, to add a single entity, or...
Remove an entity, or sub-entity group to this EntityGroup. :type entity: Entity :param entity: The entity to remove. :type sub_entity_kind: Optional EntityKind :param sub_entity_kind: If a sub_entity_kind is given, all sub_entities of the entity will be removed from this ...
Remove many entities and sub-entity groups to this EntityGroup. :type entities_and_kinds: List of (Entity, EntityKind) pairs. :param entities_and_kinds: A list of entity, entity-kind pairs to remove from the group. In the pairs, the entity-kind can be ``None``, to add a single e...
Update the group to the given entities and sub-entity groups. After this operation, the only members of this EntityGroup will be the given entities, and sub-entity groups. :type entities_and_kinds: List of (Entity, EntityKind) pairs. :param entities_and_kinds: A list of entity, entity-...
A copy of spectator.core.models.SluggedModelMixin._generate_slug() def generate_slug(value): "A copy of spectator.core.models.SluggedModelMixin._generate_slug()" alphabet = 'abcdefghijkmnopqrstuvwxyz23456789' salt = 'Django Spectator' if hasattr(settings, 'SPECTATOR_SLUG_ALPHABET'): alphabet =...
Create a slug for each Work already in the DB. def set_slug(apps, schema_editor, class_name): """ Create a slug for each Work already in the DB. """ Cls = apps.get_model('spectator_events', class_name) for obj in Cls.objects.all(): obj.slug = generate_slug(obj.pk) obj.save(update_f...
e.g. 'Gig' or 'Movie'. def kind_name(self): "e.g. 'Gig' or 'Movie'." return {k:v for (k,v) in self.KIND_CHOICES}[self.kind]
e.g. 'Gigs' or 'Movies'. def get_kind_name_plural(kind): "e.g. 'Gigs' or 'Movies'." if kind in ['comedy', 'cinema', 'dance', 'theatre']: return kind.title() elif kind == 'museum': return 'Galleries/Museums' else: return '{}s'.format(Event.get_kind_nam...
Returns a dict of all the data about the kinds, keyed to the kind value. e.g: { 'gig': { 'name': 'Gig', 'slug': 'gigs', 'name_plural': 'Gigs', }, # etc } def get_kinds_data(): ...
Get the list URL for this Work. You can also pass a kind_slug in (e.g. 'movies') and it will use that instead of the Work's kind_slug. (Why? Useful in views. Or tests of views, at least.) def get_list_url(self, kind_slug=None): """ Get the list URL for this Work. You can...
Convert descriptor and rows to Pandas def convert_descriptor_and_rows(self, descriptor, rows): """Convert descriptor and rows to Pandas """ # Prepare primary_key = None schema = tableschema.Schema(descriptor) if len(schema.primary_key) == 1: primary_key = sc...
Convert type to Pandas def convert_type(self, type): """Convert type to Pandas """ # Mapping mapping = { 'any': np.dtype('O'), 'array': np.dtype(list), 'boolean': np.dtype(bool), 'date': np.dtype('O'), 'datetime': np.dtype('da...
Restore descriptor from Pandas def restore_descriptor(self, dataframe): """Restore descriptor from Pandas """ # Prepare fields = [] primary_key = None # Primary key if dataframe.index.name: field_type = self.restore_type(dataframe.index.dtype) ...
Restore row from Pandas def restore_row(self, row, schema, pk): """Restore row from Pandas """ result = [] for field in schema.fields: if schema.primary_key and schema.primary_key[0] == field.name: if field.type == 'number' and np.isnan(pk): ...
Restore type from Pandas def restore_type(self, dtype, sample=None): """Restore type from Pandas """ # Pandas types if pdc.is_bool_dtype(dtype): return 'boolean' elif pdc.is_datetime64_any_dtype(dtype): return 'datetime' elif pdc.is_integer_dtype...
If the user has permission to change `obj`, show a link to its Admin page. obj -- An object like Movie, Play, ClassicalWork, Publication, etc. perms -- The `perms` object that it's the template. def change_object_link_card(obj, perms): """ If the user has permission to change `obj`, show a link to its ...
Returns an HTML link to the supplied URL, but only using the domain as the text. Strips 'www.' from the start of the domain, if present. e.g. if `my_url` is 'http://www.example.org/foo/' then: {{ my_url|domain_urlize }} returns: <a href="http://www.example.org/foo/" rel="nofollow">example...
Returns the name of the current URL, namespaced, or False. Example usage: {% current_url_name as url_name %} <a href="#"{% if url_name == 'myapp:home' %} class="active"{% endif %}">Home</a> def current_url_name(context): """ Returns the name of the current URL, namespaced, or False. ...
For adding/replacing a key=value pair to the GET string for a URL. eg, if we're viewing ?p=3 and we do {% query_string order 'taken' %} then this returns "p=3&order=taken" And, if we're viewing ?p=3&order=uploaded and we do the same thing, we get the same result (ie, the existing "order=uploaded" is r...
Displays a card showing the Creators who have the most Readings associated with their Publications. In spectator_core tags, rather than spectator_reading so it can still be used on core pages, even if spectator_reading isn't installed. def most_read_creators_card(num=10): """ Displays a card showi...
Displays a card showing the Venues that have the most Events. In spectator_core tags, rather than spectator_events so it can still be used on core pages, even if spectator_events isn't installed. def most_visited_venues_card(num=10): """ Displays a card showing the Venues that have the most Events. ...
Handy for templates. def has_urls(self): "Handy for templates." if self.isbn_uk or self.isbn_us or self.official_url or self.notes_url: return True else: return False
eg, get_entity('spectator', 'version') returns `__version__` value in `__init__.py`. def get_entity(package, entity): """ eg, get_entity('spectator', 'version') returns `__version__` value in `__init__.py`. """ init_py = open(os.path.join(package, '__init__.py')).read() find = "__%s__ = ['\...
Reduce the number of queries and speed things up. def get_queryset(self): "Reduce the number of queries and speed things up." qs = super().get_queryset() qs = qs.select_related('publication__series') \ .prefetch_related('publication__roles__creator') return qs
Create a slug for each Creator already in the DB. def set_slug(apps, schema_editor): """ Create a slug for each Creator already in the DB. """ Creator = apps.get_model('spectator_core', 'Creator') for c in Creator.objects.all(): c.slug = generate_slug(c.pk) c.save(update_fields=['s...
Copy the ClassicalWork and DancePiece data to use the new through models. def forwards(apps, schema_editor): """ Copy the ClassicalWork and DancePiece data to use the new through models. """ Event = apps.get_model('spectator_events', 'Event') ClassicalWorkSelection = apps.get_model( ...
Set the venue_name field of all Events that have a Venue. def forwards(apps, schema_editor): """ Set the venue_name field of all Events that have a Venue. """ Event = apps.get_model('spectator_events', 'Event') for event in Event.objects.all(): if event.venue is not None: event...
Migrate all 'exhibition' Events to the new 'museum' Event kind. def forwards(apps, schema_editor): """ Migrate all 'exhibition' Events to the new 'museum' Event kind. """ Event = apps.get_model('spectator_events', 'Event') for ev in Event.objects.filter(kind='exhibition'): ev.kind = 'museu...
Truncate a string to a certain length, removing line breaks and mutliple spaces, optionally removing HTML, and appending a 'truncate' string. Keyword arguments: strip_html -- boolean. chars -- Number of characters to return. at_word_boundary -- Only truncate at a word boundary, which will probably ...
Given a QuerySet it will go through and add a `chart_position` property to each object returning a list of the objects. If adjacent objects have the same 'score' (based on `score_field`) then they will have the same `chart_position`. This can then be used in templates for the `value` of <li> elements i...
Gets Venues in order of how many Events have been held there. Adds a `num_visits` field to each one. event_kind filters by kind of Event, e.g. 'theatre', 'cinema', etc. def by_visits(self, event_kind=None): """ Gets Venues in order of how many Events have been held there. Adds ...
Gets Works in order of how many times they've been attached to Events. kind is the kind of Work, e.g. 'play', 'movie', etc. def by_views(self, kind=None): """ Gets Works in order of how many times they've been attached to Events. kind is the kind of Work, e.g. 'play', ...
Make a naturalized version of a general string, not a person's name. e.g., title of a book, a band's name, etc. string -- a lowercase string. def naturalize_thing(self, string): """ Make a naturalized version of a general string, not a person's name. e.g., title of a book, a ba...
Attempt to make a version of the string that has the surname, if any, at the start. 'John, Brown' to 'Brown, John' 'Sir John Brown Jr' to 'Brown, Sir John Jr' 'Prince' to 'Prince' string -- The string to change. def naturalize_person(self, string): """ Attempt ...
Makes any integers into very zero-padded numbers. e.g. '1' becomes '00000001'. def _naturalize_numbers(self, string): """ Makes any integers into very zero-padded numbers. e.g. '1' becomes '00000001'. """ def naturalize_int_match(match): return '%08d' % (int...
Returns a list of dicts, one per year of reading. In year order. Each dict is like this (if kind is 'all'): {'year': datetime.date(2003, 1, 1), 'book': 12, # only included if kind is 'all' or 'book' 'periodical': 18, # only included if kind is 'all' or 'periodical' ...
Returns a list of tuples like: [ ('AU', 'Australia'), ('GB', 'UK'), ('US', 'USA'), ] One for each country that has at least one Venue. Sorted by the label names. def lookups(self, request, model_admin): """ Return...
Returns the filtered queryset based on the value provided in the query string and retrievable via `self.value()`. def queryset(self, request, queryset): """ Returns the filtered queryset based on the value provided in the query string and retrievable via `self.value()`. ...
Copying data from the old `Event.movie` and `Event.play` ForeignKey fields into the new `Event.movies` and `Event.plays` ManyToManyFields. def forward(apps, schema_editor): """ Copying data from the old `Event.movie` and `Event.play` ForeignKey fields into the new `Event.movies` and `Event.plays` ManyT...
Create a slug for each Event already in the DB. def set_slug(apps, schema_editor): """ Create a slug for each Event already in the DB. """ Event = apps.get_model('spectator_events', 'Event') for e in Event.objects.all(): e.slug = generate_slug(e.pk) e.save(update_fields=['slug'])
Return a standard ``Page`` instance with custom, digg-specific page ranges attached. def page(self, number, *args, **kwargs): """Return a standard ``Page`` instance with custom, digg-specific page ranges attached. """ page = super().page(number, *args, **kwargs) number ...
Get the version number without importing the mrcfile package. def version(): """Get the version number without importing the mrcfile package.""" namespace = {} with open(os.path.join('mrcfile', 'version.py')) as f: exec(f.read(), namespace) return namespace['__version__']
Returns a dict like: {'counts': { 'all': 30, 'movie': 12, 'gig': 10, }} def get_event_counts(self): """ Returns a dict like: {'counts': { 'all': 30, 'movie': 12, 'gig': 10...
Unless we're on the front page we'll have a kind_slug like 'movies'. We need to translate that into an event `kind` like 'movie'. def get_event_kind(self): """ Unless we're on the front page we'll have a kind_slug like 'movies'. We need to translate that into an event `kind` like 'movie...
Restrict to a single kind of event, if any, and include Venue data. def get_queryset(self): "Restrict to a single kind of event, if any, and include Venue data." qs = super().get_queryset() kind = self.get_event_kind() if kind is not None: qs = qs.filter(kind=kind) ...
We'll have a kind_slug like 'movies'. We need to translate that into a work `kind` like 'movie'. def get_work_kind(self): """ We'll have a kind_slug like 'movies'. We need to translate that into a work `kind` like 'movie'. """ slugs_to_kinds = {v:k for k,v in Work.KIND_S...
Returns a list of dicts, one per country that has at least one Venue in it. Each dict has 'code' and 'name' elements. The list is sorted by the country 'name's. def get_countries(self): """ Returns a list of dicts, one per country that has at least one Venue in it. ...
Re-save all the Works because something earlier didn't create their slugs. def forwards(apps, schema_editor): """ Re-save all the Works because something earlier didn't create their slugs. """ Work = apps.get_model('spectator_events', 'Work') for work in Work.objects.all(): if not work.slu...
Returns a QuerySet of dicts, each one with these keys: * year - a date object representing the year * total - the number of events of `kind` that year kind - The Event `kind`, or 'all' for all kinds (default). def annual_event_counts(kind='all'): """ Returns a QuerySet of dicts, each one ...
Displays years and the number of events per year. kind is an Event kind (like 'cinema', 'gig', etc.) or 'all' (default). current_year is an optional date object representing the year we're already showing information about. def annual_event_counts_card(kind='all', current_year=None): """ Displ...
Render a date/datetime (d) as a date, using the SPECTATOR_DATE_FORMAT setting. Wrap the output in a <time> tag. Time tags: http://www.brucelawson.co.uk/2012/best-of-time/ def display_date(d): """ Render a date/datetime (d) as a date, using the SPECTATOR_DATE_FORMAT setting. Wrap the output in a <t...
Displays the tabs to different event_list pages. `counts` is a dict of number of events for each kind, like: {'all': 30, 'gig': 12, 'movie': 18,} `current_kind` is the event kind that's active, if any. e.g. 'gig', 'movie', etc. `page_number` is the current page of this kind of events we'r...
Displays Events that happened on the supplied date. `date` is a date object. def day_events_card(date): """ Displays Events that happened on the supplied date. `date` is a date object. """ d = date.strftime(app_settings.DATE_FORMAT) card_title = 'Events on {}'.format(d) return { ...
Displays a card showing the Creators that are associated with the most Events. def most_seen_creators_card(event_kind=None, num=10): """ Displays a card showing the Creators that are associated with the most Events. """ object_list = most_seen_creators(event_kind=event_kind, num=num) object_list =...
Returns a QuerySet of the Creators that are associated with the most Works. def most_seen_creators_by_works(work_kind=None, role_name=None, num=10): """ Returns a QuerySet of the Creators that are associated with the most Works. """ return Creator.objects.by_works(kind=work_kind, role_name=role_name)[:...