repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
tBaxter/django-fretboard | fretboard/templatetags/fretboard_tags.py | get_new_topics_count | def get_new_topics_count(last_seen=None, for_member=False):
"""
Returns count of new topics since last visit, or one day.
{% get_new_topics_count as new_topic_count %}
"""
if not last_seen:
last_seen = yesterday()
if not for_member:
return Topic.objects.filter(created__gt=last_se... | python | def get_new_topics_count(last_seen=None, for_member=False):
"""
Returns count of new topics since last visit, or one day.
{% get_new_topics_count as new_topic_count %}
"""
if not last_seen:
last_seen = yesterday()
if not for_member:
return Topic.objects.filter(created__gt=last_se... | [
"def",
"get_new_topics_count",
"(",
"last_seen",
"=",
"None",
",",
"for_member",
"=",
"False",
")",
":",
"if",
"not",
"last_seen",
":",
"last_seen",
"=",
"yesterday",
"(",
")",
"if",
"not",
"for_member",
":",
"return",
"Topic",
".",
"objects",
".",
"filter... | Returns count of new topics since last visit, or one day.
{% get_new_topics_count as new_topic_count %} | [
"Returns",
"count",
"of",
"new",
"topics",
"since",
"last",
"visit",
"or",
"one",
"day",
".",
"{",
"%",
"get_new_topics_count",
"as",
"new_topic_count",
"%",
"}"
] | train | https://github.com/tBaxter/django-fretboard/blob/3c3f9557089821283f315a07f3e5a57a2725ab3b/fretboard/templatetags/fretboard_tags.py#L22-L31 |
tBaxter/django-fretboard | fretboard/templatetags/fretboard_tags.py | get_active_topics_count | def get_active_topics_count(last_seen_timestamp=None):
"""
Returns count of new topics since last visit, or one day.
{% get_active_topics_count as active_topic_count %}
"""
if not last_seen_timestamp:
last_seen_timestamp = yesterday_timestamp()
return Topic.objects.filter(modified_int__g... | python | def get_active_topics_count(last_seen_timestamp=None):
"""
Returns count of new topics since last visit, or one day.
{% get_active_topics_count as active_topic_count %}
"""
if not last_seen_timestamp:
last_seen_timestamp = yesterday_timestamp()
return Topic.objects.filter(modified_int__g... | [
"def",
"get_active_topics_count",
"(",
"last_seen_timestamp",
"=",
"None",
")",
":",
"if",
"not",
"last_seen_timestamp",
":",
"last_seen_timestamp",
"=",
"yesterday_timestamp",
"(",
")",
"return",
"Topic",
".",
"objects",
".",
"filter",
"(",
"modified_int__gt",
"=",... | Returns count of new topics since last visit, or one day.
{% get_active_topics_count as active_topic_count %} | [
"Returns",
"count",
"of",
"new",
"topics",
"since",
"last",
"visit",
"or",
"one",
"day",
".",
"{",
"%",
"get_active_topics_count",
"as",
"active_topic_count",
"%",
"}"
] | train | https://github.com/tBaxter/django-fretboard/blob/3c3f9557089821283f315a07f3e5a57a2725ab3b/fretboard/templatetags/fretboard_tags.py#L35-L42 |
tBaxter/django-fretboard | fretboard/templatetags/fretboard_tags.py | topic_quick_links | def topic_quick_links(context, topic, latest, last_seen_time):
"""
Creates topic listing page links for the given topic, with the given
number of posts per page.
Topics with between 2 and 5 pages will have page links displayed for
each page.
Topics with more than 5 pages will have page links d... | python | def topic_quick_links(context, topic, latest, last_seen_time):
"""
Creates topic listing page links for the given topic, with the given
number of posts per page.
Topics with between 2 and 5 pages will have page links displayed for
each page.
Topics with more than 5 pages will have page links d... | [
"def",
"topic_quick_links",
"(",
"context",
",",
"topic",
",",
"latest",
",",
"last_seen_time",
")",
":",
"output_text",
"=",
"u''",
"pages",
"=",
"topic",
".",
"page_count",
"if",
"not",
"pages",
"or",
"pages",
"==",
"0",
":",
"hits",
"=",
"topic",
".",... | Creates topic listing page links for the given topic, with the given
number of posts per page.
Topics with between 2 and 5 pages will have page links displayed for
each page.
Topics with more than 5 pages will have page links displayed for the
first page and the last 3 pages. | [
"Creates",
"topic",
"listing",
"page",
"links",
"for",
"the",
"given",
"topic",
"with",
"the",
"given",
"number",
"of",
"posts",
"per",
"page",
"."
] | train | https://github.com/tBaxter/django-fretboard/blob/3c3f9557089821283f315a07f3e5a57a2725ab3b/fretboard/templatetags/fretboard_tags.py#L46-L101 |
tBaxter/django-fretboard | fretboard/templatetags/fretboard_tags.py | get_topic_list | def get_topic_list(num=10, top_items=False):
"""
Returns a list of top recent topics, excluding less valuable forums.
Default is 10 topics.
Can be sorted for most active topics by votes and post count.
Usage:
{% get_topic_list 5 as topics %}
{% get_topic_list 7 top_items=True as topics %}
... | python | def get_topic_list(num=10, top_items=False):
"""
Returns a list of top recent topics, excluding less valuable forums.
Default is 10 topics.
Can be sorted for most active topics by votes and post count.
Usage:
{% get_topic_list 5 as topics %}
{% get_topic_list 7 top_items=True as topics %}
... | [
"def",
"get_topic_list",
"(",
"num",
"=",
"10",
",",
"top_items",
"=",
"False",
")",
":",
"excluded_forum_ids",
"=",
"[",
"3",
",",
"7",
",",
"10",
",",
"12",
",",
"15",
",",
"16",
",",
"17",
",",
"18",
",",
"19",
",",
"23",
"]",
"topics",
"=",... | Returns a list of top recent topics, excluding less valuable forums.
Default is 10 topics.
Can be sorted for most active topics by votes and post count.
Usage:
{% get_topic_list 5 as topics %}
{% get_topic_list 7 top_items=True as topics %} | [
"Returns",
"a",
"list",
"of",
"top",
"recent",
"topics",
"excluding",
"less",
"valuable",
"forums",
".",
"Default",
"is",
"10",
"topics",
".",
"Can",
"be",
"sorted",
"for",
"most",
"active",
"topics",
"by",
"votes",
"and",
"post",
"count",
".",
"Usage",
... | train | https://github.com/tBaxter/django-fretboard/blob/3c3f9557089821283f315a07f3e5a57a2725ab3b/fretboard/templatetags/fretboard_tags.py#L115-L128 |
lehins/python-wepay | wepay/calls/checkout.py | Checkout.__create | def __create(self, account_id, short_description, type, amount, **kwargs):
"""Call documentation: `/checkout/create
<https://www.wepay.com/developer/reference/checkout#create>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
... | python | def __create(self, account_id, short_description, type, amount, **kwargs):
"""Call documentation: `/checkout/create
<https://www.wepay.com/developer/reference/checkout#create>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
... | [
"def",
"__create",
"(",
"self",
",",
"account_id",
",",
"short_description",
",",
"type",
",",
"amount",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'account_id'",
":",
"account_id",
",",
"'short_description'",
":",
"short_description",
",",
"'ty... | Call documentation: `/checkout/create
<https://www.wepay.com/developer/reference/checkout#create>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_mode=True`` will set `authorization`
par... | [
"Call",
"documentation",
":",
"/",
"checkout",
"/",
"create",
"<https",
":",
"//",
"www",
".",
"wepay",
".",
"com",
"/",
"developer",
"/",
"reference",
"/",
"checkout#create",
">",
"_",
"plus",
"extra",
"keyword",
"parameters",
":",
":",
"keyword",
"str",
... | train | https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/checkout.py#L62-L88 |
lehins/python-wepay | wepay/calls/checkout.py | Checkout.__cancel | def __cancel(self, checkout_id, cancel_reason, **kwargs):
"""Call documentation: `/checkout/cancel
<https://www.wepay.com/developer/reference/checkout#cancel>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_toke... | python | def __cancel(self, checkout_id, cancel_reason, **kwargs):
"""Call documentation: `/checkout/cancel
<https://www.wepay.com/developer/reference/checkout#cancel>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_toke... | [
"def",
"__cancel",
"(",
"self",
",",
"checkout_id",
",",
"cancel_reason",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'checkout_id'",
":",
"checkout_id",
",",
"'cancel_reason'",
":",
"cancel_reason",
"}",
"return",
"self",
".",
"make_call",
"(",
... | Call documentation: `/checkout/cancel
<https://www.wepay.com/developer/reference/checkout#cancel>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_mode=True`` will set `authorization`
par... | [
"Call",
"documentation",
":",
"/",
"checkout",
"/",
"cancel",
"<https",
":",
"//",
"www",
".",
"wepay",
".",
"com",
"/",
"developer",
"/",
"reference",
"/",
"checkout#cancel",
">",
"_",
"plus",
"extra",
"keyword",
"parameters",
":",
":",
"keyword",
"str",
... | train | https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/checkout.py#L108-L131 |
lehins/python-wepay | wepay/calls/checkout.py | Checkout.__refund | def __refund(self, checkout_id, refund_reason, **kwargs):
"""Call documentation: `/checkout/refund
<https://www.wepay.com/developer/reference/checkout#refund>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_toke... | python | def __refund(self, checkout_id, refund_reason, **kwargs):
"""Call documentation: `/checkout/refund
<https://www.wepay.com/developer/reference/checkout#refund>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_toke... | [
"def",
"__refund",
"(",
"self",
",",
"checkout_id",
",",
"refund_reason",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'checkout_id'",
":",
"checkout_id",
",",
"'refund_reason'",
":",
"refund_reason",
"}",
"return",
"self",
".",
"make_call",
"(",
... | Call documentation: `/checkout/refund
<https://www.wepay.com/developer/reference/checkout#refund>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_mode=True`` will set `authorization`
par... | [
"Call",
"documentation",
":",
"/",
"checkout",
"/",
"refund",
"<https",
":",
"//",
"www",
".",
"wepay",
".",
"com",
"/",
"developer",
"/",
"reference",
"/",
"checkout#refund",
">",
"_",
"plus",
"extra",
"keyword",
"parameters",
":",
":",
"keyword",
"str",
... | train | https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/checkout.py#L135-L158 |
lehins/python-wepay | wepay/calls/checkout.py | Checkout.__capture | def __capture(self, checkout_id, **kwargs):
"""Call documentation: `/checkout/capture
<https://www.wepay.com/developer/reference/checkout#capture>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``... | python | def __capture(self, checkout_id, **kwargs):
"""Call documentation: `/checkout/capture
<https://www.wepay.com/developer/reference/checkout#capture>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``... | [
"def",
"__capture",
"(",
"self",
",",
"checkout_id",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'checkout_id'",
":",
"checkout_id",
"}",
"return",
"self",
".",
"make_call",
"(",
"self",
".",
"__capture",
",",
"params",
",",
"kwargs",
")"
] | Call documentation: `/checkout/capture
<https://www.wepay.com/developer/reference/checkout#capture>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_mode=True`` will set `authorization`
p... | [
"Call",
"documentation",
":",
"/",
"checkout",
"/",
"capture",
"<https",
":",
"//",
"www",
".",
"wepay",
".",
"com",
"/",
"developer",
"/",
"reference",
"/",
"checkout#capture",
">",
"_",
"plus",
"extra",
"keyword",
"parameters",
":",
":",
"keyword",
"str"... | train | https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/checkout.py#L165-L187 |
lehins/python-wepay | wepay/calls/checkout.py | Checkout.__modify | def __modify(self, checkout_id, **kwargs):
"""Call documentation: `/checkout/modify
<https://www.wepay.com/developer/reference/checkout#modify>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``bat... | python | def __modify(self, checkout_id, **kwargs):
"""Call documentation: `/checkout/modify
<https://www.wepay.com/developer/reference/checkout#modify>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``bat... | [
"def",
"__modify",
"(",
"self",
",",
"checkout_id",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'checkout_id'",
":",
"checkout_id",
"}",
"return",
"self",
".",
"make_call",
"(",
"self",
".",
"__modify",
",",
"params",
",",
"kwargs",
")"
] | Call documentation: `/checkout/modify
<https://www.wepay.com/developer/reference/checkout#modify>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_mode=True`` will set `authorization`
par... | [
"Call",
"documentation",
":",
"/",
"checkout",
"/",
"modify",
"<https",
":",
"//",
"www",
".",
"wepay",
".",
"com",
"/",
"developer",
"/",
"reference",
"/",
"checkout#modify",
">",
"_",
"plus",
"extra",
"keyword",
"parameters",
":",
":",
"keyword",
"str",
... | train | https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/checkout.py#L191-L213 |
django-xxx/django-mobi2 | mobi2/middleware.py | ignore_user_agent | def ignore_user_agent(user_agent):
""" compare the useragent from the broswer to the ignore list
This is popular if you want a mobile device to not trigger
as mobile. For example iPad."""
if user_agent:
for ua in MOBI_USER_AGENT_IGNORE_LIST:
if ua and ua.lower() in user_agent... | python | def ignore_user_agent(user_agent):
""" compare the useragent from the broswer to the ignore list
This is popular if you want a mobile device to not trigger
as mobile. For example iPad."""
if user_agent:
for ua in MOBI_USER_AGENT_IGNORE_LIST:
if ua and ua.lower() in user_agent... | [
"def",
"ignore_user_agent",
"(",
"user_agent",
")",
":",
"if",
"user_agent",
":",
"for",
"ua",
"in",
"MOBI_USER_AGENT_IGNORE_LIST",
":",
"if",
"ua",
"and",
"ua",
".",
"lower",
"(",
")",
"in",
"user_agent",
".",
"lower",
"(",
")",
":",
"return",
"True",
"... | compare the useragent from the broswer to the ignore list
This is popular if you want a mobile device to not trigger
as mobile. For example iPad. | [
"compare",
"the",
"useragent",
"from",
"the",
"broswer",
"to",
"the",
"ignore",
"list",
"This",
"is",
"popular",
"if",
"you",
"want",
"a",
"mobile",
"device",
"to",
"not",
"trigger",
"as",
"mobile",
".",
"For",
"example",
"iPad",
"."
] | train | https://github.com/django-xxx/django-mobi2/blob/7ac323faa1a9599f3cd39acd3c49626819ce0538/mobi2/middleware.py#L13-L21 |
django-xxx/django-mobi2 | mobi2/middleware.py | MobileDetectionMiddleware.process_request | def process_request(request):
"""Adds a "mobile" attribute to the request which is True or False
depending on whether the request should be considered to come from a
small-screen device such as a phone or a PDA"""
if 'HTTP_X_OPERAMINI_FEATURES' in request.META:
# Then ... | python | def process_request(request):
"""Adds a "mobile" attribute to the request which is True or False
depending on whether the request should be considered to come from a
small-screen device such as a phone or a PDA"""
if 'HTTP_X_OPERAMINI_FEATURES' in request.META:
# Then ... | [
"def",
"process_request",
"(",
"request",
")",
":",
"if",
"'HTTP_X_OPERAMINI_FEATURES'",
"in",
"request",
".",
"META",
":",
"# Then it's running opera mini. 'Nuff said.",
"# Reference from:",
"# http://dev.opera.com/articles/view/opera-mini-request-headers/",
"request",
".",
"mob... | Adds a "mobile" attribute to the request which is True or False
depending on whether the request should be considered to come from a
small-screen device such as a phone or a PDA | [
"Adds",
"a",
"mobile",
"attribute",
"to",
"the",
"request",
"which",
"is",
"True",
"or",
"False",
"depending",
"on",
"whether",
"the",
"request",
"should",
"be",
"considered",
"to",
"come",
"from",
"a",
"small",
"-",
"screen",
"device",
"such",
"as",
"a",
... | train | https://github.com/django-xxx/django-mobi2/blob/7ac323faa1a9599f3cd39acd3c49626819ce0538/mobi2/middleware.py#L26-L64 |
hvishwanath/libpaas | libpaas/drivers/manager.py | DriverManager.getInstance | def getInstance(cls, *args):
'''
Returns a singleton instance of the class
'''
if not cls.__singleton:
cls.__singleton = DriverManager(*args)
return cls.__singleton | python | def getInstance(cls, *args):
'''
Returns a singleton instance of the class
'''
if not cls.__singleton:
cls.__singleton = DriverManager(*args)
return cls.__singleton | [
"def",
"getInstance",
"(",
"cls",
",",
"*",
"args",
")",
":",
"if",
"not",
"cls",
".",
"__singleton",
":",
"cls",
".",
"__singleton",
"=",
"DriverManager",
"(",
"*",
"args",
")",
"return",
"cls",
".",
"__singleton"
] | Returns a singleton instance of the class | [
"Returns",
"a",
"singleton",
"instance",
"of",
"the",
"class"
] | train | https://github.com/hvishwanath/libpaas/blob/3df07adca59c003ee754c4e919cf506c13953be1/libpaas/drivers/manager.py#L19-L25 |
veltzer/pydmt | pydmt/core/pydmt.py | PyDMT.build_by_builder | def build_by_builder(self, builder: Builder, stats: BuildProcessStats):
""" run one builder, return statistics about the run """
logger = logging.getLogger(__name__)
target_signature = builder.get_signature()
assert target_signature is not None, "builder signature is None"
if sel... | python | def build_by_builder(self, builder: Builder, stats: BuildProcessStats):
""" run one builder, return statistics about the run """
logger = logging.getLogger(__name__)
target_signature = builder.get_signature()
assert target_signature is not None, "builder signature is None"
if sel... | [
"def",
"build_by_builder",
"(",
"self",
",",
"builder",
":",
"Builder",
",",
"stats",
":",
"BuildProcessStats",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"target_signature",
"=",
"builder",
".",
"get_signature",
"(",
")",
"a... | run one builder, return statistics about the run | [
"run",
"one",
"builder",
"return",
"statistics",
"about",
"the",
"run"
] | train | https://github.com/veltzer/pydmt/blob/11d3db7ea079756c1e4137d3dd8a2cabbcc98bf7/pydmt/core/pydmt.py#L53-L109 |
veltzer/pydmt | pydmt/core/pydmt.py | PyDMT.build_all | def build_all(self) -> BuildProcessStats:
"""
Build all the targets, very high level method
:return:
"""
stats = BuildProcessStats()
for builder in self.builders:
self.build_by_builder(
builder=builder,
stats=stats,
... | python | def build_all(self) -> BuildProcessStats:
"""
Build all the targets, very high level method
:return:
"""
stats = BuildProcessStats()
for builder in self.builders:
self.build_by_builder(
builder=builder,
stats=stats,
... | [
"def",
"build_all",
"(",
"self",
")",
"->",
"BuildProcessStats",
":",
"stats",
"=",
"BuildProcessStats",
"(",
")",
"for",
"builder",
"in",
"self",
".",
"builders",
":",
"self",
".",
"build_by_builder",
"(",
"builder",
"=",
"builder",
",",
"stats",
"=",
"st... | Build all the targets, very high level method
:return: | [
"Build",
"all",
"the",
"targets",
"very",
"high",
"level",
"method",
":",
"return",
":"
] | train | https://github.com/veltzer/pydmt/blob/11d3db7ea079756c1e4137d3dd8a2cabbcc98bf7/pydmt/core/pydmt.py#L119-L130 |
rgmining/ria | ria/bipartite.py | Reviewer.anomalous_score | def anomalous_score(self):
"""Anomalous score of this reviewer.
Initial anomalous score is :math:`1 / |R|`
where :math:`R` is a set of reviewers.
"""
return self._anomalous if self._anomalous else 1. / len(self._graph.reviewers) | python | def anomalous_score(self):
"""Anomalous score of this reviewer.
Initial anomalous score is :math:`1 / |R|`
where :math:`R` is a set of reviewers.
"""
return self._anomalous if self._anomalous else 1. / len(self._graph.reviewers) | [
"def",
"anomalous_score",
"(",
"self",
")",
":",
"return",
"self",
".",
"_anomalous",
"if",
"self",
".",
"_anomalous",
"else",
"1.",
"/",
"len",
"(",
"self",
".",
"_graph",
".",
"reviewers",
")"
] | Anomalous score of this reviewer.
Initial anomalous score is :math:`1 / |R|`
where :math:`R` is a set of reviewers. | [
"Anomalous",
"score",
"of",
"this",
"reviewer",
"."
] | train | https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L151-L157 |
rgmining/ria | ria/bipartite.py | Reviewer.update_anomalous_score | def update_anomalous_score(self):
"""Update anomalous score.
New anomalous score is a weighted average of differences
between current summary and reviews. The weights come from credibilities.
Therefore, the new anomalous score of reviewer :math:`p` is as
.. math::
... | python | def update_anomalous_score(self):
"""Update anomalous score.
New anomalous score is a weighted average of differences
between current summary and reviews. The weights come from credibilities.
Therefore, the new anomalous score of reviewer :math:`p` is as
.. math::
... | [
"def",
"update_anomalous_score",
"(",
"self",
")",
":",
"products",
"=",
"self",
".",
"_graph",
".",
"retrieve_products",
"(",
"self",
")",
"diffs",
"=",
"[",
"p",
".",
"summary",
".",
"difference",
"(",
"self",
".",
"_graph",
".",
"retrieve_review",
"(",
... | Update anomalous score.
New anomalous score is a weighted average of differences
between current summary and reviews. The weights come from credibilities.
Therefore, the new anomalous score of reviewer :math:`p` is as
.. math::
{\\rm anomalous}(r) = \\frac{
\\... | [
"Update",
"anomalous",
"score",
"."
] | train | https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L168-L206 |
rgmining/ria | ria/bipartite.py | Product.summary | def summary(self):
"""Summary of reviews for this product.
Initial summary is computed by
.. math::
\\frac{1}{|R|} \\sum_{r \\in R} \\mbox{review}(r),
where :math:`\\mbox{review}(r)` means review from reviewer :math:`r`.
"""
if self._summary:
r... | python | def summary(self):
"""Summary of reviews for this product.
Initial summary is computed by
.. math::
\\frac{1}{|R|} \\sum_{r \\in R} \\mbox{review}(r),
where :math:`\\mbox{review}(r)` means review from reviewer :math:`r`.
"""
if self._summary:
r... | [
"def",
"summary",
"(",
"self",
")",
":",
"if",
"self",
".",
"_summary",
":",
"return",
"self",
".",
"_summary",
"reviewers",
"=",
"self",
".",
"_graph",
".",
"retrieve_reviewers",
"(",
"self",
")",
"return",
"self",
".",
"_summary_cls",
"(",
"[",
"self",... | Summary of reviews for this product.
Initial summary is computed by
.. math::
\\frac{1}{|R|} \\sum_{r \\in R} \\mbox{review}(r),
where :math:`\\mbox{review}(r)` means review from reviewer :math:`r`. | [
"Summary",
"of",
"reviews",
"for",
"this",
"product",
"."
] | train | https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L226-L242 |
rgmining/ria | ria/bipartite.py | Product.summary | def summary(self, v):
"""Set summary.
Args:
v: A new summary. It could be a single number or lists.
"""
if hasattr(v, "__iter__"):
self._summary = self._summary_cls(v)
else:
self._summary = self._summary_cls(float(v)) | python | def summary(self, v):
"""Set summary.
Args:
v: A new summary. It could be a single number or lists.
"""
if hasattr(v, "__iter__"):
self._summary = self._summary_cls(v)
else:
self._summary = self._summary_cls(float(v)) | [
"def",
"summary",
"(",
"self",
",",
"v",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"__iter__\"",
")",
":",
"self",
".",
"_summary",
"=",
"self",
".",
"_summary_cls",
"(",
"v",
")",
"else",
":",
"self",
".",
"_summary",
"=",
"self",
".",
"_summary... | Set summary.
Args:
v: A new summary. It could be a single number or lists. | [
"Set",
"summary",
"."
] | train | https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L245-L254 |
rgmining/ria | ria/bipartite.py | Product.update_summary | def update_summary(self, w):
"""Update summary.
The new summary is a weighted average of reviews i.e.
.. math::
\\frac{\\sum_{r \\in R} \\mbox{weight}(r) \\times \\mbox{review}(r)}
{\\sum_{r \\in R} \\mbox{weight}(r)},
where :math:`R` is a set of reviewers... | python | def update_summary(self, w):
"""Update summary.
The new summary is a weighted average of reviews i.e.
.. math::
\\frac{\\sum_{r \\in R} \\mbox{weight}(r) \\times \\mbox{review}(r)}
{\\sum_{r \\in R} \\mbox{weight}(r)},
where :math:`R` is a set of reviewers... | [
"def",
"update_summary",
"(",
"self",
",",
"w",
")",
":",
"old",
"=",
"self",
".",
"summary",
".",
"v",
"# pylint: disable=no-member",
"reviewers",
"=",
"self",
".",
"_graph",
".",
"retrieve_reviewers",
"(",
"self",
")",
"reviews",
"=",
"[",
"self",
".",
... | Update summary.
The new summary is a weighted average of reviews i.e.
.. math::
\\frac{\\sum_{r \\in R} \\mbox{weight}(r) \\times \\mbox{review}(r)}
{\\sum_{r \\in R} \\mbox{weight}(r)},
where :math:`R` is a set of reviewers reviewing this product,
:math:`... | [
"Update",
"summary",
"."
] | train | https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L256-L286 |
rgmining/ria | ria/bipartite.py | BipartiteGraph.new_reviewer | def new_reviewer(self, name, anomalous=None):
"""Create a new reviewer.
Args:
name: name of the new reviewer.
anomalous: initial anomalous score. (default: None)
Returns:
A new reviewer instance.
"""
n = self._reviewer_cls(
self, name=n... | python | def new_reviewer(self, name, anomalous=None):
"""Create a new reviewer.
Args:
name: name of the new reviewer.
anomalous: initial anomalous score. (default: None)
Returns:
A new reviewer instance.
"""
n = self._reviewer_cls(
self, name=n... | [
"def",
"new_reviewer",
"(",
"self",
",",
"name",
",",
"anomalous",
"=",
"None",
")",
":",
"n",
"=",
"self",
".",
"_reviewer_cls",
"(",
"self",
",",
"name",
"=",
"name",
",",
"credibility",
"=",
"self",
".",
"credibility",
",",
"anomalous",
"=",
"anomal... | Create a new reviewer.
Args:
name: name of the new reviewer.
anomalous: initial anomalous score. (default: None)
Returns:
A new reviewer instance. | [
"Create",
"a",
"new",
"reviewer",
"."
] | train | https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L333-L347 |
rgmining/ria | ria/bipartite.py | BipartiteGraph.new_product | def new_product(self, name):
"""Create a new product.
Args:
name: name of the new product.
Returns:
A new product instance.
"""
n = self._product_cls(self, name, summary_cls=self._summary_cls)
self.graph.add_node(n)
self.products.append(n)
... | python | def new_product(self, name):
"""Create a new product.
Args:
name: name of the new product.
Returns:
A new product instance.
"""
n = self._product_cls(self, name, summary_cls=self._summary_cls)
self.graph.add_node(n)
self.products.append(n)
... | [
"def",
"new_product",
"(",
"self",
",",
"name",
")",
":",
"n",
"=",
"self",
".",
"_product_cls",
"(",
"self",
",",
"name",
",",
"summary_cls",
"=",
"self",
".",
"_summary_cls",
")",
"self",
".",
"graph",
".",
"add_node",
"(",
"n",
")",
"self",
".",
... | Create a new product.
Args:
name: name of the new product.
Returns:
A new product instance. | [
"Create",
"a",
"new",
"product",
"."
] | train | https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L349-L361 |
rgmining/ria | ria/bipartite.py | BipartiteGraph.add_review | def add_review(self, reviewer, product, review, date=None):
"""Add a new review from a given reviewer to a given product.
Args:
reviewer: an instance of Reviewer.
product: an instance of Product.
review: a float value.
date: date the review issued.
Retur... | python | def add_review(self, reviewer, product, review, date=None):
"""Add a new review from a given reviewer to a given product.
Args:
reviewer: an instance of Reviewer.
product: an instance of Product.
review: a float value.
date: date the review issued.
Retur... | [
"def",
"add_review",
"(",
"self",
",",
"reviewer",
",",
"product",
",",
"review",
",",
"date",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"reviewer",
",",
"self",
".",
"_reviewer_cls",
")",
":",
"raise",
"TypeError",
"(",
"\"Type of given revie... | Add a new review from a given reviewer to a given product.
Args:
reviewer: an instance of Reviewer.
product: an instance of Product.
review: a float value.
date: date the review issued.
Returns:
the added new review object.
Raises:
T... | [
"Add",
"a",
"new",
"review",
"from",
"a",
"given",
"reviewer",
"to",
"a",
"given",
"product",
"."
] | train | https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L363-L389 |
rgmining/ria | ria/bipartite.py | BipartiteGraph.retrieve_products | def retrieve_products(self, reviewer):
"""Retrieve products reviewed by a given reviewer.
Args:
reviewer: A reviewer.
Returns:
A list of products which the reviewer reviews.
Raises:
TypeError: when given reviewer isn't instance of specified reviewer
... | python | def retrieve_products(self, reviewer):
"""Retrieve products reviewed by a given reviewer.
Args:
reviewer: A reviewer.
Returns:
A list of products which the reviewer reviews.
Raises:
TypeError: when given reviewer isn't instance of specified reviewer
... | [
"def",
"retrieve_products",
"(",
"self",
",",
"reviewer",
")",
":",
"if",
"not",
"isinstance",
"(",
"reviewer",
",",
"self",
".",
"_reviewer_cls",
")",
":",
"raise",
"TypeError",
"(",
"\"Type of given reviewer isn't acceptable:\"",
",",
"reviewer",
",",
"\", expec... | Retrieve products reviewed by a given reviewer.
Args:
reviewer: A reviewer.
Returns:
A list of products which the reviewer reviews.
Raises:
TypeError: when given reviewer isn't instance of specified reviewer
class when this graph is constructed. | [
"Retrieve",
"products",
"reviewed",
"by",
"a",
"given",
"reviewer",
"."
] | train | https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L392-L409 |
rgmining/ria | ria/bipartite.py | BipartiteGraph.retrieve_reviewers | def retrieve_reviewers(self, product):
"""Retrieve reviewers who reviewed a given product.
Args:
product: A product specifying reviewers.
Returns:
A list of reviewers who review the product.
Raises:
TypeError: when given product isn't instance of specifie... | python | def retrieve_reviewers(self, product):
"""Retrieve reviewers who reviewed a given product.
Args:
product: A product specifying reviewers.
Returns:
A list of reviewers who review the product.
Raises:
TypeError: when given product isn't instance of specifie... | [
"def",
"retrieve_reviewers",
"(",
"self",
",",
"product",
")",
":",
"if",
"not",
"isinstance",
"(",
"product",
",",
"self",
".",
"_product_cls",
")",
":",
"raise",
"TypeError",
"(",
"\"Type of given product isn't acceptable:\"",
",",
"product",
",",
"\", expected:... | Retrieve reviewers who reviewed a given product.
Args:
product: A product specifying reviewers.
Returns:
A list of reviewers who review the product.
Raises:
TypeError: when given product isn't instance of specified product
class when this graph is con... | [
"Retrieve",
"reviewers",
"who",
"reviewed",
"a",
"given",
"product",
"."
] | train | https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L412-L429 |
rgmining/ria | ria/bipartite.py | BipartiteGraph.retrieve_review | def retrieve_review(self, reviewer, product):
"""Retrieve review that the given reviewer put the given product.
Args:
reviewer: An instance of Reviewer.
product: An instance of Product.
Returns:
A review object.
Raises:
TypeError: when given rev... | python | def retrieve_review(self, reviewer, product):
"""Retrieve review that the given reviewer put the given product.
Args:
reviewer: An instance of Reviewer.
product: An instance of Product.
Returns:
A review object.
Raises:
TypeError: when given rev... | [
"def",
"retrieve_review",
"(",
"self",
",",
"reviewer",
",",
"product",
")",
":",
"if",
"not",
"isinstance",
"(",
"reviewer",
",",
"self",
".",
"_reviewer_cls",
")",
":",
"raise",
"TypeError",
"(",
"\"Type of given reviewer isn't acceptable:\"",
",",
"reviewer",
... | Retrieve review that the given reviewer put the given product.
Args:
reviewer: An instance of Reviewer.
product: An instance of Product.
Returns:
A review object.
Raises:
TypeError: when given reviewer and product aren't instance of
specifie... | [
"Retrieve",
"review",
"that",
"the",
"given",
"reviewer",
"put",
"the",
"given",
"product",
"."
] | train | https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L432-L460 |
rgmining/ria | ria/bipartite.py | BipartiteGraph.update | def update(self):
"""Update reviewers' anomalous scores and products' summaries.
Returns:
maximum absolute difference between old summary and new one, and
old anomalous score and new one.
"""
w = self._weight_generator(self.reviewers)
diff_p = max(p.update_su... | python | def update(self):
"""Update reviewers' anomalous scores and products' summaries.
Returns:
maximum absolute difference between old summary and new one, and
old anomalous score and new one.
"""
w = self._weight_generator(self.reviewers)
diff_p = max(p.update_su... | [
"def",
"update",
"(",
"self",
")",
":",
"w",
"=",
"self",
".",
"_weight_generator",
"(",
"self",
".",
"reviewers",
")",
"diff_p",
"=",
"max",
"(",
"p",
".",
"update_summary",
"(",
"w",
")",
"for",
"p",
"in",
"self",
".",
"products",
")",
"diff_a",
... | Update reviewers' anomalous scores and products' summaries.
Returns:
maximum absolute difference between old summary and new one, and
old anomalous score and new one. | [
"Update",
"reviewers",
"anomalous",
"scores",
"and",
"products",
"summaries",
"."
] | train | https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L462-L472 |
rgmining/ria | ria/bipartite.py | BipartiteGraph._weight_generator | def _weight_generator(self, reviewers):
"""Compute a weight function for the given reviewers.
Args:
reviewers: a set of reviewers to compute weight function.
Returns:
a function computing a weight for a reviewer.
"""
scores = [r.anomalous_score for r in revi... | python | def _weight_generator(self, reviewers):
"""Compute a weight function for the given reviewers.
Args:
reviewers: a set of reviewers to compute weight function.
Returns:
a function computing a weight for a reviewer.
"""
scores = [r.anomalous_score for r in revi... | [
"def",
"_weight_generator",
"(",
"self",
",",
"reviewers",
")",
":",
"scores",
"=",
"[",
"r",
".",
"anomalous_score",
"for",
"r",
"in",
"reviewers",
"]",
"mu",
"=",
"np",
".",
"average",
"(",
"scores",
")",
"sigma",
"=",
"np",
".",
"std",
"(",
"score... | Compute a weight function for the given reviewers.
Args:
reviewers: a set of reviewers to compute weight function.
Returns:
a function computing a weight for a reviewer. | [
"Compute",
"a",
"weight",
"function",
"for",
"the",
"given",
"reviewers",
"."
] | train | https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L474-L507 |
rgmining/ria | ria/bipartite.py | BipartiteGraph.dump_credibilities | def dump_credibilities(self, output):
"""Dump credibilities of all products.
Args:
output: a writable object.
"""
for p in self.products:
json.dump({
"product_id": p.name,
"credibility": self.credibility(p)
}, output)
... | python | def dump_credibilities(self, output):
"""Dump credibilities of all products.
Args:
output: a writable object.
"""
for p in self.products:
json.dump({
"product_id": p.name,
"credibility": self.credibility(p)
}, output)
... | [
"def",
"dump_credibilities",
"(",
"self",
",",
"output",
")",
":",
"for",
"p",
"in",
"self",
".",
"products",
":",
"json",
".",
"dump",
"(",
"{",
"\"product_id\"",
":",
"p",
".",
"name",
",",
"\"credibility\"",
":",
"self",
".",
"credibility",
"(",
"p"... | Dump credibilities of all products.
Args:
output: a writable object. | [
"Dump",
"credibilities",
"of",
"all",
"products",
"."
] | train | https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L509-L520 |
minhhoit/yacms | yacms/blog/models.py | BlogPost.get_absolute_url | def get_absolute_url(self):
"""
URLs for blog posts can either be just their slug, or prefixed
with a portion of the post's publish date, controlled by the
setting ``BLOG_URLS_DATE_FORMAT``, which can contain the value
``year``, ``month``, or ``day``. Each of these maps to the na... | python | def get_absolute_url(self):
"""
URLs for blog posts can either be just their slug, or prefixed
with a portion of the post's publish date, controlled by the
setting ``BLOG_URLS_DATE_FORMAT``, which can contain the value
``year``, ``month``, or ``day``. Each of these maps to the na... | [
"def",
"get_absolute_url",
"(",
"self",
")",
":",
"url_name",
"=",
"\"blog_post_detail\"",
"kwargs",
"=",
"{",
"\"slug\"",
":",
"self",
".",
"slug",
"}",
"date_parts",
"=",
"(",
"\"year\"",
",",
"\"month\"",
",",
"\"day\"",
")",
"if",
"settings",
".",
"BLO... | URLs for blog posts can either be just their slug, or prefixed
with a portion of the post's publish date, controlled by the
setting ``BLOG_URLS_DATE_FORMAT``, which can contain the value
``year``, ``month``, or ``day``. Each of these maps to the name
of the corresponding urlpattern, and ... | [
"URLs",
"for",
"blog",
"posts",
"can",
"either",
"be",
"just",
"their",
"slug",
"or",
"prefixed",
"with",
"a",
"portion",
"of",
"the",
"post",
"s",
"publish",
"date",
"controlled",
"by",
"the",
"setting",
"BLOG_URLS_DATE_FORMAT",
"which",
"can",
"contain",
"... | train | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/blog/models.py#L40-L64 |
FujiMakoto/IPS-Vagrant | ips_vagrant/downloaders/ips.py | IpsManager._read_zip | def _read_zip(self, filepath):
"""
Read an IPS installation zipfile and return the core version number
@type filepath: str
@rtype: Version
"""
with ZipFile(filepath) as zip:
namelist = zip.namelist()
if re.match(r'^ips_\w{5}/?$', namelist[0]):
... | python | def _read_zip(self, filepath):
"""
Read an IPS installation zipfile and return the core version number
@type filepath: str
@rtype: Version
"""
with ZipFile(filepath) as zip:
namelist = zip.namelist()
if re.match(r'^ips_\w{5}/?$', namelist[0]):
... | [
"def",
"_read_zip",
"(",
"self",
",",
"filepath",
")",
":",
"with",
"ZipFile",
"(",
"filepath",
")",
"as",
"zip",
":",
"namelist",
"=",
"zip",
".",
"namelist",
"(",
")",
"if",
"re",
".",
"match",
"(",
"r'^ips_\\w{5}/?$'",
",",
"namelist",
"[",
"0",
"... | Read an IPS installation zipfile and return the core version number
@type filepath: str
@rtype: Version | [
"Read",
"an",
"IPS",
"installation",
"zipfile",
"and",
"return",
"the",
"core",
"version",
"number"
] | train | https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/downloaders/ips.py#L71-L93 |
pjuren/pyokit | src/pyokit/io/maf.py | merge_dictionaries | def merge_dictionaries(a, b):
"""Merge two dictionaries; duplicate keys get value from b."""
res = {}
for k in a:
res[k] = a[k]
for k in b:
res[k] = b[k]
return res | python | def merge_dictionaries(a, b):
"""Merge two dictionaries; duplicate keys get value from b."""
res = {}
for k in a:
res[k] = a[k]
for k in b:
res[k] = b[k]
return res | [
"def",
"merge_dictionaries",
"(",
"a",
",",
"b",
")",
":",
"res",
"=",
"{",
"}",
"for",
"k",
"in",
"a",
":",
"res",
"[",
"k",
"]",
"=",
"a",
"[",
"k",
"]",
"for",
"k",
"in",
"b",
":",
"res",
"[",
"k",
"]",
"=",
"b",
"[",
"k",
"]",
"retu... | Merge two dictionaries; duplicate keys get value from b. | [
"Merge",
"two",
"dictionaries",
";",
"duplicate",
"keys",
"get",
"value",
"from",
"b",
"."
] | train | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/io/maf.py#L73-L80 |
pjuren/pyokit | src/pyokit/io/maf.py | __build_sequence | def __build_sequence(parts):
"""Build a sequence object using the pre-tokenized parts from a MAF line.
s -- a sequence line; has 6 fields in addition to 's':
* source sequence,
* start coord. of seq., zero-based. If -'ve strand, rel to start of
rev. comp.
* ungapped length... | python | def __build_sequence(parts):
"""Build a sequence object using the pre-tokenized parts from a MAF line.
s -- a sequence line; has 6 fields in addition to 's':
* source sequence,
* start coord. of seq., zero-based. If -'ve strand, rel to start of
rev. comp.
* ungapped length... | [
"def",
"__build_sequence",
"(",
"parts",
")",
":",
"strand",
"=",
"parts",
"[",
"4",
"]",
"seq_length",
"=",
"int",
"(",
"parts",
"[",
"3",
"]",
")",
"total_seq_len",
"=",
"int",
"(",
"parts",
"[",
"5",
"]",
")",
"start",
"=",
"(",
"int",
"(",
"p... | Build a sequence object using the pre-tokenized parts from a MAF line.
s -- a sequence line; has 6 fields in addition to 's':
* source sequence,
* start coord. of seq., zero-based. If -'ve strand, rel to start of
rev. comp.
* ungapped length of the sequence
* stran... | [
"Build",
"a",
"sequence",
"object",
"using",
"the",
"pre",
"-",
"tokenized",
"parts",
"from",
"a",
"MAF",
"line",
"."
] | train | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/io/maf.py#L83-L102 |
pjuren/pyokit | src/pyokit/io/maf.py | __build_unknown_sequence | def __build_unknown_sequence(parts):
"""Build unknown seq (e lines) using pre-tokenized parts from MAF line.
e -- indicates that there is no aligning sequence for a species, but that
there are blocks before and after this one that do align. Format is the
same as the 's' lines, but the start and lengt... | python | def __build_unknown_sequence(parts):
"""Build unknown seq (e lines) using pre-tokenized parts from MAF line.
e -- indicates that there is no aligning sequence for a species, but that
there are blocks before and after this one that do align. Format is the
same as the 's' lines, but the start and lengt... | [
"def",
"__build_unknown_sequence",
"(",
"parts",
")",
":",
"strand",
"=",
"parts",
"[",
"4",
"]",
"seq_length",
"=",
"int",
"(",
"parts",
"[",
"3",
"]",
")",
"total_seq_len",
"=",
"int",
"(",
"parts",
"[",
"5",
"]",
")",
"start",
"=",
"(",
"int",
"... | Build unknown seq (e lines) using pre-tokenized parts from MAF line.
e -- indicates that there is no aligning sequence for a species, but that
there are blocks before and after this one that do align. Format is the
same as the 's' lines, but the start and length indicate the start and
size of th... | [
"Build",
"unknown",
"seq",
"(",
"e",
"lines",
")",
"using",
"pre",
"-",
"tokenized",
"parts",
"from",
"MAF",
"line",
"."
] | train | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/io/maf.py#L105-L132 |
pjuren/pyokit | src/pyokit/io/maf.py | __annotate_sequence_with_context | def __annotate_sequence_with_context(seq, i_line_parts):
"""Extract meta data from pre-tokenized maf i-line and populate sequence.
i -- always come after s lines, and contain information about the context of
the sequence. Five fields are given, not counting the 'i'
* source sequence (must match s ... | python | def __annotate_sequence_with_context(seq, i_line_parts):
"""Extract meta data from pre-tokenized maf i-line and populate sequence.
i -- always come after s lines, and contain information about the context of
the sequence. Five fields are given, not counting the 'i'
* source sequence (must match s ... | [
"def",
"__annotate_sequence_with_context",
"(",
"seq",
",",
"i_line_parts",
")",
":",
"if",
"i_line_parts",
"[",
"1",
"]",
"!=",
"seq",
".",
"name",
":",
"raise",
"MAFError",
"(",
"\"Trying to populate meta data for sequence \"",
"+",
"seq",
".",
"name",
"+",
"\... | Extract meta data from pre-tokenized maf i-line and populate sequence.
i -- always come after s lines, and contain information about the context of
the sequence. Five fields are given, not counting the 'i'
* source sequence (must match s line before this)
* left status (see below)
... | [
"Extract",
"meta",
"data",
"from",
"pre",
"-",
"tokenized",
"maf",
"i",
"-",
"line",
"and",
"populate",
"sequence",
"."
] | train | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/io/maf.py#L135-L169 |
pjuren/pyokit | src/pyokit/io/maf.py | __annotate_sequence_with_quality | def __annotate_sequence_with_quality(seq, q_line_parts):
"""Extract meta data from pre-tokenized maf q-line and populate sequence.
q -- quality information about an aligned base in a species. Two fields after
the 'q': the source name and a single digit for each nucleotide in its
sequence (0-9 or F, o... | python | def __annotate_sequence_with_quality(seq, q_line_parts):
"""Extract meta data from pre-tokenized maf q-line and populate sequence.
q -- quality information about an aligned base in a species. Two fields after
the 'q': the source name and a single digit for each nucleotide in its
sequence (0-9 or F, o... | [
"def",
"__annotate_sequence_with_quality",
"(",
"seq",
",",
"q_line_parts",
")",
":",
"if",
"q_line_parts",
"[",
"1",
"]",
"!=",
"seq",
".",
"name",
":",
"raise",
"MAFError",
"(",
"\"trying to populate meta data for sequence \"",
"+",
"seq",
".",
"name",
"+",
"\... | Extract meta data from pre-tokenized maf q-line and populate sequence.
q -- quality information about an aligned base in a species. Two fields after
the 'q': the source name and a single digit for each nucleotide in its
sequence (0-9 or F, or - to indicate a gap). | [
"Extract",
"meta",
"data",
"from",
"pre",
"-",
"tokenized",
"maf",
"q",
"-",
"line",
"and",
"populate",
"sequence",
"."
] | train | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/io/maf.py#L172-L188 |
pjuren/pyokit | src/pyokit/io/maf.py | maf_iterator | def maf_iterator(fn, index_friendly=False,
yield_class=MultipleSequenceAlignment, yield_kw_args={},
verbose=False):
"""
Iterate of MAF format file and yield <yield_class> objects for each block.
MAF files are arranged in blocks. Each block is a multiple alignment. Within
a blo... | python | def maf_iterator(fn, index_friendly=False,
yield_class=MultipleSequenceAlignment, yield_kw_args={},
verbose=False):
"""
Iterate of MAF format file and yield <yield_class> objects for each block.
MAF files are arranged in blocks. Each block is a multiple alignment. Within
a blo... | [
"def",
"maf_iterator",
"(",
"fn",
",",
"index_friendly",
"=",
"False",
",",
"yield_class",
"=",
"MultipleSequenceAlignment",
",",
"yield_kw_args",
"=",
"{",
"}",
",",
"verbose",
"=",
"False",
")",
":",
"try",
":",
"fh",
"=",
"open",
"(",
"fn",
")",
"exce... | Iterate of MAF format file and yield <yield_class> objects for each block.
MAF files are arranged in blocks. Each block is a multiple alignment. Within
a block, the first character of a line indicates what kind of line it is:
a -- key-value pair meta data for block; one per block, should be first line
s -- a ... | [
"Iterate",
"of",
"MAF",
"format",
"file",
"and",
"yield",
"<yield_class",
">",
"objects",
"for",
"each",
"block",
"."
] | train | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/io/maf.py#L195-L271 |
AguaClara/aide_document-DEPRECATED | aide_document/jekyll.py | add_frontmatter | def add_frontmatter(file_name, title, makenew=False):
"""
Adds basic frontmatter to a MarkDown file that will be used in a Jekyll project.
Parameters
==========
file_name : String
Relative file path from where this method is called to the location of the file that will have frontmatter adde... | python | def add_frontmatter(file_name, title, makenew=False):
"""
Adds basic frontmatter to a MarkDown file that will be used in a Jekyll project.
Parameters
==========
file_name : String
Relative file path from where this method is called to the location of the file that will have frontmatter adde... | [
"def",
"add_frontmatter",
"(",
"file_name",
",",
"title",
",",
"makenew",
"=",
"False",
")",
":",
"with",
"open",
"(",
"file_name",
",",
"\"r+\"",
")",
"as",
"oldfile",
":",
"# Creates new file and writes to it if specified",
"if",
"makenew",
":",
"with",
"open"... | Adds basic frontmatter to a MarkDown file that will be used in a Jekyll project.
Parameters
==========
file_name : String
Relative file path from where this method is called to the location of the file that will have frontmatter added.
title : String
Title of the page that will go into ... | [
"Adds",
"basic",
"frontmatter",
"to",
"a",
"MarkDown",
"file",
"that",
"will",
"be",
"used",
"in",
"a",
"Jekyll",
"project",
"."
] | train | https://github.com/AguaClara/aide_document-DEPRECATED/blob/3f3b5c9f321264e0e4d8ed68dfbc080762579815/aide_document/jekyll.py#L12-L50 |
jvanasco/pyramid_debugtoolbar_dogpile | pyramid_debugtoolbar_dogpile/__init__.py | LoggingProxy._derive_db | def _derive_db(self):
"""
this may not have a client on __init__, so this is deferred to
a @property descriptor
"""
client = self
while hasattr(client, 'proxied'):
client = client.proxied
if hasattr(client, 'client'):
client = client.client... | python | def _derive_db(self):
"""
this may not have a client on __init__, so this is deferred to
a @property descriptor
"""
client = self
while hasattr(client, 'proxied'):
client = client.proxied
if hasattr(client, 'client'):
client = client.client... | [
"def",
"_derive_db",
"(",
"self",
")",
":",
"client",
"=",
"self",
"while",
"hasattr",
"(",
"client",
",",
"'proxied'",
")",
":",
"client",
"=",
"client",
".",
"proxied",
"if",
"hasattr",
"(",
"client",
",",
"'client'",
")",
":",
"client",
"=",
"client... | this may not have a client on __init__, so this is deferred to
a @property descriptor | [
"this",
"may",
"not",
"have",
"a",
"client",
"on",
"__init__",
"so",
"this",
"is",
"deferred",
"to",
"a"
] | train | https://github.com/jvanasco/pyramid_debugtoolbar_dogpile/blob/67821b5206886b946e9a6dbd51114a3302c7d644/pyramid_debugtoolbar_dogpile/__init__.py#L59-L73 |
ramrod-project/database-brain | auditpool/run_audit.py | write_log_file | def write_log_file(namespace, document):
"""Writes a line to a log file
Arguments:
namespace {str} -- namespace of document
document {dict} -- document to write to the logs
"""
log_timestamp = asctime(gmtime(document[TS]))
with open("{}{}.{}.log".format(LOG_DIR, namespace, DAY_S... | python | def write_log_file(namespace, document):
"""Writes a line to a log file
Arguments:
namespace {str} -- namespace of document
document {dict} -- document to write to the logs
"""
log_timestamp = asctime(gmtime(document[TS]))
with open("{}{}.{}.log".format(LOG_DIR, namespace, DAY_S... | [
"def",
"write_log_file",
"(",
"namespace",
",",
"document",
")",
":",
"log_timestamp",
"=",
"asctime",
"(",
"gmtime",
"(",
"document",
"[",
"TS",
"]",
")",
")",
"with",
"open",
"(",
"\"{}{}.{}.log\"",
".",
"format",
"(",
"LOG_DIR",
",",
"namespace",
",",
... | Writes a line to a log file
Arguments:
namespace {str} -- namespace of document
document {dict} -- document to write to the logs | [
"Writes",
"a",
"line",
"to",
"a",
"log",
"file",
"Arguments",
":",
"namespace",
"{",
"str",
"}",
"--",
"namespace",
"of",
"document",
"document",
"{",
"dict",
"}",
"--",
"document",
"to",
"write",
"to",
"the",
"logs"
] | train | https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/auditpool/run_audit.py#L27-L41 |
TheSighing/climber | climber/summary.py | FrequencySummarizer._compute_frequencies | def _compute_frequencies(self, word_sent):
"""
Compute the frequency of each of word.
Input:
word_sent, a list of sentences already tokenized.
Output:
freq, a dictionary where freq[w] is the frequency of w.
"""
freq = defaultdict(int)
for s in word_sent:
for word... | python | def _compute_frequencies(self, word_sent):
"""
Compute the frequency of each of word.
Input:
word_sent, a list of sentences already tokenized.
Output:
freq, a dictionary where freq[w] is the frequency of w.
"""
freq = defaultdict(int)
for s in word_sent:
for word... | [
"def",
"_compute_frequencies",
"(",
"self",
",",
"word_sent",
")",
":",
"freq",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"s",
"in",
"word_sent",
":",
"for",
"word",
"in",
"s",
":",
"if",
"word",
"not",
"in",
"self",
".",
"_stopwords",
":",
"freq",
... | Compute the frequency of each of word.
Input:
word_sent, a list of sentences already tokenized.
Output:
freq, a dictionary where freq[w] is the frequency of w. | [
"Compute",
"the",
"frequency",
"of",
"each",
"of",
"word",
".",
"Input",
":",
"word_sent",
"a",
"list",
"of",
"sentences",
"already",
"tokenized",
".",
"Output",
":",
"freq",
"a",
"dictionary",
"where",
"freq",
"[",
"w",
"]",
"is",
"the",
"frequency",
"o... | train | https://github.com/TheSighing/climber/blob/39e4e70c9a768c82a995d8704679d1c046910666/climber/summary.py#L18-L37 |
TheSighing/climber | climber/summary.py | FrequencySummarizer.summarize | def summarize(self, text, n):
"""
Return a list of n sentences
which represent the summary of text.
"""
sents = sent_tokenize(text)
assert n <= len(sents)
word_sent = [word_tokenize(s.lower()) for s in sents]
self._freq = self._compute_frequencies(word_sent)
ranking = defaultdic... | python | def summarize(self, text, n):
"""
Return a list of n sentences
which represent the summary of text.
"""
sents = sent_tokenize(text)
assert n <= len(sents)
word_sent = [word_tokenize(s.lower()) for s in sents]
self._freq = self._compute_frequencies(word_sent)
ranking = defaultdic... | [
"def",
"summarize",
"(",
"self",
",",
"text",
",",
"n",
")",
":",
"sents",
"=",
"sent_tokenize",
"(",
"text",
")",
"assert",
"n",
"<=",
"len",
"(",
"sents",
")",
"word_sent",
"=",
"[",
"word_tokenize",
"(",
"s",
".",
"lower",
"(",
")",
")",
"for",
... | Return a list of n sentences
which represent the summary of text. | [
"Return",
"a",
"list",
"of",
"n",
"sentences",
"which",
"represent",
"the",
"summary",
"of",
"text",
"."
] | train | https://github.com/TheSighing/climber/blob/39e4e70c9a768c82a995d8704679d1c046910666/climber/summary.py#L39-L54 |
TheSighing/climber | climber/summary.py | FrequencySummarizer._rank | def _rank(self, ranking, n):
""" return the first n sentences with highest ranking """
return nlargest(n, ranking, key=ranking.get) | python | def _rank(self, ranking, n):
""" return the first n sentences with highest ranking """
return nlargest(n, ranking, key=ranking.get) | [
"def",
"_rank",
"(",
"self",
",",
"ranking",
",",
"n",
")",
":",
"return",
"nlargest",
"(",
"n",
",",
"ranking",
",",
"key",
"=",
"ranking",
".",
"get",
")"
] | return the first n sentences with highest ranking | [
"return",
"the",
"first",
"n",
"sentences",
"with",
"highest",
"ranking"
] | train | https://github.com/TheSighing/climber/blob/39e4e70c9a768c82a995d8704679d1c046910666/climber/summary.py#L56-L58 |
sys-git/certifiable | certifiable/utils.py | make_certifier | def make_certifier():
"""
Decorator that can wrap raw functions to create a certifier function.
Certifier functions support partial application. If a function wrapped by
`make_certifier` is called with a value as its first argument it will be
certified immediately. If no value is passed, then it ... | python | def make_certifier():
"""
Decorator that can wrap raw functions to create a certifier function.
Certifier functions support partial application. If a function wrapped by
`make_certifier` is called with a value as its first argument it will be
certified immediately. If no value is passed, then it ... | [
"def",
"make_certifier",
"(",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"six",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"value",
"=",
"_undefined",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"certify",
"(",
"val",
")",
... | Decorator that can wrap raw functions to create a certifier function.
Certifier functions support partial application. If a function wrapped by
`make_certifier` is called with a value as its first argument it will be
certified immediately. If no value is passed, then it will return a
function that ca... | [
"Decorator",
"that",
"can",
"wrap",
"raw",
"functions",
"to",
"create",
"a",
"certifier",
"function",
"."
] | train | https://github.com/sys-git/certifiable/blob/a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8/certifiable/utils.py#L33-L65 |
sys-git/certifiable | certifiable/utils.py | certify_required | def certify_required(value, required=False):
"""
Certify that a value is present if required.
:param object value:
The value that is to be certified.
:param bool required:
Is the value required?
:raises CertifierValueError:
Required value is `None`.
"""
# Certify ou... | python | def certify_required(value, required=False):
"""
Certify that a value is present if required.
:param object value:
The value that is to be certified.
:param bool required:
Is the value required?
:raises CertifierValueError:
Required value is `None`.
"""
# Certify ou... | [
"def",
"certify_required",
"(",
"value",
",",
"required",
"=",
"False",
")",
":",
"# Certify our kwargs:",
"if",
"not",
"isinstance",
"(",
"required",
",",
"bool",
")",
":",
"raise",
"CertifierParamError",
"(",
"'required'",
",",
"required",
",",
")",
"if",
... | Certify that a value is present if required.
:param object value:
The value that is to be certified.
:param bool required:
Is the value required?
:raises CertifierValueError:
Required value is `None`. | [
"Certify",
"that",
"a",
"value",
"is",
"present",
"if",
"required",
"."
] | train | https://github.com/sys-git/certifiable/blob/a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8/certifiable/utils.py#L68-L91 |
sys-git/certifiable | certifiable/utils.py | _certify_int_param | def _certify_int_param(value, negative=True, required=False):
"""
A private certifier (to `certifiable`) to certify integers from `certify_int`.
:param int value:
The value to certify is an integer.
:param bool negative:
If the value can be negative. Default=False.
:param bool requi... | python | def _certify_int_param(value, negative=True, required=False):
"""
A private certifier (to `certifiable`) to certify integers from `certify_int`.
:param int value:
The value to certify is an integer.
:param bool negative:
If the value can be negative. Default=False.
:param bool requi... | [
"def",
"_certify_int_param",
"(",
"value",
",",
"negative",
"=",
"True",
",",
"required",
"=",
"False",
")",
":",
"if",
"value",
"is",
"None",
"and",
"not",
"required",
":",
"return",
"if",
"not",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"rais... | A private certifier (to `certifiable`) to certify integers from `certify_int`.
:param int value:
The value to certify is an integer.
:param bool negative:
If the value can be negative. Default=False.
:param bool required:
If the value is required. Default=False.
:raises Certifi... | [
"A",
"private",
"certifier",
"(",
"to",
"certifiable",
")",
"to",
"certify",
"integers",
"from",
"certify_int",
"."
] | train | https://github.com/sys-git/certifiable/blob/a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8/certifiable/utils.py#L94-L120 |
sys-git/certifiable | certifiable/utils.py | certify_parameter | def certify_parameter(certifier, name, value, kwargs=None):
"""
Internal certifier for kwargs passed to Certifiable public methods.
:param callable certifier:
The certifier to use
:param str name:
The name of the kwargs
:param object value:
The value of the kwarg.
:param... | python | def certify_parameter(certifier, name, value, kwargs=None):
"""
Internal certifier for kwargs passed to Certifiable public methods.
:param callable certifier:
The certifier to use
:param str name:
The name of the kwargs
:param object value:
The value of the kwarg.
:param... | [
"def",
"certify_parameter",
"(",
"certifier",
",",
"name",
",",
"value",
",",
"kwargs",
"=",
"None",
")",
":",
"try",
":",
"certifier",
"(",
"value",
",",
"*",
"*",
"kwargs",
"or",
"{",
"}",
")",
"except",
"CertifierError",
"as",
"err",
":",
"six",
"... | Internal certifier for kwargs passed to Certifiable public methods.
:param callable certifier:
The certifier to use
:param str name:
The name of the kwargs
:param object value:
The value of the kwarg.
:param bool required:
Is the param required. Default=False.
:raise... | [
"Internal",
"certifier",
"for",
"kwargs",
"passed",
"to",
"Certifiable",
"public",
"methods",
"."
] | train | https://github.com/sys-git/certifiable/blob/a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8/certifiable/utils.py#L123-L146 |
sys-git/certifiable | certifiable/utils.py | enable_from_env | def enable_from_env(state=None):
"""
Enable certification for this thread based on the environment variable `CERTIFIABLE_STATE`.
:param bool state:
Default status to use.
:return:
The new state.
:rtype:
bool
"""
try:
x = os.environ.get(
ENVVAR,
... | python | def enable_from_env(state=None):
"""
Enable certification for this thread based on the environment variable `CERTIFIABLE_STATE`.
:param bool state:
Default status to use.
:return:
The new state.
:rtype:
bool
"""
try:
x = os.environ.get(
ENVVAR,
... | [
"def",
"enable_from_env",
"(",
"state",
"=",
"None",
")",
":",
"try",
":",
"x",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"ENVVAR",
",",
"state",
",",
")",
"value",
"=",
"bool",
"(",
"int",
"(",
"x",
")",
")",
"except",
"Exception",
":",
"# pyl... | Enable certification for this thread based on the environment variable `CERTIFIABLE_STATE`.
:param bool state:
Default status to use.
:return:
The new state.
:rtype:
bool | [
"Enable",
"certification",
"for",
"this",
"thread",
"based",
"on",
"the",
"environment",
"variable",
"CERTIFIABLE_STATE",
"."
] | train | https://github.com/sys-git/certifiable/blob/a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8/certifiable/utils.py#L196-L216 |
motiejus/tictactoelib | tictactoelib/noninteractive.py | compete | def compete(source_x, source_o, timeout=None, memlimit=None, cgroup='tictactoe',
cgroup_path='/sys/fs/cgroup'):
"""Fights two source files.
Returns either:
* ('ok', 'x' | 'draw' | 'o', GAMEPLAY)
* ('error', GUILTY, REASON, GAMEPLAY)
REASON := utf8-encoded error string (can be up to 65k... | python | def compete(source_x, source_o, timeout=None, memlimit=None, cgroup='tictactoe',
cgroup_path='/sys/fs/cgroup'):
"""Fights two source files.
Returns either:
* ('ok', 'x' | 'draw' | 'o', GAMEPLAY)
* ('error', GUILTY, REASON, GAMEPLAY)
REASON := utf8-encoded error string (can be up to 65k... | [
"def",
"compete",
"(",
"source_x",
",",
"source_o",
",",
"timeout",
"=",
"None",
",",
"memlimit",
"=",
"None",
",",
"cgroup",
"=",
"'tictactoe'",
",",
"cgroup_path",
"=",
"'/sys/fs/cgroup'",
")",
":",
"gameplay",
"=",
"[",
"]",
"for",
"xo",
",",
"moveres... | Fights two source files.
Returns either:
* ('ok', 'x' | 'draw' | 'o', GAMEPLAY)
* ('error', GUILTY, REASON, GAMEPLAY)
REASON := utf8-encoded error string (can be up to 65k chars)
GAMEPLAY := [ NUM ]
GUILTY := 'x' | 'o' (during whose turn the error occured)
NUM := 1..81 | 0
NUM=0 means... | [
"Fights",
"two",
"source",
"files",
"."
] | train | https://github.com/motiejus/tictactoelib/blob/c884e206f11d9472ce0b7d08e06f894b24a20989/tictactoelib/noninteractive.py#L3-L30 |
motiejus/tictactoelib | tictactoelib/noninteractive.py | coords_to_num | def coords_to_num(coords):
"""
>>> coords_to_num((1,1,1,1))
1
>>> coords_to_num((3,3,3,3))
81
>>> coords_to_num((1,1,1,3))
3
>>> coords_to_num((1,3,1,1))
7
>>> coords_to_num((3,3,3,1))
79
>>> coords_to_num((3,3,2,2))
71
>>> coords_to_num((2,1,1,1))
28
>>> ... | python | def coords_to_num(coords):
"""
>>> coords_to_num((1,1,1,1))
1
>>> coords_to_num((3,3,3,3))
81
>>> coords_to_num((1,1,1,3))
3
>>> coords_to_num((1,3,1,1))
7
>>> coords_to_num((3,3,3,1))
79
>>> coords_to_num((3,3,2,2))
71
>>> coords_to_num((2,1,1,1))
28
>>> ... | [
"def",
"coords_to_num",
"(",
"coords",
")",
":",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
"=",
"coords",
"row",
",",
"col",
"=",
"(",
"x1",
"-",
"1",
")",
"*",
"3",
"+",
"x2",
",",
"(",
"y1",
"-",
"1",
")",
"*",
"3",
"+",
"y2",
"# row,col on ... | >>> coords_to_num((1,1,1,1))
1
>>> coords_to_num((3,3,3,3))
81
>>> coords_to_num((1,1,1,3))
3
>>> coords_to_num((1,3,1,1))
7
>>> coords_to_num((3,3,3,1))
79
>>> coords_to_num((3,3,2,2))
71
>>> coords_to_num((2,1,1,1))
28
>>> coords_to_num((2,2,2,2))
41 | [
">>>",
"coords_to_num",
"((",
"1",
"1",
"1",
"1",
"))",
"1",
">>>",
"coords_to_num",
"((",
"3",
"3",
"3",
"3",
"))",
"81",
">>>",
"coords_to_num",
"((",
"1",
"1",
"1",
"3",
"))",
"3",
">>>",
"coords_to_num",
"((",
"1",
"3",
"1",
"1",
"))",
"7",
... | train | https://github.com/motiejus/tictactoelib/blob/c884e206f11d9472ce0b7d08e06f894b24a20989/tictactoelib/noninteractive.py#L33-L54 |
dossier/dossier.fc | python/dossier/fc/string_counter.py | mutates | def mutates(f):
'''Decorator for functions that mutate :class:`StringCounter`.
This raises :exc:`~dossier.fc.exceptions.ReadOnlyException` if
the object is read-only, and increments the generation counter
otherwise.
'''
@wraps(f)
def wrapper(self, *args, **kwargs):
if self.read_only... | python | def mutates(f):
'''Decorator for functions that mutate :class:`StringCounter`.
This raises :exc:`~dossier.fc.exceptions.ReadOnlyException` if
the object is read-only, and increments the generation counter
otherwise.
'''
@wraps(f)
def wrapper(self, *args, **kwargs):
if self.read_only... | [
"def",
"mutates",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"read_only",
":",
"raise",
"ReadOnlyException",
"(",
")",
"self",
".",
"next... | Decorator for functions that mutate :class:`StringCounter`.
This raises :exc:`~dossier.fc.exceptions.ReadOnlyException` if
the object is read-only, and increments the generation counter
otherwise. | [
"Decorator",
"for",
"functions",
"that",
"mutate",
":",
"class",
":",
"StringCounter",
"."
] | train | https://github.com/dossier/dossier.fc/blob/3e969d0cb2592fc06afc1c849d2b22283450b5e2/python/dossier/fc/string_counter.py#L19-L32 |
dossier/dossier.fc | python/dossier/fc/string_counter.py | StringCounter._fix_key | def _fix_key(key):
'''Normalize keys to Unicode strings.'''
if isinstance(key, unicode):
return key
if isinstance(key, str):
# On my system, the default encoding is `ascii`, so let's
# explicitly say UTF-8?
return unicode(key, 'utf-8')
rais... | python | def _fix_key(key):
'''Normalize keys to Unicode strings.'''
if isinstance(key, unicode):
return key
if isinstance(key, str):
# On my system, the default encoding is `ascii`, so let's
# explicitly say UTF-8?
return unicode(key, 'utf-8')
rais... | [
"def",
"_fix_key",
"(",
"key",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"unicode",
")",
":",
"return",
"key",
"if",
"isinstance",
"(",
"key",
",",
"str",
")",
":",
"# On my system, the default encoding is `ascii`, so let's",
"# explicitly say UTF-8?",
"retur... | Normalize keys to Unicode strings. | [
"Normalize",
"keys",
"to",
"Unicode",
"strings",
"."
] | train | https://github.com/dossier/dossier.fc/blob/3e969d0cb2592fc06afc1c849d2b22283450b5e2/python/dossier/fc/string_counter.py#L137-L145 |
dossier/dossier.fc | python/dossier/fc/string_counter.py | StringCounter.truncate_most_common | def truncate_most_common(self, truncation_length):
'''
Sorts the counter and keeps only the most common items up to
``truncation_length`` in place.
:type truncation_length: int
'''
keep_keys = set(v[0] for v in self.most_common(truncation_length))
for key in self... | python | def truncate_most_common(self, truncation_length):
'''
Sorts the counter and keeps only the most common items up to
``truncation_length`` in place.
:type truncation_length: int
'''
keep_keys = set(v[0] for v in self.most_common(truncation_length))
for key in self... | [
"def",
"truncate_most_common",
"(",
"self",
",",
"truncation_length",
")",
":",
"keep_keys",
"=",
"set",
"(",
"v",
"[",
"0",
"]",
"for",
"v",
"in",
"self",
".",
"most_common",
"(",
"truncation_length",
")",
")",
"for",
"key",
"in",
"self",
".",
"keys",
... | Sorts the counter and keeps only the most common items up to
``truncation_length`` in place.
:type truncation_length: int | [
"Sorts",
"the",
"counter",
"and",
"keeps",
"only",
"the",
"most",
"common",
"items",
"up",
"to",
"truncation_length",
"in",
"place",
"."
] | train | https://github.com/dossier/dossier.fc/blob/3e969d0cb2592fc06afc1c849d2b22283450b5e2/python/dossier/fc/string_counter.py#L194-L204 |
MakerReduxCorp/MARDS | MARDS/standard_types.py | rst | def rst(value_rule):
'''Given the data and type information, generate a list of strings for
insertion into a RST document.
'''
lines = []
if value_rule.has('type'):
value_type = value_rule['type'].value
else:
value_type = 'string'
if value_type=='ignore':
pass
els... | python | def rst(value_rule):
'''Given the data and type information, generate a list of strings for
insertion into a RST document.
'''
lines = []
if value_rule.has('type'):
value_type = value_rule['type'].value
else:
value_type = 'string'
if value_type=='ignore':
pass
els... | [
"def",
"rst",
"(",
"value_rule",
")",
":",
"lines",
"=",
"[",
"]",
"if",
"value_rule",
".",
"has",
"(",
"'type'",
")",
":",
"value_type",
"=",
"value_rule",
"[",
"'type'",
"]",
".",
"value",
"else",
":",
"value_type",
"=",
"'string'",
"if",
"value_type... | Given the data and type information, generate a list of strings for
insertion into a RST document. | [
"Given",
"the",
"data",
"and",
"type",
"information",
"generate",
"a",
"list",
"of",
"strings",
"for",
"insertion",
"into",
"a",
"RST",
"document",
"."
] | train | https://github.com/MakerReduxCorp/MARDS/blob/f8ddecc70f2ce1703984cb403c9d5417895170d6/MARDS/standard_types.py#L114-L176 |
MakerReduxCorp/MARDS | MARDS/standard_types.py | split_number_unit | def split_number_unit(string, strip_list=None):
'''
takes a string and grabs the leading number and the following unit
both the number and unit returned are simple strings
returns a triple tuple of (successFlag, number, unit)
successFlag is False if the number is invalid
'''
... | python | def split_number_unit(string, strip_list=None):
'''
takes a string and grabs the leading number and the following unit
both the number and unit returned are simple strings
returns a triple tuple of (successFlag, number, unit)
successFlag is False if the number is invalid
'''
... | [
"def",
"split_number_unit",
"(",
"string",
",",
"strip_list",
"=",
"None",
")",
":",
"successFlag",
"=",
"True",
"state",
"=",
"0",
"number_so_far",
"=",
"\"\"",
"unit_so_far",
"=",
"\"\"",
"decimal_found",
"=",
"False",
"negate_flag",
"=",
"False",
"if",
"s... | takes a string and grabs the leading number and the following unit
both the number and unit returned are simple strings
returns a triple tuple of (successFlag, number, unit)
successFlag is False if the number is invalid | [
"takes",
"a",
"string",
"and",
"grabs",
"the",
"leading",
"number",
"and",
"the",
"following",
"unit",
"both",
"the",
"number",
"and",
"unit",
"returned",
"are",
"simple",
"strings",
"returns",
"a",
"triple",
"tuple",
"of",
"(",
"successFlag",
"number",
"uni... | train | https://github.com/MakerReduxCorp/MARDS/blob/f8ddecc70f2ce1703984cb403c9d5417895170d6/MARDS/standard_types.py#L692-L759 |
kxgames/vecrec | vecrec/collisions.py | circle_touching_line | def circle_touching_line(center, radius, start, end):
""" Return true if the given circle intersects the given segment. Note
that this checks for intersection with a line segment, and not an actual
line.
:param center: Center of the circle.
:type center: Vector
:param radius: Radius of the c... | python | def circle_touching_line(center, radius, start, end):
""" Return true if the given circle intersects the given segment. Note
that this checks for intersection with a line segment, and not an actual
line.
:param center: Center of the circle.
:type center: Vector
:param radius: Radius of the c... | [
"def",
"circle_touching_line",
"(",
"center",
",",
"radius",
",",
"start",
",",
"end",
")",
":",
"C",
",",
"R",
"=",
"center",
",",
"radius",
"A",
",",
"B",
"=",
"start",
",",
"end",
"a",
"=",
"(",
"B",
".",
"x",
"-",
"A",
".",
"x",
")",
"**"... | Return true if the given circle intersects the given segment. Note
that this checks for intersection with a line segment, and not an actual
line.
:param center: Center of the circle.
:type center: Vector
:param radius: Radius of the circle.
:type radius: float
:param start: The first end... | [
"Return",
"true",
"if",
"the",
"given",
"circle",
"intersects",
"the",
"given",
"segment",
".",
"Note",
"that",
"this",
"checks",
"for",
"intersection",
"with",
"a",
"line",
"segment",
"and",
"not",
"an",
"actual",
"line",
"."
] | train | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/collisions.py#L3-L40 |
nir0s/serv | serv/init/upstart.py | Upstart.generate | def generate(self, overwrite=False):
"""Generate a config file for an upstart service.
"""
super(Upstart, self).generate(overwrite=overwrite)
svc_file_template = self.template_prefix + '.conf'
self.svc_file_path = self.generate_into_prefix + '.conf'
self.generate_file_f... | python | def generate(self, overwrite=False):
"""Generate a config file for an upstart service.
"""
super(Upstart, self).generate(overwrite=overwrite)
svc_file_template = self.template_prefix + '.conf'
self.svc_file_path = self.generate_into_prefix + '.conf'
self.generate_file_f... | [
"def",
"generate",
"(",
"self",
",",
"overwrite",
"=",
"False",
")",
":",
"super",
"(",
"Upstart",
",",
"self",
")",
".",
"generate",
"(",
"overwrite",
"=",
"overwrite",
")",
"svc_file_template",
"=",
"self",
".",
"template_prefix",
"+",
"'.conf'",
"self",... | Generate a config file for an upstart service. | [
"Generate",
"a",
"config",
"file",
"for",
"an",
"upstart",
"service",
"."
] | train | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/init/upstart.py#L21-L30 |
nir0s/serv | serv/init/upstart.py | Upstart.install | def install(self):
"""Enable the service"""
super(Upstart, self).install()
self.deploy_service_file(self.svc_file_path, self.svc_file_dest) | python | def install(self):
"""Enable the service"""
super(Upstart, self).install()
self.deploy_service_file(self.svc_file_path, self.svc_file_dest) | [
"def",
"install",
"(",
"self",
")",
":",
"super",
"(",
"Upstart",
",",
"self",
")",
".",
"install",
"(",
")",
"self",
".",
"deploy_service_file",
"(",
"self",
".",
"svc_file_path",
",",
"self",
".",
"svc_file_dest",
")"
] | Enable the service | [
"Enable",
"the",
"service"
] | train | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/init/upstart.py#L32-L36 |
totokaka/pySpaceGDN | pyspacegdn/requests/request.py | Request._fetch | def _fetch(self, default_path):
""" Internal method for fetching.
This differs from :meth:`.fetch` in that it accepts a default path as
an argument.
"""
if not self._path:
path = default_path
else:
path = self._path
req_type = 'GET' if l... | python | def _fetch(self, default_path):
""" Internal method for fetching.
This differs from :meth:`.fetch` in that it accepts a default path as
an argument.
"""
if not self._path:
path = default_path
else:
path = self._path
req_type = 'GET' if l... | [
"def",
"_fetch",
"(",
"self",
",",
"default_path",
")",
":",
"if",
"not",
"self",
".",
"_path",
":",
"path",
"=",
"default_path",
"else",
":",
"path",
"=",
"self",
".",
"_path",
"req_type",
"=",
"'GET'",
"if",
"len",
"(",
"self",
".",
"_post_params",
... | Internal method for fetching.
This differs from :meth:`.fetch` in that it accepts a default path as
an argument. | [
"Internal",
"method",
"for",
"fetching",
"."
] | train | https://github.com/totokaka/pySpaceGDN/blob/55c8be8d751e24873e0a7f7e99d2b715442ec878/pyspacegdn/requests/request.py#L98-L120 |
dossier/dossier.fc | python/dossier/fc/feature_tokens.py | FeatureTokens.tokens | def tokens(self, si, k):
'''`si` is a stream item and `k` is a key in this feature. The purpose
of this method is to dereference the token pointers with
respect to the given stream item. That is, it translates each
sequence of token pointers to a sequence of `Token`.
'''
... | python | def tokens(self, si, k):
'''`si` is a stream item and `k` is a key in this feature. The purpose
of this method is to dereference the token pointers with
respect to the given stream item. That is, it translates each
sequence of token pointers to a sequence of `Token`.
'''
... | [
"def",
"tokens",
"(",
"self",
",",
"si",
",",
"k",
")",
":",
"for",
"tokens",
"in",
"self",
"[",
"k",
"]",
":",
"yield",
"[",
"si",
".",
"body",
".",
"sentences",
"[",
"tagid",
"]",
"[",
"sid",
"]",
".",
"tokens",
"[",
"tid",
"]",
"for",
"tag... | `si` is a stream item and `k` is a key in this feature. The purpose
of this method is to dereference the token pointers with
respect to the given stream item. That is, it translates each
sequence of token pointers to a sequence of `Token`. | [
"si",
"is",
"a",
"stream",
"item",
"and",
"k",
"is",
"a",
"key",
"in",
"this",
"feature",
".",
"The",
"purpose",
"of",
"this",
"method",
"is",
"to",
"dereference",
"the",
"token",
"pointers",
"with",
"respect",
"to",
"the",
"given",
"stream",
"item",
"... | train | https://github.com/dossier/dossier.fc/blob/3e969d0cb2592fc06afc1c849d2b22283450b5e2/python/dossier/fc/feature_tokens.py#L45-L55 |
kyleam/wcut | wcut/io.py | get_lines | def get_lines(fname):
"""Return generator with line number and line for file `fname`."""
for line in fileinput.input(fname):
yield fileinput.filelineno(), line.strip() | python | def get_lines(fname):
"""Return generator with line number and line for file `fname`."""
for line in fileinput.input(fname):
yield fileinput.filelineno(), line.strip() | [
"def",
"get_lines",
"(",
"fname",
")",
":",
"for",
"line",
"in",
"fileinput",
".",
"input",
"(",
"fname",
")",
":",
"yield",
"fileinput",
".",
"filelineno",
"(",
")",
",",
"line",
".",
"strip",
"(",
")"
] | Return generator with line number and line for file `fname`. | [
"Return",
"generator",
"with",
"line",
"number",
"and",
"line",
"for",
"file",
"fname",
"."
] | train | https://github.com/kyleam/wcut/blob/36f6e10a4c3b4dae274a55010463c6acce83bc71/wcut/io.py#L21-L24 |
mkouhei/tonicdnscli | src/tonicdnscli/connect.py | get_token | def get_token(username, password, server):
"""Retrieve token of TonicDNS API.
Arguments:
usename: TonicDNS API username
password: TonicDNS API password
server: TonicDNS API server
"""
method = 'PUT'
uri = 'https://' + server + '/authenticate'
token = ''
authinfo... | python | def get_token(username, password, server):
"""Retrieve token of TonicDNS API.
Arguments:
usename: TonicDNS API username
password: TonicDNS API password
server: TonicDNS API server
"""
method = 'PUT'
uri = 'https://' + server + '/authenticate'
token = ''
authinfo... | [
"def",
"get_token",
"(",
"username",
",",
"password",
",",
"server",
")",
":",
"method",
"=",
"'PUT'",
"uri",
"=",
"'https://'",
"+",
"server",
"+",
"'/authenticate'",
"token",
"=",
"''",
"authinfo",
"=",
"{",
"\"username\"",
":",
"username",
",",
"\"passw... | Retrieve token of TonicDNS API.
Arguments:
usename: TonicDNS API username
password: TonicDNS API password
server: TonicDNS API server | [
"Retrieve",
"token",
"of",
"TonicDNS",
"API",
"."
] | train | https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/connect.py#L30-L50 |
mkouhei/tonicdnscli | src/tonicdnscli/connect.py | tonicdns_client | def tonicdns_client(uri, method, token='', data='', keyword='',
content='', raw_flag=False):
"""TonicDNS API client
Arguments:
uri: TonicDNS API URI
method: TonicDNS API request method
token: TonicDNS API authentication token
data: Post data to... | python | def tonicdns_client(uri, method, token='', data='', keyword='',
content='', raw_flag=False):
"""TonicDNS API client
Arguments:
uri: TonicDNS API URI
method: TonicDNS API request method
token: TonicDNS API authentication token
data: Post data to... | [
"def",
"tonicdns_client",
"(",
"uri",
",",
"method",
",",
"token",
"=",
"''",
",",
"data",
"=",
"''",
",",
"keyword",
"=",
"''",
",",
"content",
"=",
"''",
",",
"raw_flag",
"=",
"False",
")",
":",
"res",
"=",
"request",
"(",
"uri",
",",
"method",
... | TonicDNS API client
Arguments:
uri: TonicDNS API URI
method: TonicDNS API request method
token: TonicDNS API authentication token
data: Post data to TonicDNS API
keyword: Processing keyword of response
content: data exist flag
raw_flag: True ... | [
"TonicDNS",
"API",
"client"
] | train | https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/connect.py#L53-L89 |
mkouhei/tonicdnscli | src/tonicdnscli/connect.py | request | def request(uri, method, data, token=''):
"""Request to TonicDNS API.
Arguments:
uri: TonicDNS API URI
method: TonicDNS API request method
data: Post data to TonicDNS API
token: TonicDNS API authentication token
"""
socket.setdefaulttimeout(__timeout__)
o... | python | def request(uri, method, data, token=''):
"""Request to TonicDNS API.
Arguments:
uri: TonicDNS API URI
method: TonicDNS API request method
data: Post data to TonicDNS API
token: TonicDNS API authentication token
"""
socket.setdefaulttimeout(__timeout__)
o... | [
"def",
"request",
"(",
"uri",
",",
"method",
",",
"data",
",",
"token",
"=",
"''",
")",
":",
"socket",
".",
"setdefaulttimeout",
"(",
"__timeout__",
")",
"obj",
"=",
"urllib",
".",
"build_opener",
"(",
"urllib",
".",
"HTTPHandler",
")",
"# encoding json",
... | Request to TonicDNS API.
Arguments:
uri: TonicDNS API URI
method: TonicDNS API request method
data: Post data to TonicDNS API
token: TonicDNS API authentication token | [
"Request",
"to",
"TonicDNS",
"API",
"."
] | train | https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/connect.py#L92-L132 |
mkouhei/tonicdnscli | src/tonicdnscli/connect.py | response | def response(uri, method, res, token='', keyword='',
content='', raw_flag=False):
"""Response of tonicdns_client request
Arguments:
uri: TonicDNS API URI
method: TonicDNS API request method
res: Response of against request to TonicDNS API
token: Toni... | python | def response(uri, method, res, token='', keyword='',
content='', raw_flag=False):
"""Response of tonicdns_client request
Arguments:
uri: TonicDNS API URI
method: TonicDNS API request method
res: Response of against request to TonicDNS API
token: Toni... | [
"def",
"response",
"(",
"uri",
",",
"method",
",",
"res",
",",
"token",
"=",
"''",
",",
"keyword",
"=",
"''",
",",
"content",
"=",
"''",
",",
"raw_flag",
"=",
"False",
")",
":",
"if",
"method",
"==",
"'GET'",
"or",
"(",
"method",
"==",
"'PUT'",
"... | Response of tonicdns_client request
Arguments:
uri: TonicDNS API URI
method: TonicDNS API request method
res: Response of against request to TonicDNS API
token: TonicDNS API token
keyword: Processing keyword
content: JSON data
raw_flag: True... | [
"Response",
"of",
"tonicdns_client",
"request"
] | train | https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/connect.py#L135-L207 |
mkouhei/tonicdnscli | src/tonicdnscli/connect.py | search_record | def search_record(datas, keyword):
"""Search target JSON -> dictionary
Arguments:
datas: dictionary of record datas
keyword: search keyword (default is null)
Key target is "name" or "content" or "type". default null.
Either key and type, or on the other hand.
When keyword has inc... | python | def search_record(datas, keyword):
"""Search target JSON -> dictionary
Arguments:
datas: dictionary of record datas
keyword: search keyword (default is null)
Key target is "name" or "content" or "type". default null.
Either key and type, or on the other hand.
When keyword has inc... | [
"def",
"search_record",
"(",
"datas",
",",
"keyword",
")",
":",
"key_name",
",",
"key_type",
",",
"key_content",
"=",
"False",
",",
"False",
",",
"False",
"if",
"keyword",
".",
"find",
"(",
"','",
")",
">",
"-",
"1",
":",
"if",
"len",
"(",
"keyword",... | Search target JSON -> dictionary
Arguments:
datas: dictionary of record datas
keyword: search keyword (default is null)
Key target is "name" or "content" or "type". default null.
Either key and type, or on the other hand.
When keyword has include camma ",",
Separate keyword to na... | [
"Search",
"target",
"JSON",
"-",
">",
"dictionary"
] | train | https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/connect.py#L210-L253 |
mkouhei/tonicdnscli | src/tonicdnscli/connect.py | print_formatted | def print_formatted(datas):
"""Pretty print JSON DATA
Argument:
datas: dictionary of data
"""
if not datas:
print("No data")
exit(1)
if isinstance(datas, list):
# get all zones
# API /zone without :identifier
hr()
print('%-20s %-8s %-12s'
... | python | def print_formatted(datas):
"""Pretty print JSON DATA
Argument:
datas: dictionary of data
"""
if not datas:
print("No data")
exit(1)
if isinstance(datas, list):
# get all zones
# API /zone without :identifier
hr()
print('%-20s %-8s %-12s'
... | [
"def",
"print_formatted",
"(",
"datas",
")",
":",
"if",
"not",
"datas",
":",
"print",
"(",
"\"No data\"",
")",
"exit",
"(",
"1",
")",
"if",
"isinstance",
"(",
"datas",
",",
"list",
")",
":",
"# get all zones",
"# API /zone without :identifier",
"hr",
"(",
... | Pretty print JSON DATA
Argument:
datas: dictionary of data | [
"Pretty",
"print",
"JSON",
"DATA"
] | train | https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/connect.py#L256-L374 |
EventTeam/beliefs | src/beliefs/beliefstate.py | BeliefState.add_deferred_effect | def add_deferred_effect(self, effect, pos):
""" Pushes an (pos, effect) tuple onto a stack to later be executed if the
state reaches the 'pos'."""
if not isinstance(pos, (unicode, str)):
raise Exception("Invalid POS tag. Must be string not %d" % (type(pos)))
if self['speaker_... | python | def add_deferred_effect(self, effect, pos):
""" Pushes an (pos, effect) tuple onto a stack to later be executed if the
state reaches the 'pos'."""
if not isinstance(pos, (unicode, str)):
raise Exception("Invalid POS tag. Must be string not %d" % (type(pos)))
if self['speaker_... | [
"def",
"add_deferred_effect",
"(",
"self",
",",
"effect",
",",
"pos",
")",
":",
"if",
"not",
"isinstance",
"(",
"pos",
",",
"(",
"unicode",
",",
"str",
")",
")",
":",
"raise",
"Exception",
"(",
"\"Invalid POS tag. Must be string not %d\"",
"%",
"(",
"type",
... | Pushes an (pos, effect) tuple onto a stack to later be executed if the
state reaches the 'pos'. | [
"Pushes",
"an",
"(",
"pos",
"effect",
")",
"tuple",
"onto",
"a",
"stack",
"to",
"later",
"be",
"executed",
"if",
"the",
"state",
"reaches",
"the",
"pos",
"."
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/beliefstate.py#L67-L77 |
EventTeam/beliefs | src/beliefs/beliefstate.py | BeliefState.execute_deferred_effects | def execute_deferred_effects(self, pos):
""" Evaluates deferred effects that are triggered by the prefix of the
pos on the current beliefstate. For instance, if the effect is triggered
by the 'NN' pos, then the effect will be triggered by 'NN' or 'NNS'."""
costs = 0
to_delete = [... | python | def execute_deferred_effects(self, pos):
""" Evaluates deferred effects that are triggered by the prefix of the
pos on the current beliefstate. For instance, if the effect is triggered
by the 'NN' pos, then the effect will be triggered by 'NN' or 'NNS'."""
costs = 0
to_delete = [... | [
"def",
"execute_deferred_effects",
"(",
"self",
",",
"pos",
")",
":",
"costs",
"=",
"0",
"to_delete",
"=",
"[",
"]",
"for",
"entry",
"in",
"self",
".",
"__dict__",
"[",
"'deferred_effects'",
"]",
":",
"effect_pos",
",",
"effect",
"=",
"entry",
"if",
"pos... | Evaluates deferred effects that are triggered by the prefix of the
pos on the current beliefstate. For instance, if the effect is triggered
by the 'NN' pos, then the effect will be triggered by 'NN' or 'NNS'. | [
"Evaluates",
"deferred",
"effects",
"that",
"are",
"triggered",
"by",
"the",
"prefix",
"of",
"the",
"pos",
"on",
"the",
"current",
"beliefstate",
".",
"For",
"instance",
"if",
"the",
"effect",
"is",
"triggered",
"by",
"the",
"NN",
"pos",
"then",
"the",
"ef... | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/beliefstate.py#L79-L94 |
EventTeam/beliefs | src/beliefs/beliefstate.py | BeliefState.set_environment_variable | def set_environment_variable(self, key, val):
""" Sets a variable if that variable is not already set """
if self.get_environment_variable(key) in [None, val]:
self.__dict__['environment_variables'][key] = val
else:
raise Contradiction("Could not set environment variable ... | python | def set_environment_variable(self, key, val):
""" Sets a variable if that variable is not already set """
if self.get_environment_variable(key) in [None, val]:
self.__dict__['environment_variables'][key] = val
else:
raise Contradiction("Could not set environment variable ... | [
"def",
"set_environment_variable",
"(",
"self",
",",
"key",
",",
"val",
")",
":",
"if",
"self",
".",
"get_environment_variable",
"(",
"key",
")",
"in",
"[",
"None",
",",
"val",
"]",
":",
"self",
".",
"__dict__",
"[",
"'environment_variables'",
"]",
"[",
... | Sets a variable if that variable is not already set | [
"Sets",
"a",
"variable",
"if",
"that",
"variable",
"is",
"not",
"already",
"set"
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/beliefstate.py#L96-L101 |
EventTeam/beliefs | src/beliefs/beliefstate.py | BeliefState.iter_breadth_first | def iter_breadth_first(self, root=None):
""" Traverses the belief state's structure breadth-first """
if root == None:
root = self
yield root
last = root
for node in self.iter_breadth_first(root):
if isinstance(node, DictCell):
# recurse
... | python | def iter_breadth_first(self, root=None):
""" Traverses the belief state's structure breadth-first """
if root == None:
root = self
yield root
last = root
for node in self.iter_breadth_first(root):
if isinstance(node, DictCell):
# recurse
... | [
"def",
"iter_breadth_first",
"(",
"self",
",",
"root",
"=",
"None",
")",
":",
"if",
"root",
"==",
"None",
":",
"root",
"=",
"self",
"yield",
"root",
"last",
"=",
"root",
"for",
"node",
"in",
"self",
".",
"iter_breadth_first",
"(",
"root",
")",
":",
"... | Traverses the belief state's structure breadth-first | [
"Traverses",
"the",
"belief",
"state",
"s",
"structure",
"breadth",
"-",
"first"
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/beliefstate.py#L119-L132 |
EventTeam/beliefs | src/beliefs/beliefstate.py | BeliefState.find_path | def find_path(self, test_function=None, on_targets=False):
"""
General helper method that iterates breadth-first over the referential_domain's
cells and returns a path where the test_function is True
"""
assert self.has_referential_domain(), "need context set"
if not tes... | python | def find_path(self, test_function=None, on_targets=False):
"""
General helper method that iterates breadth-first over the referential_domain's
cells and returns a path where the test_function is True
"""
assert self.has_referential_domain(), "need context set"
if not tes... | [
"def",
"find_path",
"(",
"self",
",",
"test_function",
"=",
"None",
",",
"on_targets",
"=",
"False",
")",
":",
"assert",
"self",
".",
"has_referential_domain",
"(",
")",
",",
"\"need context set\"",
"if",
"not",
"test_function",
":",
"test_function",
"=",
"lam... | General helper method that iterates breadth-first over the referential_domain's
cells and returns a path where the test_function is True | [
"General",
"helper",
"method",
"that",
"iterates",
"breadth",
"-",
"first",
"over",
"the",
"referential_domain",
"s",
"cells",
"and",
"returns",
"a",
"path",
"where",
"the",
"test_function",
"is",
"True"
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/beliefstate.py#L134-L169 |
EventTeam/beliefs | src/beliefs/beliefstate.py | BeliefState.get_nth_unique_value | def get_nth_unique_value(self, keypath, n, distance_from, open_interval=True):
"""
Returns the `n-1`th unique value, or raises
a contradiction if that is out of bounds
"""
unique_values = self.get_ordered_values(keypath, distance_from, open_interval)
if 0 <= n < len(uniqu... | python | def get_nth_unique_value(self, keypath, n, distance_from, open_interval=True):
"""
Returns the `n-1`th unique value, or raises
a contradiction if that is out of bounds
"""
unique_values = self.get_ordered_values(keypath, distance_from, open_interval)
if 0 <= n < len(uniqu... | [
"def",
"get_nth_unique_value",
"(",
"self",
",",
"keypath",
",",
"n",
",",
"distance_from",
",",
"open_interval",
"=",
"True",
")",
":",
"unique_values",
"=",
"self",
".",
"get_ordered_values",
"(",
"keypath",
",",
"distance_from",
",",
"open_interval",
")",
"... | Returns the `n-1`th unique value, or raises
a contradiction if that is out of bounds | [
"Returns",
"the",
"n",
"-",
"1",
"th",
"unique",
"value",
"or",
"raises",
"a",
"contradiction",
"if",
"that",
"is",
"out",
"of",
"bounds"
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/beliefstate.py#L172-L182 |
EventTeam/beliefs | src/beliefs/beliefstate.py | BeliefState.get_ordered_values | def get_ordered_values(self, keypath, distance_from, open_interval=True):
"""
Retrieves the referents's values sorted by their distance from the
min, max, or mid value.
"""
values = []
if keypath[0] == 'target':
# instances start with 'target' prefix, but
... | python | def get_ordered_values(self, keypath, distance_from, open_interval=True):
"""
Retrieves the referents's values sorted by their distance from the
min, max, or mid value.
"""
values = []
if keypath[0] == 'target':
# instances start with 'target' prefix, but
... | [
"def",
"get_ordered_values",
"(",
"self",
",",
"keypath",
",",
"distance_from",
",",
"open_interval",
"=",
"True",
")",
":",
"values",
"=",
"[",
"]",
"if",
"keypath",
"[",
"0",
"]",
"==",
"'target'",
":",
"# instances start with 'target' prefix, but ",
"# don't ... | Retrieves the referents's values sorted by their distance from the
min, max, or mid value. | [
"Retrieves",
"the",
"referents",
"s",
"values",
"sorted",
"by",
"their",
"distance",
"from",
"the",
"min",
"max",
"or",
"mid",
"value",
"."
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/beliefstate.py#L184-L236 |
EventTeam/beliefs | src/beliefs/beliefstate.py | BeliefState.get_paths_for_attribute_set | def get_paths_for_attribute_set(self, keys):
"""
Given a list/set of keys (or one key), returns the parts that have
all of the keys in the list.
Because on_targets=True, this DOES NOT WORK WITH TOP LEVEL PROPERTIES,
only those of targets.
These paths are not pointers to... | python | def get_paths_for_attribute_set(self, keys):
"""
Given a list/set of keys (or one key), returns the parts that have
all of the keys in the list.
Because on_targets=True, this DOES NOT WORK WITH TOP LEVEL PROPERTIES,
only those of targets.
These paths are not pointers to... | [
"def",
"get_paths_for_attribute_set",
"(",
"self",
",",
"keys",
")",
":",
"if",
"not",
"isinstance",
"(",
"keys",
",",
"(",
"list",
",",
"set",
")",
")",
":",
"keys",
"=",
"[",
"keys",
"]",
"has_all_keys",
"=",
"lambda",
"name",
",",
"structure",
":",
... | Given a list/set of keys (or one key), returns the parts that have
all of the keys in the list.
Because on_targets=True, this DOES NOT WORK WITH TOP LEVEL PROPERTIES,
only those of targets.
These paths are not pointers to the objects themselves, but tuples of
attribute names th... | [
"Given",
"a",
"list",
"/",
"set",
"of",
"keys",
"(",
"or",
"one",
"key",
")",
"returns",
"the",
"parts",
"that",
"have",
"all",
"of",
"the",
"keys",
"in",
"the",
"list",
"."
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/beliefstate.py#L238-L255 |
EventTeam/beliefs | src/beliefs/beliefstate.py | BeliefState.get_parts | def get_parts(self):
"""
Searches for all DictCells (with nested structure)
"""
return self.find_path(lambda x: isinstance(x[1], DictCell), on_targets=True) | python | def get_parts(self):
"""
Searches for all DictCells (with nested structure)
"""
return self.find_path(lambda x: isinstance(x[1], DictCell), on_targets=True) | [
"def",
"get_parts",
"(",
"self",
")",
":",
"return",
"self",
".",
"find_path",
"(",
"lambda",
"x",
":",
"isinstance",
"(",
"x",
"[",
"1",
"]",
",",
"DictCell",
")",
",",
"on_targets",
"=",
"True",
")"
] | Searches for all DictCells (with nested structure) | [
"Searches",
"for",
"all",
"DictCells",
"(",
"with",
"nested",
"structure",
")"
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/beliefstate.py#L257-L261 |
EventTeam/beliefs | src/beliefs/beliefstate.py | BeliefState.get_paths_for_attribute | def get_paths_for_attribute(self, attribute_name):
"""
Returns a path list to all attributes that have with a particular name.
"""
has_name = lambda name, structure: name == attribute_name
return self.find_path(has_name, on_targets=True) | python | def get_paths_for_attribute(self, attribute_name):
"""
Returns a path list to all attributes that have with a particular name.
"""
has_name = lambda name, structure: name == attribute_name
return self.find_path(has_name, on_targets=True) | [
"def",
"get_paths_for_attribute",
"(",
"self",
",",
"attribute_name",
")",
":",
"has_name",
"=",
"lambda",
"name",
",",
"structure",
":",
"name",
"==",
"attribute_name",
"return",
"self",
".",
"find_path",
"(",
"has_name",
",",
"on_targets",
"=",
"True",
")"
] | Returns a path list to all attributes that have with a particular name. | [
"Returns",
"a",
"path",
"list",
"to",
"all",
"attributes",
"that",
"have",
"with",
"a",
"particular",
"name",
"."
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/beliefstate.py#L263-L268 |
EventTeam/beliefs | src/beliefs/beliefstate.py | BeliefState.merge | def merge(self, keypath, value, op='set'):
"""
First gets the cell at BeliefState's keypath, or creates a new cell
from the first target that has that keypath (This could mess up if the
member its copying from has a different Cell or domain for that keypath.)
Second, this merges... | python | def merge(self, keypath, value, op='set'):
"""
First gets the cell at BeliefState's keypath, or creates a new cell
from the first target that has that keypath (This could mess up if the
member its copying from has a different Cell or domain for that keypath.)
Second, this merges... | [
"def",
"merge",
"(",
"self",
",",
"keypath",
",",
"value",
",",
"op",
"=",
"'set'",
")",
":",
"negated",
"=",
"False",
"keypath",
"=",
"keypath",
"[",
":",
"]",
"# copy it ",
"if",
"keypath",
"[",
"0",
"]",
"==",
"'target'",
":",
"# only pull negated i... | First gets the cell at BeliefState's keypath, or creates a new cell
from the first target that has that keypath (This could mess up if the
member its copying from has a different Cell or domain for that keypath.)
Second, this merges that cell with the value | [
"First",
"gets",
"the",
"cell",
"at",
"BeliefState",
"s",
"keypath",
"or",
"creates",
"a",
"new",
"cell",
"from",
"the",
"first",
"target",
"that",
"has",
"that",
"keypath",
"(",
"This",
"could",
"mess",
"up",
"if",
"the",
"member",
"its",
"copying",
"fr... | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/beliefstate.py#L270-L321 |
EventTeam/beliefs | src/beliefs/beliefstate.py | BeliefState.add_cell | def add_cell(self, keypath, cell):
""" Adds a new cell to the end of `keypath` of type `cell`"""
keypath = keypath[:] # copy
inner = self # the most inner dict where cell is added
cellname = keypath # the name of the cell
assert keypath not in self, "Already exists: %s " % (str... | python | def add_cell(self, keypath, cell):
""" Adds a new cell to the end of `keypath` of type `cell`"""
keypath = keypath[:] # copy
inner = self # the most inner dict where cell is added
cellname = keypath # the name of the cell
assert keypath not in self, "Already exists: %s " % (str... | [
"def",
"add_cell",
"(",
"self",
",",
"keypath",
",",
"cell",
")",
":",
"keypath",
"=",
"keypath",
"[",
":",
"]",
"# copy",
"inner",
"=",
"self",
"# the most inner dict where cell is added",
"cellname",
"=",
"keypath",
"# the name of the cell",
"assert",
"keypath",... | Adds a new cell to the end of `keypath` of type `cell` | [
"Adds",
"a",
"new",
"cell",
"to",
"the",
"end",
"of",
"keypath",
"of",
"type",
"cell"
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/beliefstate.py#L323-L338 |
EventTeam/beliefs | src/beliefs/beliefstate.py | BeliefState.is_entailed_by | def is_entailed_by(self, other):
"""
Given two beliefstates, returns True iff the calling instance
implies the other beliefstate, meaning it contains at least the same
structure (for all structures) and all values (for all defined values).
Inverse of `entails`.
... | python | def is_entailed_by(self, other):
"""
Given two beliefstates, returns True iff the calling instance
implies the other beliefstate, meaning it contains at least the same
structure (for all structures) and all values (for all defined values).
Inverse of `entails`.
... | [
"def",
"is_entailed_by",
"(",
"self",
",",
"other",
")",
":",
"for",
"(",
"s_key",
",",
"s_val",
")",
"in",
"self",
":",
"if",
"s_key",
"in",
"other",
":",
"if",
"not",
"hasattr",
"(",
"other",
"[",
"s_key",
"]",
",",
"'implies'",
")",
":",
"raise"... | Given two beliefstates, returns True iff the calling instance
implies the other beliefstate, meaning it contains at least the same
structure (for all structures) and all values (for all defined values).
Inverse of `entails`.
Note: this only compares the items in the DictCell, n... | [
"Given",
"two",
"beliefstates",
"returns",
"True",
"iff",
"the",
"calling",
"instance",
"implies",
"the",
"other",
"beliefstate",
"meaning",
"it",
"contains",
"at",
"least",
"the",
"same",
"structure",
"(",
"for",
"all",
"structures",
")",
"and",
"all",
"value... | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/beliefstate.py#L351-L370 |
EventTeam/beliefs | src/beliefs/beliefstate.py | BeliefState.is_equal | def is_equal(self, other):
"""
Two beliefstates are equal if all of their part names are equal and all
of their cell's values return True for is_equal().
Note: this only compares the items in the DictCell, not `pos`,
`environment_variables` or `deferred_effects`.
"""
... | python | def is_equal(self, other):
"""
Two beliefstates are equal if all of their part names are equal and all
of their cell's values return True for is_equal().
Note: this only compares the items in the DictCell, not `pos`,
`environment_variables` or `deferred_effects`.
"""
... | [
"def",
"is_equal",
"(",
"self",
",",
"other",
")",
":",
"return",
"hash",
"(",
"self",
")",
"==",
"hash",
"(",
"other",
")",
"for",
"(",
"this",
",",
"that",
")",
"in",
"itertools",
".",
"izip_longest",
"(",
"self",
",",
"other",
")",
":",
"if",
... | Two beliefstates are equal if all of their part names are equal and all
of their cell's values return True for is_equal().
Note: this only compares the items in the DictCell, not `pos`,
`environment_variables` or `deferred_effects`. | [
"Two",
"beliefstates",
"are",
"equal",
"if",
"all",
"of",
"their",
"part",
"names",
"are",
"equal",
"and",
"all",
"of",
"their",
"cell",
"s",
"values",
"return",
"True",
"for",
"is_equal",
"()",
"."
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/beliefstate.py#L372-L388 |
EventTeam/beliefs | src/beliefs/beliefstate.py | BeliefState.is_contradictory | def is_contradictory(self, other):
""" Two beliefstates are incompatible if the other beliefstates's entities
are not consistent with or accessible from the caller.
Note: this only compares the items in the DictCell, not `pos`,
`environment_variables` or `deferred_effects`.
... | python | def is_contradictory(self, other):
""" Two beliefstates are incompatible if the other beliefstates's entities
are not consistent with or accessible from the caller.
Note: this only compares the items in the DictCell, not `pos`,
`environment_variables` or `deferred_effects`.
... | [
"def",
"is_contradictory",
"(",
"self",
",",
"other",
")",
":",
"for",
"(",
"s_key",
",",
"s_val",
")",
"in",
"self",
":",
"if",
"s_key",
"in",
"other",
"and",
"s_val",
".",
"is_contradictory",
"(",
"other",
"[",
"s_key",
"]",
")",
":",
"return",
"Tr... | Two beliefstates are incompatible if the other beliefstates's entities
are not consistent with or accessible from the caller.
Note: this only compares the items in the DictCell, not `pos`,
`environment_variables` or `deferred_effects`. | [
"Two",
"beliefstates",
"are",
"incompatible",
"if",
"the",
"other",
"beliefstates",
"s",
"entities",
"are",
"not",
"consistent",
"with",
"or",
"accessible",
"from",
"the",
"caller",
".",
"Note",
":",
"this",
"only",
"compares",
"the",
"items",
"in",
"the",
"... | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/beliefstate.py#L390-L400 |
EventTeam/beliefs | src/beliefs/beliefstate.py | BeliefState.size | def size(self):
""" Returns the size of the belief state.
Initially if there are $n$ consistent members, (the result of `self.number_of_singleton_referents()`)
then there are generally $2^{n}-1$ valid belief states.
"""
n = self.number_of_singleton_referents()
targets =... | python | def size(self):
""" Returns the size of the belief state.
Initially if there are $n$ consistent members, (the result of `self.number_of_singleton_referents()`)
then there are generally $2^{n}-1$ valid belief states.
"""
n = self.number_of_singleton_referents()
targets =... | [
"def",
"size",
"(",
"self",
")",
":",
"n",
"=",
"self",
".",
"number_of_singleton_referents",
"(",
")",
"targets",
"=",
"list",
"(",
"self",
".",
"iter_referents_tuples",
"(",
")",
")",
"n_targets",
"=",
"len",
"(",
"targets",
")",
"if",
"n",
"==",
"0"... | Returns the size of the belief state.
Initially if there are $n$ consistent members, (the result of `self.number_of_singleton_referents()`)
then there are generally $2^{n}-1$ valid belief states. | [
"Returns",
"the",
"size",
"of",
"the",
"belief",
"state",
"."
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/beliefstate.py#L402-L419 |
EventTeam/beliefs | src/beliefs/beliefstate.py | BeliefState.iter_referents | def iter_referents(self):
""" Generates target sets that are compatible with the current beliefstate. """
tlow, thigh = self['targetset_arity'].get_tuple()
clow, chigh = self['contrast_arity'].get_tuple()
referents = list(self.iter_singleton_referents())
t = len(referents)
... | python | def iter_referents(self):
""" Generates target sets that are compatible with the current beliefstate. """
tlow, thigh = self['targetset_arity'].get_tuple()
clow, chigh = self['contrast_arity'].get_tuple()
referents = list(self.iter_singleton_referents())
t = len(referents)
... | [
"def",
"iter_referents",
"(",
"self",
")",
":",
"tlow",
",",
"thigh",
"=",
"self",
"[",
"'targetset_arity'",
"]",
".",
"get_tuple",
"(",
")",
"clow",
",",
"chigh",
"=",
"self",
"[",
"'contrast_arity'",
"]",
".",
"get_tuple",
"(",
")",
"referents",
"=",
... | Generates target sets that are compatible with the current beliefstate. | [
"Generates",
"target",
"sets",
"that",
"are",
"compatible",
"with",
"the",
"current",
"beliefstate",
"."
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/beliefstate.py#L431-L444 |
EventTeam/beliefs | src/beliefs/beliefstate.py | BeliefState.iter_referents_tuples | def iter_referents_tuples(self):
""" Generates target sets (as tuples of indicies) that are compatible with
the current beliefstate."""
tlow, thigh = self['targetset_arity'].get_tuple()
clow, chigh = self['contrast_arity'].get_tuple()
singletons = list([int(i) for i,_ in self.ite... | python | def iter_referents_tuples(self):
""" Generates target sets (as tuples of indicies) that are compatible with
the current beliefstate."""
tlow, thigh = self['targetset_arity'].get_tuple()
clow, chigh = self['contrast_arity'].get_tuple()
singletons = list([int(i) for i,_ in self.ite... | [
"def",
"iter_referents_tuples",
"(",
"self",
")",
":",
"tlow",
",",
"thigh",
"=",
"self",
"[",
"'targetset_arity'",
"]",
".",
"get_tuple",
"(",
")",
"clow",
",",
"chigh",
"=",
"self",
"[",
"'contrast_arity'",
"]",
".",
"get_tuple",
"(",
")",
"singletons",
... | Generates target sets (as tuples of indicies) that are compatible with
the current beliefstate. | [
"Generates",
"target",
"sets",
"(",
"as",
"tuples",
"of",
"indicies",
")",
"that",
"are",
"compatible",
"with",
"the",
"current",
"beliefstate",
"."
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/beliefstate.py#L446-L458 |
EventTeam/beliefs | src/beliefs/beliefstate.py | BeliefState.number_of_singleton_referents | def number_of_singleton_referents(self):
"""
Returns the number of singleton elements of the referential domain that are
compatible with the current belief state.
This is the size of the union of all referent sets.
"""
if self.__dict__['referential_domain']:
... | python | def number_of_singleton_referents(self):
"""
Returns the number of singleton elements of the referential domain that are
compatible with the current belief state.
This is the size of the union of all referent sets.
"""
if self.__dict__['referential_domain']:
... | [
"def",
"number_of_singleton_referents",
"(",
"self",
")",
":",
"if",
"self",
".",
"__dict__",
"[",
"'referential_domain'",
"]",
":",
"ct",
"=",
"0",
"for",
"i",
"in",
"self",
".",
"iter_singleton_referents",
"(",
")",
":",
"ct",
"+=",
"1",
"return",
"ct",
... | Returns the number of singleton elements of the referential domain that are
compatible with the current belief state.
This is the size of the union of all referent sets. | [
"Returns",
"the",
"number",
"of",
"singleton",
"elements",
"of",
"the",
"referential",
"domain",
"that",
"are",
"compatible",
"with",
"the",
"current",
"belief",
"state",
"."
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/beliefstate.py#L460-L473 |
EventTeam/beliefs | src/beliefs/beliefstate.py | BeliefState.iter_singleton_referents | def iter_singleton_referents(self):
"""
Iterator of all of the singleton members of the context set.
NOTE: this evaluates entities one-at-a-time, and does not handle relational constraints.
"""
try:
for member in self.__dict__['referential_domain'].iter_entities():
... | python | def iter_singleton_referents(self):
"""
Iterator of all of the singleton members of the context set.
NOTE: this evaluates entities one-at-a-time, and does not handle relational constraints.
"""
try:
for member in self.__dict__['referential_domain'].iter_entities():
... | [
"def",
"iter_singleton_referents",
"(",
"self",
")",
":",
"try",
":",
"for",
"member",
"in",
"self",
".",
"__dict__",
"[",
"'referential_domain'",
"]",
".",
"iter_entities",
"(",
")",
":",
"if",
"self",
"[",
"'target'",
"]",
".",
"is_entailed_by",
"(",
"me... | Iterator of all of the singleton members of the context set.
NOTE: this evaluates entities one-at-a-time, and does not handle relational constraints. | [
"Iterator",
"of",
"all",
"of",
"the",
"singleton",
"members",
"of",
"the",
"context",
"set",
"."
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/beliefstate.py#L475-L486 |
EventTeam/beliefs | src/beliefs/beliefstate.py | BeliefState.iter_singleton_referents_tuples | def iter_singleton_referents_tuples(self):
"""
Iterator of all of the singleton members's id number of the context set.
NOTE: this evaluates entities one-at-a-time, and does not handle relational constraints.
"""
try:
for member in self.__dict__['referential_domain']... | python | def iter_singleton_referents_tuples(self):
"""
Iterator of all of the singleton members's id number of the context set.
NOTE: this evaluates entities one-at-a-time, and does not handle relational constraints.
"""
try:
for member in self.__dict__['referential_domain']... | [
"def",
"iter_singleton_referents_tuples",
"(",
"self",
")",
":",
"try",
":",
"for",
"member",
"in",
"self",
".",
"__dict__",
"[",
"'referential_domain'",
"]",
".",
"iter_entities",
"(",
")",
":",
"if",
"self",
"[",
"'target'",
"]",
".",
"is_entailed_by",
"("... | Iterator of all of the singleton members's id number of the context set.
NOTE: this evaluates entities one-at-a-time, and does not handle relational constraints. | [
"Iterator",
"of",
"all",
"of",
"the",
"singleton",
"members",
"s",
"id",
"number",
"of",
"the",
"context",
"set",
"."
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/beliefstate.py#L488-L499 |
EventTeam/beliefs | src/beliefs/beliefstate.py | BeliefState.to_latex | def to_latex(self, number=0):
""" Returns a raw text string that contains a latex representation of
the belief state as an attribute-value matrix. This requires:
\usepackage{avm}
"""
latex = r"""\avmfont{\sc}
\avmoptions{sorted,active}
\avmvalfont{\rm}"""
latex += "... | python | def to_latex(self, number=0):
""" Returns a raw text string that contains a latex representation of
the belief state as an attribute-value matrix. This requires:
\usepackage{avm}
"""
latex = r"""\avmfont{\sc}
\avmoptions{sorted,active}
\avmvalfont{\rm}"""
latex += "... | [
"def",
"to_latex",
"(",
"self",
",",
"number",
"=",
"0",
")",
":",
"latex",
"=",
"r\"\"\"\\avmfont{\\sc}\n\\avmoptions{sorted,active}\n\\avmvalfont{\\rm}\"\"\"",
"latex",
"+=",
"\"\\n\\nb_%i = \\\\begin{avm} \\n \"",
"%",
"number",
"latex",
"+=",
"DictCell",
".",
"to_late... | Returns a raw text string that contains a latex representation of
the belief state as an attribute-value matrix. This requires:
\usepackage{avm} | [
"Returns",
"a",
"raw",
"text",
"string",
"that",
"contains",
"a",
"latex",
"representation",
"of",
"the",
"belief",
"state",
"as",
"an",
"attribute",
"-",
"value",
"matrix",
".",
"This",
"requires",
":",
"\\",
"usepackage",
"{",
"avm",
"}"
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/beliefstate.py#L501-L512 |
EventTeam/beliefs | src/beliefs/beliefstate.py | BeliefState.copy | def copy(self):
"""
Copies the BeliefState by recursively deep-copying all of
its parts. Domains are not copied, as they do not change
during the interpretation or generation.
"""
copied = BeliefState(self.__dict__['referential_domain'])
for key in ['environment... | python | def copy(self):
"""
Copies the BeliefState by recursively deep-copying all of
its parts. Domains are not copied, as they do not change
during the interpretation or generation.
"""
copied = BeliefState(self.__dict__['referential_domain'])
for key in ['environment... | [
"def",
"copy",
"(",
"self",
")",
":",
"copied",
"=",
"BeliefState",
"(",
"self",
".",
"__dict__",
"[",
"'referential_domain'",
"]",
")",
"for",
"key",
"in",
"[",
"'environment_variables'",
",",
"'deferred_effects'",
",",
"'pos'",
",",
"'p'",
"]",
":",
"cop... | Copies the BeliefState by recursively deep-copying all of
its parts. Domains are not copied, as they do not change
during the interpretation or generation. | [
"Copies",
"the",
"BeliefState",
"by",
"recursively",
"deep",
"-",
"copying",
"all",
"of",
"its",
"parts",
".",
"Domains",
"are",
"not",
"copied",
"as",
"they",
"do",
"not",
"change",
"during",
"the",
"interpretation",
"or",
"generation",
"."
] | train | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/beliefstate.py#L515-L524 |
carlitux/turboengine | src/turboengine/webservices/hacks.py | SOAPCallbackHandler.processRequest | def processRequest(cls, ps, **kw):
"""invokes callback that should return a (request,response) tuple.
representing the SOAP request and response respectively.
ps -- ParsedSoap instance representing HTTP Body.
request -- twisted.web.server.Request
"""
resource = kw['resour... | python | def processRequest(cls, ps, **kw):
"""invokes callback that should return a (request,response) tuple.
representing the SOAP request and response respectively.
ps -- ParsedSoap instance representing HTTP Body.
request -- twisted.web.server.Request
"""
resource = kw['resour... | [
"def",
"processRequest",
"(",
"cls",
",",
"ps",
",",
"*",
"*",
"kw",
")",
":",
"resource",
"=",
"kw",
"[",
"'resource'",
"]",
"method",
"=",
"resource",
".",
"getOperation",
"(",
"ps",
",",
"None",
")",
"# This getOperation method is valid for ServiceSOAPBindi... | invokes callback that should return a (request,response) tuple.
representing the SOAP request and response respectively.
ps -- ParsedSoap instance representing HTTP Body.
request -- twisted.web.server.Request | [
"invokes",
"callback",
"that",
"should",
"return",
"a",
"(",
"request",
"response",
")",
"tuple",
".",
"representing",
"the",
"SOAP",
"request",
"and",
"response",
"respectively",
".",
"ps",
"--",
"ParsedSoap",
"instance",
"representing",
"HTTP",
"Body",
".",
... | train | https://github.com/carlitux/turboengine/blob/627b6dbc400d8c16e2ff7e17afd01915371ea287/src/turboengine/webservices/hacks.py#L47-L56 |
pbrisk/unicum | unicum/visibleobject.py | VisibleObject.from_range | def from_range(cls, range_list, register_flag=True):
""" core class method to create visible objects from a range (nested list) """
s = dict_from_range(range_list)
obj = cls.from_serializable(s, register_flag)
return obj | python | def from_range(cls, range_list, register_flag=True):
""" core class method to create visible objects from a range (nested list) """
s = dict_from_range(range_list)
obj = cls.from_serializable(s, register_flag)
return obj | [
"def",
"from_range",
"(",
"cls",
",",
"range_list",
",",
"register_flag",
"=",
"True",
")",
":",
"s",
"=",
"dict_from_range",
"(",
"range_list",
")",
"obj",
"=",
"cls",
".",
"from_serializable",
"(",
"s",
",",
"register_flag",
")",
"return",
"obj"
] | core class method to create visible objects from a range (nested list) | [
"core",
"class",
"method",
"to",
"create",
"visible",
"objects",
"from",
"a",
"range",
"(",
"nested",
"list",
")"
] | train | https://github.com/pbrisk/unicum/blob/24bfa7355f36847a06646c58e9fd75bd3b689bfe/unicum/visibleobject.py#L68-L72 |
tschaume/ccsgp_get_started | ccsgp_get_started/examples/gp_datdir.py | gp_datdir | def gp_datdir(initial, topN):
"""example for plotting from a text file via numpy.loadtxt
1. prepare input/output directories
2. load the data into an OrderedDict() [adjust axes units]
3. sort countries from highest to lowest population
4. select the <topN> most populated countries
5. call ccsgp.make_plot w... | python | def gp_datdir(initial, topN):
"""example for plotting from a text file via numpy.loadtxt
1. prepare input/output directories
2. load the data into an OrderedDict() [adjust axes units]
3. sort countries from highest to lowest population
4. select the <topN> most populated countries
5. call ccsgp.make_plot w... | [
"def",
"gp_datdir",
"(",
"initial",
",",
"topN",
")",
":",
"# prepare input/output directories",
"inDir",
",",
"outDir",
"=",
"getWorkDirs",
"(",
")",
"initial",
"=",
"initial",
".",
"capitalize",
"(",
")",
"inDir",
"=",
"os",
".",
"path",
".",
"join",
"("... | example for plotting from a text file via numpy.loadtxt
1. prepare input/output directories
2. load the data into an OrderedDict() [adjust axes units]
3. sort countries from highest to lowest population
4. select the <topN> most populated countries
5. call ccsgp.make_plot with data from 4
Below is an outp... | [
"example",
"for",
"plotting",
"from",
"a",
"text",
"file",
"via",
"numpy",
".",
"loadtxt"
] | train | https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/gp_datdir.py#L8-L78 |
unixorn/haze | haze/commands/awsmetadata.py | awsReadMetadataKey | def awsReadMetadataKey():
"""Print key from a running instance's metadata"""
parser = argparse.ArgumentParser()
parser.add_argument("--key",
dest="keyname",
help="Which metadata key to read")
cli = parser.parse_args()
print getMetadataKey(name=cli.keyname) | python | def awsReadMetadataKey():
"""Print key from a running instance's metadata"""
parser = argparse.ArgumentParser()
parser.add_argument("--key",
dest="keyname",
help="Which metadata key to read")
cli = parser.parse_args()
print getMetadataKey(name=cli.keyname) | [
"def",
"awsReadMetadataKey",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"--key\"",
",",
"dest",
"=",
"\"keyname\"",
",",
"help",
"=",
"\"Which metadata key to read\"",
")",
"cli",
"=",
"pars... | Print key from a running instance's metadata | [
"Print",
"key",
"from",
"a",
"running",
"instance",
"s",
"metadata"
] | train | https://github.com/unixorn/haze/blob/77692b18e6574ac356e3e16659b96505c733afff/haze/commands/awsmetadata.py#L23-L33 |
matheuscas/django-tastypie-hmacauth | tastypie_hmacauth/authentication.py | HMACAuthentication.is_timestamp_valid | def is_timestamp_valid(self, timestamp):
"""Timestamp must be string in %Y-%m-%dT%H:%M:%S. format """
try:
timestamp_server = datetime.utcnow()
timestamp_client = datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S")
d1_ts = time.mktime(timestamp_client.timetuple())
... | python | def is_timestamp_valid(self, timestamp):
"""Timestamp must be string in %Y-%m-%dT%H:%M:%S. format """
try:
timestamp_server = datetime.utcnow()
timestamp_client = datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S")
d1_ts = time.mktime(timestamp_client.timetuple())
... | [
"def",
"is_timestamp_valid",
"(",
"self",
",",
"timestamp",
")",
":",
"try",
":",
"timestamp_server",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"timestamp_client",
"=",
"datetime",
".",
"strptime",
"(",
"timestamp",
",",
"\"%Y-%m-%dT%H:%M:%S\"",
")",
"d1_ts",
... | Timestamp must be string in %Y-%m-%dT%H:%M:%S. format | [
"Timestamp",
"must",
"be",
"string",
"in",
"%Y",
"-",
"%m",
"-",
"%dT%H",
":",
"%M",
":",
"%S",
".",
"format"
] | train | https://github.com/matheuscas/django-tastypie-hmacauth/blob/f96621e41be025666c5b34031c73640b2a6df885/tastypie_hmacauth/authentication.py#L93-L110 |
thespacedoctor/qubits | qubits/results.py | import_results | def import_results(log, pathToYamlFile):
"""
*Import the results of the simulation (the filename is an argument of this models)*
**Key Arguments:**
- ``log`` -- logger
- ``pathToYamlFile`` -- the path to the yaml file to be imported
**Return:**
- None
"""
##############... | python | def import_results(log, pathToYamlFile):
"""
*Import the results of the simulation (the filename is an argument of this models)*
**Key Arguments:**
- ``log`` -- logger
- ``pathToYamlFile`` -- the path to the yaml file to be imported
**Return:**
- None
"""
##############... | [
"def",
"import_results",
"(",
"log",
",",
"pathToYamlFile",
")",
":",
"################ > IMPORTS ################",
"## STANDARD LIB ##",
"## THIRD PARTY ##",
"import",
"yaml",
"## LOCAL APPLICATION ##",
"################ >ACTION(S) ################",
"fileName",
"=",
"pathToYamlF... | *Import the results of the simulation (the filename is an argument of this models)*
**Key Arguments:**
- ``log`` -- logger
- ``pathToYamlFile`` -- the path to the yaml file to be imported
**Return:**
- None | [
"*",
"Import",
"the",
"results",
"of",
"the",
"simulation",
"(",
"the",
"filename",
"is",
"an",
"argument",
"of",
"this",
"models",
")",
"*"
] | train | https://github.com/thespacedoctor/qubits/blob/3c02ace7226389841c6bb838d045c11bed61a3c2/qubits/results.py#L36-L69 |
thespacedoctor/qubits | qubits/results.py | plot_cadence_wheel | def plot_cadence_wheel(
log,
cadenceDictionary,
pathToOutputPlotFolder):
"""
*Generate the cadence wheel for the survey*
**Key Arguments:**
- ``log`` -- logger
- ``cadenceDictionary`` -- the cadence for the survey
- ``pathToOutputPlotDirectory`` -- path to ad... | python | def plot_cadence_wheel(
log,
cadenceDictionary,
pathToOutputPlotFolder):
"""
*Generate the cadence wheel for the survey*
**Key Arguments:**
- ``log`` -- logger
- ``cadenceDictionary`` -- the cadence for the survey
- ``pathToOutputPlotDirectory`` -- path to ad... | [
"def",
"plot_cadence_wheel",
"(",
"log",
",",
"cadenceDictionary",
",",
"pathToOutputPlotFolder",
")",
":",
"################ > IMPORTS ################",
"## STANDARD LIB ##",
"## THIRD PARTY ##",
"import",
"numpy",
"as",
"np",
"import",
"matplotlib",
".",
"pyplot",
"as",
... | *Generate the cadence wheel for the survey*
**Key Arguments:**
- ``log`` -- logger
- ``cadenceDictionary`` -- the cadence for the survey
- ``pathToOutputPlotDirectory`` -- path to add plots to
**Return:**
- None | [
"*",
"Generate",
"the",
"cadence",
"wheel",
"for",
"the",
"survey",
"*"
] | train | https://github.com/thespacedoctor/qubits/blob/3c02ace7226389841c6bb838d045c11bed61a3c2/qubits/results.py#L75-L179 |
thespacedoctor/qubits | qubits/results.py | plot_sn_discovery_map | def plot_sn_discovery_map(log,
snSurveyDiscoveryTimes,
peakAppMagList,
snCampaignLengthList,
redshifts,
extraSurveyConstraints,
pathToOutputPlotFolder):
"""
... | python | def plot_sn_discovery_map(log,
snSurveyDiscoveryTimes,
peakAppMagList,
snCampaignLengthList,
redshifts,
extraSurveyConstraints,
pathToOutputPlotFolder):
"""
... | [
"def",
"plot_sn_discovery_map",
"(",
"log",
",",
"snSurveyDiscoveryTimes",
",",
"peakAppMagList",
",",
"snCampaignLengthList",
",",
"redshifts",
",",
"extraSurveyConstraints",
",",
"pathToOutputPlotFolder",
")",
":",
"################ > IMPORTS ################",
"## STANDARD L... | *Plot the SN discoveries in a polar plot as function of redshift & time*
**Key Arguments:**
- ``log`` -- logger
- ``snSurveyDiscoveryTimes`` --
- ``peakAppMagList`` --
- ``snCampaignLengthList`` -- a list of campaign lengths in each filter
- ``redshifts`` --
- ``extr... | [
"*",
"Plot",
"the",
"SN",
"discoveries",
"in",
"a",
"polar",
"plot",
"as",
"function",
"of",
"redshift",
"&",
"time",
"*"
] | train | https://github.com/thespacedoctor/qubits/blob/3c02ace7226389841c6bb838d045c11bed61a3c2/qubits/results.py#L186-L374 |
thespacedoctor/qubits | qubits/results.py | plot_sn_discovery_ratio_map | def plot_sn_discovery_ratio_map(log,
snSurveyDiscoveryTimes,
redshifts,
peakAppMagList,
snCampaignLengthList,
extraSurveyConstraints,
... | python | def plot_sn_discovery_ratio_map(log,
snSurveyDiscoveryTimes,
redshifts,
peakAppMagList,
snCampaignLengthList,
extraSurveyConstraints,
... | [
"def",
"plot_sn_discovery_ratio_map",
"(",
"log",
",",
"snSurveyDiscoveryTimes",
",",
"redshifts",
",",
"peakAppMagList",
",",
"snCampaignLengthList",
",",
"extraSurveyConstraints",
",",
"pathToOutputPlotFolder",
")",
":",
"################ > IMPORTS ################",
"## STAN... | *Plot the SN discoveries and non-discoveries in a polar plot as function of redshift*
**Key Arguments:**
- ``log`` -- logger
- ``snSurveyDiscoveryTimes`` --
- ``redshifts`` --
- ``peakAppMagList`` -- the list of peakmags for each SN in each filter
- ``snCampaignLengthList`` ... | [
"*",
"Plot",
"the",
"SN",
"discoveries",
"and",
"non",
"-",
"discoveries",
"in",
"a",
"polar",
"plot",
"as",
"function",
"of",
"redshift",
"*"
] | train | https://github.com/thespacedoctor/qubits/blob/3c02ace7226389841c6bb838d045c11bed61a3c2/qubits/results.py#L380-L481 |
thespacedoctor/qubits | qubits/results.py | determine_sn_rate | def determine_sn_rate(
log,
lightCurveDiscoveryTimes,
snSurveyDiscoveryTimes,
redshifts,
surveyCadenceSettings,
surveyArea,
CCSNRateFraction,
transientToCCSNRateFraction,
peakAppMagList,
snCampaignLengthList,
extraSurveyConstraints,... | python | def determine_sn_rate(
log,
lightCurveDiscoveryTimes,
snSurveyDiscoveryTimes,
redshifts,
surveyCadenceSettings,
surveyArea,
CCSNRateFraction,
transientToCCSNRateFraction,
peakAppMagList,
snCampaignLengthList,
extraSurveyConstraints,... | [
"def",
"determine_sn_rate",
"(",
"log",
",",
"lightCurveDiscoveryTimes",
",",
"snSurveyDiscoveryTimes",
",",
"redshifts",
",",
"surveyCadenceSettings",
",",
"surveyArea",
",",
"CCSNRateFraction",
",",
"transientToCCSNRateFraction",
",",
"peakAppMagList",
",",
"snCampaignLen... | *Plot the SFR History as a function of redshift*
**Key Arguments:**
- ``log`` -- logger
- ``lightCurveDiscoveryTimes`` -- the lightcurve discovery times of the SN
- ``snSurveyDiscoveryTimes`` -- the supernova discovery times relative to the survey year
- ``redshifts`` -- the redshif... | [
"*",
"Plot",
"the",
"SFR",
"History",
"as",
"a",
"function",
"of",
"redshift",
"*"
] | train | https://github.com/thespacedoctor/qubits/blob/3c02ace7226389841c6bb838d045c11bed61a3c2/qubits/results.py#L487-L774 |
thespacedoctor/qubits | qubits/results.py | log_the_survey_settings | def log_the_survey_settings(
log,
pathToYamlFile):
"""
*Create a MD log of the survey settings*
**Key Arguments:**
- ``log`` -- logger
- ``pathToYamlFile`` -- yaml results file
**Return:**
- None
"""
################ > IMPORTS ################
## STA... | python | def log_the_survey_settings(
log,
pathToYamlFile):
"""
*Create a MD log of the survey settings*
**Key Arguments:**
- ``log`` -- logger
- ``pathToYamlFile`` -- yaml results file
**Return:**
- None
"""
################ > IMPORTS ################
## STA... | [
"def",
"log_the_survey_settings",
"(",
"log",
",",
"pathToYamlFile",
")",
":",
"################ > IMPORTS ################",
"## STANDARD LIB ##",
"## THIRD PARTY ##",
"import",
"yaml",
"## LOCAL APPLICATION ##",
"from",
"datetime",
"import",
"datetime",
",",
"date",
",",
... | *Create a MD log of the survey settings*
**Key Arguments:**
- ``log`` -- logger
- ``pathToYamlFile`` -- yaml results file
**Return:**
- None | [
"*",
"Create",
"a",
"MD",
"log",
"of",
"the",
"survey",
"settings",
"*"
] | train | https://github.com/thespacedoctor/qubits/blob/3c02ace7226389841c6bb838d045c11bed61a3c2/qubits/results.py#L780-L945 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.