_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q26700
EntryAdmin.get_sites
train
def get_sites(self, entry): """ Return the sites linked in HTML. """ try: index_url = reverse('zinnia:entry_archive_index') except NoReverseMatch: index_url = '' return format_html_join(
python
{ "resource": "" }
q26701
EntryAdmin.get_short_url
train
def get_short_url(self, entry): """ Return the short url in HTML. """ try: short_url = entry.short_url
python
{ "resource": "" }
q26702
EntryAdmin.get_queryset
train
def get_queryset(self, request): """ Make special filtering by user's permissions. """ if not request.user.has_perm('zinnia.can_view_all'): queryset = self.model.objects.filter(authors__pk=request.user.pk) else:
python
{ "resource": "" }
q26703
EntryAdmin.get_changeform_initial_data
train
def get_changeform_initial_data(self, request): """ Provide initial datas when creating an entry. """ get_data = super(EntryAdmin, self).get_changeform_initial_data(request) return get_data or {
python
{ "resource": "" }
q26704
EntryAdmin.formfield_for_manytomany
train
def formfield_for_manytomany(self, db_field, request, **kwargs): """ Filter the disposable authors. """ if db_field.name == 'authors': kwargs['queryset'] = Author.objects.filter( Q(is_staff=True) | Q(entries__isnull=False)
python
{ "resource": "" }
q26705
EntryAdmin.get_readonly_fields
train
def get_readonly_fields(self, request, obj=None): """ Return readonly fields by user's permissions. """ readonly_fields = list(super(EntryAdmin, self).get_readonly_fields( request, obj)) if not request.user.has_perm('zinnia.can_change_status'):
python
{ "resource": "" }
q26706
EntryAdmin.get_actions
train
def get_actions(self, request): """ Define actions by user's permissions. """ actions = super(EntryAdmin, self).get_actions(request) if not actions: return actions if (not request.user.has_perm('zinnia.can_change_author') or not request.user.ha...
python
{ "resource": "" }
q26707
EntryAdmin.make_mine
train
def make_mine(self, request, queryset): """ Set the entries to the current user. """ author = Author.objects.get(pk=request.user.pk) for entry in queryset: if author not in entry.authors.all():
python
{ "resource": "" }
q26708
EntryAdmin.make_published
train
def make_published(self, request, queryset): """ Set entries selected as published. """ queryset.update(status=PUBLISHED) EntryPublishedVectorBuilder().cache_flush() self.ping_directories(request,
python
{ "resource": "" }
q26709
EntryAdmin.make_hidden
train
def make_hidden(self, request, queryset): """ Set entries selected as hidden. """ queryset.update(status=HIDDEN)
python
{ "resource": "" }
q26710
EntryAdmin.close_comments
train
def close_comments(self, request, queryset): """ Close the comments for selected entries. """ queryset.update(comment_enabled=False)
python
{ "resource": "" }
q26711
EntryAdmin.close_pingbacks
train
def close_pingbacks(self, request, queryset): """ Close the pingbacks for selected entries. """ queryset.update(pingback_enabled=False)
python
{ "resource": "" }
q26712
EntryAdmin.close_trackbacks
train
def close_trackbacks(self, request, queryset): """ Close the trackbacks for selected entries. """ queryset.update(trackback_enabled=False)
python
{ "resource": "" }
q26713
EntryAdmin.put_on_top
train
def put_on_top(self, request, queryset): """ Put the selected entries on top at the current date. """ queryset.update(publication_date=timezone.now()) self.ping_directories(request,
python
{ "resource": "" }
q26714
EntryAdmin.mark_featured
train
def mark_featured(self, request, queryset): """ Mark selected as featured post. """ queryset.update(featured=True)
python
{ "resource": "" }
q26715
EntryAdmin.unmark_featured
train
def unmark_featured(self, request, queryset): """ Un-Mark selected featured posts. """ queryset.update(featured=False)
python
{ "resource": "" }
q26716
EntryAdmin.ping_directories
train
def ping_directories(self, request, queryset, messages=True): """ Ping web directories for selected entries. """ for directory in settings.PING_DIRECTORIES: pinger = DirectoryPinger(directory, queryset) pinger.join() if messages: succes...
python
{ "resource": "" }
q26717
MPTTModelChoiceIterator.choice
train
def choice(self, obj): """ Overloads the choice method to add the position of the object in the tree for future sorting. """ tree_id =
python
{ "resource": "" }
q26718
MPTTModelMultipleChoiceField.label_from_instance
train
def label_from_instance(self, obj): """ Create labels which represent the tree level of each node when generating option labels.
python
{ "resource": "" }
q26719
CapabilityView.get_context_data
train
def get_context_data(self, **kwargs): """ Populate the context of the template with technical informations for building urls. """ context = super(CapabilityView, self).get_context_data(**kwargs) context.update({'protocol': PROTOCOL, 'copyright':
python
{ "resource": "" }
q26720
get_user_flagger
train
def get_user_flagger(): """ Return an User instance used by the system when flagging a comment as trackback or pingback. """ user_klass = get_user_model() try: user = user_klass.objects.get(pk=COMMENT_FLAG_USER_ID) except user_klass.DoesNotExist: try: user = user_...
python
{ "resource": "" }
q26721
EntryQuerysetTemplateResponseMixin.get_model_type
train
def get_model_type(self): """ Return the model type for templates. """ if self.model_type is None: raise ImproperlyConfigured( "%s requires either a definition of "
python
{ "resource": "" }
q26722
EntryQuerysetTemplateResponseMixin.get_model_name
train
def get_model_name(self): """ Return the model name for templates. """ if self.model_name is None: raise ImproperlyConfigured( "%s requires either a definition of "
python
{ "resource": "" }
q26723
EntryQuerysetArchiveTodayTemplateResponseMixin.get_archive_part_value
train
def get_archive_part_value(self, part): """Return archive part for today""" parts_dict = {'year': '%Y', 'month': self.month_format, 'week': self.week_format,
python
{ "resource": "" }
q26724
EntryArchiveTemplateResponseMixin.get_default_base_template_names
train
def get_default_base_template_names(self): """ Return the Entry.template value. """ return [self.object.detail_template,
python
{ "resource": "" }
q26725
DiscussionsEntry.discussions
train
def discussions(self): """ Returns a queryset of the published discussions. """ return
python
{ "resource": "" }
q26726
DiscussionsEntry.comments
train
def comments(self): """ Returns a queryset of the published comments. """ return
python
{ "resource": "" }
q26727
DiscussionsEntry.discussion_is_still_open
train
def discussion_is_still_open(self, discussion_type, auto_close_after): """ Checks if a type of discussion is still open are a certain number of days. """ discussion_enabled = getattr(self, discussion_type) if (discussion_enabled and isinstance(auto_close_after, int) and ...
python
{ "resource": "" }
q26728
ExcerptEntry.save
train
def save(self, *args, **kwargs): """ Overrides the save method to create an excerpt from the content field if void. """
python
{ "resource": "" }
q26729
ImageEntry.image_upload_to
train
def image_upload_to(self, filename): """ Compute the upload path for the image field. """ now = timezone.now() filename, extension = os.path.splitext(filename) return os.path.join( UPLOAD_TO,
python
{ "resource": "" }
q26730
get_category_or_404
train
def get_category_or_404(path): """ Retrieve a Category instance by a path.
python
{ "resource": "" }
q26731
BaseCategoryDetail.get_queryset
train
def get_queryset(self): """ Retrieve the category by his path and build a queryset of her published entries. """
python
{ "resource": "" }
q26732
BaseCategoryDetail.get_context_data
train
def get_context_data(self, **kwargs): """ Add the current category in context. """
python
{ "resource": "" }
q26733
EntryFeed.item_author_name
train
def item_author_name(self, item): """ Return the first author of an entry. """ if item.authors.count():
python
{ "resource": "" }
q26734
EntryFeed.item_author_link
train
def item_author_link(self, item): """ Return the author's URL. Should not be called if self.item_author_name has returned None. """ try: author_url = self.item_author.get_absolute_url()
python
{ "resource": "" }
q26735
EntryFeed.item_enclosure_url
train
def item_enclosure_url(self, item): """ Return an image for enclosure. """ try: url = item.image.url except (AttributeError, ValueError): img = BeautifulSoup(item.html_content, 'html.parser').find('img') url = img.get('src') if img else None ...
python
{ "resource": "" }
q26736
TagEntries.items
train
def items(self, obj): """ Items are the published entries of the tag. """
python
{ "resource": "" }
q26737
SearchEntries.get_object
train
def get_object(self, request): """ The GET parameter 'pattern' is the object. """ pattern = request.GET.get('pattern', '')
python
{ "resource": "" }
q26738
LastDiscussions.items
train
def items(self): """ Items are the discussions on the entries. """ content_type = ContentType.objects.get_for_model(Entry) return comments.get_model().objects.filter(
python
{ "resource": "" }
q26739
EntryDiscussions.get_object
train
def get_object(self, request, year, month, day, slug): """ Retrieve the discussions by entry's slug. """ return get_object_or_404(Entry, slug=slug, publication_date__year=year,
python
{ "resource": "" }
q26740
textile
train
def textile(value): """ Textile processing. """ try: import textile except ImportError:
python
{ "resource": "" }
q26741
markdown
train
def markdown(value, extensions=MARKDOWN_EXTENSIONS): """ Markdown processing with optionally using various extensions that python-markdown supports. `extensions` is an iterable of either markdown.Extension instances or extension paths. """ try: import markdown except ImportError:...
python
{ "resource": "" }
q26742
restructuredtext
train
def restructuredtext(value, settings=RESTRUCTUREDTEXT_SETTINGS): """ RestructuredText processing with optionnally custom settings. """ try: from docutils.core import publish_parts except ImportError: warnings.warn("The Python docutils library isn't installed.",
python
{ "resource": "" }
q26743
html_format
train
def html_format(value): """ Returns the value formatted in HTML, depends on MARKUP_LANGUAGE setting. """ if not value: return '' elif MARKUP_LANGUAGE == 'markdown':
python
{ "resource": "" }
q26744
CategoryAdminForm.clean_parent
train
def clean_parent(self): """ Check if category parent is not selfish. """ data = self.cleaned_data['parent'] if data == self.instance: raise forms.ValidationError(
python
{ "resource": "" }
q26745
pearson_score
train
def pearson_score(list1, list2): """ Compute the Pearson' score between 2 lists of vectors. """ size = len(list1) sum1 = sum(list1) sum2 = sum(list2) sum_sq1 = sum([pow(l, 2) for l in list1]) sum_sq2 = sum([pow(l, 2) for l in list2]) prod_sum = sum([list1[i] * list2[i] for i in rang...
python
{ "resource": "" }
q26746
ModelVectorBuilder.get_related
train
def get_related(self, instance, number): """ Return a list of the most related objects to instance. """ related_pks = self.compute_related(instance.pk)[:number] related_pks = [pk for pk, score in related_pks] related_objects = sorted(
python
{ "resource": "" }
q26747
ModelVectorBuilder.compute_related
train
def compute_related(self, object_id, score=pearson_score): """ Compute the most related pks to an object's pk. """ dataset = self.dataset object_vector = dataset.get(object_id) if not object_vector: return [] object_related = {} for o_id, o_ve...
python
{ "resource": "" }
q26748
ModelVectorBuilder.raw_dataset
train
def raw_dataset(self): """ Generate a raw dataset based on the queryset and the specified fields. """ dataset = {} queryset = self.queryset.values_list(*(['pk'] + self.fields))
python
{ "resource": "" }
q26749
ModelVectorBuilder.raw_clean
train
def raw_clean(self, datas): """ Apply a cleaning on raw datas. """ datas = strip_tags(datas) # Remove HTML datas = STOP_WORDS.rebase(datas, '') # Remove STOP WORDS
python
{ "resource": "" }
q26750
ModelVectorBuilder.columns_dataset
train
def columns_dataset(self): """ Generate the columns and the whole dataset. """ data = {} words_total = {} for instance, words in self.raw_dataset.items(): words_item_total = {} for word in words: words_total.setdefault(word, 0) ...
python
{ "resource": "" }
q26751
CachedModelVectorBuilder.set_cache
train
def set_cache(self, value): """ Assign the cache in cache. """ value.update(self.cache)
python
{ "resource": "" }
q26752
CachedModelVectorBuilder.get_related
train
def get_related(self, instance, number): """ Implement high level cache system for get_related. """ cache = self.cache cache_key = '%s:%s' % (instance.pk, number)
python
{ "resource": "" }
q26753
CachedModelVectorBuilder.columns_dataset
train
def columns_dataset(self): """ Implement high level cache system for columns and dataset. """ cache = self.cache cache_key = 'columns_dataset' if cache_key not in cache: columns_dataset = super(CachedModelVectorBuilder, self
python
{ "resource": "" }
q26754
EntryPublishedVectorBuilder.cache_key
train
def cache_key(self): """ Key for the cache handling current site. """ return
python
{ "resource": "" }
q26755
EntryPreviewMixin.get_object
train
def get_object(self, queryset=None): """ If the status of the entry is not PUBLISHED, a preview is requested, so we check if the user has the 'zinnia.can_view_all' permission or if it's an author of the entry. """ obj = super(EntryPreviewMixin, self).get_object(qu...
python
{ "resource": "" }
q26756
EntryShortLink.get_redirect_url
train
def get_redirect_url(self, **kwargs): """ Get entry corresponding to 'pk' encoded in base36 in the 'token' variable and
python
{ "resource": "" }
q26757
advanced_search
train
def advanced_search(pattern): """ Parse the grammar of a pattern and build a queryset with it. """
python
{ "resource": "" }
q26758
CategoryAdmin.get_tree_path
train
def get_tree_path(self, category): """ Return the category's tree path in HTML. """ try: return format_html(
python
{ "resource": "" }
q26759
Command.write_out
train
def write_out(self, message, verbosity_level=1): """ Convenient method for outputing. """ if self.verbosity and
python
{ "resource": "" }
q26760
RelatedPublishedFilter.lookups
train
def lookups(self, request, model_admin): """ Return published objects with the number of entries. """ active_objects = self.model.published.all().annotate( count_entries_published=Count('entries')).order_by( '-count_entries_published', '-pk') for active_ob...
python
{ "resource": "" }
q26761
RelatedPublishedFilter.queryset
train
def queryset(self, request, queryset): """ Return the object's entries if a value is set.
python
{ "resource": "" }
q26762
year_crumb
train
def year_crumb(date): """ Crumb for a year. """ year = date.strftime('%Y')
python
{ "resource": "" }
q26763
month_crumb
train
def month_crumb(date): """ Crumb for a month. """ year = date.strftime('%Y') month = date.strftime('%m') month_text = DateFormat(date).format('F').capitalize()
python
{ "resource": "" }
q26764
day_crumb
train
def day_crumb(date): """ Crumb for a day. """ year = date.strftime('%Y') month = date.strftime('%m') day = date.strftime('%d')
python
{ "resource": "" }
q26765
entry_breadcrumbs
train
def entry_breadcrumbs(entry): """ Breadcrumbs for an Entry. """ date = entry.publication_date if is_aware(date): date = localtime(date)
python
{ "resource": "" }
q26766
handle_page_crumb
train
def handle_page_crumb(func): """ Decorator for handling the current page in the breadcrumbs. """ @wraps(func) def wrapper(path, model, page, root_name): path = PAGE_REGEXP.sub('', path) breadcrumbs = func(path, model, root_name) if page:
python
{ "resource": "" }
q26767
retrieve_breadcrumbs
train
def retrieve_breadcrumbs(path, model_instance, root_name=''): """ Build a semi-hardcoded breadcrumbs based of the model's url handled by Zinnia. """ breadcrumbs = [] zinnia_root_path = reverse('zinnia:entry_archive_index') if root_name: breadcrumbs.append(Crumb(root_name, zinnia_roo...
python
{ "resource": "" }
q26768
authenticate
train
def authenticate(username, password, permission=None): """ Authenticate staff_user with permission. """ try: author = Author.objects.get( **{'%s__exact' % Author.USERNAME_FIELD: username}) except Author.DoesNotExist: raise Fault(LOGIN_ERROR, _('Username is incorrect.')) ...
python
{ "resource": "" }
q26769
blog_structure
train
def blog_structure(site): """ A blog structure. """ return {'blogid': settings.SITE_ID, 'blogName': site.name, 'url': '%s://%s%s' % (
python
{ "resource": "" }
q26770
user_structure
train
def user_structure(user, site): """ An user structure. """ full_name = user.get_full_name().split() first_name = full_name[0] try: last_name = full_name[1] except IndexError: last_name = '' return {'userid': user.pk, 'email': user.email,
python
{ "resource": "" }
q26771
author_structure
train
def author_structure(user): """ An author structure. """ return {'user_id': user.pk, 'user_login': user.get_username(),
python
{ "resource": "" }
q26772
category_structure
train
def category_structure(category, site): """ A category structure. """ return {'description': category.title, 'htmlUrl': '%s://%s%s' % ( PROTOCOL, site.domain, category.get_absolute_url()), 'rssUrl': '%s://%s%s' % (
python
{ "resource": "" }
q26773
tag_structure
train
def tag_structure(tag, site): """ A tag structure. """ return {'tag_id': tag.pk, 'name': tag.name, 'count': tag.count, 'slug': tag.name, 'html_url': '%s://%s%s' % ( PROTOCOL, site.domain,
python
{ "resource": "" }
q26774
post_structure
train
def post_structure(entry, site): """ A post structure with extensions. """ author = entry.authors.all()[0] return {'title': entry.title, 'description': six.text_type(entry.html_content), 'link': '%s://%s%s' % (PROTOCOL, site.domain, entry.ge...
python
{ "resource": "" }
q26775
EntryRandom.get_redirect_url
train
def get_redirect_url(self, **kwargs): """ Get entry corresponding to 'pk' and return the get_absolute_url of the entry. """
python
{ "resource": "" }
q26776
MPTTFilteredSelectMultiple.media
train
def media(self): """ MPTTFilteredSelectMultiple's Media. """ js = ['admin/js/core.js', 'zinnia/admin/mptt/js/mptt_m2m_selectbox.js',
python
{ "resource": "" }
q26777
TagAutoComplete.render
train
def render(self, name, value, attrs=None, renderer=None): """ Render the default widget and initialize select2. """ output = [super(TagAutoComplete, self).render(name, value, attrs)] output.append('<script type="text/javascript">') output.append('(function($) {') ...
python
{ "resource": "" }
q26778
TagAutoComplete.media
train
def media(self): """ TagAutoComplete's Media. """ def static(path): return staticfiles_storage.url( 'zinnia/admin/select2/%s' % path) return Media(
python
{ "resource": "" }
q26779
PrefetchRelatedMixin.get_queryset
train
def get_queryset(self): """ Check if relation_names is correctly set and do a prefetch related on the queryset with it. """ if self.relation_names is None: raise ImproperlyConfigured( "'%s' must define 'relation_names'" %
python
{ "resource": "" }
q26780
get_context_first_matching_object
train
def get_context_first_matching_object(context, context_lookups): """ Return the first object found in the context, from a list of keys, with the matching key. """ for key in
python
{ "resource": "" }
q26781
get_context_loop_positions
train
def get_context_loop_positions(context): """ Return the paginated current position within a loop, and the non-paginated position. """ try: loop_counter = context['forloop']['counter'] except KeyError: return 0, 0 try: page = context['page_obj']
python
{ "resource": "" }
q26782
CallableQuerysetMixin.get_queryset
train
def get_queryset(self): """ Check that the queryset is defined and call it. """ if self.queryset is
python
{ "resource": "" }
q26783
base36
train
def base36(value): """ Encode int to base 36. """ result = '' while value: value, i = divmod(value,
python
{ "resource": "" }
q26784
backend
train
def backend(entry): """ Default URL shortener backend for Zinnia. """ return '%s://%s%s' % (
python
{ "resource": "" }
q26785
BaseEntryChannel.get_context_data
train
def get_context_data(self, **kwargs): """ Add query in context. """
python
{ "resource": "" }
q26786
tags_published
train
def tags_published(): """ Return the published tags. """ from tagging.models import Tag from zinnia.models.entry import Entry tags_entry_published = Tag.objects.usage_for_queryset( Entry.published.all()) # Need to
python
{ "resource": "" }
q26787
entries_published
train
def entries_published(queryset): """ Return only the entries published. """ now = timezone.now() return queryset.filter( models.Q(start_publication__lte=now) | models.Q(start_publication=None),
python
{ "resource": "" }
q26788
EntryPublishedManager.on_site
train
def on_site(self): """ Return entries published on current site.
python
{ "resource": "" }
q26789
EntryPublishedManager.search
train
def search(self, pattern): """ Top level search method on entries. """ try:
python
{ "resource": "" }
q26790
EntryPublishedManager.basic_search
train
def basic_search(self, pattern): """ Basic search on entries. """ lookup = None for pattern in pattern.split(): query_part = models.Q() for field in SEARCH_FIELDS: query_part |= models.Q(**{'%s__icontains' % field: pattern})
python
{ "resource": "" }
q26791
EntryRelatedPublishedManager.get_queryset
train
def get_queryset(self): """ Return a queryset containing published entries. """ now = timezone.now() return super( EntryRelatedPublishedManager, self).get_queryset().filter( models.Q(entries__start_publication__lte=now) | models.Q(entries__star...
python
{ "resource": "" }
q26792
EntryRelatedSitemap.items
train
def items(self): """ Get a queryset, cache infos for standardized access to them later then compute the maximum of entries to define the priority of each items. """ queryset =
python
{ "resource": "" }
q26793
EntryRelatedSitemap.get_queryset
train
def get_queryset(self): """ Build a queryset of items with published entries and annotated with the number of entries and the latest modification date.
python
{ "resource": "" }
q26794
EntryRelatedSitemap.cache_infos
train
def cache_infos(self, queryset): """ Cache infos like the number of entries published and the last modification date for standardized access later. """ self.cache = {} for item in queryset:
python
{ "resource": "" }
q26795
EntryRelatedSitemap.set_max_entries
train
def set_max_entries(self): """ Define the maximum of entries for computing the priority of each items later. """ if self.cache:
python
{ "resource": "" }
q26796
EntryRelatedSitemap.priority
train
def priority(self, item): """ The priority of the item depends of the number of entries published in the cache divided by the maximum of entries.
python
{ "resource": "" }
q26797
TagSitemap.get_queryset
train
def get_queryset(self): """ Return the published Tags with option counts. """ self.entries_qs = Entry.published.all()
python
{ "resource": "" }
q26798
TagSitemap.cache_infos
train
def cache_infos(self, queryset): """ Cache the number of entries published and the last modification date under each tag. """ self.cache = {} for item in queryset: # If the sitemap is too slow, don't hesitate to do this :
python
{ "resource": "" }
q26799
DirectoryPinger.run
train
def run(self): """ Ping entries to a directory in a thread. """ logger = getLogger('zinnia.ping.directory') socket.setdefaulttimeout(self.timeout) for entry in self.entries: reply = self.ping_entry(entry)
python
{ "resource": "" }