repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
ic-labs/django-icekit | icekit/publishing/models.py | PublishingModel.get_draft | def get_draft(self):
"""
Return self if this object is a draft, otherwise return the draft
copy of a published item.
"""
if self.is_draft:
return self
elif self.is_published:
draft = self.publishing_draft
# Previously the reverse relati... | python | def get_draft(self):
"""
Return self if this object is a draft, otherwise return the draft
copy of a published item.
"""
if self.is_draft:
return self
elif self.is_published:
draft = self.publishing_draft
# Previously the reverse relati... | [
"def",
"get_draft",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_draft",
":",
"return",
"self",
"elif",
"self",
".",
"is_published",
":",
"draft",
"=",
"self",
".",
"publishing_draft",
"if",
"hasattr",
"(",
"draft",
",",
"'get_draft_payload'",
")",
":",
... | Return self if this object is a draft, otherwise return the draft
copy of a published item. | [
"Return",
"self",
"if",
"this",
"object",
"is",
"a",
"draft",
"otherwise",
"return",
"the",
"draft",
"copy",
"of",
"a",
"published",
"item",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/publishing/models.py#L143-L160 | train |
ic-labs/django-icekit | icekit/publishing/models.py | PublishingModel.get_published | def get_published(self):
"""
Return self is this object is published, otherwise return the
published copy of a draft item. If this object is a draft with
no published copy it will return ``None``.
"""
if self.is_published:
return self
elif self.is_draf... | python | def get_published(self):
"""
Return self is this object is published, otherwise return the
published copy of a draft item. If this object is a draft with
no published copy it will return ``None``.
"""
if self.is_published:
return self
elif self.is_draf... | [
"def",
"get_published",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_published",
":",
"return",
"self",
"elif",
"self",
".",
"is_draft",
":",
"return",
"self",
".",
"publishing_linked",
"raise",
"ValueError",
"(",
"\"Publishable object %r is neither draft nor publi... | Return self is this object is published, otherwise return the
published copy of a draft item. If this object is a draft with
no published copy it will return ``None``. | [
"Return",
"self",
"is",
"this",
"object",
"is",
"published",
"otherwise",
"return",
"the",
"published",
"copy",
"of",
"a",
"draft",
"item",
".",
"If",
"this",
"object",
"is",
"a",
"draft",
"with",
"no",
"published",
"copy",
"it",
"will",
"return",
"None",
... | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/publishing/models.py#L162-L173 | train |
ic-labs/django-icekit | icekit/publishing/models.py | PublishingModel.get_published_or_draft | def get_published_or_draft(self):
"""
Return the published item, if it exists, otherwise, for privileged
users, return the draft version.
"""
if self.is_published:
return self
elif self.publishing_linked_id:
return self.publishing_linked
if... | python | def get_published_or_draft(self):
"""
Return the published item, if it exists, otherwise, for privileged
users, return the draft version.
"""
if self.is_published:
return self
elif self.publishing_linked_id:
return self.publishing_linked
if... | [
"def",
"get_published_or_draft",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_published",
":",
"return",
"self",
"elif",
"self",
".",
"publishing_linked_id",
":",
"return",
"self",
".",
"publishing_linked",
"if",
"is_draft_request_context",
"(",
")",
":",
"retu... | Return the published item, if it exists, otherwise, for privileged
users, return the draft version. | [
"Return",
"the",
"published",
"item",
"if",
"it",
"exists",
"otherwise",
"for",
"privileged",
"users",
"return",
"the",
"draft",
"version",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/publishing/models.py#L186-L199 | train |
ic-labs/django-icekit | icekit/publishing/models.py | PublishingModel.publish | def publish(self):
"""
Publishes the object.
The decorator `assert_draft` makes sure that you cannot publish
a published object.
:param self: The object to tbe published.
:return: The published object.
"""
if self.is_draft:
# If the object has... | python | def publish(self):
"""
Publishes the object.
The decorator `assert_draft` makes sure that you cannot publish
a published object.
:param self: The object to tbe published.
:return: The published object.
"""
if self.is_draft:
# If the object has... | [
"def",
"publish",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_draft",
":",
"if",
"self",
".",
"publishing_linked",
":",
"self",
".",
"patch_placeholders",
"(",
")",
"type",
"(",
"self",
".",
"publishing_linked",
")",
".",
"objects",
".",
"filter",
"(",... | Publishes the object.
The decorator `assert_draft` makes sure that you cannot publish
a published object.
:param self: The object to tbe published.
:return: The published object. | [
"Publishes",
"the",
"object",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/publishing/models.py#L237-L320 | train |
ic-labs/django-icekit | icekit/publishing/models.py | PublishingModel.unpublish | def unpublish(self):
"""
Un-publish the current object.
"""
if self.is_draft and self.publishing_linked:
publishing_signals.publishing_pre_unpublish.send(
sender=type(self), instance=self)
# Unlink draft and published copies then delete published.
... | python | def unpublish(self):
"""
Un-publish the current object.
"""
if self.is_draft and self.publishing_linked:
publishing_signals.publishing_pre_unpublish.send(
sender=type(self), instance=self)
# Unlink draft and published copies then delete published.
... | [
"def",
"unpublish",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_draft",
"and",
"self",
".",
"publishing_linked",
":",
"publishing_signals",
".",
"publishing_pre_unpublish",
".",
"send",
"(",
"sender",
"=",
"type",
"(",
"self",
")",
",",
"instance",
"=",
... | Un-publish the current object. | [
"Un",
"-",
"publish",
"the",
"current",
"object",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/publishing/models.py#L323-L347 | train |
ic-labs/django-icekit | icekit/publishing/models.py | PublishingModel.publishing_prepare_published_copy | def publishing_prepare_published_copy(self, draft_obj):
""" Prepare published copy of draft prior to saving it """
# We call super here, somewhat perversely, to ensure this method will
# be called on publishable subclasses if implemented there.
mysuper = super(PublishingModel, self)
... | python | def publishing_prepare_published_copy(self, draft_obj):
""" Prepare published copy of draft prior to saving it """
# We call super here, somewhat perversely, to ensure this method will
# be called on publishable subclasses if implemented there.
mysuper = super(PublishingModel, self)
... | [
"def",
"publishing_prepare_published_copy",
"(",
"self",
",",
"draft_obj",
")",
":",
"mysuper",
"=",
"super",
"(",
"PublishingModel",
",",
"self",
")",
"if",
"hasattr",
"(",
"mysuper",
",",
"'publishing_prepare_published_copy'",
")",
":",
"mysuper",
".",
"publishi... | Prepare published copy of draft prior to saving it | [
"Prepare",
"published",
"copy",
"of",
"draft",
"prior",
"to",
"saving",
"it"
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/publishing/models.py#L357-L363 | train |
ic-labs/django-icekit | icekit/publishing/models.py | PublishingModel.clone_fluent_placeholders_and_content_items | def clone_fluent_placeholders_and_content_items(self, dst_obj):
"""
Clone each `Placeholder` and its `ContentItem`s.
:param self: The object for which the placeholders are
to be cloned from.
:param dst_obj: The object which the cloned placeholders
are to be related.
... | python | def clone_fluent_placeholders_and_content_items(self, dst_obj):
"""
Clone each `Placeholder` and its `ContentItem`s.
:param self: The object for which the placeholders are
to be cloned from.
:param dst_obj: The object which the cloned placeholders
are to be related.
... | [
"def",
"clone_fluent_placeholders_and_content_items",
"(",
"self",
",",
"dst_obj",
")",
":",
"if",
"not",
"self",
".",
"has_placeholder_relationships",
"(",
")",
":",
"return",
"for",
"src_placeholder",
"in",
"Placeholder",
".",
"objects",
".",
"parent",
"(",
"sel... | Clone each `Placeholder` and its `ContentItem`s.
:param self: The object for which the placeholders are
to be cloned from.
:param dst_obj: The object which the cloned placeholders
are to be related.
:return: None | [
"Clone",
"each",
"Placeholder",
"and",
"its",
"ContentItem",
"s",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/publishing/models.py#L595-L617 | train |
ic-labs/django-icekit | icekit/management/commands/rebuild_page_tree.py | Command.handle_noargs | def handle_noargs(self, **options):
"""
By default this function runs on all objects.
As we are using a publishing system it should only update draft
objects which can be modified in the tree structure.
Once published the tree preferences should remain the same to
ensur... | python | def handle_noargs(self, **options):
"""
By default this function runs on all objects.
As we are using a publishing system it should only update draft
objects which can be modified in the tree structure.
Once published the tree preferences should remain the same to
ensur... | [
"def",
"handle_noargs",
"(",
"self",
",",
"**",
"options",
")",
":",
"is_dry_run",
"=",
"options",
".",
"get",
"(",
"'dry-run'",
",",
"False",
")",
"mptt_only",
"=",
"options",
".",
"get",
"(",
"'mptt-only'",
",",
"False",
")",
"slugs",
"=",
"{",
"}",
... | By default this function runs on all objects.
As we are using a publishing system it should only update draft
objects which can be modified in the tree structure.
Once published the tree preferences should remain the same to
ensure the tree data structure is consistent with what was
... | [
"By",
"default",
"this",
"function",
"runs",
"on",
"all",
"objects",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/management/commands/rebuild_page_tree.py#L26-L133 | train |
ic-labs/django-icekit | icekit/utils/search/search_indexes.py | AbstractLayoutIndex.full_prepare | def full_prepare(self, obj):
"""
Make django_ct equal to the type of get_model, to make polymorphic
children show up in results.
"""
prepared_data = super(AbstractLayoutIndex, self).full_prepare(obj)
prepared_data['django_ct'] = get_model_ct(self.get_model())
retu... | python | def full_prepare(self, obj):
"""
Make django_ct equal to the type of get_model, to make polymorphic
children show up in results.
"""
prepared_data = super(AbstractLayoutIndex, self).full_prepare(obj)
prepared_data['django_ct'] = get_model_ct(self.get_model())
retu... | [
"def",
"full_prepare",
"(",
"self",
",",
"obj",
")",
":",
"prepared_data",
"=",
"super",
"(",
"AbstractLayoutIndex",
",",
"self",
")",
".",
"full_prepare",
"(",
"obj",
")",
"prepared_data",
"[",
"'django_ct'",
"]",
"=",
"get_model_ct",
"(",
"self",
".",
"g... | Make django_ct equal to the type of get_model, to make polymorphic
children show up in results. | [
"Make",
"django_ct",
"equal",
"to",
"the",
"type",
"of",
"get_model",
"to",
"make",
"polymorphic",
"children",
"show",
"up",
"in",
"results",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/utils/search/search_indexes.py#L53-L60 | train |
ic-labs/django-icekit | icekit/templatetags/icekit_tags.py | grammatical_join | def grammatical_join(l, initial_joins=", ", final_join=" and "):
"""
Display a list of items nicely, with a different string before the final
item. Useful for using lists in sentences.
>>> grammatical_join(['apples', 'pears', 'bananas'])
'apples, pears and bananas'
>>> grammatical_join(['apple... | python | def grammatical_join(l, initial_joins=", ", final_join=" and "):
"""
Display a list of items nicely, with a different string before the final
item. Useful for using lists in sentences.
>>> grammatical_join(['apples', 'pears', 'bananas'])
'apples, pears and bananas'
>>> grammatical_join(['apple... | [
"def",
"grammatical_join",
"(",
"l",
",",
"initial_joins",
"=",
"\", \"",
",",
"final_join",
"=",
"\" and \"",
")",
":",
"return",
"initial_joins",
".",
"join",
"(",
"l",
"[",
":",
"-",
"2",
"]",
"+",
"[",
"final_join",
".",
"join",
"(",
"l",
"[",
"-... | Display a list of items nicely, with a different string before the final
item. Useful for using lists in sentences.
>>> grammatical_join(['apples', 'pears', 'bananas'])
'apples, pears and bananas'
>>> grammatical_join(['apples', 'pears', 'bananas'], initial_joins=";", final_join="; or ")
'apples; ... | [
"Display",
"a",
"list",
"of",
"items",
"nicely",
"with",
"a",
"different",
"string",
"before",
"the",
"final",
"item",
".",
"Useful",
"for",
"using",
"lists",
"in",
"sentences",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/templatetags/icekit_tags.py#L64-L81 | train |
ic-labs/django-icekit | icekit/templatetags/icekit_tags.py | update_GET | def update_GET(parser, token):
"""
``update_GET`` allows you to substitute parameters into the current request's
GET parameters. This is useful for updating search filters, page numbers,
without losing the current set.
For example, the template fragment::
<a href="?{% update_GET 'attr1' +=... | python | def update_GET(parser, token):
"""
``update_GET`` allows you to substitute parameters into the current request's
GET parameters. This is useful for updating search filters, page numbers,
without losing the current set.
For example, the template fragment::
<a href="?{% update_GET 'attr1' +=... | [
"def",
"update_GET",
"(",
"parser",
",",
"token",
")",
":",
"try",
":",
"args",
"=",
"token",
".",
"split_contents",
"(",
")",
"[",
"1",
":",
"]",
"triples",
"=",
"list",
"(",
"_chunks",
"(",
"args",
",",
"3",
")",
")",
"if",
"triples",
"and",
"l... | ``update_GET`` allows you to substitute parameters into the current request's
GET parameters. This is useful for updating search filters, page numbers,
without losing the current set.
For example, the template fragment::
<a href="?{% update_GET 'attr1' += value1 'attr2' -= value2
'attr3' =... | [
"update_GET",
"allows",
"you",
"to",
"substitute",
"parameters",
"into",
"the",
"current",
"request",
"s",
"GET",
"parameters",
".",
"This",
"is",
"useful",
"for",
"updating",
"search",
"filters",
"page",
"numbers",
"without",
"losing",
"the",
"current",
"set",
... | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/templatetags/icekit_tags.py#L103-L154 | train |
ic-labs/django-icekit | icekit/templatetags/icekit_tags.py | oembed | def oembed(url, params=""):
"""
Render an OEmbed-compatible link as an embedded item.
:param url: A URL of an OEmbed provider.
:return: The OEMbed ``<embed>`` code.
"""
# Note: this method isn't currently very efficient - the data isn't
# cached or stored.
kwargs = dict(urlparse.parse_... | python | def oembed(url, params=""):
"""
Render an OEmbed-compatible link as an embedded item.
:param url: A URL of an OEmbed provider.
:return: The OEMbed ``<embed>`` code.
"""
# Note: this method isn't currently very efficient - the data isn't
# cached or stored.
kwargs = dict(urlparse.parse_... | [
"def",
"oembed",
"(",
"url",
",",
"params",
"=",
"\"\"",
")",
":",
"kwargs",
"=",
"dict",
"(",
"urlparse",
".",
"parse_qsl",
"(",
"params",
")",
")",
"try",
":",
"return",
"mark_safe",
"(",
"get_oembed_data",
"(",
"url",
",",
"**",
"kwargs",
")",
"["... | Render an OEmbed-compatible link as an embedded item.
:param url: A URL of an OEmbed provider.
:return: The OEMbed ``<embed>`` code. | [
"Render",
"an",
"OEmbed",
"-",
"compatible",
"link",
"as",
"an",
"embedded",
"item",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/templatetags/icekit_tags.py#L226-L246 | train |
ic-labs/django-icekit | icekit/templatetags/icekit_tags.py | admin_link | def admin_link(obj):
"""
Returns a link to the admin URL of an object.
No permissions checking is involved, so use with caution to avoid exposing
the link to unauthorised users.
Example::
{{ foo_obj|admin_link }}
renders as::
<a href='/admin/foo/123'>Foo</a>
:param obj:... | python | def admin_link(obj):
"""
Returns a link to the admin URL of an object.
No permissions checking is involved, so use with caution to avoid exposing
the link to unauthorised users.
Example::
{{ foo_obj|admin_link }}
renders as::
<a href='/admin/foo/123'>Foo</a>
:param obj:... | [
"def",
"admin_link",
"(",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'get_admin_link'",
")",
":",
"return",
"mark_safe",
"(",
"obj",
".",
"get_admin_link",
"(",
")",
")",
"return",
"mark_safe",
"(",
"admin_link_fn",
"(",
"obj",
")",
")"
] | Returns a link to the admin URL of an object.
No permissions checking is involved, so use with caution to avoid exposing
the link to unauthorised users.
Example::
{{ foo_obj|admin_link }}
renders as::
<a href='/admin/foo/123'>Foo</a>
:param obj: A Django model instance.
:re... | [
"Returns",
"a",
"link",
"to",
"the",
"admin",
"URL",
"of",
"an",
"object",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/templatetags/icekit_tags.py#L250-L271 | train |
ic-labs/django-icekit | icekit/templatetags/icekit_tags.py | admin_url | def admin_url(obj):
"""
Returns the admin URL of the object.
No permissions checking is involved, so use with caution to avoid exposing
the link to unauthorised users.
Example::
{{ foo_obj|admin_url }}
renders as::
/admin/foo/123
:param obj: A Django model instance.
... | python | def admin_url(obj):
"""
Returns the admin URL of the object.
No permissions checking is involved, so use with caution to avoid exposing
the link to unauthorised users.
Example::
{{ foo_obj|admin_url }}
renders as::
/admin/foo/123
:param obj: A Django model instance.
... | [
"def",
"admin_url",
"(",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'get_admin_url'",
")",
":",
"return",
"mark_safe",
"(",
"obj",
".",
"get_admin_url",
"(",
")",
")",
"return",
"mark_safe",
"(",
"admin_url_fn",
"(",
"obj",
")",
")"
] | Returns the admin URL of the object.
No permissions checking is involved, so use with caution to avoid exposing
the link to unauthorised users.
Example::
{{ foo_obj|admin_url }}
renders as::
/admin/foo/123
:param obj: A Django model instance.
:return: the admin URL of the o... | [
"Returns",
"the",
"admin",
"URL",
"of",
"the",
"object",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/templatetags/icekit_tags.py#L275-L295 | train |
ic-labs/django-icekit | icekit/templatetags/icekit_tags.py | sharedcontent_exists | def sharedcontent_exists(slug):
"""
Return `True` if shared content with the given slug name exists.
This filter makes it possible to conditionally include shared content with
surrounding markup only when the shared content item actually exits, and
avoid outputting the surrounding markup when it do... | python | def sharedcontent_exists(slug):
"""
Return `True` if shared content with the given slug name exists.
This filter makes it possible to conditionally include shared content with
surrounding markup only when the shared content item actually exits, and
avoid outputting the surrounding markup when it do... | [
"def",
"sharedcontent_exists",
"(",
"slug",
")",
":",
"from",
"django",
".",
"contrib",
".",
"sites",
".",
"models",
"import",
"Site",
"from",
"fluent_contents",
".",
"plugins",
".",
"sharedcontent",
".",
"models",
"import",
"SharedContent",
"site",
"=",
"Site... | Return `True` if shared content with the given slug name exists.
This filter makes it possible to conditionally include shared content with
surrounding markup only when the shared content item actually exits, and
avoid outputting the surrounding markup when it doesn't.
Example usage:
{% load ... | [
"Return",
"True",
"if",
"shared",
"content",
"with",
"the",
"given",
"slug",
"name",
"exists",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/templatetags/icekit_tags.py#L342-L363 | train |
ic-labs/django-icekit | icekit/admin_tools/previews.py | RawIdPreviewAdminMixin.render_field_error | def render_field_error(self, obj_id, obj, exception, request):
"""
Default rendering for items in field where the the usual rendering
method raised an exception.
"""
if obj is None:
msg = 'No match for ID={0}'.format(obj_id)
else:
msg = unicode(exc... | python | def render_field_error(self, obj_id, obj, exception, request):
"""
Default rendering for items in field where the the usual rendering
method raised an exception.
"""
if obj is None:
msg = 'No match for ID={0}'.format(obj_id)
else:
msg = unicode(exc... | [
"def",
"render_field_error",
"(",
"self",
",",
"obj_id",
",",
"obj",
",",
"exception",
",",
"request",
")",
":",
"if",
"obj",
"is",
"None",
":",
"msg",
"=",
"'No match for ID={0}'",
".",
"format",
"(",
"obj_id",
")",
"else",
":",
"msg",
"=",
"unicode",
... | Default rendering for items in field where the the usual rendering
method raised an exception. | [
"Default",
"rendering",
"for",
"items",
"in",
"field",
"where",
"the",
"the",
"usual",
"rendering",
"method",
"raised",
"an",
"exception",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/admin_tools/previews.py#L65-L74 | train |
ic-labs/django-icekit | icekit/admin_tools/previews.py | RawIdPreviewAdminMixin.render_field_previews | def render_field_previews(self, id_and_obj_list, admin, request, field_name):
"""
Override this to customise the preview representation of all objects.
"""
obj_preview_list = []
for obj_id, obj in id_and_obj_list:
try:
# Handle invalid IDs
... | python | def render_field_previews(self, id_and_obj_list, admin, request, field_name):
"""
Override this to customise the preview representation of all objects.
"""
obj_preview_list = []
for obj_id, obj in id_and_obj_list:
try:
# Handle invalid IDs
... | [
"def",
"render_field_previews",
"(",
"self",
",",
"id_and_obj_list",
",",
"admin",
",",
"request",
",",
"field_name",
")",
":",
"obj_preview_list",
"=",
"[",
"]",
"for",
"obj_id",
",",
"obj",
"in",
"id_and_obj_list",
":",
"try",
":",
"if",
"obj",
"is",
"No... | Override this to customise the preview representation of all objects. | [
"Override",
"this",
"to",
"customise",
"the",
"preview",
"representation",
"of",
"all",
"objects",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/admin_tools/previews.py#L76-L111 | train |
ic-labs/django-icekit | icekit/plugins/links/abstract_models.py | AbstractLinkItem.get_item | def get_item(self):
"If the item is publishable, get the visible version"
if hasattr(self, 'get_draft'):
draft = self.get_draft()
else:
draft = self
if not hasattr(self, '_item_cache'):
try:
self._item_cache = draft.item.get_published... | python | def get_item(self):
"If the item is publishable, get the visible version"
if hasattr(self, 'get_draft'):
draft = self.get_draft()
else:
draft = self
if not hasattr(self, '_item_cache'):
try:
self._item_cache = draft.item.get_published... | [
"def",
"get_item",
"(",
"self",
")",
":",
"\"If the item is publishable, get the visible version\"",
"if",
"hasattr",
"(",
"self",
",",
"'get_draft'",
")",
":",
"draft",
"=",
"self",
".",
"get_draft",
"(",
")",
"else",
":",
"draft",
"=",
"self",
"if",
"not",
... | If the item is publishable, get the visible version | [
"If",
"the",
"item",
"is",
"publishable",
"get",
"the",
"visible",
"version"
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/plugins/links/abstract_models.py#L39-L53 | train |
ic-labs/django-icekit | icekit/plugins/links/abstract_models.py | LinkPlugin.render | def render(self, request, instance, **kwargs):
"""
Only render the plugin if the item can be shown to the user
"""
if instance.get_item():
return super(LinkPlugin, self).render(request, instance, **kwargs)
return "" | python | def render(self, request, instance, **kwargs):
"""
Only render the plugin if the item can be shown to the user
"""
if instance.get_item():
return super(LinkPlugin, self).render(request, instance, **kwargs)
return "" | [
"def",
"render",
"(",
"self",
",",
"request",
",",
"instance",
",",
"**",
"kwargs",
")",
":",
"if",
"instance",
".",
"get_item",
"(",
")",
":",
"return",
"super",
"(",
"LinkPlugin",
",",
"self",
")",
".",
"render",
"(",
"request",
",",
"instance",
",... | Only render the plugin if the item can be shown to the user | [
"Only",
"render",
"the",
"plugin",
"if",
"the",
"item",
"can",
"be",
"shown",
"to",
"the",
"user"
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/plugins/links/abstract_models.py#L109-L115 | train |
ic-labs/django-icekit | icekit/api/base_serializers.py | ModelSubSerializer.get_fields | def get_fields(self):
"""
Convert default field names for this sub-serializer into versions where
the field name has the prefix removed, but each field object knows the
real model field name by setting the field's `source` attribute.
"""
prefix = getattr(self.Meta, 'sourc... | python | def get_fields(self):
"""
Convert default field names for this sub-serializer into versions where
the field name has the prefix removed, but each field object knows the
real model field name by setting the field's `source` attribute.
"""
prefix = getattr(self.Meta, 'sourc... | [
"def",
"get_fields",
"(",
"self",
")",
":",
"prefix",
"=",
"getattr",
"(",
"self",
".",
"Meta",
",",
"'source_prefix'",
",",
"''",
")",
"fields",
"=",
"super",
"(",
"ModelSubSerializer",
",",
"self",
")",
".",
"get_fields",
"(",
")",
"fields_without_prefix... | Convert default field names for this sub-serializer into versions where
the field name has the prefix removed, but each field object knows the
real model field name by setting the field's `source` attribute. | [
"Convert",
"default",
"field",
"names",
"for",
"this",
"sub",
"-",
"serializer",
"into",
"versions",
"where",
"the",
"field",
"name",
"has",
"the",
"prefix",
"removed",
"but",
"each",
"field",
"object",
"knows",
"the",
"real",
"model",
"field",
"name",
"by",... | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/api/base_serializers.py#L51-L69 | train |
ic-labs/django-icekit | icekit/api/base_serializers.py | WritableSerializerHelperMixin._populate_validated_data_with_sub_field_data | def _populate_validated_data_with_sub_field_data(self, validated_data):
"""
Move field data nested in `ModelSubSerializer` fields back into the
overall validated data dict.
"""
for fieldname, field in self.get_fields().items():
if isinstance(field, ModelSubSerializer)... | python | def _populate_validated_data_with_sub_field_data(self, validated_data):
"""
Move field data nested in `ModelSubSerializer` fields back into the
overall validated data dict.
"""
for fieldname, field in self.get_fields().items():
if isinstance(field, ModelSubSerializer)... | [
"def",
"_populate_validated_data_with_sub_field_data",
"(",
"self",
",",
"validated_data",
")",
":",
"for",
"fieldname",
",",
"field",
"in",
"self",
".",
"get_fields",
"(",
")",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"field",
",",
"ModelSubSeria... | Move field data nested in `ModelSubSerializer` fields back into the
overall validated data dict. | [
"Move",
"field",
"data",
"nested",
"in",
"ModelSubSerializer",
"fields",
"back",
"into",
"the",
"overall",
"validated",
"data",
"dict",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/api/base_serializers.py#L123-L132 | train |
ic-labs/django-icekit | icekit/api/base_serializers.py | WritableSerializerHelperMixin._prepare_related_single_or_m2m_relations | def _prepare_related_single_or_m2m_relations(self, validated_data):
"""
Handle writing to nested related model fields for both single and
many-to-many relationships.
For single relationships, any existing or new instance resulting from
the provided data is set back into the prov... | python | def _prepare_related_single_or_m2m_relations(self, validated_data):
"""
Handle writing to nested related model fields for both single and
many-to-many relationships.
For single relationships, any existing or new instance resulting from
the provided data is set back into the prov... | [
"def",
"_prepare_related_single_or_m2m_relations",
"(",
"self",
",",
"validated_data",
")",
":",
"many_to_many_relationships",
"=",
"{",
"}",
"for",
"fieldname",
",",
"field",
"in",
"self",
".",
"get_fields",
"(",
")",
".",
"items",
"(",
")",
":",
"if",
"(",
... | Handle writing to nested related model fields for both single and
many-to-many relationships.
For single relationships, any existing or new instance resulting from
the provided data is set back into the provided `validated_data` to
be applied by DjangoRestFramework's default handling.
... | [
"Handle",
"writing",
"to",
"nested",
"related",
"model",
"fields",
"for",
"both",
"single",
"and",
"many",
"-",
"to",
"-",
"many",
"relationships",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/api/base_serializers.py#L134-L194 | train |
ic-labs/django-icekit | icekit/api/base_serializers.py | WritableSerializerHelperMixin._get_or_update_or_create_related_instance | def _get_or_update_or_create_related_instance(
self, ModelClass, fieldname, field_data
):
"""
Handle lookup, update, or creation of related instances based on the
field data provided and the field's `writable_related_fields` settings
as defined on the serializer's `Meta`.... | python | def _get_or_update_or_create_related_instance(
self, ModelClass, fieldname, field_data
):
"""
Handle lookup, update, or creation of related instances based on the
field data provided and the field's `writable_related_fields` settings
as defined on the serializer's `Meta`.... | [
"def",
"_get_or_update_or_create_related_instance",
"(",
"self",
",",
"ModelClass",
",",
"fieldname",
",",
"field_data",
")",
":",
"writable_related_fields",
"=",
"getattr",
"(",
"self",
".",
"Meta",
",",
"'writable_related_fields'",
",",
"{",
"}",
")",
"if",
"fie... | Handle lookup, update, or creation of related instances based on the
field data provided and the field's `writable_related_fields` settings
as defined on the serializer's `Meta`.
This method will:
- fail immediately if the field does not have
`writable_related_fields`... | [
"Handle",
"lookup",
"update",
"or",
"creation",
"of",
"related",
"instances",
"based",
"on",
"the",
"field",
"data",
"provided",
"and",
"the",
"field",
"s",
"writable_related_fields",
"settings",
"as",
"defined",
"on",
"the",
"serializer",
"s",
"Meta",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/api/base_serializers.py#L196-L327 | train |
ic-labs/django-icekit | icekit/api/base_serializers.py | WritableSerializerHelperMixin._write_related_m2m_relations | def _write_related_m2m_relations(self, obj, many_to_many_relationships):
"""
For the given `many_to_many_relationships` dict mapping field names to
a list of object instances, apply the instance listing to the `obj`s
named many-to-many relationship field.
"""
for fieldnam... | python | def _write_related_m2m_relations(self, obj, many_to_many_relationships):
"""
For the given `many_to_many_relationships` dict mapping field names to
a list of object instances, apply the instance listing to the `obj`s
named many-to-many relationship field.
"""
for fieldnam... | [
"def",
"_write_related_m2m_relations",
"(",
"self",
",",
"obj",
",",
"many_to_many_relationships",
")",
":",
"for",
"fieldname",
",",
"related_objs",
"in",
"many_to_many_relationships",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"obj",
",",
"fieldname",
",",
"... | For the given `many_to_many_relationships` dict mapping field names to
a list of object instances, apply the instance listing to the `obj`s
named many-to-many relationship field. | [
"For",
"the",
"given",
"many_to_many_relationships",
"dict",
"mapping",
"field",
"names",
"to",
"a",
"list",
"of",
"object",
"instances",
"apply",
"the",
"instance",
"listing",
"to",
"the",
"obj",
"s",
"named",
"many",
"-",
"to",
"-",
"many",
"relationship",
... | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/api/base_serializers.py#L329-L337 | train |
ic-labs/django-icekit | icekit/plugins/__init__.py | FileSystemLayoutsPlugin.get_choices | def get_choices(self):
"""
Return a list of choices for source files found in configured layout
template directories.
"""
choices = []
for label_prefix, templates_dir, template_name_prefix in \
appsettings.LAYOUT_TEMPLATES:
source_dir = os.path... | python | def get_choices(self):
"""
Return a list of choices for source files found in configured layout
template directories.
"""
choices = []
for label_prefix, templates_dir, template_name_prefix in \
appsettings.LAYOUT_TEMPLATES:
source_dir = os.path... | [
"def",
"get_choices",
"(",
"self",
")",
":",
"choices",
"=",
"[",
"]",
"for",
"label_prefix",
",",
"templates_dir",
",",
"template_name_prefix",
"in",
"appsettings",
".",
"LAYOUT_TEMPLATES",
":",
"source_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"templ... | Return a list of choices for source files found in configured layout
template directories. | [
"Return",
"a",
"list",
"of",
"choices",
"for",
"source",
"files",
"found",
"in",
"configured",
"layout",
"template",
"directories",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/plugins/__init__.py#L116-L132 | train |
ic-labs/django-icekit | icekit/project/jinja2.py | environment | def environment(**options):
"""
Add ``static`` and ``url`` functions to the ``environment`` context
processor and return as a Jinja2 ``Environment`` object.
"""
env = Environment(**options)
env.globals.update({
'static': staticfiles_storage.url,
'url': reverse,
})
env.glo... | python | def environment(**options):
"""
Add ``static`` and ``url`` functions to the ``environment`` context
processor and return as a Jinja2 ``Environment`` object.
"""
env = Environment(**options)
env.globals.update({
'static': staticfiles_storage.url,
'url': reverse,
})
env.glo... | [
"def",
"environment",
"(",
"**",
"options",
")",
":",
"env",
"=",
"Environment",
"(",
"**",
"options",
")",
"env",
".",
"globals",
".",
"update",
"(",
"{",
"'static'",
":",
"staticfiles_storage",
".",
"url",
",",
"'url'",
":",
"reverse",
",",
"}",
")",... | Add ``static`` and ``url`` functions to the ``environment`` context
processor and return as a Jinja2 ``Environment`` object. | [
"Add",
"static",
"and",
"url",
"functions",
"to",
"the",
"environment",
"context",
"processor",
"and",
"return",
"as",
"a",
"Jinja2",
"Environment",
"object",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/project/jinja2.py#L9-L20 | train |
ic-labs/django-icekit | icekit/apps.py | update_site | def update_site(sender, **kwargs):
"""
Update `Site` object matching `SITE_ID` setting with `SITE_DOMAIN` and
`SITE_PORT` settings.
"""
Site = apps.get_model('sites', 'Site')
domain = settings.SITE_DOMAIN
if settings.SITE_PORT:
domain += ':%s' % settings.SITE_PORT
Site.objects.up... | python | def update_site(sender, **kwargs):
"""
Update `Site` object matching `SITE_ID` setting with `SITE_DOMAIN` and
`SITE_PORT` settings.
"""
Site = apps.get_model('sites', 'Site')
domain = settings.SITE_DOMAIN
if settings.SITE_PORT:
domain += ':%s' % settings.SITE_PORT
Site.objects.up... | [
"def",
"update_site",
"(",
"sender",
",",
"**",
"kwargs",
")",
":",
"Site",
"=",
"apps",
".",
"get_model",
"(",
"'sites'",
",",
"'Site'",
")",
"domain",
"=",
"settings",
".",
"SITE_DOMAIN",
"if",
"settings",
".",
"SITE_PORT",
":",
"domain",
"+=",
"':%s'"... | Update `Site` object matching `SITE_ID` setting with `SITE_DOMAIN` and
`SITE_PORT` settings. | [
"Update",
"Site",
"object",
"matching",
"SITE_ID",
"setting",
"with",
"SITE_DOMAIN",
"and",
"SITE_PORT",
"settings",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/apps.py#L16-L37 | train |
ic-labs/django-icekit | icekit_events/templatetags/events_tags.py | _format_with_same_year | def _format_with_same_year(format_specifier):
"""
Return a version of `format_specifier` that renders a date
assuming it has the same year as another date. Usually this means ommitting
the year.
This can be overridden by specifying a format that has `_SAME_YEAR` appended
to the name in the ... | python | def _format_with_same_year(format_specifier):
"""
Return a version of `format_specifier` that renders a date
assuming it has the same year as another date. Usually this means ommitting
the year.
This can be overridden by specifying a format that has `_SAME_YEAR` appended
to the name in the ... | [
"def",
"_format_with_same_year",
"(",
"format_specifier",
")",
":",
"test_format_specifier",
"=",
"format_specifier",
"+",
"\"_SAME_YEAR\"",
"test_format",
"=",
"get_format",
"(",
"test_format_specifier",
",",
"use_l10n",
"=",
"True",
")",
"if",
"test_format",
"==",
"... | Return a version of `format_specifier` that renders a date
assuming it has the same year as another date. Usually this means ommitting
the year.
This can be overridden by specifying a format that has `_SAME_YEAR` appended
to the name in the project's `formats` spec. | [
"Return",
"a",
"version",
"of",
"format_specifier",
"that",
"renders",
"a",
"date",
"assuming",
"it",
"has",
"the",
"same",
"year",
"as",
"another",
"date",
".",
"Usually",
"this",
"means",
"ommitting",
"the",
"year",
".",
"This",
"can",
"be",
"overridden",
... | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit_events/templatetags/events_tags.py#L46-L63 | train |
ic-labs/django-icekit | icekit_events/templatetags/events_tags.py | _format_with_same_year_and_month | def _format_with_same_year_and_month(format_specifier):
"""
Return a version of `format_specifier` that renders a date
assuming it has the same year and month as another date. Usually this
means ommitting the year and month.
This can be overridden by specifying a format that has
`_SAME_YEAR_S... | python | def _format_with_same_year_and_month(format_specifier):
"""
Return a version of `format_specifier` that renders a date
assuming it has the same year and month as another date. Usually this
means ommitting the year and month.
This can be overridden by specifying a format that has
`_SAME_YEAR_S... | [
"def",
"_format_with_same_year_and_month",
"(",
"format_specifier",
")",
":",
"test_format_specifier",
"=",
"format_specifier",
"+",
"\"_SAME_YEAR_SAME_MONTH\"",
"test_format",
"=",
"get_format",
"(",
"test_format_specifier",
",",
"use_l10n",
"=",
"True",
")",
"if",
"test... | Return a version of `format_specifier` that renders a date
assuming it has the same year and month as another date. Usually this
means ommitting the year and month.
This can be overridden by specifying a format that has
`_SAME_YEAR_SAME_MONTH` appended to the name in the project's `formats`
spec... | [
"Return",
"a",
"version",
"of",
"format_specifier",
"that",
"renders",
"a",
"date",
"assuming",
"it",
"has",
"the",
"same",
"year",
"and",
"month",
"as",
"another",
"date",
".",
"Usually",
"this",
"means",
"ommitting",
"the",
"year",
"and",
"month",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit_events/templatetags/events_tags.py#L65-L83 | train |
ic-labs/django-icekit | icekit/admin.py | LayoutAdmin._get_ctypes | def _get_ctypes(self):
"""
Returns all related objects for this model.
"""
ctypes = []
for related_object in self.model._meta.get_all_related_objects():
model = getattr(related_object, 'related_model', related_object.model)
ctypes.append(ContentType.object... | python | def _get_ctypes(self):
"""
Returns all related objects for this model.
"""
ctypes = []
for related_object in self.model._meta.get_all_related_objects():
model = getattr(related_object, 'related_model', related_object.model)
ctypes.append(ContentType.object... | [
"def",
"_get_ctypes",
"(",
"self",
")",
":",
"ctypes",
"=",
"[",
"]",
"for",
"related_object",
"in",
"self",
".",
"model",
".",
"_meta",
".",
"get_all_related_objects",
"(",
")",
":",
"model",
"=",
"getattr",
"(",
"related_object",
",",
"'related_model'",
... | Returns all related objects for this model. | [
"Returns",
"all",
"related",
"objects",
"for",
"this",
"model",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/admin.py#L18-L29 | train |
ic-labs/django-icekit | icekit/admin.py | LayoutAdmin.placeholder_data_view | def placeholder_data_view(self, request, id):
"""
Return placeholder data for the given layout's template.
"""
# See: `fluent_pages.pagetypes.fluentpage.admin.FluentPageAdmin`.
try:
layout = models.Layout.objects.get(pk=id)
except models.Layout.DoesNotExist:
... | python | def placeholder_data_view(self, request, id):
"""
Return placeholder data for the given layout's template.
"""
# See: `fluent_pages.pagetypes.fluentpage.admin.FluentPageAdmin`.
try:
layout = models.Layout.objects.get(pk=id)
except models.Layout.DoesNotExist:
... | [
"def",
"placeholder_data_view",
"(",
"self",
",",
"request",
",",
"id",
")",
":",
"try",
":",
"layout",
"=",
"models",
".",
"Layout",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"id",
")",
"except",
"models",
".",
"Layout",
".",
"DoesNotExist",
":",
... | Return placeholder data for the given layout's template. | [
"Return",
"placeholder",
"data",
"for",
"the",
"given",
"layout",
"s",
"template",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/admin.py#L37-L66 | train |
ic-labs/django-icekit | icekit/admin.py | LayoutAdmin.get_urls | def get_urls(self):
"""
Add ``layout_placeholder_data`` URL.
"""
# See: `fluent_pages.pagetypes.fluentpage.admin.FluentPageAdmin`.
urls = super(LayoutAdmin, self).get_urls()
my_urls = patterns(
'',
url(
r'^placeholder_data/(?P<id>\d... | python | def get_urls(self):
"""
Add ``layout_placeholder_data`` URL.
"""
# See: `fluent_pages.pagetypes.fluentpage.admin.FluentPageAdmin`.
urls = super(LayoutAdmin, self).get_urls()
my_urls = patterns(
'',
url(
r'^placeholder_data/(?P<id>\d... | [
"def",
"get_urls",
"(",
"self",
")",
":",
"urls",
"=",
"super",
"(",
"LayoutAdmin",
",",
"self",
")",
".",
"get_urls",
"(",
")",
"my_urls",
"=",
"patterns",
"(",
"''",
",",
"url",
"(",
"r'^placeholder_data/(?P<id>\\d+)/$'",
",",
"self",
".",
"admin_site",
... | Add ``layout_placeholder_data`` URL. | [
"Add",
"layout_placeholder_data",
"URL",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/admin.py#L68-L82 | train |
ic-labs/django-icekit | icekit_events/forms.py | RecurrenceRuleWidget.decompress | def decompress(self, value):
"""
Return the primary key value for the ``Select`` widget if the given
recurrence rule exists in the queryset.
"""
if value:
try:
pk = self.queryset.get(recurrence_rule=value).pk
except self.queryset.model.Does... | python | def decompress(self, value):
"""
Return the primary key value for the ``Select`` widget if the given
recurrence rule exists in the queryset.
"""
if value:
try:
pk = self.queryset.get(recurrence_rule=value).pk
except self.queryset.model.Does... | [
"def",
"decompress",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
":",
"try",
":",
"pk",
"=",
"self",
".",
"queryset",
".",
"get",
"(",
"recurrence_rule",
"=",
"value",
")",
".",
"pk",
"except",
"self",
".",
"queryset",
".",
"model",
".",
"D... | Return the primary key value for the ``Select`` widget if the given
recurrence rule exists in the queryset. | [
"Return",
"the",
"primary",
"key",
"value",
"for",
"the",
"Select",
"widget",
"if",
"the",
"given",
"recurrence",
"rule",
"exists",
"in",
"the",
"queryset",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit_events/forms.py#L61-L72 | train |
ic-labs/django-icekit | icekit_events/forms.py | RecurrenceRuleField._set_queryset | def _set_queryset(self, queryset):
"""
Set the queryset on the ``ModelChoiceField`` and choices on the widget.
"""
self.fields[0].queryset = self.widget.queryset = queryset
self.widget.choices = self.fields[0].choices | python | def _set_queryset(self, queryset):
"""
Set the queryset on the ``ModelChoiceField`` and choices on the widget.
"""
self.fields[0].queryset = self.widget.queryset = queryset
self.widget.choices = self.fields[0].choices | [
"def",
"_set_queryset",
"(",
"self",
",",
"queryset",
")",
":",
"self",
".",
"fields",
"[",
"0",
"]",
".",
"queryset",
"=",
"self",
".",
"widget",
".",
"queryset",
"=",
"queryset",
"self",
".",
"widget",
".",
"choices",
"=",
"self",
".",
"fields",
"[... | Set the queryset on the ``ModelChoiceField`` and choices on the widget. | [
"Set",
"the",
"queryset",
"on",
"the",
"ModelChoiceField",
"and",
"choices",
"on",
"the",
"widget",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit_events/forms.py#L171-L176 | train |
ic-labs/django-icekit | icekit_events/plugins/event_content_listing/forms.py | EventContentListingAdminForm.filter_content_types | def filter_content_types(self, content_type_qs):
""" Filter the content types selectable to only event subclasses """
valid_ct_ids = []
for ct in content_type_qs:
model = ct.model_class()
if model and issubclass(model, EventBase):
valid_ct_ids.append(ct.id... | python | def filter_content_types(self, content_type_qs):
""" Filter the content types selectable to only event subclasses """
valid_ct_ids = []
for ct in content_type_qs:
model = ct.model_class()
if model and issubclass(model, EventBase):
valid_ct_ids.append(ct.id... | [
"def",
"filter_content_types",
"(",
"self",
",",
"content_type_qs",
")",
":",
"valid_ct_ids",
"=",
"[",
"]",
"for",
"ct",
"in",
"content_type_qs",
":",
"model",
"=",
"ct",
".",
"model_class",
"(",
")",
"if",
"model",
"and",
"issubclass",
"(",
"model",
",",... | Filter the content types selectable to only event subclasses | [
"Filter",
"the",
"content",
"types",
"selectable",
"to",
"only",
"event",
"subclasses"
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit_events/plugins/event_content_listing/forms.py#L18-L25 | train |
ic-labs/django-icekit | icekit/utils/pagination.py | describe_page_numbers | def describe_page_numbers(current_page, total_count, per_page, page_numbers_at_ends=3, pages_numbers_around_current=3):
"""
Produces a description of how to display a paginated list's page numbers. Rather than just
spitting out a list of every page available, the page numbers returned will be trimmed
to... | python | def describe_page_numbers(current_page, total_count, per_page, page_numbers_at_ends=3, pages_numbers_around_current=3):
"""
Produces a description of how to display a paginated list's page numbers. Rather than just
spitting out a list of every page available, the page numbers returned will be trimmed
to... | [
"def",
"describe_page_numbers",
"(",
"current_page",
",",
"total_count",
",",
"per_page",
",",
"page_numbers_at_ends",
"=",
"3",
",",
"pages_numbers_around_current",
"=",
"3",
")",
":",
"if",
"total_count",
":",
"page_count",
"=",
"int",
"(",
"math",
".",
"ceil"... | Produces a description of how to display a paginated list's page numbers. Rather than just
spitting out a list of every page available, the page numbers returned will be trimmed
to display only the immediate numbers around the start, end, and the current page.
:param current_page: the current page number (... | [
"Produces",
"a",
"description",
"of",
"how",
"to",
"display",
"a",
"paginated",
"list",
"s",
"page",
"numbers",
".",
"Rather",
"than",
"just",
"spitting",
"out",
"a",
"list",
"of",
"every",
"page",
"available",
"the",
"page",
"numbers",
"returned",
"will",
... | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/utils/pagination.py#L16-L62 | train |
ic-labs/django-icekit | icekit/middleware.py | render_stats | def render_stats(stats, sort, format):
"""
Returns a StringIO containing the formatted statistics from _statsfile_.
_sort_ is a list of fields to sort by.
_format_ is the name of the method that pstats uses to format the data.
"""
output = StdoutWrapper()
if hasattr(stats, "stream"):
... | python | def render_stats(stats, sort, format):
"""
Returns a StringIO containing the formatted statistics from _statsfile_.
_sort_ is a list of fields to sort by.
_format_ is the name of the method that pstats uses to format the data.
"""
output = StdoutWrapper()
if hasattr(stats, "stream"):
... | [
"def",
"render_stats",
"(",
"stats",
",",
"sort",
",",
"format",
")",
":",
"output",
"=",
"StdoutWrapper",
"(",
")",
"if",
"hasattr",
"(",
"stats",
",",
"\"stream\"",
")",
":",
"stats",
".",
"stream",
"=",
"output",
".",
"stream",
"stats",
".",
"sort_s... | Returns a StringIO containing the formatted statistics from _statsfile_.
_sort_ is a list of fields to sort by.
_format_ is the name of the method that pstats uses to format the data. | [
"Returns",
"a",
"StringIO",
"containing",
"the",
"formatted",
"statistics",
"from",
"_statsfile_",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/middleware.py#L42-L54 | train |
ic-labs/django-icekit | icekit/middleware.py | render_queries | def render_queries(queries, sort):
"""
Returns a StringIO containing the formatted SQL queries.
_sort_ is a field to sort by.
"""
output = StringIO()
if sort == 'order':
print >>output, " time query"
for query in queries:
print >>output, " %8s %s" % (query["time"... | python | def render_queries(queries, sort):
"""
Returns a StringIO containing the formatted SQL queries.
_sort_ is a field to sort by.
"""
output = StringIO()
if sort == 'order':
print >>output, " time query"
for query in queries:
print >>output, " %8s %s" % (query["time"... | [
"def",
"render_queries",
"(",
"queries",
",",
"sort",
")",
":",
"output",
"=",
"StringIO",
"(",
")",
"if",
"sort",
"==",
"'order'",
":",
"print",
">>",
"output",
",",
"\" time query\"",
"for",
"query",
"in",
"queries",
":",
"print",
">>",
"output",
"... | Returns a StringIO containing the formatted SQL queries.
_sort_ is a field to sort by. | [
"Returns",
"a",
"StringIO",
"containing",
"the",
"formatted",
"SQL",
"queries",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/middleware.py#L57-L91 | train |
ic-labs/django-icekit | icekit/middleware.py | unpickle_stats | def unpickle_stats(stats):
"""Unpickle a pstats.Stats object"""
stats = cPickle.loads(stats)
stats.stream = True
return stats | python | def unpickle_stats(stats):
"""Unpickle a pstats.Stats object"""
stats = cPickle.loads(stats)
stats.stream = True
return stats | [
"def",
"unpickle_stats",
"(",
"stats",
")",
":",
"stats",
"=",
"cPickle",
".",
"loads",
"(",
"stats",
")",
"stats",
".",
"stream",
"=",
"True",
"return",
"stats"
] | Unpickle a pstats.Stats object | [
"Unpickle",
"a",
"pstats",
".",
"Stats",
"object"
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/middleware.py#L101-L105 | train |
ic-labs/django-icekit | icekit/middleware.py | display_stats | def display_stats(request, stats, queries):
"""
Generate a HttpResponse of functions for a profiling run.
_stats_ should contain a pstats.Stats of a hotshot session.
_queries_ should contain a list of SQL queries.
"""
sort = [
request.REQUEST.get('sort_first', 'time'),
request.R... | python | def display_stats(request, stats, queries):
"""
Generate a HttpResponse of functions for a profiling run.
_stats_ should contain a pstats.Stats of a hotshot session.
_queries_ should contain a list of SQL queries.
"""
sort = [
request.REQUEST.get('sort_first', 'time'),
request.R... | [
"def",
"display_stats",
"(",
"request",
",",
"stats",
",",
"queries",
")",
":",
"sort",
"=",
"[",
"request",
".",
"REQUEST",
".",
"get",
"(",
"'sort_first'",
",",
"'time'",
")",
",",
"request",
".",
"REQUEST",
".",
"get",
"(",
"'sort_second'",
",",
"'c... | Generate a HttpResponse of functions for a profiling run.
_stats_ should contain a pstats.Stats of a hotshot session.
_queries_ should contain a list of SQL queries. | [
"Generate",
"a",
"HttpResponse",
"of",
"functions",
"for",
"a",
"profiling",
"run",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/middleware.py#L201-L233 | train |
ic-labs/django-icekit | icekit/middleware.py | display_queries | def display_queries(request, stats, queries):
"""
Generate a HttpResponse of SQL queries for a profiling run.
_stats_ should contain a pstats.Stats of a hotshot session.
_queries_ should contain a list of SQL queries.
"""
sort = request.REQUEST.get('sort_by', 'time')
sort_buttons = RadioBut... | python | def display_queries(request, stats, queries):
"""
Generate a HttpResponse of SQL queries for a profiling run.
_stats_ should contain a pstats.Stats of a hotshot session.
_queries_ should contain a list of SQL queries.
"""
sort = request.REQUEST.get('sort_by', 'time')
sort_buttons = RadioBut... | [
"def",
"display_queries",
"(",
"request",
",",
"stats",
",",
"queries",
")",
":",
"sort",
"=",
"request",
".",
"REQUEST",
".",
"get",
"(",
"'sort_by'",
",",
"'time'",
")",
"sort_buttons",
"=",
"RadioButtons",
"(",
"'sort_by'",
",",
"sort",
",",
"(",
"(",... | Generate a HttpResponse of SQL queries for a profiling run.
_stats_ should contain a pstats.Stats of a hotshot session.
_queries_ should contain a list of SQL queries. | [
"Generate",
"a",
"HttpResponse",
"of",
"SQL",
"queries",
"for",
"a",
"profiling",
"run",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/middleware.py#L260-L283 | train |
ic-labs/django-icekit | icekit/middleware.py | ProfileMiddleware.process_request | def process_request(self, request):
"""
Setup the profiler for a profiling run and clear the SQL query log.
If this is a resort of an existing profiling run, just return
the resorted list.
"""
def unpickle(params):
stats = unpickle_stats(b64decode(params.get(... | python | def process_request(self, request):
"""
Setup the profiler for a profiling run and clear the SQL query log.
If this is a resort of an existing profiling run, just return
the resorted list.
"""
def unpickle(params):
stats = unpickle_stats(b64decode(params.get(... | [
"def",
"process_request",
"(",
"self",
",",
"request",
")",
":",
"def",
"unpickle",
"(",
"params",
")",
":",
"stats",
"=",
"unpickle_stats",
"(",
"b64decode",
"(",
"params",
".",
"get",
"(",
"'stats'",
",",
"''",
")",
")",
")",
"queries",
"=",
"cPickle... | Setup the profiler for a profiling run and clear the SQL query log.
If this is a resort of an existing profiling run, just return
the resorted list. | [
"Setup",
"the",
"profiler",
"for",
"a",
"profiling",
"run",
"and",
"clear",
"the",
"SQL",
"query",
"log",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/middleware.py#L293-L326 | train |
ic-labs/django-icekit | icekit/middleware.py | ProfileMiddleware.process_view | def process_view(self, request, view_func, view_args, view_kwargs):
"""Run the profiler on _view_func_."""
profiler = getattr(request, 'profiler', None)
if profiler:
# Make sure profiler variables don't get passed into view_func
original_get = request.GET
requ... | python | def process_view(self, request, view_func, view_args, view_kwargs):
"""Run the profiler on _view_func_."""
profiler = getattr(request, 'profiler', None)
if profiler:
# Make sure profiler variables don't get passed into view_func
original_get = request.GET
requ... | [
"def",
"process_view",
"(",
"self",
",",
"request",
",",
"view_func",
",",
"view_args",
",",
"view_kwargs",
")",
":",
"profiler",
"=",
"getattr",
"(",
"request",
",",
"'profiler'",
",",
"None",
")",
"if",
"profiler",
":",
"original_get",
"=",
"request",
".... | Run the profiler on _view_func_. | [
"Run",
"the",
"profiler",
"on",
"_view_func_",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/middleware.py#L328-L343 | train |
ic-labs/django-icekit | icekit/middleware.py | ProfileMiddleware.process_response | def process_response(self, request, response):
"""Finish profiling and render the results."""
profiler = getattr(request, 'profiler', None)
if profiler:
profiler.close()
params = request.REQUEST
stats = hotshot.stats.load(request.statsfile.name)
qu... | python | def process_response(self, request, response):
"""Finish profiling and render the results."""
profiler = getattr(request, 'profiler', None)
if profiler:
profiler.close()
params = request.REQUEST
stats = hotshot.stats.load(request.statsfile.name)
qu... | [
"def",
"process_response",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"profiler",
"=",
"getattr",
"(",
"request",
",",
"'profiler'",
",",
"None",
")",
"if",
"profiler",
":",
"profiler",
".",
"close",
"(",
")",
"params",
"=",
"request",
".",
... | Finish profiling and render the results. | [
"Finish",
"profiling",
"and",
"render",
"the",
"results",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/middleware.py#L345-L358 | train |
ic-labs/django-icekit | glamkit_collections/etl/base.py | ETL.items_to_extract | def items_to_extract(self, offset=0, length=None):
"""
Return an iterable of specific items to extract.
As a side-effect, set self.items_to_extract_length.
:param offset: where to start extracting
:param length: how many to extract
:return: An iterable of the specific
... | python | def items_to_extract(self, offset=0, length=None):
"""
Return an iterable of specific items to extract.
As a side-effect, set self.items_to_extract_length.
:param offset: where to start extracting
:param length: how many to extract
:return: An iterable of the specific
... | [
"def",
"items_to_extract",
"(",
"self",
",",
"offset",
"=",
"0",
",",
"length",
"=",
"None",
")",
":",
"endoffset",
"=",
"length",
"and",
"offset",
"+",
"length",
"qs",
"=",
"self",
".",
"origin_data",
"(",
")",
"[",
"offset",
":",
"endoffset",
"]",
... | Return an iterable of specific items to extract.
As a side-effect, set self.items_to_extract_length.
:param offset: where to start extracting
:param length: how many to extract
:return: An iterable of the specific | [
"Return",
"an",
"iterable",
"of",
"specific",
"items",
"to",
"extract",
".",
"As",
"a",
"side",
"-",
"effect",
"set",
"self",
".",
"items_to_extract_length",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/glamkit_collections/etl/base.py#L17-L29 | train |
ic-labs/django-icekit | icekit/utils/sequences.py | dedupe_and_sort | def dedupe_and_sort(sequence, first=None, last=None):
"""
De-dupe and partially sort a sequence.
The `first` argument should contain all the items that might appear in
`sequence` and for which the order (relative to each other) is important.
The `last` argument is the same, but matching items will... | python | def dedupe_and_sort(sequence, first=None, last=None):
"""
De-dupe and partially sort a sequence.
The `first` argument should contain all the items that might appear in
`sequence` and for which the order (relative to each other) is important.
The `last` argument is the same, but matching items will... | [
"def",
"dedupe_and_sort",
"(",
"sequence",
",",
"first",
"=",
"None",
",",
"last",
"=",
"None",
")",
":",
"first",
"=",
"first",
"or",
"[",
"]",
"last",
"=",
"last",
"or",
"[",
"]",
"new_sequence",
"=",
"[",
"i",
"for",
"i",
"in",
"first",
"if",
... | De-dupe and partially sort a sequence.
The `first` argument should contain all the items that might appear in
`sequence` and for which the order (relative to each other) is important.
The `last` argument is the same, but matching items will be placed at the
end of the sequence.
For example, `INST... | [
"De",
"-",
"dupe",
"and",
"partially",
"sort",
"a",
"sequence",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/utils/sequences.py#L1-L32 | train |
ic-labs/django-icekit | icekit/utils/sequences.py | slice_sequences | def slice_sequences(sequences, start, end, apply_slice=None):
"""
Performs a slice across multiple sequences.
Useful when paginating across chained collections.
:param sequences: an iterable of iterables, each nested iterable should contain
a sequence and its size
:param start: starting index... | python | def slice_sequences(sequences, start, end, apply_slice=None):
"""
Performs a slice across multiple sequences.
Useful when paginating across chained collections.
:param sequences: an iterable of iterables, each nested iterable should contain
a sequence and its size
:param start: starting index... | [
"def",
"slice_sequences",
"(",
"sequences",
",",
"start",
",",
"end",
",",
"apply_slice",
"=",
"None",
")",
":",
"if",
"start",
"<",
"0",
"or",
"end",
"<",
"0",
"or",
"end",
"<=",
"start",
":",
"raise",
"ValueError",
"(",
"'Start and/or End out of range. S... | Performs a slice across multiple sequences.
Useful when paginating across chained collections.
:param sequences: an iterable of iterables, each nested iterable should contain
a sequence and its size
:param start: starting index to apply the slice from
:param end: index that the slice should end a... | [
"Performs",
"a",
"slice",
"across",
"multiple",
"sequences",
".",
"Useful",
"when",
"paginating",
"across",
"chained",
"collections",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/utils/sequences.py#L39-L85 | train |
ic-labs/django-icekit | icekit/admin_tools/widgets.py | quote | def quote(key, value):
"""Certain options support string values. We want clients to be able to pass Python strings in
but we need them to be quoted in the output. Unfortunately some of those options also allow
numbers so we type check the value before wrapping it in quotes.
"""
if key in quoted_opt... | python | def quote(key, value):
"""Certain options support string values. We want clients to be able to pass Python strings in
but we need them to be quoted in the output. Unfortunately some of those options also allow
numbers so we type check the value before wrapping it in quotes.
"""
if key in quoted_opt... | [
"def",
"quote",
"(",
"key",
",",
"value",
")",
":",
"if",
"key",
"in",
"quoted_options",
"and",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"return",
"\"'%s'\"",
"%",
"value",
"if",
"key",
"in",
"quoted_bool_options",
"and",
"isinstance",
"(... | Certain options support string values. We want clients to be able to pass Python strings in
but we need them to be quoted in the output. Unfortunately some of those options also allow
numbers so we type check the value before wrapping it in quotes. | [
"Certain",
"options",
"support",
"string",
"values",
".",
"We",
"want",
"clients",
"to",
"be",
"able",
"to",
"pass",
"Python",
"strings",
"in",
"but",
"we",
"need",
"them",
"to",
"be",
"quoted",
"in",
"the",
"output",
".",
"Unfortunately",
"some",
"of",
... | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/admin_tools/widgets.py#L146-L158 | train |
ic-labs/django-icekit | icekit/utils/images.py | scale_and_crop_with_ranges | def scale_and_crop_with_ranges(
im, size, size_range=None, crop=False, upscale=False, zoom=None, target=None, **kwargs):
"""
An easy_thumbnails processor that accepts a `size_range` tuple, which
indicates that one or both dimensions can give by a number of pixels in
order to minimize cropping.
"... | python | def scale_and_crop_with_ranges(
im, size, size_range=None, crop=False, upscale=False, zoom=None, target=None, **kwargs):
"""
An easy_thumbnails processor that accepts a `size_range` tuple, which
indicates that one or both dimensions can give by a number of pixels in
order to minimize cropping.
"... | [
"def",
"scale_and_crop_with_ranges",
"(",
"im",
",",
"size",
",",
"size_range",
"=",
"None",
",",
"crop",
"=",
"False",
",",
"upscale",
"=",
"False",
",",
"zoom",
"=",
"None",
",",
"target",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"min_width",
",",... | An easy_thumbnails processor that accepts a `size_range` tuple, which
indicates that one or both dimensions can give by a number of pixels in
order to minimize cropping. | [
"An",
"easy_thumbnails",
"processor",
"that",
"accepts",
"a",
"size_range",
"tuple",
"which",
"indicates",
"that",
"one",
"or",
"both",
"dimensions",
"can",
"give",
"by",
"a",
"number",
"of",
"pixels",
"in",
"order",
"to",
"minimize",
"cropping",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/utils/images.py#L4-L39 | train |
ic-labs/django-icekit | icekit/utils/implementation.py | check_settings | def check_settings(required_settings):
"""
Checks all settings required by a module have been set.
If a setting is required and it could not be found a
NotImplementedError will be raised informing which settings are
missing.
:param required_settings: List of settings names (as strings) that
... | python | def check_settings(required_settings):
"""
Checks all settings required by a module have been set.
If a setting is required and it could not be found a
NotImplementedError will be raised informing which settings are
missing.
:param required_settings: List of settings names (as strings) that
... | [
"def",
"check_settings",
"(",
"required_settings",
")",
":",
"defined_settings",
"=",
"[",
"setting",
"if",
"hasattr",
"(",
"settings",
",",
"setting",
")",
"else",
"None",
"for",
"setting",
"in",
"required_settings",
"]",
"if",
"not",
"all",
"(",
"defined_set... | Checks all settings required by a module have been set.
If a setting is required and it could not be found a
NotImplementedError will be raised informing which settings are
missing.
:param required_settings: List of settings names (as strings) that
are anticipated to be in the settings module.
... | [
"Checks",
"all",
"settings",
"required",
"by",
"a",
"module",
"have",
"been",
"set",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/utils/implementation.py#L4-L25 | train |
ic-labs/django-icekit | icekit_events/managers.py | OccurrenceQueryset.available_on_day | def available_on_day(self, day):
"""
Return events that are available on a given day.
"""
if isinstance(day, datetime):
d = day.date()
else:
d = day
return self.starts_within(d, d) | python | def available_on_day(self, day):
"""
Return events that are available on a given day.
"""
if isinstance(day, datetime):
d = day.date()
else:
d = day
return self.starts_within(d, d) | [
"def",
"available_on_day",
"(",
"self",
",",
"day",
")",
":",
"if",
"isinstance",
"(",
"day",
",",
"datetime",
")",
":",
"d",
"=",
"day",
".",
"date",
"(",
")",
"else",
":",
"d",
"=",
"day",
"return",
"self",
".",
"starts_within",
"(",
"d",
",",
... | Return events that are available on a given day. | [
"Return",
"events",
"that",
"are",
"available",
"on",
"a",
"given",
"day",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit_events/managers.py#L204-L212 | train |
ic-labs/django-icekit | icekit/utils/management/base.py | CronBaseCommand.cleanup | def cleanup(self):
"""
Performs clean-up after task is completed before it is executed again
in the next internal.
"""
# Closes connections to all databases to avoid the long running process
# from holding connections indefinitely.
for alias in db.connections.data... | python | def cleanup(self):
"""
Performs clean-up after task is completed before it is executed again
in the next internal.
"""
# Closes connections to all databases to avoid the long running process
# from holding connections indefinitely.
for alias in db.connections.data... | [
"def",
"cleanup",
"(",
"self",
")",
":",
"for",
"alias",
"in",
"db",
".",
"connections",
".",
"databases",
":",
"logger",
".",
"info",
"(",
"'Closing database connection: %s'",
",",
"alias",
")",
"db",
".",
"connections",
"[",
"alias",
"]",
".",
"close",
... | Performs clean-up after task is completed before it is executed again
in the next internal. | [
"Performs",
"clean",
"-",
"up",
"after",
"task",
"is",
"completed",
"before",
"it",
"is",
"executed",
"again",
"in",
"the",
"next",
"internal",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/utils/management/base.py#L34-L43 | train |
ic-labs/django-icekit | icekit/plugins/base.py | PluginMount.get_plugins | def get_plugins(cls, *args, **kwargs):
"""
Return a list of plugin instances and pass through arguments.
"""
return [plugin(*args, **kwargs) for plugin in cls.plugins] | python | def get_plugins(cls, *args, **kwargs):
"""
Return a list of plugin instances and pass through arguments.
"""
return [plugin(*args, **kwargs) for plugin in cls.plugins] | [
"def",
"get_plugins",
"(",
"cls",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"[",
"plugin",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"for",
"plugin",
"in",
"cls",
".",
"plugins",
"]"
] | Return a list of plugin instances and pass through arguments. | [
"Return",
"a",
"list",
"of",
"plugin",
"instances",
"and",
"pass",
"through",
"arguments",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/plugins/base.py#L41-L45 | train |
ic-labs/django-icekit | icekit/utils/search/views.py | ICEkitSearchView.pre_facet_sqs | def pre_facet_sqs(self):
"""
Return the queryset used for generating facets, before any facets
are applied
"""
sqs = SearchQuerySet()
if self.query:
sqs = sqs.filter(
SQ(content=AutoQuery(self.query)) | # Search `text` document
... | python | def pre_facet_sqs(self):
"""
Return the queryset used for generating facets, before any facets
are applied
"""
sqs = SearchQuerySet()
if self.query:
sqs = sqs.filter(
SQ(content=AutoQuery(self.query)) | # Search `text` document
... | [
"def",
"pre_facet_sqs",
"(",
"self",
")",
":",
"sqs",
"=",
"SearchQuerySet",
"(",
")",
"if",
"self",
".",
"query",
":",
"sqs",
"=",
"sqs",
".",
"filter",
"(",
"SQ",
"(",
"content",
"=",
"AutoQuery",
"(",
"self",
".",
"query",
")",
")",
"|",
"SQ",
... | Return the queryset used for generating facets, before any facets
are applied | [
"Return",
"the",
"queryset",
"used",
"for",
"generating",
"facets",
"before",
"any",
"facets",
"are",
"applied"
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/utils/search/views.py#L40-L54 | train |
ic-labs/django-icekit | icekit/utils/search/views.py | ICEkitSearchView.get | def get(self, request, *args, **kwargs):
"""User has conducted a search, or default state"""
form_class = self.get_form_class()
form = self.get_form(form_class)
top_value = self.get_top_level_facet_value()
subfacets = SEARCH_SUBFACETS.get(top_value, [])
self.active_face... | python | def get(self, request, *args, **kwargs):
"""User has conducted a search, or default state"""
form_class = self.get_form_class()
form = self.get_form(form_class)
top_value = self.get_top_level_facet_value()
subfacets = SEARCH_SUBFACETS.get(top_value, [])
self.active_face... | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"form_class",
"=",
"self",
".",
"get_form_class",
"(",
")",
"form",
"=",
"self",
".",
"get_form",
"(",
"form_class",
")",
"top_value",
"=",
"self",
".",
"get_... | User has conducted a search, or default state | [
"User",
"has",
"conducted",
"a",
"search",
"or",
"default",
"state"
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/utils/search/views.py#L56-L94 | train |
ic-labs/django-icekit | icekit_events/views.py | index | def index(request):
"""
Listing page for event `Occurrence`s.
:param request: Django request object.
:param is_preview: Should the listing page be generated as a preview? This
will allow preview specific actions to be done in the
template such as turning of... | python | def index(request):
"""
Listing page for event `Occurrence`s.
:param request: Django request object.
:param is_preview: Should the listing page be generated as a preview? This
will allow preview specific actions to be done in the
template such as turning of... | [
"def",
"index",
"(",
"request",
")",
":",
"warnings",
".",
"warn",
"(",
"\"icekit_events.views.index is deprecated and will disappear in a \"",
"\"future version. If you need this code, copy it into your project.\"",
",",
"DeprecationWarning",
")",
"occurrences",
"=",
"models",
"... | Listing page for event `Occurrence`s.
:param request: Django request object.
:param is_preview: Should the listing page be generated as a preview? This
will allow preview specific actions to be done in the
template such as turning off tracking options or adding
... | [
"Listing",
"page",
"for",
"event",
"Occurrence",
"s",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit_events/views.py#L20-L41 | train |
ic-labs/django-icekit | icekit/workflow/templatetags/workflow_tags.py | get_assigned_to_user | def get_assigned_to_user(parser, token):
"""
Populates a template variable with the content with WorkflowState assignd
for the given criteria.
Usage::
{% get_assigned_to_user [limit] as [varname] for_user [context_var_containing_user_obj] %}
Examples::
{% get_assigned_to_user 10 ... | python | def get_assigned_to_user(parser, token):
"""
Populates a template variable with the content with WorkflowState assignd
for the given criteria.
Usage::
{% get_assigned_to_user [limit] as [varname] for_user [context_var_containing_user_obj] %}
Examples::
{% get_assigned_to_user 10 ... | [
"def",
"get_assigned_to_user",
"(",
"parser",
",",
"token",
")",
":",
"tokens",
"=",
"token",
".",
"contents",
".",
"split",
"(",
")",
"if",
"len",
"(",
"tokens",
")",
"<",
"4",
":",
"raise",
"template",
".",
"TemplateSyntaxError",
"(",
"\"'get_assigned_to... | Populates a template variable with the content with WorkflowState assignd
for the given criteria.
Usage::
{% get_assigned_to_user [limit] as [varname] for_user [context_var_containing_user_obj] %}
Examples::
{% get_assigned_to_user 10 as content_list for_user 23 %}
{% get_assigne... | [
"Populates",
"a",
"template",
"variable",
"with",
"the",
"content",
"with",
"WorkflowState",
"assignd",
"for",
"the",
"given",
"criteria",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/workflow/templatetags/workflow_tags.py#L28-L60 | train |
ic-labs/django-icekit | icekit_events/migrations/0002_recurrence_rules.py | forwards | def forwards(apps, schema_editor):
"""
Create initial recurrence rules.
"""
RecurrenceRule = apps.get_model('icekit_events', 'RecurrenceRule')
for description, recurrence_rule in RULES:
RecurrenceRule.objects.get_or_create(
description=description,
defaults=dict(recur... | python | def forwards(apps, schema_editor):
"""
Create initial recurrence rules.
"""
RecurrenceRule = apps.get_model('icekit_events', 'RecurrenceRule')
for description, recurrence_rule in RULES:
RecurrenceRule.objects.get_or_create(
description=description,
defaults=dict(recur... | [
"def",
"forwards",
"(",
"apps",
",",
"schema_editor",
")",
":",
"RecurrenceRule",
"=",
"apps",
".",
"get_model",
"(",
"'icekit_events'",
",",
"'RecurrenceRule'",
")",
"for",
"description",
",",
"recurrence_rule",
"in",
"RULES",
":",
"RecurrenceRule",
".",
"objec... | Create initial recurrence rules. | [
"Create",
"initial",
"recurrence",
"rules",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit_events/migrations/0002_recurrence_rules.py#L18-L27 | train |
ic-labs/django-icekit | icekit_events/migrations/0002_recurrence_rules.py | backwards | def backwards(apps, schema_editor):
"""
Delete initial recurrence rules.
"""
RecurrenceRule = apps.get_model('icekit_events', 'RecurrenceRule')
descriptions = [d for d, rr in RULES]
RecurrenceRule.objects.filter(description__in=descriptions).delete() | python | def backwards(apps, schema_editor):
"""
Delete initial recurrence rules.
"""
RecurrenceRule = apps.get_model('icekit_events', 'RecurrenceRule')
descriptions = [d for d, rr in RULES]
RecurrenceRule.objects.filter(description__in=descriptions).delete() | [
"def",
"backwards",
"(",
"apps",
",",
"schema_editor",
")",
":",
"RecurrenceRule",
"=",
"apps",
".",
"get_model",
"(",
"'icekit_events'",
",",
"'RecurrenceRule'",
")",
"descriptions",
"=",
"[",
"d",
"for",
"d",
",",
"rr",
"in",
"RULES",
"]",
"RecurrenceRule"... | Delete initial recurrence rules. | [
"Delete",
"initial",
"recurrence",
"rules",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit_events/migrations/0002_recurrence_rules.py#L30-L36 | train |
ic-labs/django-icekit | icekit/project/context_processors.py | environment | def environment(request=None):
"""
Return ``COMPRESS_ENABLED``, ``SITE_NAME``, and any settings listed
in ``ICEKIT_CONTEXT_PROCESSOR_SETTINGS`` as context.
"""
context = {
'COMPRESS_ENABLED': settings.COMPRESS_ENABLED,
'SITE_NAME': settings.SITE_NAME,
}
for key in settings.IC... | python | def environment(request=None):
"""
Return ``COMPRESS_ENABLED``, ``SITE_NAME``, and any settings listed
in ``ICEKIT_CONTEXT_PROCESSOR_SETTINGS`` as context.
"""
context = {
'COMPRESS_ENABLED': settings.COMPRESS_ENABLED,
'SITE_NAME': settings.SITE_NAME,
}
for key in settings.IC... | [
"def",
"environment",
"(",
"request",
"=",
"None",
")",
":",
"context",
"=",
"{",
"'COMPRESS_ENABLED'",
":",
"settings",
".",
"COMPRESS_ENABLED",
",",
"'SITE_NAME'",
":",
"settings",
".",
"SITE_NAME",
",",
"}",
"for",
"key",
"in",
"settings",
".",
"ICEKIT_CO... | Return ``COMPRESS_ENABLED``, ``SITE_NAME``, and any settings listed
in ``ICEKIT_CONTEXT_PROCESSOR_SETTINGS`` as context. | [
"Return",
"COMPRESS_ENABLED",
"SITE_NAME",
"and",
"any",
"settings",
"listed",
"in",
"ICEKIT_CONTEXT_PROCESSOR_SETTINGS",
"as",
"context",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/project/context_processors.py#L4-L15 | train |
ic-labs/django-icekit | icekit/publishing/monkey_patches.py | get_proxy_ancestor_classes | def get_proxy_ancestor_classes(klass):
"""
Return a set containing all the proxy model classes that are ancestors
of the given class.
NOTE: This implementation is for Django 1.7, it might need to work
differently for other versions especially 1.8+.
"""
proxy_ancestor_classes = set()
for... | python | def get_proxy_ancestor_classes(klass):
"""
Return a set containing all the proxy model classes that are ancestors
of the given class.
NOTE: This implementation is for Django 1.7, it might need to work
differently for other versions especially 1.8+.
"""
proxy_ancestor_classes = set()
for... | [
"def",
"get_proxy_ancestor_classes",
"(",
"klass",
")",
":",
"proxy_ancestor_classes",
"=",
"set",
"(",
")",
"for",
"superclass",
"in",
"klass",
".",
"__bases__",
":",
"if",
"hasattr",
"(",
"superclass",
",",
"'_meta'",
")",
"and",
"superclass",
".",
"_meta",
... | Return a set containing all the proxy model classes that are ancestors
of the given class.
NOTE: This implementation is for Django 1.7, it might need to work
differently for other versions especially 1.8+. | [
"Return",
"a",
"set",
"containing",
"all",
"the",
"proxy",
"model",
"classes",
"that",
"are",
"ancestors",
"of",
"the",
"given",
"class",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/publishing/monkey_patches.py#L186-L200 | train |
ic-labs/django-icekit | glamkit_collections/contrib/work_creator/plugins/person/models.py | PersonCreator.derive_and_set_name_fields_and_slug | def derive_and_set_name_fields_and_slug(
self, set_name_sort=True, set_slug=True
):
"""
Override this method from `CreatorBase` to handle additional name
fields for Person creators.
This method is called during `save()`
"""
super(PersonCreator, self).derive_a... | python | def derive_and_set_name_fields_and_slug(
self, set_name_sort=True, set_slug=True
):
"""
Override this method from `CreatorBase` to handle additional name
fields for Person creators.
This method is called during `save()`
"""
super(PersonCreator, self).derive_a... | [
"def",
"derive_and_set_name_fields_and_slug",
"(",
"self",
",",
"set_name_sort",
"=",
"True",
",",
"set_slug",
"=",
"True",
")",
":",
"super",
"(",
"PersonCreator",
",",
"self",
")",
".",
"derive_and_set_name_fields_and_slug",
"(",
"set_name_sort",
"=",
"False",
"... | Override this method from `CreatorBase` to handle additional name
fields for Person creators.
This method is called during `save()` | [
"Override",
"this",
"method",
"from",
"CreatorBase",
"to",
"handle",
"additional",
"name",
"fields",
"for",
"Person",
"creators",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/glamkit_collections/contrib/work_creator/plugins/person/models.py#L93-L123 | train |
ic-labs/django-icekit | icekit/managers.py | LayoutQuerySet.for_model | def for_model(self, model, **kwargs):
"""
Return layouts that are allowed for the given model.
"""
queryset = self.filter(
content_types=ContentType.objects.get_for_model(model),
**kwargs
)
return queryset | python | def for_model(self, model, **kwargs):
"""
Return layouts that are allowed for the given model.
"""
queryset = self.filter(
content_types=ContentType.objects.get_for_model(model),
**kwargs
)
return queryset | [
"def",
"for_model",
"(",
"self",
",",
"model",
",",
"**",
"kwargs",
")",
":",
"queryset",
"=",
"self",
".",
"filter",
"(",
"content_types",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"model",
")",
",",
"**",
"kwargs",
")",
"return",
... | Return layouts that are allowed for the given model. | [
"Return",
"layouts",
"that",
"are",
"allowed",
"for",
"the",
"given",
"model",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/managers.py#L7-L15 | train |
ic-labs/django-icekit | icekit/publishing/managers.py | _order_by_pks | def _order_by_pks(qs, pks):
"""
Adjust the given queryset to order items according to the explicit ordering
of PKs provided.
This is a PostgreSQL-specific DB hack, based on:
blog.mathieu-leplatre.info/django-create-a-queryset-from-a-list-preserving-order.html
"""
pk_colname = '%s.%s' % (
... | python | def _order_by_pks(qs, pks):
"""
Adjust the given queryset to order items according to the explicit ordering
of PKs provided.
This is a PostgreSQL-specific DB hack, based on:
blog.mathieu-leplatre.info/django-create-a-queryset-from-a-list-preserving-order.html
"""
pk_colname = '%s.%s' % (
... | [
"def",
"_order_by_pks",
"(",
"qs",
",",
"pks",
")",
":",
"pk_colname",
"=",
"'%s.%s'",
"%",
"(",
"qs",
".",
"model",
".",
"_meta",
".",
"db_table",
",",
"qs",
".",
"model",
".",
"_meta",
".",
"pk",
".",
"column",
")",
"clauses",
"=",
"' '",
".",
... | Adjust the given queryset to order items according to the explicit ordering
of PKs provided.
This is a PostgreSQL-specific DB hack, based on:
blog.mathieu-leplatre.info/django-create-a-queryset-from-a-list-preserving-order.html | [
"Adjust",
"the",
"given",
"queryset",
"to",
"order",
"items",
"according",
"to",
"the",
"explicit",
"ordering",
"of",
"PKs",
"provided",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/publishing/managers.py#L169-L185 | train |
ic-labs/django-icekit | icekit/publishing/managers.py | _queryset_iterator | def _queryset_iterator(qs):
"""
Override default iterator to wrap returned items in a publishing
sanity-checker "booby trap" to lazily raise an exception if DRAFT
items are mistakenly returned and mis-used in a public context
where only PUBLISHED items should be used.
This booby trap is added w... | python | def _queryset_iterator(qs):
"""
Override default iterator to wrap returned items in a publishing
sanity-checker "booby trap" to lazily raise an exception if DRAFT
items are mistakenly returned and mis-used in a public context
where only PUBLISHED items should be used.
This booby trap is added w... | [
"def",
"_queryset_iterator",
"(",
"qs",
")",
":",
"if",
"issubclass",
"(",
"type",
"(",
"qs",
")",
",",
"UrlNodeQuerySet",
")",
":",
"super_without_boobytrap_iterator",
"=",
"super",
"(",
"UrlNodeQuerySet",
",",
"qs",
")",
"else",
":",
"super_without_boobytrap_i... | Override default iterator to wrap returned items in a publishing
sanity-checker "booby trap" to lazily raise an exception if DRAFT
items are mistakenly returned and mis-used in a public context
where only PUBLISHED items should be used.
This booby trap is added when all of:
- the publishing middle... | [
"Override",
"default",
"iterator",
"to",
"wrap",
"returned",
"items",
"in",
"a",
"publishing",
"sanity",
"-",
"checker",
"booby",
"trap",
"to",
"lazily",
"raise",
"an",
"exception",
"if",
"DRAFT",
"items",
"are",
"mistakenly",
"returned",
"and",
"mis",
"-",
... | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/publishing/managers.py#L201-L233 | train |
ic-labs/django-icekit | icekit/publishing/managers.py | PublishingUrlNodeQuerySet.published | def published(self, for_user=UNSET, force_exchange=False):
"""
Apply additional filtering of published items over that done in
`PublishingQuerySet.published` to filter based on additional publising
date fields used by Fluent.
"""
if for_user is not UNSET:
retu... | python | def published(self, for_user=UNSET, force_exchange=False):
"""
Apply additional filtering of published items over that done in
`PublishingQuerySet.published` to filter based on additional publising
date fields used by Fluent.
"""
if for_user is not UNSET:
retu... | [
"def",
"published",
"(",
"self",
",",
"for_user",
"=",
"UNSET",
",",
"force_exchange",
"=",
"False",
")",
":",
"if",
"for_user",
"is",
"not",
"UNSET",
":",
"return",
"self",
".",
"visible",
"(",
")",
"queryset",
"=",
"super",
"(",
"PublishingUrlNodeQuerySe... | Apply additional filtering of published items over that done in
`PublishingQuerySet.published` to filter based on additional publising
date fields used by Fluent. | [
"Apply",
"additional",
"filtering",
"of",
"published",
"items",
"over",
"that",
"done",
"in",
"PublishingQuerySet",
".",
"published",
"to",
"filter",
"based",
"on",
"additional",
"publising",
"date",
"fields",
"used",
"by",
"Fluent",
"."
] | c507ea5b1864303732c53ad7c5800571fca5fa94 | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/publishing/managers.py#L342-L367 | train |
wikimedia/ores | ores/scoring_systems/celery_queue.py | redis_from_url | def redis_from_url(url):
"""
Converts a redis URL used by celery into a `redis.Redis` object.
"""
# Makes sure that we only try to import redis when we need
# to use it
import redis
url = url or ""
parsed_url = urlparse(url)
if parsed_url.scheme != "redis":
return None
... | python | def redis_from_url(url):
"""
Converts a redis URL used by celery into a `redis.Redis` object.
"""
# Makes sure that we only try to import redis when we need
# to use it
import redis
url = url or ""
parsed_url = urlparse(url)
if parsed_url.scheme != "redis":
return None
... | [
"def",
"redis_from_url",
"(",
"url",
")",
":",
"import",
"redis",
"url",
"=",
"url",
"or",
"\"\"",
"parsed_url",
"=",
"urlparse",
"(",
"url",
")",
"if",
"parsed_url",
".",
"scheme",
"!=",
"\"redis\"",
":",
"return",
"None",
"kwargs",
"=",
"{",
"}",
"ma... | Converts a redis URL used by celery into a `redis.Redis` object. | [
"Converts",
"a",
"redis",
"URL",
"used",
"by",
"celery",
"into",
"a",
"redis",
".",
"Redis",
"object",
"."
] | 75599b6ba0172c86d94f7f7e1e05a3c282333a18 | https://github.com/wikimedia/ores/blob/75599b6ba0172c86d94f7f7e1e05a3c282333a18/ores/scoring_systems/celery_queue.py#L263-L289 | train |
wikimedia/ores | ores/scoring_context.py | ScoringContext.process_model_scores | def process_model_scores(self, model_names, root_cache,
include_features=False):
"""
Generates a score map for a set of models based on a `root_cache`.
This method performs no substantial IO, but may incur substantial CPU
usage.
:Parameters:
... | python | def process_model_scores(self, model_names, root_cache,
include_features=False):
"""
Generates a score map for a set of models based on a `root_cache`.
This method performs no substantial IO, but may incur substantial CPU
usage.
:Parameters:
... | [
"def",
"process_model_scores",
"(",
"self",
",",
"model_names",
",",
"root_cache",
",",
"include_features",
"=",
"False",
")",
":",
"model_scores",
"=",
"{",
"}",
"for",
"model_name",
"in",
"model_names",
":",
"model_scores",
"[",
"model_name",
"]",
"=",
"{",
... | Generates a score map for a set of models based on a `root_cache`.
This method performs no substantial IO, but may incur substantial CPU
usage.
:Parameters:
model_names : `set` ( `str` )
A set of models to score
root_cache : `dict` ( `str` --> `mixed` )
... | [
"Generates",
"a",
"score",
"map",
"for",
"a",
"set",
"of",
"models",
"based",
"on",
"a",
"root_cache",
".",
"This",
"method",
"performs",
"no",
"substantial",
"IO",
"but",
"may",
"incur",
"substantial",
"CPU",
"usage",
"."
] | 75599b6ba0172c86d94f7f7e1e05a3c282333a18 | https://github.com/wikimedia/ores/blob/75599b6ba0172c86d94f7f7e1e05a3c282333a18/ores/scoring_context.py#L61-L93 | train |
wikimedia/ores | ores/scoring_context.py | ScoringContext._process_score | def _process_score(self, model_name, dependency_cache=None):
"""
Generates a score for a given model using the `dependency_cache`.
"""
version = self[model_name].version
start = time.time()
feature_values = self._solve_features(model_name, dependency_cache)
logge... | python | def _process_score(self, model_name, dependency_cache=None):
"""
Generates a score for a given model using the `dependency_cache`.
"""
version = self[model_name].version
start = time.time()
feature_values = self._solve_features(model_name, dependency_cache)
logge... | [
"def",
"_process_score",
"(",
"self",
",",
"model_name",
",",
"dependency_cache",
"=",
"None",
")",
":",
"version",
"=",
"self",
"[",
"model_name",
"]",
".",
"version",
"start",
"=",
"time",
".",
"time",
"(",
")",
"feature_values",
"=",
"self",
".",
"_so... | Generates a score for a given model using the `dependency_cache`. | [
"Generates",
"a",
"score",
"for",
"a",
"given",
"model",
"using",
"the",
"dependency_cache",
"."
] | 75599b6ba0172c86d94f7f7e1e05a3c282333a18 | https://github.com/wikimedia/ores/blob/75599b6ba0172c86d94f7f7e1e05a3c282333a18/ores/scoring_context.py#L114-L132 | train |
wikimedia/ores | ores/scoring_context.py | ScoringContext.map_from_config | def map_from_config(cls, config, context_names,
section_key="scoring_contexts"):
"""
Loads a whole set of ScoringContext's from a configuration file
while maintaining a cache of model names. This aids in better memory
management and allows model aliases to be imp... | python | def map_from_config(cls, config, context_names,
section_key="scoring_contexts"):
"""
Loads a whole set of ScoringContext's from a configuration file
while maintaining a cache of model names. This aids in better memory
management and allows model aliases to be imp... | [
"def",
"map_from_config",
"(",
"cls",
",",
"config",
",",
"context_names",
",",
"section_key",
"=",
"\"scoring_contexts\"",
")",
":",
"model_key_map",
"=",
"{",
"}",
"context_map",
"=",
"{",
"}",
"for",
"context_name",
"in",
"context_names",
":",
"section",
"=... | Loads a whole set of ScoringContext's from a configuration file
while maintaining a cache of model names. This aids in better memory
management and allows model aliases to be implemented at the
configuration level.
:Returns:
A map of context_names and ScoringContext's where... | [
"Loads",
"a",
"whole",
"set",
"of",
"ScoringContext",
"s",
"from",
"a",
"configuration",
"file",
"while",
"maintaining",
"a",
"cache",
"of",
"model",
"names",
".",
"This",
"aids",
"in",
"better",
"memory",
"management",
"and",
"allows",
"model",
"aliases",
"... | 75599b6ba0172c86d94f7f7e1e05a3c282333a18 | https://github.com/wikimedia/ores/blob/75599b6ba0172c86d94f7f7e1e05a3c282333a18/ores/scoring_context.py#L186-L216 | train |
wikimedia/ores | ores/wsgi/util.py | build_event_set | def build_event_set(event):
"""
Turn an EventStream event into a set of event types that ORES
uses internally.
"""
event_set = set()
if re.match(r"([^\.]+.)?mediawiki\.revision-create$",
event['meta']['topic']):
event_set.add('edit')
user_groups = event.get('perf... | python | def build_event_set(event):
"""
Turn an EventStream event into a set of event types that ORES
uses internally.
"""
event_set = set()
if re.match(r"([^\.]+.)?mediawiki\.revision-create$",
event['meta']['topic']):
event_set.add('edit')
user_groups = event.get('perf... | [
"def",
"build_event_set",
"(",
"event",
")",
":",
"event_set",
"=",
"set",
"(",
")",
"if",
"re",
".",
"match",
"(",
"r\"([^\\.]+.)?mediawiki\\.revision-create$\"",
",",
"event",
"[",
"'meta'",
"]",
"[",
"'topic'",
"]",
")",
":",
"event_set",
".",
"add",
"(... | Turn an EventStream event into a set of event types that ORES
uses internally. | [
"Turn",
"an",
"EventStream",
"event",
"into",
"a",
"set",
"of",
"event",
"types",
"that",
"ORES",
"uses",
"internally",
"."
] | 75599b6ba0172c86d94f7f7e1e05a3c282333a18 | https://github.com/wikimedia/ores/blob/75599b6ba0172c86d94f7f7e1e05a3c282333a18/ores/wsgi/util.py#L179-L202 | train |
wikimedia/ores | ores/wsgi/util.py | build_precache_map | def build_precache_map(config):
"""
Build a mapping of contexts and models from the configuration
"""
precache_map = {}
ss_name = config['ores']['scoring_system']
for context in config['scoring_systems'][ss_name]['scoring_contexts']:
precache_map[context] = {}
for model in config... | python | def build_precache_map(config):
"""
Build a mapping of contexts and models from the configuration
"""
precache_map = {}
ss_name = config['ores']['scoring_system']
for context in config['scoring_systems'][ss_name]['scoring_contexts']:
precache_map[context] = {}
for model in config... | [
"def",
"build_precache_map",
"(",
"config",
")",
":",
"precache_map",
"=",
"{",
"}",
"ss_name",
"=",
"config",
"[",
"'ores'",
"]",
"[",
"'scoring_system'",
"]",
"for",
"context",
"in",
"config",
"[",
"'scoring_systems'",
"]",
"[",
"ss_name",
"]",
"[",
"'sc... | Build a mapping of contexts and models from the configuration | [
"Build",
"a",
"mapping",
"of",
"contexts",
"and",
"models",
"from",
"the",
"configuration"
] | 75599b6ba0172c86d94f7f7e1e05a3c282333a18 | https://github.com/wikimedia/ores/blob/75599b6ba0172c86d94f7f7e1e05a3c282333a18/ores/wsgi/util.py#L209-L233 | train |
wikimedia/ores | ores/scoring/models/rev_id_scorer.py | RevIdScorer.calculate_statistics | def calculate_statistics(self):
"Jam some data through to generate statistics"
rev_ids = range(0, 100, 1)
feature_values = zip(rev_ids, [0] * 100)
scores = [self.score(f) for f in feature_values]
labels = [s['prediction'] for s in scores]
statistics = Classification(label... | python | def calculate_statistics(self):
"Jam some data through to generate statistics"
rev_ids = range(0, 100, 1)
feature_values = zip(rev_ids, [0] * 100)
scores = [self.score(f) for f in feature_values]
labels = [s['prediction'] for s in scores]
statistics = Classification(label... | [
"def",
"calculate_statistics",
"(",
"self",
")",
":",
"\"Jam some data through to generate statistics\"",
"rev_ids",
"=",
"range",
"(",
"0",
",",
"100",
",",
"1",
")",
"feature_values",
"=",
"zip",
"(",
"rev_ids",
",",
"[",
"0",
"]",
"*",
"100",
")",
"scores... | Jam some data through to generate statistics | [
"Jam",
"some",
"data",
"through",
"to",
"generate",
"statistics"
] | 75599b6ba0172c86d94f7f7e1e05a3c282333a18 | https://github.com/wikimedia/ores/blob/75599b6ba0172c86d94f7f7e1e05a3c282333a18/ores/scoring/models/rev_id_scorer.py#L67-L76 | train |
openclimatedata/pyhector | pyhector/__init__.py | read_hector_input | def read_hector_input(csv_file):
"""
Reads a Hector CSV file and returns it as a Pandas DataFrame.
"""
df = pd.read_csv(csv_file, skiprows=3, index_col=0)
df.name = os.path.splitext(os.path.basename(csv_file))[0]
return df | python | def read_hector_input(csv_file):
"""
Reads a Hector CSV file and returns it as a Pandas DataFrame.
"""
df = pd.read_csv(csv_file, skiprows=3, index_col=0)
df.name = os.path.splitext(os.path.basename(csv_file))[0]
return df | [
"def",
"read_hector_input",
"(",
"csv_file",
")",
":",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"csv_file",
",",
"skiprows",
"=",
"3",
",",
"index_col",
"=",
"0",
")",
"df",
".",
"name",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path"... | Reads a Hector CSV file and returns it as a Pandas DataFrame. | [
"Reads",
"a",
"Hector",
"CSV",
"file",
"and",
"returns",
"it",
"as",
"a",
"Pandas",
"DataFrame",
"."
] | 1649efcc0ed19dc66d8de8dec7a5105fa08df01a | https://github.com/openclimatedata/pyhector/blob/1649efcc0ed19dc66d8de8dec7a5105fa08df01a/pyhector/__init__.py#L97-L103 | train |
openclimatedata/pyhector | pyhector/__init__.py | write_hector_input | def write_hector_input(scenario, path=None):
"""
Writes a scenario DataFrame to a CSV emissions file as used in Hector.
Parameters
----------
scenario : DataFrame
DataFrame with emissions.
path: file-like object or path
Returns
-------
out : str
If no path is given ... | python | def write_hector_input(scenario, path=None):
"""
Writes a scenario DataFrame to a CSV emissions file as used in Hector.
Parameters
----------
scenario : DataFrame
DataFrame with emissions.
path: file-like object or path
Returns
-------
out : str
If no path is given ... | [
"def",
"write_hector_input",
"(",
"scenario",
",",
"path",
"=",
"None",
")",
":",
"out",
"=",
"\"\"",
"try",
":",
"name",
"=",
"\"; \"",
"+",
"scenario",
".",
"name",
"+",
"\"\\n\"",
"except",
"AttributeError",
":",
"name",
"=",
"\"; Hector Scenario\\n\"",
... | Writes a scenario DataFrame to a CSV emissions file as used in Hector.
Parameters
----------
scenario : DataFrame
DataFrame with emissions.
path: file-like object or path
Returns
-------
out : str
If no path is given a String of the output is returned. | [
"Writes",
"a",
"scenario",
"DataFrame",
"to",
"a",
"CSV",
"emissions",
"file",
"as",
"used",
"in",
"Hector",
"."
] | 1649efcc0ed19dc66d8de8dec7a5105fa08df01a | https://github.com/openclimatedata/pyhector/blob/1649efcc0ed19dc66d8de8dec7a5105fa08df01a/pyhector/__init__.py#L106-L149 | train |
openclimatedata/pyhector | pyhector/__init__.py | read_hector_constraint | def read_hector_constraint(constraint_file):
"""
Reads a Hector contraint CSV file and returns it as a Pandas Series
"""
df = pd.read_csv(constraint_file, index_col=0, comment=";")
df = df[df.applymap(lambda x: isinstance(x, (int, float)))]
df.index = df.index.astype(int)
return df.iloc[:, 0... | python | def read_hector_constraint(constraint_file):
"""
Reads a Hector contraint CSV file and returns it as a Pandas Series
"""
df = pd.read_csv(constraint_file, index_col=0, comment=";")
df = df[df.applymap(lambda x: isinstance(x, (int, float)))]
df.index = df.index.astype(int)
return df.iloc[:, 0... | [
"def",
"read_hector_constraint",
"(",
"constraint_file",
")",
":",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"constraint_file",
",",
"index_col",
"=",
"0",
",",
"comment",
"=",
"\";\"",
")",
"df",
"=",
"df",
"[",
"df",
".",
"applymap",
"(",
"lambda",
"x",
... | Reads a Hector contraint CSV file and returns it as a Pandas Series | [
"Reads",
"a",
"Hector",
"contraint",
"CSV",
"file",
"and",
"returns",
"it",
"as",
"a",
"Pandas",
"Series"
] | 1649efcc0ed19dc66d8de8dec7a5105fa08df01a | https://github.com/openclimatedata/pyhector/blob/1649efcc0ed19dc66d8de8dec7a5105fa08df01a/pyhector/__init__.py#L152-L159 | train |
openclimatedata/pyhector | pyhector/__init__.py | read_hector_output | def read_hector_output(csv_file):
"""
Reads a Hector output stream CSV file and returns a wide DataFrame with
Hector output data.
"""
# Filter out spin-up values. In Hector 1.x RCP output streams years are
# given as end of simulation year.
# See https://github.com/JGCRI/hector/issues/177
... | python | def read_hector_output(csv_file):
"""
Reads a Hector output stream CSV file and returns a wide DataFrame with
Hector output data.
"""
# Filter out spin-up values. In Hector 1.x RCP output streams years are
# given as end of simulation year.
# See https://github.com/JGCRI/hector/issues/177
... | [
"def",
"read_hector_output",
"(",
"csv_file",
")",
":",
"start_year",
"=",
"1746",
"output_stream",
"=",
"pd",
".",
"read_csv",
"(",
"csv_file",
",",
"skiprows",
"=",
"1",
")",
"wide",
"=",
"output_stream",
"[",
"output_stream",
".",
"year",
">=",
"start_yea... | Reads a Hector output stream CSV file and returns a wide DataFrame with
Hector output data. | [
"Reads",
"a",
"Hector",
"output",
"stream",
"CSV",
"file",
"and",
"returns",
"a",
"wide",
"DataFrame",
"with",
"Hector",
"output",
"data",
"."
] | 1649efcc0ed19dc66d8de8dec7a5105fa08df01a | https://github.com/openclimatedata/pyhector/blob/1649efcc0ed19dc66d8de8dec7a5105fa08df01a/pyhector/__init__.py#L162-L177 | train |
openclimatedata/pyhector | pyhector/__init__.py | run | def run(scenario, config=None, base_config=None, outputs=None, return_config=False):
"""
Runs a scenario through the Hector climate model.
Parameters
----------
scenario : DataFrame
DataFrame with emissions. See ``pyhector.rcp26`` for an
example and :mod:`pyhector.units` for units o... | python | def run(scenario, config=None, base_config=None, outputs=None, return_config=False):
"""
Runs a scenario through the Hector climate model.
Parameters
----------
scenario : DataFrame
DataFrame with emissions. See ``pyhector.rcp26`` for an
example and :mod:`pyhector.units` for units o... | [
"def",
"run",
"(",
"scenario",
",",
"config",
"=",
"None",
",",
"base_config",
"=",
"None",
",",
"outputs",
"=",
"None",
",",
"return_config",
"=",
"False",
")",
":",
"if",
"outputs",
"is",
"None",
":",
"outputs",
"=",
"[",
"\"temperature.Tgav\"",
",",
... | Runs a scenario through the Hector climate model.
Parameters
----------
scenario : DataFrame
DataFrame with emissions. See ``pyhector.rcp26`` for an
example and :mod:`pyhector.units` for units of emissions values.
config : dictionary, default ``None``
Additional config options t... | [
"Runs",
"a",
"scenario",
"through",
"the",
"Hector",
"climate",
"model",
"."
] | 1649efcc0ed19dc66d8de8dec7a5105fa08df01a | https://github.com/openclimatedata/pyhector/blob/1649efcc0ed19dc66d8de8dec7a5105fa08df01a/pyhector/__init__.py#L195-L265 | train |
openclimatedata/pyhector | pyhector/__init__.py | Hector.config | def config(self, config):
"""Set config values from config dictionary."""
for section, data in config.items():
for variable, value in data.items():
self.set_value(section, variable, value) | python | def config(self, config):
"""Set config values from config dictionary."""
for section, data in config.items():
for variable, value in data.items():
self.set_value(section, variable, value) | [
"def",
"config",
"(",
"self",
",",
"config",
")",
":",
"for",
"section",
",",
"data",
"in",
"config",
".",
"items",
"(",
")",
":",
"for",
"variable",
",",
"value",
"in",
"data",
".",
"items",
"(",
")",
":",
"self",
".",
"set_value",
"(",
"section",... | Set config values from config dictionary. | [
"Set",
"config",
"values",
"from",
"config",
"dictionary",
"."
] | 1649efcc0ed19dc66d8de8dec7a5105fa08df01a | https://github.com/openclimatedata/pyhector/blob/1649efcc0ed19dc66d8de8dec7a5105fa08df01a/pyhector/__init__.py#L80-L84 | train |
openclimatedata/pyhector | pyhector/__init__.py | Hector.set_emissions | def set_emissions(self, scenario):
"""Set emissions from Pandas DataFrame."""
for section in emissions:
for source in emissions[section]:
if source not in scenario.columns:
continue
self._set_timed_array(
section, source... | python | def set_emissions(self, scenario):
"""Set emissions from Pandas DataFrame."""
for section in emissions:
for source in emissions[section]:
if source not in scenario.columns:
continue
self._set_timed_array(
section, source... | [
"def",
"set_emissions",
"(",
"self",
",",
"scenario",
")",
":",
"for",
"section",
"in",
"emissions",
":",
"for",
"source",
"in",
"emissions",
"[",
"section",
"]",
":",
"if",
"source",
"not",
"in",
"scenario",
".",
"columns",
":",
"continue",
"self",
".",... | Set emissions from Pandas DataFrame. | [
"Set",
"emissions",
"from",
"Pandas",
"DataFrame",
"."
] | 1649efcc0ed19dc66d8de8dec7a5105fa08df01a | https://github.com/openclimatedata/pyhector/blob/1649efcc0ed19dc66d8de8dec7a5105fa08df01a/pyhector/__init__.py#L86-L94 | train |
wikimedia/ores | setup.py | requirements | def requirements(fname):
"""
Generator to parse requirements.txt file
Supports bits of extended pip format (git urls)
"""
with open(fname) as f:
for line in f:
match = re.search('#egg=(.*)$', line)
if match:
yield match.groups()[0]
else:
... | python | def requirements(fname):
"""
Generator to parse requirements.txt file
Supports bits of extended pip format (git urls)
"""
with open(fname) as f:
for line in f:
match = re.search('#egg=(.*)$', line)
if match:
yield match.groups()[0]
else:
... | [
"def",
"requirements",
"(",
"fname",
")",
":",
"with",
"open",
"(",
"fname",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"match",
"=",
"re",
".",
"search",
"(",
"'#egg=(.*)$'",
",",
"line",
")",
"if",
"match",
":",
"yield",
"match",
".",
... | Generator to parse requirements.txt file
Supports bits of extended pip format (git urls) | [
"Generator",
"to",
"parse",
"requirements",
".",
"txt",
"file"
] | 75599b6ba0172c86d94f7f7e1e05a3c282333a18 | https://github.com/wikimedia/ores/blob/75599b6ba0172c86d94f7f7e1e05a3c282333a18/setup.py#L20-L32 | train |
wikimedia/ores | ores/api.py | Session.score | def score(self, context, models, revids):
"""
Genetate scores for model applied to a sequence of revisions.
:Parameters:
context : str
The name of the context -- usually the database name of a wiki
models : `iterable`
The names of a models... | python | def score(self, context, models, revids):
"""
Genetate scores for model applied to a sequence of revisions.
:Parameters:
context : str
The name of the context -- usually the database name of a wiki
models : `iterable`
The names of a models... | [
"def",
"score",
"(",
"self",
",",
"context",
",",
"models",
",",
"revids",
")",
":",
"if",
"isinstance",
"(",
"revids",
",",
"int",
")",
":",
"rev_ids",
"=",
"[",
"revids",
"]",
"else",
":",
"rev_ids",
"=",
"[",
"int",
"(",
"rid",
")",
"for",
"ri... | Genetate scores for model applied to a sequence of revisions.
:Parameters:
context : str
The name of the context -- usually the database name of a wiki
models : `iterable`
The names of a models to apply
revids : `iterable`
A se... | [
"Genetate",
"scores",
"for",
"model",
"applied",
"to",
"a",
"sequence",
"of",
"revisions",
"."
] | 75599b6ba0172c86d94f7f7e1e05a3c282333a18 | https://github.com/wikimedia/ores/blob/75599b6ba0172c86d94f7f7e1e05a3c282333a18/ores/api.py#L68-L85 | train |
mattjj/pybasicbayes | examples/factor_analysis.py | principal_angle | def principal_angle(A,B):
"""
Find the principal angle between two subspaces
spanned by columns of A and B
"""
from numpy.linalg import qr, svd
qA, _ = qr(A)
qB, _ = qr(B)
U,S,V = svd(qA.T.dot(qB))
return np.arccos(min(S.min(), 1.0)) | python | def principal_angle(A,B):
"""
Find the principal angle between two subspaces
spanned by columns of A and B
"""
from numpy.linalg import qr, svd
qA, _ = qr(A)
qB, _ = qr(B)
U,S,V = svd(qA.T.dot(qB))
return np.arccos(min(S.min(), 1.0)) | [
"def",
"principal_angle",
"(",
"A",
",",
"B",
")",
":",
"from",
"numpy",
".",
"linalg",
"import",
"qr",
",",
"svd",
"qA",
",",
"_",
"=",
"qr",
"(",
"A",
")",
"qB",
",",
"_",
"=",
"qr",
"(",
"B",
")",
"U",
",",
"S",
",",
"V",
"=",
"svd",
"... | Find the principal angle between two subspaces
spanned by columns of A and B | [
"Find",
"the",
"principal",
"angle",
"between",
"two",
"subspaces",
"spanned",
"by",
"columns",
"of",
"A",
"and",
"B"
] | 76aef00f011415cc5c858cd1a101f3aab971a62d | https://github.com/mattjj/pybasicbayes/blob/76aef00f011415cc5c858cd1a101f3aab971a62d/examples/factor_analysis.py#L15-L24 | train |
mattjj/pybasicbayes | pybasicbayes/distributions/regression.py | DiagonalRegression.resample | def resample(self, data, stats=None, mask=None, niter=None):
"""
Introduce a mask that allows for missing data
"""
stats = self._get_statistics(data, mask=mask) if stats is None else stats
stats = self._stats_ensure_array(stats)
niter = niter if niter else self.niter
... | python | def resample(self, data, stats=None, mask=None, niter=None):
"""
Introduce a mask that allows for missing data
"""
stats = self._get_statistics(data, mask=mask) if stats is None else stats
stats = self._stats_ensure_array(stats)
niter = niter if niter else self.niter
... | [
"def",
"resample",
"(",
"self",
",",
"data",
",",
"stats",
"=",
"None",
",",
"mask",
"=",
"None",
",",
"niter",
"=",
"None",
")",
":",
"stats",
"=",
"self",
".",
"_get_statistics",
"(",
"data",
",",
"mask",
"=",
"mask",
")",
"if",
"stats",
"is",
... | Introduce a mask that allows for missing data | [
"Introduce",
"a",
"mask",
"that",
"allows",
"for",
"missing",
"data"
] | 76aef00f011415cc5c858cd1a101f3aab971a62d | https://github.com/mattjj/pybasicbayes/blob/76aef00f011415cc5c858cd1a101f3aab971a62d/pybasicbayes/distributions/regression.py#L734-L744 | train |
mattjj/pybasicbayes | pybasicbayes/util/stats.py | sample_truncated_gaussian | def sample_truncated_gaussian(mu=0, sigma=1, lb=-np.Inf, ub=np.Inf):
"""
Sample a truncated normal with the specified params. This
is not the most stable way but it works as long as the
truncation region is not too far from the mean.
"""
# Broadcast arrays to be of the same shape
mu, sigma, ... | python | def sample_truncated_gaussian(mu=0, sigma=1, lb=-np.Inf, ub=np.Inf):
"""
Sample a truncated normal with the specified params. This
is not the most stable way but it works as long as the
truncation region is not too far from the mean.
"""
# Broadcast arrays to be of the same shape
mu, sigma, ... | [
"def",
"sample_truncated_gaussian",
"(",
"mu",
"=",
"0",
",",
"sigma",
"=",
"1",
",",
"lb",
"=",
"-",
"np",
".",
"Inf",
",",
"ub",
"=",
"np",
".",
"Inf",
")",
":",
"mu",
",",
"sigma",
",",
"lb",
",",
"ub",
"=",
"np",
".",
"broadcast_arrays",
"(... | Sample a truncated normal with the specified params. This
is not the most stable way but it works as long as the
truncation region is not too far from the mean. | [
"Sample",
"a",
"truncated",
"normal",
"with",
"the",
"specified",
"params",
".",
"This",
"is",
"not",
"the",
"most",
"stable",
"way",
"but",
"it",
"works",
"as",
"long",
"as",
"the",
"truncation",
"region",
"is",
"not",
"too",
"far",
"from",
"the",
"mean... | 76aef00f011415cc5c858cd1a101f3aab971a62d | https://github.com/mattjj/pybasicbayes/blob/76aef00f011415cc5c858cd1a101f3aab971a62d/pybasicbayes/util/stats.py#L124-L150 | train |
mattjj/pybasicbayes | pybasicbayes/models/mixture.py | CRPMixture.log_likelihood | def log_likelihood(self,x, K_extra=1):
"""
Estimate the log likelihood with samples from
the model. Draw k_extra components which were not populated by
the current model in order to create a truncated approximate
mixture model.
"""
x = np.asarray(x)
ks ... | python | def log_likelihood(self,x, K_extra=1):
"""
Estimate the log likelihood with samples from
the model. Draw k_extra components which were not populated by
the current model in order to create a truncated approximate
mixture model.
"""
x = np.asarray(x)
ks ... | [
"def",
"log_likelihood",
"(",
"self",
",",
"x",
",",
"K_extra",
"=",
"1",
")",
":",
"x",
"=",
"np",
".",
"asarray",
"(",
"x",
")",
"ks",
"=",
"self",
".",
"_get_occupied",
"(",
")",
"K",
"=",
"len",
"(",
"ks",
")",
"K_total",
"=",
"K",
"+",
"... | Estimate the log likelihood with samples from
the model. Draw k_extra components which were not populated by
the current model in order to create a truncated approximate
mixture model. | [
"Estimate",
"the",
"log",
"likelihood",
"with",
"samples",
"from",
"the",
"model",
".",
"Draw",
"k_extra",
"components",
"which",
"were",
"not",
"populated",
"by",
"the",
"current",
"model",
"in",
"order",
"to",
"create",
"a",
"truncated",
"approximate",
"mixt... | 76aef00f011415cc5c858cd1a101f3aab971a62d | https://github.com/mattjj/pybasicbayes/blob/76aef00f011415cc5c858cd1a101f3aab971a62d/pybasicbayes/models/mixture.py#L801-L841 | train |
closeio/redis-hashring | redis_hashring/__init__.py | RingNode.debug_print | def debug_print(self):
"""
Prints the ring for debugging purposes.
"""
ring = self._fetch_all()
print('Hash ring "{key}" replicas:'.format(key=self.key))
now = time.time()
n_replicas = len(ring)
if ring:
print('{:10} {:6} {:7} {}'.format('St... | python | def debug_print(self):
"""
Prints the ring for debugging purposes.
"""
ring = self._fetch_all()
print('Hash ring "{key}" replicas:'.format(key=self.key))
now = time.time()
n_replicas = len(ring)
if ring:
print('{:10} {:6} {:7} {}'.format('St... | [
"def",
"debug_print",
"(",
"self",
")",
":",
"ring",
"=",
"self",
".",
"_fetch_all",
"(",
")",
"print",
"(",
"'Hash ring \"{key}\" replicas:'",
".",
"format",
"(",
"key",
"=",
"self",
".",
"key",
")",
")",
"now",
"=",
"time",
".",
"time",
"(",
")",
"... | Prints the ring for debugging purposes. | [
"Prints",
"the",
"ring",
"for",
"debugging",
"purposes",
"."
] | d767018571fbfb5705b6115d81619b2e84b6e50e | https://github.com/closeio/redis-hashring/blob/d767018571fbfb5705b6115d81619b2e84b6e50e/redis_hashring/__init__.py#L135-L194 | train |
closeio/redis-hashring | redis_hashring/__init__.py | RingNode.update | def update(self):
"""
Fetches the updated ring from Redis and updates the current ranges.
"""
ring = self._fetch()
n_replicas = len(ring)
replica_set = set([r[1] for r in self.replicas])
self.ranges = []
for n, (start, replica) in enumerate(ring):
... | python | def update(self):
"""
Fetches the updated ring from Redis and updates the current ranges.
"""
ring = self._fetch()
n_replicas = len(ring)
replica_set = set([r[1] for r in self.replicas])
self.ranges = []
for n, (start, replica) in enumerate(ring):
... | [
"def",
"update",
"(",
"self",
")",
":",
"ring",
"=",
"self",
".",
"_fetch",
"(",
")",
"n_replicas",
"=",
"len",
"(",
"ring",
")",
"replica_set",
"=",
"set",
"(",
"[",
"r",
"[",
"1",
"]",
"for",
"r",
"in",
"self",
".",
"replicas",
"]",
")",
"sel... | Fetches the updated ring from Redis and updates the current ranges. | [
"Fetches",
"the",
"updated",
"ring",
"from",
"Redis",
"and",
"updates",
"the",
"current",
"ranges",
"."
] | d767018571fbfb5705b6115d81619b2e84b6e50e | https://github.com/closeio/redis-hashring/blob/d767018571fbfb5705b6115d81619b2e84b6e50e/redis_hashring/__init__.py#L244-L261 | train |
closeio/redis-hashring | redis_hashring/__init__.py | RingNode.contains | def contains(self, key):
"""
Returns a boolean indicating if this node is responsible for handling
the given key.
"""
n = binascii.crc32(key.encode()) % RING_SIZE
for start, end in self.ranges:
if start <= n < end:
return True
return Fa... | python | def contains(self, key):
"""
Returns a boolean indicating if this node is responsible for handling
the given key.
"""
n = binascii.crc32(key.encode()) % RING_SIZE
for start, end in self.ranges:
if start <= n < end:
return True
return Fa... | [
"def",
"contains",
"(",
"self",
",",
"key",
")",
":",
"n",
"=",
"binascii",
".",
"crc32",
"(",
"key",
".",
"encode",
"(",
")",
")",
"%",
"RING_SIZE",
"for",
"start",
",",
"end",
"in",
"self",
".",
"ranges",
":",
"if",
"start",
"<=",
"n",
"<",
"... | Returns a boolean indicating if this node is responsible for handling
the given key. | [
"Returns",
"a",
"boolean",
"indicating",
"if",
"this",
"node",
"is",
"responsible",
"for",
"handling",
"the",
"given",
"key",
"."
] | d767018571fbfb5705b6115d81619b2e84b6e50e | https://github.com/closeio/redis-hashring/blob/d767018571fbfb5705b6115d81619b2e84b6e50e/redis_hashring/__init__.py#L263-L272 | train |
closeio/redis-hashring | redis_hashring/__init__.py | RingNode.gevent_start | def gevent_start(self):
"""
Helper method to start the node for gevent-based applications.
"""
import gevent
import gevent.select
self._poller_greenlet = gevent.spawn(self.poll)
self._select = gevent.select.select
self.heartbeat()
self.update() | python | def gevent_start(self):
"""
Helper method to start the node for gevent-based applications.
"""
import gevent
import gevent.select
self._poller_greenlet = gevent.spawn(self.poll)
self._select = gevent.select.select
self.heartbeat()
self.update() | [
"def",
"gevent_start",
"(",
"self",
")",
":",
"import",
"gevent",
"import",
"gevent",
".",
"select",
"self",
".",
"_poller_greenlet",
"=",
"gevent",
".",
"spawn",
"(",
"self",
".",
"poll",
")",
"self",
".",
"_select",
"=",
"gevent",
".",
"select",
".",
... | Helper method to start the node for gevent-based applications. | [
"Helper",
"method",
"to",
"start",
"the",
"node",
"for",
"gevent",
"-",
"based",
"applications",
"."
] | d767018571fbfb5705b6115d81619b2e84b6e50e | https://github.com/closeio/redis-hashring/blob/d767018571fbfb5705b6115d81619b2e84b6e50e/redis_hashring/__init__.py#L317-L326 | train |
closeio/redis-hashring | redis_hashring/__init__.py | RingNode.gevent_stop | def gevent_stop(self):
"""
Helper method to stop the node for gevent-based applications.
"""
import gevent
gevent.kill(self._poller_greenlet)
self.remove()
self._select = select.select | python | def gevent_stop(self):
"""
Helper method to stop the node for gevent-based applications.
"""
import gevent
gevent.kill(self._poller_greenlet)
self.remove()
self._select = select.select | [
"def",
"gevent_stop",
"(",
"self",
")",
":",
"import",
"gevent",
"gevent",
".",
"kill",
"(",
"self",
".",
"_poller_greenlet",
")",
"self",
".",
"remove",
"(",
")",
"self",
".",
"_select",
"=",
"select",
".",
"select"
] | Helper method to stop the node for gevent-based applications. | [
"Helper",
"method",
"to",
"stop",
"the",
"node",
"for",
"gevent",
"-",
"based",
"applications",
"."
] | d767018571fbfb5705b6115d81619b2e84b6e50e | https://github.com/closeio/redis-hashring/blob/d767018571fbfb5705b6115d81619b2e84b6e50e/redis_hashring/__init__.py#L328-L335 | train |
pepkit/peppy | peppy/project.py | suggest_implied_attributes | def suggest_implied_attributes(prj):
"""
If given project contains what could be implied attributes, suggest that.
:param Iterable prj: Intent is a Project, but this could be any iterable
of strings to check for suitability of declaration as implied attr
:return list[str]: (likely empty) list o... | python | def suggest_implied_attributes(prj):
"""
If given project contains what could be implied attributes, suggest that.
:param Iterable prj: Intent is a Project, but this could be any iterable
of strings to check for suitability of declaration as implied attr
:return list[str]: (likely empty) list o... | [
"def",
"suggest_implied_attributes",
"(",
"prj",
")",
":",
"def",
"suggest",
"(",
"key",
")",
":",
"return",
"\"To declare {}, consider using {}\"",
".",
"format",
"(",
"key",
",",
"IMPLICATIONS_DECLARATION",
")",
"return",
"[",
"suggest",
"(",
"k",
")",
"for",
... | If given project contains what could be implied attributes, suggest that.
:param Iterable prj: Intent is a Project, but this could be any iterable
of strings to check for suitability of declaration as implied attr
:return list[str]: (likely empty) list of warning messages about project
config k... | [
"If",
"given",
"project",
"contains",
"what",
"could",
"be",
"implied",
"attributes",
"suggest",
"that",
"."
] | f0f725e1557936b81c86573a77400e6f8da78f05 | https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/project.py#L1068-L1080 | train |
pepkit/peppy | peppy/utils.py | check_bam | def check_bam(bam, o):
"""
Check reads in BAM file for read type and lengths.
:param str bam: BAM file path.
:param int o: Number of reads to look at for estimation.
"""
try:
p = sp.Popen(['samtools', 'view', bam], stdout=sp.PIPE)
# Count paired alignments
paired = 0
... | python | def check_bam(bam, o):
"""
Check reads in BAM file for read type and lengths.
:param str bam: BAM file path.
:param int o: Number of reads to look at for estimation.
"""
try:
p = sp.Popen(['samtools', 'view', bam], stdout=sp.PIPE)
# Count paired alignments
paired = 0
... | [
"def",
"check_bam",
"(",
"bam",
",",
"o",
")",
":",
"try",
":",
"p",
"=",
"sp",
".",
"Popen",
"(",
"[",
"'samtools'",
",",
"'view'",
",",
"bam",
"]",
",",
"stdout",
"=",
"sp",
".",
"PIPE",
")",
"paired",
"=",
"0",
"read_lengths",
"=",
"defaultdic... | Check reads in BAM file for read type and lengths.
:param str bam: BAM file path.
:param int o: Number of reads to look at for estimation. | [
"Check",
"reads",
"in",
"BAM",
"file",
"for",
"read",
"type",
"and",
"lengths",
"."
] | f0f725e1557936b81c86573a77400e6f8da78f05 | https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L62-L91 | train |
pepkit/peppy | peppy/utils.py | grab_project_data | def grab_project_data(prj):
"""
From the given Project, grab Sample-independent data.
There are some aspects of a Project of which it's beneficial for a Sample
to be aware, particularly for post-hoc analysis. Since Sample objects
within a Project are mutually independent, though, each doesn't need ... | python | def grab_project_data(prj):
"""
From the given Project, grab Sample-independent data.
There are some aspects of a Project of which it's beneficial for a Sample
to be aware, particularly for post-hoc analysis. Since Sample objects
within a Project are mutually independent, though, each doesn't need ... | [
"def",
"grab_project_data",
"(",
"prj",
")",
":",
"if",
"not",
"prj",
":",
"return",
"{",
"}",
"data",
"=",
"{",
"}",
"for",
"section",
"in",
"SAMPLE_INDEPENDENT_PROJECT_SECTIONS",
":",
"try",
":",
"data",
"[",
"section",
"]",
"=",
"getattr",
"(",
"prj",... | From the given Project, grab Sample-independent data.
There are some aspects of a Project of which it's beneficial for a Sample
to be aware, particularly for post-hoc analysis. Since Sample objects
within a Project are mutually independent, though, each doesn't need to
know about any of the others. A P... | [
"From",
"the",
"given",
"Project",
"grab",
"Sample",
"-",
"independent",
"data",
"."
] | f0f725e1557936b81c86573a77400e6f8da78f05 | https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L214-L236 | train |
pepkit/peppy | peppy/utils.py | import_from_source | def import_from_source(module_filepath):
"""
Import a module from a particular filesystem location.
:param str module_filepath: path to the file that constitutes the module
to import
:return module: module imported from the given location, named as indicated
:raises ValueError: if path prov... | python | def import_from_source(module_filepath):
"""
Import a module from a particular filesystem location.
:param str module_filepath: path to the file that constitutes the module
to import
:return module: module imported from the given location, named as indicated
:raises ValueError: if path prov... | [
"def",
"import_from_source",
"(",
"module_filepath",
")",
":",
"import",
"sys",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"module_filepath",
")",
":",
"raise",
"ValueError",
"(",
"\"Path to alleged module file doesn't point to an \"",
"\"extant file: '{}'\"",
... | Import a module from a particular filesystem location.
:param str module_filepath: path to the file that constitutes the module
to import
:return module: module imported from the given location, named as indicated
:raises ValueError: if path provided does not point to an extant file | [
"Import",
"a",
"module",
"from",
"a",
"particular",
"filesystem",
"location",
"."
] | f0f725e1557936b81c86573a77400e6f8da78f05 | https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L250-L285 | train |
pepkit/peppy | peppy/utils.py | infer_delimiter | def infer_delimiter(filepath):
"""
From extension infer delimiter used in a separated values file.
:param str filepath: path to file about which to make inference
:return str | NoneType: extension if inference succeeded; else null
"""
ext = os.path.splitext(filepath)[1][1:].lower()
return {... | python | def infer_delimiter(filepath):
"""
From extension infer delimiter used in a separated values file.
:param str filepath: path to file about which to make inference
:return str | NoneType: extension if inference succeeded; else null
"""
ext = os.path.splitext(filepath)[1][1:].lower()
return {... | [
"def",
"infer_delimiter",
"(",
"filepath",
")",
":",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filepath",
")",
"[",
"1",
"]",
"[",
"1",
":",
"]",
".",
"lower",
"(",
")",
"return",
"{",
"\"txt\"",
":",
"\"\\t\"",
",",
"\"tsv\"",
":",
"... | From extension infer delimiter used in a separated values file.
:param str filepath: path to file about which to make inference
:return str | NoneType: extension if inference succeeded; else null | [
"From",
"extension",
"infer",
"delimiter",
"used",
"in",
"a",
"separated",
"values",
"file",
"."
] | f0f725e1557936b81c86573a77400e6f8da78f05 | https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L288-L296 | train |
pepkit/peppy | peppy/utils.py | is_null_like | def is_null_like(x):
"""
Determine whether an object is effectively null.
:param object x: Object for which null likeness is to be determined.
:return bool: Whether given object is effectively "null."
"""
return x in [None, ""] or \
(coll_like(x) and isinstance(x, Sized) and 0 == len(x)... | python | def is_null_like(x):
"""
Determine whether an object is effectively null.
:param object x: Object for which null likeness is to be determined.
:return bool: Whether given object is effectively "null."
"""
return x in [None, ""] or \
(coll_like(x) and isinstance(x, Sized) and 0 == len(x)... | [
"def",
"is_null_like",
"(",
"x",
")",
":",
"return",
"x",
"in",
"[",
"None",
",",
"\"\"",
"]",
"or",
"(",
"coll_like",
"(",
"x",
")",
"and",
"isinstance",
"(",
"x",
",",
"Sized",
")",
"and",
"0",
"==",
"len",
"(",
"x",
")",
")"
] | Determine whether an object is effectively null.
:param object x: Object for which null likeness is to be determined.
:return bool: Whether given object is effectively "null." | [
"Determine",
"whether",
"an",
"object",
"is",
"effectively",
"null",
"."
] | f0f725e1557936b81c86573a77400e6f8da78f05 | https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L299-L307 | train |
pepkit/peppy | peppy/utils.py | parse_ftype | def parse_ftype(input_file):
"""
Checks determine filetype from extension.
:param str input_file: String to check.
:return str: filetype (extension without dot prefix)
:raises TypeError: if file does not appear of a supported type
"""
if input_file.endswith(".bam"):
return "bam"
... | python | def parse_ftype(input_file):
"""
Checks determine filetype from extension.
:param str input_file: String to check.
:return str: filetype (extension without dot prefix)
:raises TypeError: if file does not appear of a supported type
"""
if input_file.endswith(".bam"):
return "bam"
... | [
"def",
"parse_ftype",
"(",
"input_file",
")",
":",
"if",
"input_file",
".",
"endswith",
"(",
"\".bam\"",
")",
":",
"return",
"\"bam\"",
"elif",
"input_file",
".",
"endswith",
"(",
"\".fastq\"",
")",
"or",
"input_file",
".",
"endswith",
"(",
"\".fq\"",
")",
... | Checks determine filetype from extension.
:param str input_file: String to check.
:return str: filetype (extension without dot prefix)
:raises TypeError: if file does not appear of a supported type | [
"Checks",
"determine",
"filetype",
"from",
"extension",
"."
] | f0f725e1557936b81c86573a77400e6f8da78f05 | https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L331-L348 | train |
pepkit/peppy | peppy/utils.py | parse_text_data | def parse_text_data(lines_or_path, delimiter=os.linesep):
"""
Interpret input argument as lines of data. This is intended to support
multiple input argument types to core model constructors.
:param str | collections.Iterable lines_or_path:
:param str delimiter: line separator used when parsing a ra... | python | def parse_text_data(lines_or_path, delimiter=os.linesep):
"""
Interpret input argument as lines of data. This is intended to support
multiple input argument types to core model constructors.
:param str | collections.Iterable lines_or_path:
:param str delimiter: line separator used when parsing a ra... | [
"def",
"parse_text_data",
"(",
"lines_or_path",
",",
"delimiter",
"=",
"os",
".",
"linesep",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"lines_or_path",
")",
":",
"with",
"open",
"(",
"lines_or_path",
",",
"'r'",
")",
"as",
"f",
":",
"retur... | Interpret input argument as lines of data. This is intended to support
multiple input argument types to core model constructors.
:param str | collections.Iterable lines_or_path:
:param str delimiter: line separator used when parsing a raw string that's
not a file
:return collections.Iterable: l... | [
"Interpret",
"input",
"argument",
"as",
"lines",
"of",
"data",
".",
"This",
"is",
"intended",
"to",
"support",
"multiple",
"input",
"argument",
"types",
"to",
"core",
"model",
"constructors",
"."
] | f0f725e1557936b81c86573a77400e6f8da78f05 | https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L351-L376 | train |
pepkit/peppy | peppy/utils.py | sample_folder | def sample_folder(prj, sample):
"""
Get the path to this Project's root folder for the given Sample.
:param attmap.PathExAttMap | Project prj: project with which sample is associated
:param Mapping sample: Sample or sample data for which to get root output
folder path.
:return str: this Pro... | python | def sample_folder(prj, sample):
"""
Get the path to this Project's root folder for the given Sample.
:param attmap.PathExAttMap | Project prj: project with which sample is associated
:param Mapping sample: Sample or sample data for which to get root output
folder path.
:return str: this Pro... | [
"def",
"sample_folder",
"(",
"prj",
",",
"sample",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"prj",
".",
"metadata",
".",
"results_subdir",
",",
"sample",
"[",
"\"sample_name\"",
"]",
")"
] | Get the path to this Project's root folder for the given Sample.
:param attmap.PathExAttMap | Project prj: project with which sample is associated
:param Mapping sample: Sample or sample data for which to get root output
folder path.
:return str: this Project's root folder for the given Sample | [
"Get",
"the",
"path",
"to",
"this",
"Project",
"s",
"root",
"folder",
"for",
"the",
"given",
"Sample",
"."
] | f0f725e1557936b81c86573a77400e6f8da78f05 | https://github.com/pepkit/peppy/blob/f0f725e1557936b81c86573a77400e6f8da78f05/peppy/utils.py#L379-L389 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.