Search is not available for this dataset
identifier stringlengths 1 155 | parameters stringlengths 2 6.09k | docstring stringlengths 11 63.4k | docstring_summary stringlengths 0 63.4k | function stringlengths 29 99.8k | function_tokens list | start_point list | end_point list | language stringclasses 1
value | docstring_language stringlengths 2 7 | docstring_language_predictions stringlengths 18 23 | is_langid_reliable stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
StreamMessagesTest.test_message_to_stream | (self) |
If you send a message to a stream, everyone subscribed to the stream
receives the messages.
|
If you send a message to a stream, everyone subscribed to the stream
receives the messages.
| def test_message_to_stream(self) -> None:
"""
If you send a message to a stream, everyone subscribed to the stream
receives the messages.
"""
self.assert_stream_message("Scotland") | [
"def",
"test_message_to_stream",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"assert_stream_message",
"(",
"\"Scotland\"",
")"
] | [
1905,
4
] | [
1910,
46
] | python | en | ['en', 'error', 'th'] | False |
StreamMessagesTest.test_non_ascii_stream_message | (self) |
Sending a stream message containing non-ASCII characters in the stream
name, topic, or message body succeeds.
|
Sending a stream message containing non-ASCII characters in the stream
name, topic, or message body succeeds.
| def test_non_ascii_stream_message(self) -> None:
"""
Sending a stream message containing non-ASCII characters in the stream
name, topic, or message body succeeds.
"""
self.login("hamlet")
# Subscribe everyone to a stream with non-ASCII characters.
non_ascii_strea... | [
"def",
"test_non_ascii_stream_message",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"login",
"(",
"\"hamlet\"",
")",
"# Subscribe everyone to a stream with non-ASCII characters.",
"non_ascii_stream_name",
"=",
"\"hümbüǵ\"",
"realm",
"=",
"get_realm",
"(",
"\"zulip\"... | [
1912,
4
] | [
1928,
102
] | python | en | ['en', 'error', 'th'] | False |
PersonalMessageSendTest.test_personal_to_self | (self) |
If you send a personal to yourself, only you see it.
|
If you send a personal to yourself, only you see it.
| def test_personal_to_self(self) -> None:
"""
If you send a personal to yourself, only you see it.
"""
old_user_profiles = list(UserProfile.objects.all())
test_email = self.nonreg_email("test1")
self.register(test_email, "test1")
old_messages = []
for user... | [
"def",
"test_personal_to_self",
"(",
"self",
")",
"->",
"None",
":",
"old_user_profiles",
"=",
"list",
"(",
"UserProfile",
".",
"objects",
".",
"all",
"(",
")",
")",
"test_email",
"=",
"self",
".",
"nonreg_email",
"(",
"\"test1\"",
")",
"self",
".",
"regis... | [
1961,
4
] | [
1984,
80
] | python | en | ['en', 'error', 'th'] | False |
PersonalMessageSendTest.assert_personal | (
self, sender: UserProfile, receiver: UserProfile, content: str = "testcontent"
) |
Send a private message from `sender_email` to `receiver_email` and check
that only those two parties actually received the message.
|
Send a private message from `sender_email` to `receiver_email` and check
that only those two parties actually received the message.
| def assert_personal(
self, sender: UserProfile, receiver: UserProfile, content: str = "testcontent"
) -> None:
"""
Send a private message from `sender_email` to `receiver_email` and check
that only those two parties actually received the message.
"""
sender_messages =... | [
"def",
"assert_personal",
"(",
"self",
",",
"sender",
":",
"UserProfile",
",",
"receiver",
":",
"UserProfile",
",",
"content",
":",
"str",
"=",
"\"testcontent\"",
")",
"->",
"None",
":",
"sender_messages",
"=",
"message_stream_count",
"(",
"sender",
")",
"rece... | [
1986,
4
] | [
2016,
76
] | python | en | ['en', 'error', 'th'] | False |
PersonalMessageSendTest.test_personal | (self) |
If you send a personal, only you and the recipient see it.
|
If you send a personal, only you and the recipient see it.
| def test_personal(self) -> None:
"""
If you send a personal, only you and the recipient see it.
"""
self.login("hamlet")
self.assert_personal(
sender=self.example_user("hamlet"),
receiver=self.example_user("othello"),
) | [
"def",
"test_personal",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"login",
"(",
"\"hamlet\"",
")",
"self",
".",
"assert_personal",
"(",
"sender",
"=",
"self",
".",
"example_user",
"(",
"\"hamlet\"",
")",
",",
"receiver",
"=",
"self",
".",
"exampl... | [
2018,
4
] | [
2026,
9
] | python | en | ['en', 'error', 'th'] | False |
PersonalMessageSendTest.test_private_message_policy | (self) |
Tests that PRIVATE_MESSAGE_POLICY_DISABLED works correctly.
|
Tests that PRIVATE_MESSAGE_POLICY_DISABLED works correctly.
| def test_private_message_policy(self) -> None:
"""
Tests that PRIVATE_MESSAGE_POLICY_DISABLED works correctly.
"""
user_profile = self.example_user("hamlet")
self.login_user(user_profile)
do_set_realm_property(
user_profile.realm,
"private_message_... | [
"def",
"test_private_message_policy",
"(",
"self",
")",
"->",
"None",
":",
"user_profile",
"=",
"self",
".",
"example_user",
"(",
"\"hamlet\"",
")",
"self",
".",
"login_user",
"(",
"user_profile",
")",
"do_set_realm_property",
"(",
"user_profile",
".",
"realm",
... | [
2028,
4
] | [
2046,
61
] | python | en | ['en', 'error', 'th'] | False |
PersonalMessageSendTest.test_non_ascii_personal | (self) |
Sending a PM containing non-ASCII characters succeeds.
|
Sending a PM containing non-ASCII characters succeeds.
| def test_non_ascii_personal(self) -> None:
"""
Sending a PM containing non-ASCII characters succeeds.
"""
self.login("hamlet")
self.assert_personal(
sender=self.example_user("hamlet"),
receiver=self.example_user("othello"),
content="hümbüǵ",
... | [
"def",
"test_non_ascii_personal",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"login",
"(",
"\"hamlet\"",
")",
"self",
".",
"assert_personal",
"(",
"sender",
"=",
"self",
".",
"example_user",
"(",
"\"hamlet\"",
")",
",",
"receiver",
"=",
"self",
".",... | [
2048,
4
] | [
2057,
9
] | python | en | ['en', 'error', 'th'] | False |
SessionStore.flush | (self) |
Removes the current session data from the database and regenerates the
key.
|
Removes the current session data from the database and regenerates the
key.
| def flush(self):
"""
Removes the current session data from the database and regenerates the
key.
"""
self.clear()
self.delete(self.session_key)
self._session_key = None | [
"def",
"flush",
"(",
"self",
")",
":",
"self",
".",
"clear",
"(",
")",
"self",
".",
"delete",
"(",
"self",
".",
"session_key",
")",
"self",
".",
"_session_key",
"=",
"None"
] | [
73,
4
] | [
80,
32
] | python | en | ['en', 'error', 'th'] | False |
AdaBound.step | (self, closure: OptLossClosure = None) | r"""Performs a single optimization step.
Arguments:
closure: A closure that reevaluates the model and returns the loss.
| r"""Performs a single optimization step. | def step(self, closure: OptLossClosure = None) -> OptFloat:
r"""Performs a single optimization step.
Arguments:
closure: A closure that reevaluates the model and returns the loss.
"""
loss = None
if closure is not None:
loss = closure()
for group... | [
"def",
"step",
"(",
"self",
",",
"closure",
":",
"OptLossClosure",
"=",
"None",
")",
"->",
"OptFloat",
":",
"loss",
"=",
"None",
"if",
"closure",
"is",
"not",
"None",
":",
"loss",
"=",
"closure",
"(",
")",
"for",
"group",
",",
"base_lr",
"in",
"zip",... | [
93,
4
] | [
176,
19
] | python | en | ['en', 'en', 'en'] | True |
create_streams_if_needed | (
realm: Realm, stream_dicts: List[StreamDict], acting_user: Optional[UserProfile] = None
) | Note that stream_dict["name"] is assumed to already be stripped of
whitespace | Note that stream_dict["name"] is assumed to already be stripped of
whitespace | def create_streams_if_needed(
realm: Realm, stream_dicts: List[StreamDict], acting_user: Optional[UserProfile] = None
) -> Tuple[List[Stream], List[Stream]]:
"""Note that stream_dict["name"] is assumed to already be stripped of
whitespace"""
added_streams: List[Stream] = []
existing_streams: List[St... | [
"def",
"create_streams_if_needed",
"(",
"realm",
":",
"Realm",
",",
"stream_dicts",
":",
"List",
"[",
"StreamDict",
"]",
",",
"acting_user",
":",
"Optional",
"[",
"UserProfile",
"]",
"=",
"None",
")",
"->",
"Tuple",
"[",
"List",
"[",
"Stream",
"]",
",",
... | [
140,
0
] | [
166,
42
] | python | en | ['en', 'en', 'en'] | True |
access_stream_common | (
user_profile: UserProfile,
stream: Stream,
error: str,
require_active: bool = True,
allow_realm_admin: bool = False,
) | Common function for backend code where the target use attempts to
access the target stream, returning all the data fetched along the
way. If that user does not have permission to access that stream,
we throw an exception. A design goal is that the error message is
the same for streams you can't access... | Common function for backend code where the target use attempts to
access the target stream, returning all the data fetched along the
way. If that user does not have permission to access that stream,
we throw an exception. A design goal is that the error message is
the same for streams you can't access... | def access_stream_common(
user_profile: UserProfile,
stream: Stream,
error: str,
require_active: bool = True,
allow_realm_admin: bool = False,
) -> Optional[Subscription]:
"""Common function for backend code where the target use attempts to
access the target stream, returning all the data fe... | [
"def",
"access_stream_common",
"(",
"user_profile",
":",
"UserProfile",
",",
"stream",
":",
"Stream",
",",
"error",
":",
"str",
",",
"require_active",
":",
"bool",
"=",
"True",
",",
"allow_realm_admin",
":",
"bool",
"=",
"False",
",",
")",
"->",
"Optional",
... | [
321,
0
] | [
367,
30
] | python | en | ['en', 'en', 'en'] | True |
access_stream_for_unmute_topic_by_name | (
user_profile: UserProfile, stream_name: str, error: str
) |
It may seem a little silly to have this helper function for unmuting
topics, but it gets around a linter warning, and it helps to be able
to review all security-related stuff in one place.
Our policy for accessing streams when you unmute a topic is that you
don't necessarily need to have an active... |
It may seem a little silly to have this helper function for unmuting
topics, but it gets around a linter warning, and it helps to be able
to review all security-related stuff in one place. | def access_stream_for_unmute_topic_by_name(
user_profile: UserProfile, stream_name: str, error: str
) -> Stream:
"""
It may seem a little silly to have this helper function for unmuting
topics, but it gets around a linter warning, and it helps to be able
to review all security-related stuff in one p... | [
"def",
"access_stream_for_unmute_topic_by_name",
"(",
"user_profile",
":",
"UserProfile",
",",
"stream_name",
":",
"str",
",",
"error",
":",
"str",
")",
"->",
"Stream",
":",
"try",
":",
"stream",
"=",
"get_stream",
"(",
"stream_name",
",",
"user_profile",
".",
... | [
448,
0
] | [
468,
17
] | python | en | ['en', 'error', 'th'] | False |
can_access_stream_history | (user_profile: UserProfile, stream: Stream) | Determine whether the provided user is allowed to access the
history of the target stream. The stream is specified by name.
This is used by the caller to determine whether this user can get
historical messages before they joined for a narrowing search.
Because of the way our search is currently struc... | Determine whether the provided user is allowed to access the
history of the target stream. The stream is specified by name. | def can_access_stream_history(user_profile: UserProfile, stream: Stream) -> bool:
"""Determine whether the provided user is allowed to access the
history of the target stream. The stream is specified by name.
This is used by the caller to determine whether this user can get
historical messages before ... | [
"def",
"can_access_stream_history",
"(",
"user_profile",
":",
"UserProfile",
",",
"stream",
":",
"Stream",
")",
"->",
"bool",
":",
"if",
"user_profile",
".",
"realm_id",
"!=",
"stream",
".",
"realm_id",
":",
"raise",
"AssertionError",
"(",
"\"user_profile and stre... | [
513,
0
] | [
547,
16
] | python | en | ['en', 'en', 'en'] | True |
list_to_streams | (
streams_raw: Collection[StreamDict],
user_profile: UserProfile,
autocreate: bool = False,
admin_access_required: bool = False,
) | Converts list of dicts to a list of Streams, validating input in the process
For each stream name, we validate it to ensure it meets our
requirements for a proper stream name using check_stream_name.
This function in autocreate mode should be atomic: either an exception will be raised
during a prechec... | Converts list of dicts to a list of Streams, validating input in the process | def list_to_streams(
streams_raw: Collection[StreamDict],
user_profile: UserProfile,
autocreate: bool = False,
admin_access_required: bool = False,
) -> Tuple[List[Stream], List[Stream]]:
"""Converts list of dicts to a list of Streams, validating input in the process
For each stream name, we va... | [
"def",
"list_to_streams",
"(",
"streams_raw",
":",
"Collection",
"[",
"StreamDict",
"]",
",",
"user_profile",
":",
"UserProfile",
",",
"autocreate",
":",
"bool",
"=",
"False",
",",
"admin_access_required",
":",
"bool",
"=",
"False",
",",
")",
"->",
"Tuple",
... | [
600,
0
] | [
685,
44
] | python | en | ['en', 'en', 'en'] | True |
get_stream_by_narrow_operand_access_unchecked | (operand: Union[str, int], realm: Realm) | This is required over access_stream_* in certain cases where
we need the stream data only to prepare a response that user can access
and not send it out to unauthorized recipients.
| This is required over access_stream_* in certain cases where
we need the stream data only to prepare a response that user can access
and not send it out to unauthorized recipients.
| def get_stream_by_narrow_operand_access_unchecked(operand: Union[str, int], realm: Realm) -> Stream:
"""This is required over access_stream_* in certain cases where
we need the stream data only to prepare a response that user can access
and not send it out to unauthorized recipients.
"""
if isinstan... | [
"def",
"get_stream_by_narrow_operand_access_unchecked",
"(",
"operand",
":",
"Union",
"[",
"str",
",",
"int",
"]",
",",
"realm",
":",
"Realm",
")",
"->",
"Stream",
":",
"if",
"isinstance",
"(",
"operand",
",",
"str",
")",
":",
"return",
"get_stream",
"(",
... | [
695,
0
] | [
702,
52
] | python | en | ['en', 'en', 'en'] | True |
localtime | (value) |
Converts a datetime to local time in the active time zone.
This only makes sense within a {% localtime off %} block.
|
Converts a datetime to local time in the active time zone. | def localtime(value):
"""
Converts a datetime to local time in the active time zone.
This only makes sense within a {% localtime off %} block.
"""
return do_timezone(value, timezone.get_current_timezone()) | [
"def",
"localtime",
"(",
"value",
")",
":",
"return",
"do_timezone",
"(",
"value",
",",
"timezone",
".",
"get_current_timezone",
"(",
")",
")"
] | [
19,
0
] | [
25,
62
] | python | en | ['en', 'error', 'th'] | False |
utc | (value) |
Converts a datetime to UTC.
|
Converts a datetime to UTC.
| def utc(value):
"""
Converts a datetime to UTC.
"""
return do_timezone(value, timezone.utc) | [
"def",
"utc",
"(",
"value",
")",
":",
"return",
"do_timezone",
"(",
"value",
",",
"timezone",
".",
"utc",
")"
] | [
29,
0
] | [
33,
43
] | python | en | ['en', 'error', 'th'] | False |
do_timezone | (value, arg) |
Converts a datetime to local time in a given time zone.
The argument must be an instance of a tzinfo subclass or a time zone name.
Naive datetimes are assumed to be in local time in the default time zone.
|
Converts a datetime to local time in a given time zone. | def do_timezone(value, arg):
"""
Converts a datetime to local time in a given time zone.
The argument must be an instance of a tzinfo subclass or a time zone name.
Naive datetimes are assumed to be in local time in the default time zone.
"""
if not isinstance(value, datetime):
return '... | [
"def",
"do_timezone",
"(",
"value",
",",
"arg",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"datetime",
")",
":",
"return",
"''",
"# Obtain a timezone-aware datetime",
"try",
":",
"if",
"timezone",
".",
"is_naive",
"(",
"value",
")",
":",
"defa... | [
37,
0
] | [
77,
17
] | python | en | ['en', 'error', 'th'] | False |
localtime_tag | (parser, token) |
Forces or prevents conversion of datetime objects to local time,
regardless of the value of ``settings.USE_TZ``.
Sample usage::
{% localtime off %}{{ value_in_utc }}{% endlocaltime %}
|
Forces or prevents conversion of datetime objects to local time,
regardless of the value of ``settings.USE_TZ``. | def localtime_tag(parser, token):
"""
Forces or prevents conversion of datetime objects to local time,
regardless of the value of ``settings.USE_TZ``.
Sample usage::
{% localtime off %}{{ value_in_utc }}{% endlocaltime %}
"""
bits = token.split_contents()
if len(bits) == 1:
... | [
"def",
"localtime_tag",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"==",
"1",
":",
"use_tz",
"=",
"True",
"elif",
"len",
"(",
"bits",
")",
">",
"2",
"or",
"bits",
"... | [
125,
0
] | [
144,
42
] | python | en | ['en', 'error', 'th'] | False |
timezone_tag | (parser, token) |
Enables a given time zone just for this block.
The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a
time zone name, or ``None``. If it is ``None``, the default time zone is
used within the block.
Sample usage::
{% timezone "Europe/Paris" %}
It is {{ now }... |
Enables a given time zone just for this block. | def timezone_tag(parser, token):
"""
Enables a given time zone just for this block.
The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a
time zone name, or ``None``. If it is ``None``, the default time zone is
used within the block.
Sample usage::
{% timezone "Eur... | [
"def",
"timezone_tag",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"!=",
"2",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'%s' takes one argument (timezone)\"",
"%",
"bits",
"[... | [
148,
0
] | [
169,
37
] | python | en | ['en', 'error', 'th'] | False |
get_current_timezone_tag | (parser, token) |
Stores the name of the current time zone in the context.
Usage::
{% get_current_timezone as TIME_ZONE %}
This will fetch the currently active time zone and put its name
into the ``TIME_ZONE`` context variable.
|
Stores the name of the current time zone in the context. | def get_current_timezone_tag(parser, token):
"""
Stores the name of the current time zone in the context.
Usage::
{% get_current_timezone as TIME_ZONE %}
This will fetch the currently active time zone and put its name
into the ``TIME_ZONE`` context variable.
"""
# token.split_cont... | [
"def",
"get_current_timezone_tag",
"(",
"parser",
",",
"token",
")",
":",
"# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments",
"args",
"=",
"token",
".",
"contents",
".",
"split",
"(",
")",
"if",
"len",
"(",
"args",
")",
"!... | [
173,
0
] | [
189,
42
] | python | en | ['en', 'error', 'th'] | False |
build_wheel | (source_dir, wheel_dir, config_settings=None) | Build a wheel from a source directory using PEP 517 hooks.
:param str source_dir: Source directory containing pyproject.toml
:param str wheel_dir: Target directory to create wheel in
:param dict config_settings: Options to pass to build backend
This is a blocking function which will run pip in a subpr... | Build a wheel from a source directory using PEP 517 hooks. | def build_wheel(source_dir, wheel_dir, config_settings=None):
"""Build a wheel from a source directory using PEP 517 hooks.
:param str source_dir: Source directory containing pyproject.toml
:param str wheel_dir: Target directory to create wheel in
:param dict config_settings: Options to pass to build b... | [
"def",
"build_wheel",
"(",
"source_dir",
",",
"wheel_dir",
",",
"config_settings",
"=",
"None",
")",
":",
"if",
"config_settings",
"is",
"None",
":",
"config_settings",
"=",
"{",
"}",
"requires",
",",
"backend",
",",
"backend_path",
"=",
"_load_pyproject",
"("... | [
125,
0
] | [
144,
60
] | python | en | ['en', 'en', 'en'] | True |
build_sdist | (source_dir, sdist_dir, config_settings=None) | Build an sdist from a source directory using PEP 517 hooks.
:param str source_dir: Source directory containing pyproject.toml
:param str sdist_dir: Target directory to place sdist in
:param dict config_settings: Options to pass to build backend
This is a blocking function which will run pip in a subpr... | Build an sdist from a source directory using PEP 517 hooks. | def build_sdist(source_dir, sdist_dir, config_settings=None):
"""Build an sdist from a source directory using PEP 517 hooks.
:param str source_dir: Source directory containing pyproject.toml
:param str sdist_dir: Target directory to place sdist in
:param dict config_settings: Options to pass to build b... | [
"def",
"build_sdist",
"(",
"source_dir",
",",
"sdist_dir",
",",
"config_settings",
"=",
"None",
")",
":",
"if",
"config_settings",
"is",
"None",
":",
"config_settings",
"=",
"{",
"}",
"requires",
",",
"backend",
",",
"backend_path",
"=",
"_load_pyproject",
"("... | [
147,
0
] | [
166,
60
] | python | en | ['en', 'en', 'en'] | True |
BuildEnvironment.pip_install | (self, reqs) | Install dependencies into this env by calling pip in a subprocess | Install dependencies into this env by calling pip in a subprocess | def pip_install(self, reqs):
"""Install dependencies into this env by calling pip in a subprocess"""
if not reqs:
return
log.info('Calling pip to install %s', reqs)
cmd = [
sys.executable, '-m', 'pip', 'install', '--ignore-installed',
'--prefix', self.... | [
"def",
"pip_install",
"(",
"self",
",",
"reqs",
")",
":",
"if",
"not",
"reqs",
":",
"return",
"log",
".",
"info",
"(",
"'Calling pip to install %s'",
",",
"reqs",
")",
"cmd",
"=",
"[",
"sys",
".",
"executable",
",",
"'-m'",
",",
"'pip'",
",",
"'install... | [
91,
4
] | [
103,
9
] | python | en | ['en', 'en', 'en'] | True |
PipProvider.get_preference | (
self,
resolution, # type: Optional[Candidate]
candidates, # type: Sequence[Candidate]
information # type: Sequence[Tuple[Requirement, Candidate]]
) | Produce a sort key for given requirement based on preference.
The lower the return value is, the more preferred this group of
arguments is.
Currently pip considers the followings in order:
* Prefer if any of the known requirements points to an explicit URL.
* If equal, prefer ... | Produce a sort key for given requirement based on preference. | def get_preference(
self,
resolution, # type: Optional[Candidate]
candidates, # type: Sequence[Candidate]
information # type: Sequence[Tuple[Requirement, Candidate]]
):
# type: (...) -> Any
"""Produce a sort key for given requirement based on preference.
T... | [
"def",
"get_preference",
"(",
"self",
",",
"resolution",
",",
"# type: Optional[Candidate]",
"candidates",
",",
"# type: Sequence[Candidate]",
"information",
"# type: Sequence[Tuple[Requirement, Candidate]]",
")",
":",
"# type: (...) -> Any",
"def",
"_get_restrictive_rating",
"("... | [
61,
4
] | [
130,
57
] | python | en | ['en', 'en', 'en'] | True |
SessionBase.encode | (self, session_dict) | Returns the given session dictionary serialized and encoded as a string. | Returns the given session dictionary serialized and encoded as a string. | def encode(self, session_dict):
"Returns the given session dictionary serialized and encoded as a string."
serialized = self.serializer().dumps(session_dict)
hash = self._hash(serialized)
return base64.b64encode(hash.encode() + b":" + serialized).decode('ascii') | [
"def",
"encode",
"(",
"self",
",",
"session_dict",
")",
":",
"serialized",
"=",
"self",
".",
"serializer",
"(",
")",
".",
"dumps",
"(",
"session_dict",
")",
"hash",
"=",
"self",
".",
"_hash",
"(",
"serialized",
")",
"return",
"base64",
".",
"b64encode",
... | [
95,
4
] | [
99,
82
] | python | en | ['en', 'en', 'en'] | True |
SessionBase.is_empty | (self) | Returns True when there is no session_key and the session is empty | Returns True when there is no session_key and the session is empty | def is_empty(self):
"Returns True when there is no session_key and the session is empty"
try:
return not bool(self._session_key) and not self._session_cache
except AttributeError:
return True | [
"def",
"is_empty",
"(",
"self",
")",
":",
"try",
":",
"return",
"not",
"bool",
"(",
"self",
".",
"_session_key",
")",
"and",
"not",
"self",
".",
"_session_cache",
"except",
"AttributeError",
":",
"return",
"True"
] | [
152,
4
] | [
157,
23
] | python | en | ['en', 'en', 'en'] | True |
SessionBase._get_new_session_key | (self) | Returns session key that isn't being used. | Returns session key that isn't being used. | def _get_new_session_key(self):
"Returns session key that isn't being used."
while True:
session_key = get_random_string(32, VALID_KEY_CHARS)
if not self.exists(session_key):
break
return session_key | [
"def",
"_get_new_session_key",
"(",
"self",
")",
":",
"while",
"True",
":",
"session_key",
"=",
"get_random_string",
"(",
"32",
",",
"VALID_KEY_CHARS",
")",
"if",
"not",
"self",
".",
"exists",
"(",
"session_key",
")",
":",
"break",
"return",
"session_key"
] | [
159,
4
] | [
165,
26
] | python | en | ['en', 'en', 'en'] | True |
SessionBase._validate_session_key | (self, key) |
Key must be truthy and at least 8 characters long. 8 characters is an
arbitrary lower bound for some minimal key security.
|
Key must be truthy and at least 8 characters long. 8 characters is an
arbitrary lower bound for some minimal key security.
| def _validate_session_key(self, key):
"""
Key must be truthy and at least 8 characters long. 8 characters is an
arbitrary lower bound for some minimal key security.
"""
return key and len(key) >= 8 | [
"def",
"_validate_session_key",
"(",
"self",
",",
"key",
")",
":",
"return",
"key",
"and",
"len",
"(",
"key",
")",
">=",
"8"
] | [
172,
4
] | [
177,
36
] | python | en | ['en', 'error', 'th'] | False |
SessionBase._set_session_key | (self, value) |
Validate session key on assignment. Invalid values will set to None.
|
Validate session key on assignment. Invalid values will set to None.
| def _set_session_key(self, value):
"""
Validate session key on assignment. Invalid values will set to None.
"""
if self._validate_session_key(value):
self.__session_key = value
else:
self.__session_key = None | [
"def",
"_set_session_key",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"_validate_session_key",
"(",
"value",
")",
":",
"self",
".",
"__session_key",
"=",
"value",
"else",
":",
"self",
".",
"__session_key",
"=",
"None"
] | [
182,
4
] | [
189,
37
] | python | en | ['en', 'error', 'th'] | False |
SessionBase._get_session | (self, no_load=False) |
Lazily loads session from storage (unless "no_load" is True, when only
an empty dict is stored) and stores it in the current instance.
|
Lazily loads session from storage (unless "no_load" is True, when only
an empty dict is stored) and stores it in the current instance.
| def _get_session(self, no_load=False):
"""
Lazily loads session from storage (unless "no_load" is True, when only
an empty dict is stored) and stores it in the current instance.
"""
self.accessed = True
try:
return self._session_cache
except AttributeE... | [
"def",
"_get_session",
"(",
"self",
",",
"no_load",
"=",
"False",
")",
":",
"self",
".",
"accessed",
"=",
"True",
"try",
":",
"return",
"self",
".",
"_session_cache",
"except",
"AttributeError",
":",
"if",
"self",
".",
"session_key",
"is",
"None",
"or",
... | [
194,
4
] | [
207,
34
] | python | en | ['en', 'error', 'th'] | False |
SessionBase.get_expiry_age | (self, **kwargs) | Get the number of seconds until the session expires.
Optionally, this function accepts `modification` and `expiry` keyword
arguments specifying the modification and expiry of the session.
| Get the number of seconds until the session expires. | def get_expiry_age(self, **kwargs):
"""Get the number of seconds until the session expires.
Optionally, this function accepts `modification` and `expiry` keyword
arguments specifying the modification and expiry of the session.
"""
try:
modification = kwargs['modifica... | [
"def",
"get_expiry_age",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"modification",
"=",
"kwargs",
"[",
"'modification'",
"]",
"except",
"KeyError",
":",
"modification",
"=",
"timezone",
".",
"now",
"(",
")",
"# Make the difference between \"e... | [
211,
4
] | [
234,
49
] | python | en | ['en', 'en', 'en'] | True |
SessionBase.get_expiry_date | (self, **kwargs) | Get session the expiry date (as a datetime object).
Optionally, this function accepts `modification` and `expiry` keyword
arguments specifying the modification and expiry of the session.
| Get session the expiry date (as a datetime object). | def get_expiry_date(self, **kwargs):
"""Get session the expiry date (as a datetime object).
Optionally, this function accepts `modification` and `expiry` keyword
arguments specifying the modification and expiry of the session.
"""
try:
modification = kwargs['modifica... | [
"def",
"get_expiry_date",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"modification",
"=",
"kwargs",
"[",
"'modification'",
"]",
"except",
"KeyError",
":",
"modification",
"=",
"timezone",
".",
"now",
"(",
")",
"# Same comment as in get_expiry_... | [
236,
4
] | [
256,
55
] | python | en | ['en', 'en', 'en'] | True |
SessionBase.set_expiry | (self, value) |
Sets a custom expiration for the session. ``value`` can be an integer,
a Python ``datetime`` or ``timedelta`` object or ``None``.
If ``value`` is an integer, the session will expire after that many
seconds of inactivity. If set to ``0`` then the session will expire on
browser c... |
Sets a custom expiration for the session. ``value`` can be an integer,
a Python ``datetime`` or ``timedelta`` object or ``None``. | def set_expiry(self, value):
"""
Sets a custom expiration for the session. ``value`` can be an integer,
a Python ``datetime`` or ``timedelta`` object or ``None``.
If ``value`` is an integer, the session will expire after that many
seconds of inactivity. If set to ``0`` then the ... | [
"def",
"set_expiry",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"# Remove any custom expiration for this session.",
"try",
":",
"del",
"self",
"[",
"'_session_expiry'",
"]",
"except",
"KeyError",
":",
"pass",
"return",
"if",
"isinstan... | [
258,
4
] | [
282,
39
] | python | en | ['en', 'error', 'th'] | False |
SessionBase.get_expire_at_browser_close | (self) |
Returns ``True`` if the session is set to expire when the browser
closes, and ``False`` if there's an expiry date. Use
``get_expiry_date()`` or ``get_expiry_age()`` to find the actual expiry
date/age, if there is one.
|
Returns ``True`` if the session is set to expire when the browser
closes, and ``False`` if there's an expiry date. Use
``get_expiry_date()`` or ``get_expiry_age()`` to find the actual expiry
date/age, if there is one.
| def get_expire_at_browser_close(self):
"""
Returns ``True`` if the session is set to expire when the browser
closes, and ``False`` if there's an expiry date. Use
``get_expiry_date()`` or ``get_expiry_age()`` to find the actual expiry
date/age, if there is one.
"""
... | [
"def",
"get_expire_at_browser_close",
"(",
"self",
")",
":",
"if",
"self",
".",
"get",
"(",
"'_session_expiry'",
")",
"is",
"None",
":",
"return",
"settings",
".",
"SESSION_EXPIRE_AT_BROWSER_CLOSE",
"return",
"self",
".",
"get",
"(",
"'_session_expiry'",
")",
"=... | [
284,
4
] | [
293,
47
] | python | en | ['en', 'error', 'th'] | False |
SessionBase.flush | (self) |
Removes the current session data from the database and regenerates the
key.
|
Removes the current session data from the database and regenerates the
key.
| def flush(self):
"""
Removes the current session data from the database and regenerates the
key.
"""
self.clear()
self.delete()
self._session_key = None | [
"def",
"flush",
"(",
"self",
")",
":",
"self",
".",
"clear",
"(",
")",
"self",
".",
"delete",
"(",
")",
"self",
".",
"_session_key",
"=",
"None"
] | [
295,
4
] | [
302,
32
] | python | en | ['en', 'error', 'th'] | False |
SessionBase.cycle_key | (self) |
Creates a new session key, while retaining the current session data.
|
Creates a new session key, while retaining the current session data.
| def cycle_key(self):
"""
Creates a new session key, while retaining the current session data.
"""
try:
data = self._session_cache
except AttributeError:
data = {}
key = self.session_key
self.create()
self._session_cache = data
... | [
"def",
"cycle_key",
"(",
"self",
")",
":",
"try",
":",
"data",
"=",
"self",
".",
"_session_cache",
"except",
"AttributeError",
":",
"data",
"=",
"{",
"}",
"key",
"=",
"self",
".",
"session_key",
"self",
".",
"create",
"(",
")",
"self",
".",
"_session_c... | [
304,
4
] | [
316,
28
] | python | en | ['en', 'error', 'th'] | False |
SessionBase.exists | (self, session_key) |
Returns True if the given session_key already exists.
|
Returns True if the given session_key already exists.
| def exists(self, session_key):
"""
Returns True if the given session_key already exists.
"""
raise NotImplementedError('subclasses of SessionBase must provide an exists() method') | [
"def",
"exists",
"(",
"self",
",",
"session_key",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of SessionBase must provide an exists() method'",
")"
] | [
320,
4
] | [
324,
94
] | python | en | ['en', 'error', 'th'] | False |
SessionBase.create | (self) |
Creates a new session instance. Guaranteed to create a new object with
a unique key and will have saved the result once (with empty data)
before the method returns.
|
Creates a new session instance. Guaranteed to create a new object with
a unique key and will have saved the result once (with empty data)
before the method returns.
| def create(self):
"""
Creates a new session instance. Guaranteed to create a new object with
a unique key and will have saved the result once (with empty data)
before the method returns.
"""
raise NotImplementedError('subclasses of SessionBase must provide a create() meth... | [
"def",
"create",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of SessionBase must provide a create() method'",
")"
] | [
326,
4
] | [
332,
93
] | python | en | ['en', 'error', 'th'] | False |
SessionBase.save | (self, must_create=False) |
Saves the session data. If 'must_create' is True, a new session object
is created (otherwise a CreateError exception is raised). Otherwise,
save() only updates an existing object and does not create one
(an UpdateError is raised).
|
Saves the session data. If 'must_create' is True, a new session object
is created (otherwise a CreateError exception is raised). Otherwise,
save() only updates an existing object and does not create one
(an UpdateError is raised).
| def save(self, must_create=False):
"""
Saves the session data. If 'must_create' is True, a new session object
is created (otherwise a CreateError exception is raised). Otherwise,
save() only updates an existing object and does not create one
(an UpdateError is raised).
""... | [
"def",
"save",
"(",
"self",
",",
"must_create",
"=",
"False",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of SessionBase must provide a save() method'",
")"
] | [
334,
4
] | [
341,
91
] | python | en | ['en', 'error', 'th'] | False |
SessionBase.delete | (self, session_key=None) |
Deletes the session data under this key. If the key is None, the
current session key value is used.
|
Deletes the session data under this key. If the key is None, the
current session key value is used.
| def delete(self, session_key=None):
"""
Deletes the session data under this key. If the key is None, the
current session key value is used.
"""
raise NotImplementedError('subclasses of SessionBase must provide a delete() method') | [
"def",
"delete",
"(",
"self",
",",
"session_key",
"=",
"None",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of SessionBase must provide a delete() method'",
")"
] | [
343,
4
] | [
348,
93
] | python | en | ['en', 'error', 'th'] | False |
SessionBase.load | (self) |
Loads the session data and returns a dictionary.
|
Loads the session data and returns a dictionary.
| def load(self):
"""
Loads the session data and returns a dictionary.
"""
raise NotImplementedError('subclasses of SessionBase must provide a load() method') | [
"def",
"load",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of SessionBase must provide a load() method'",
")"
] | [
350,
4
] | [
354,
91
] | python | en | ['en', 'error', 'th'] | False |
SessionBase.clear_expired | (cls) |
Remove expired sessions from the session store.
If this operation isn't possible on a given backend, it should raise
NotImplementedError. If it isn't necessary, because the backend has
a built-in expiration mechanism, it should be a no-op.
|
Remove expired sessions from the session store. | def clear_expired(cls):
"""
Remove expired sessions from the session store.
If this operation isn't possible on a given backend, it should raise
NotImplementedError. If it isn't necessary, because the backend has
a built-in expiration mechanism, it should be a no-op.
"""... | [
"def",
"clear_expired",
"(",
"cls",
")",
":",
"raise",
"NotImplementedError",
"(",
"'This backend does not support clear_expired().'",
")"
] | [
357,
4
] | [
365,
83
] | python | en | ['en', 'error', 'th'] | False |
WsgiToAsgi.__call__ | (self, scope, receive, send) |
ASGI application instantiation point.
We return a new WsgiToAsgiInstance here with the WSGI app
and the scope, ready to respond when it is __call__ed.
|
ASGI application instantiation point.
We return a new WsgiToAsgiInstance here with the WSGI app
and the scope, ready to respond when it is __call__ed.
| async def __call__(self, scope, receive, send):
"""
ASGI application instantiation point.
We return a new WsgiToAsgiInstance here with the WSGI app
and the scope, ready to respond when it is __call__ed.
"""
await WsgiToAsgiInstance(self.wsgi_application)(scope, receive, s... | [
"async",
"def",
"__call__",
"(",
"self",
",",
"scope",
",",
"receive",
",",
"send",
")",
":",
"await",
"WsgiToAsgiInstance",
"(",
"self",
".",
"wsgi_application",
")",
"(",
"scope",
",",
"receive",
",",
"send",
")"
] | [
14,
4
] | [
20,
77
] | python | en | ['en', 'error', 'th'] | False |
WsgiToAsgiInstance.build_environ | (self, scope, body) |
Builds a scope and request body into a WSGI environ object.
|
Builds a scope and request body into a WSGI environ object.
| def build_environ(self, scope, body):
"""
Builds a scope and request body into a WSGI environ object.
"""
environ = {
"REQUEST_METHOD": scope["method"],
"SCRIPT_NAME": scope.get("root_path", "").encode("utf8").decode("latin1"),
"PATH_INFO": scope["path... | [
"def",
"build_environ",
"(",
"self",
",",
"scope",
",",
"body",
")",
":",
"environ",
"=",
"{",
"\"REQUEST_METHOD\"",
":",
"scope",
"[",
"\"method\"",
"]",
",",
"\"SCRIPT_NAME\"",
":",
"scope",
".",
"get",
"(",
"\"root_path\"",
",",
"\"\"",
")",
".",
"enc... | [
52,
4
] | [
95,
22
] | python | en | ['en', 'error', 'th'] | False |
WsgiToAsgiInstance.start_response | (self, status, response_headers, exc_info=None) |
WSGI start_response callable.
|
WSGI start_response callable.
| def start_response(self, status, response_headers, exc_info=None):
"""
WSGI start_response callable.
"""
# Don't allow re-calling once response has begun
if self.response_started:
raise exc_info[1].with_traceback(exc_info[2])
# Don't allow re-calling without e... | [
"def",
"start_response",
"(",
"self",
",",
"status",
",",
"response_headers",
",",
"exc_info",
"=",
"None",
")",
":",
"# Don't allow re-calling once response has begun",
"if",
"self",
".",
"response_started",
":",
"raise",
"exc_info",
"[",
"1",
"]",
".",
"with_tra... | [
97,
4
] | [
127,
9
] | python | en | ['en', 'error', 'th'] | False |
WsgiToAsgiInstance.run_wsgi_app | (self, body) |
Called in a subthread to run the WSGI app. We encapsulate like
this so that the start_response callable is called in the same thread.
|
Called in a subthread to run the WSGI app. We encapsulate like
this so that the start_response callable is called in the same thread.
| def run_wsgi_app(self, body):
"""
Called in a subthread to run the WSGI app. We encapsulate like
this so that the start_response callable is called in the same thread.
"""
# Translate the scope and incoming request body into a WSGI environ
environ = self.build_environ(sel... | [
"def",
"run_wsgi_app",
"(",
"self",
",",
"body",
")",
":",
"# Translate the scope and incoming request body into a WSGI environ",
"environ",
"=",
"self",
".",
"build_environ",
"(",
"self",
".",
"scope",
",",
"body",
")",
"# Run the WSGI app",
"bytes_sent",
"=",
"0",
... | [
130,
4
] | [
161,
54
] | python | en | ['en', 'error', 'th'] | False |
DatabaseFeatures._mysql_storage_engine | (self) | Internal method used in Django tests. Don't rely on this from your code | Internal method used in Django tests. Don't rely on this from your code | def _mysql_storage_engine(self):
"Internal method used in Django tests. Don't rely on this from your code"
with self.connection.cursor() as cursor:
cursor.execute("SELECT ENGINE FROM INFORMATION_SCHEMA.ENGINES WHERE SUPPORT = 'DEFAULT'")
result = cursor.fetchone()
return ... | [
"def",
"_mysql_storage_engine",
"(",
"self",
")",
":",
"with",
"self",
".",
"connection",
".",
"cursor",
"(",
")",
"as",
"cursor",
":",
"cursor",
".",
"execute",
"(",
"\"SELECT ENGINE FROM INFORMATION_SCHEMA.ENGINES WHERE SUPPORT = 'DEFAULT'\"",
")",
"result",
"=",
... | [
36,
4
] | [
41,
24
] | python | en | ['en', 'en', 'en'] | True |
DatabaseFeatures.can_introspect_foreign_keys | (self) | Confirm support for introspected foreign keys | Confirm support for introspected foreign keys | def can_introspect_foreign_keys(self):
"Confirm support for introspected foreign keys"
return self._mysql_storage_engine != 'MyISAM' | [
"def",
"can_introspect_foreign_keys",
"(",
"self",
")",
":",
"return",
"self",
".",
"_mysql_storage_engine",
"!=",
"'MyISAM'"
] | [
44,
4
] | [
46,
53
] | python | en | ['en', 'en', 'en'] | True |
DatabaseFeatures.supports_transactions | (self) |
All storage engines except MyISAM support transactions.
|
All storage engines except MyISAM support transactions.
| def supports_transactions(self):
"""
All storage engines except MyISAM support transactions.
"""
return self._mysql_storage_engine != 'MyISAM' | [
"def",
"supports_transactions",
"(",
"self",
")",
":",
"return",
"self",
".",
"_mysql_storage_engine",
"!=",
"'MyISAM'"
] | [
72,
4
] | [
76,
53
] | python | en | ['en', 'error', 'th'] | False |
empty_blockchain | () |
Provides a list of 10 valid blocks, as well as a blockchain with 9 blocks added to it.
|
Provides a list of 10 valid blocks, as well as a blockchain with 9 blocks added to it.
| async def empty_blockchain():
"""
Provides a list of 10 valid blocks, as well as a blockchain with 9 blocks added to it.
"""
bc1, connection, db_path = await create_blockchain(test_constants)
yield bc1
await connection.close()
bc1.shut_down()
db_path.unlink() | [
"async",
"def",
"empty_blockchain",
"(",
")",
":",
"bc1",
",",
"connection",
",",
"db_path",
"=",
"await",
"create_blockchain",
"(",
"test_constants",
")",
"yield",
"bc1",
"await",
"connection",
".",
"close",
"(",
")",
"bc1",
".",
"shut_down",
"(",
")",
"d... | [
32,
0
] | [
41,
20
] | python | en | ['en', 'error', 'th'] | False |
load_pyproject_toml | (
use_pep517, # type: Optional[bool]
pyproject_toml, # type: str
setup_py, # type: str
req_name # type: str
) | Load the pyproject.toml file.
Parameters:
use_pep517 - Has the user requested PEP 517 processing? None
means the user hasn't explicitly specified.
pyproject_toml - Location of the project's pyproject.toml file
setup_py - Location of the project's setup.py file
r... | Load the pyproject.toml file. | def load_pyproject_toml(
use_pep517, # type: Optional[bool]
pyproject_toml, # type: str
setup_py, # type: str
req_name # type: str
):
# type: (...) -> Optional[BuildSystemDetails]
"""Load the pyproject.toml file.
Parameters:
use_pep517 - Has the user requested PEP 517 processing... | [
"def",
"load_pyproject_toml",
"(",
"use_pep517",
",",
"# type: Optional[bool]",
"pyproject_toml",
",",
"# type: str",
"setup_py",
",",
"# type: str",
"req_name",
"# type: str",
")",
":",
"# type: (...) -> Optional[BuildSystemDetails]",
"has_pyproject",
"=",
"os",
".",
"path... | [
41,
0
] | [
195,
69
] | python | en | ['en', 'en', 'en'] | True |
find_fork_point_in_chain | (
blocks: BlockchainInterface,
block_1: Union[BlockRecord, HeaderBlock],
block_2: Union[BlockRecord, HeaderBlock],
) | Tries to find height where new chain (block_2) diverged from block_1 (assuming prev blocks
are all included in chain)
Returns -1 if chains have no common ancestor
* assumes the fork point is loaded in blocks
| Tries to find height where new chain (block_2) diverged from block_1 (assuming prev blocks
are all included in chain)
Returns -1 if chains have no common ancestor
* assumes the fork point is loaded in blocks
| def find_fork_point_in_chain(
blocks: BlockchainInterface,
block_1: Union[BlockRecord, HeaderBlock],
block_2: Union[BlockRecord, HeaderBlock],
) -> int:
"""Tries to find height where new chain (block_2) diverged from block_1 (assuming prev blocks
are all included in chain)
Returns -1 if chains h... | [
"def",
"find_fork_point_in_chain",
"(",
"blocks",
":",
"BlockchainInterface",
",",
"block_1",
":",
"Union",
"[",
"BlockRecord",
",",
"HeaderBlock",
"]",
",",
"block_2",
":",
"Union",
"[",
"BlockRecord",
",",
"HeaderBlock",
"]",
",",
")",
"->",
"int",
":",
"w... | [
7,
0
] | [
32,
12
] | python | en | ['en', 'en', 'en'] | True |
get_files_to_package | (input_files) | Find files to be added to the distribution.
input_files: list of pairs (package_path, real_path)
| Find files to be added to the distribution. | def get_files_to_package(input_files):
"""Find files to be added to the distribution.
input_files: list of pairs (package_path, real_path)
"""
files = {}
for package_path, real_path in input_files:
files[package_path] = real_path
return files | [
"def",
"get_files_to_package",
"(",
"input_files",
")",
":",
"files",
"=",
"{",
"}",
"for",
"package_path",
",",
"real_path",
"in",
"input_files",
":",
"files",
"[",
"package_path",
"]",
"=",
"real_path",
"return",
"files"
] | [
186,
0
] | [
194,
16
] | python | en | ['en', 'en', 'en'] | True |
WheelMaker.add_string | (self, filename, contents) | Add given 'contents' as filename to the distribution. | Add given 'contents' as filename to the distribution. | def add_string(self, filename, contents):
"""Add given 'contents' as filename to the distribution."""
if sys.version_info[0] > 2 and isinstance(contents, str):
contents = contents.encode('utf-8', 'surrogateescape')
self._zipfile.writestr(filename, contents)
hash = hashlib.sha... | [
"def",
"add_string",
"(",
"self",
",",
"filename",
",",
"contents",
")",
":",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
">",
"2",
"and",
"isinstance",
"(",
"contents",
",",
"str",
")",
":",
"contents",
"=",
"contents",
".",
"encode",
"(",
"'ut... | [
82,
4
] | [
90,
42
] | python | en | ['en', 'en', 'en'] | True |
WheelMaker.add_file | (self, package_filename, real_filename) | Add given file to the distribution. | Add given file to the distribution. | def add_file(self, package_filename, real_filename):
"""Add given file to the distribution."""
def arcname_from(name):
# Always use unix path separators.
normalized_arcname = name.replace(os.path.sep, '/')
for prefix in self._strip_path_prefixes:
if n... | [
"def",
"add_file",
"(",
"self",
",",
"package_filename",
",",
"real_filename",
")",
":",
"def",
"arcname_from",
"(",
"name",
")",
":",
"# Always use unix path separators.",
"normalized_arcname",
"=",
"name",
".",
"replace",
"(",
"os",
".",
"path",
".",
"sep",
... | [
92,
4
] | [
124,
72
] | python | en | ['en', 'en', 'en'] | True |
WheelMaker.add_wheelfile | (self) | Write WHEEL file to the distribution | Write WHEEL file to the distribution | def add_wheelfile(self):
"""Write WHEEL file to the distribution"""
# TODO(pstradomski): Support non-purelib wheels.
wheel_contents = """\
Wheel-Version: 1.0
Generator: bazel-wheelmaker 1.0
Root-Is-Purelib: {}
""".format("true" if self._platform == "any" else "false")
for tag in self.dis... | [
"def",
"add_wheelfile",
"(",
"self",
")",
":",
"# TODO(pstradomski): Support non-purelib wheels.",
"wheel_contents",
"=",
"\"\"\"\\\nWheel-Version: 1.0\nGenerator: bazel-wheelmaker 1.0\nRoot-Is-Purelib: {}\n\"\"\"",
".",
"format",
"(",
"\"true\"",
"if",
"self",
".",
"_platform",
... | [
126,
4
] | [
136,
68
] | python | en | ['en', 'en', 'en'] | True |
WheelMaker.add_metadata | (self, extra_headers, description, classifiers, python_requires,
requires, extra_requires) | Write METADATA file to the distribution. | Write METADATA file to the distribution. | def add_metadata(self, extra_headers, description, classifiers, python_requires,
requires, extra_requires):
"""Write METADATA file to the distribution."""
# https://www.python.org/dev/peps/pep-0566/
# https://packaging.python.org/specifications/core-metadata/
metadat... | [
"def",
"add_metadata",
"(",
"self",
",",
"extra_headers",
",",
"description",
",",
"classifiers",
",",
"python_requires",
",",
"requires",
",",
"extra_requires",
")",
":",
"# https://www.python.org/dev/peps/pep-0566/",
"# https://packaging.python.org/specifications/core-metadat... | [
138,
4
] | [
167,
65
] | python | en | ['en', 'lt', 'en'] | True |
WheelMaker.add_recordfile | (self) | Write RECORD file to the distribution. | Write RECORD file to the distribution. | def add_recordfile(self):
"""Write RECORD file to the distribution."""
record_path = self.distinfo_path('RECORD')
entries = self._record + [(record_path, b'', b'')]
entries.sort()
contents = b''
for filename, digest, size in entries:
if sys.version_info[0] > 2... | [
"def",
"add_recordfile",
"(",
"self",
")",
":",
"record_path",
"=",
"self",
".",
"distinfo_path",
"(",
"'RECORD'",
")",
"entries",
"=",
"self",
".",
"_record",
"+",
"[",
"(",
"record_path",
",",
"b''",
",",
"b''",
")",
"]",
"entries",
".",
"sort",
"(",... | [
169,
4
] | [
179,
46
] | python | en | ['en', 'en', 'en'] | True |
main | (args=None) | This is an internal API only meant for use by pip's own console scripts.
For additional details, see https://github.com/pypa/pip/issues/7498.
| This is an internal API only meant for use by pip's own console scripts. | def main(args=None):
# type: (Optional[List[str]]) -> int
"""This is an internal API only meant for use by pip's own console scripts.
For additional details, see https://github.com/pypa/pip/issues/7498.
"""
from pip._internal.utils.entrypoints import _wrapper
return _wrapper(args) | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"# type: (Optional[List[str]]) -> int",
"from",
"pip",
".",
"_internal",
".",
"utils",
".",
"entrypoints",
"import",
"_wrapper",
"return",
"_wrapper",
"(",
"args",
")"
] | [
9,
0
] | [
17,
25
] | python | en | ['en', 'en', 'en'] | True |
uts46_remap | (domain, std3_rules=True, transitional=False) | Re-map the characters in the string according to UTS46 processing. | Re-map the characters in the string according to UTS46 processing. | def uts46_remap(domain, std3_rules=True, transitional=False):
"""Re-map the characters in the string according to UTS46 processing."""
from .uts46data import uts46data
output = u""
try:
for pos, char in enumerate(domain):
code_point = ord(char)
uts46row = uts46data[code_p... | [
"def",
"uts46_remap",
"(",
"domain",
",",
"std3_rules",
"=",
"True",
",",
"transitional",
"=",
"False",
")",
":",
"from",
".",
"uts46data",
"import",
"uts46data",
"output",
"=",
"u\"\"",
"try",
":",
"for",
"pos",
",",
"char",
"in",
"enumerate",
"(",
"dom... | [
315,
0
] | [
340,
54
] | python | en | ['en', 'en', 'en'] | True |
sanitize_dict | (din) | Sanitize Django response data to purge it of internal types
so it may be used to cast a requests response object
| Sanitize Django response data to purge it of internal types
so it may be used to cast a requests response object
| def sanitize_dict(din):
"""Sanitize Django response data to purge it of internal types
so it may be used to cast a requests response object
"""
if isinstance(din, (int, str, type(None), bool)):
return din # native JSON types, no problem
elif isinstance(din, datetime.datetime):
retur... | [
"def",
"sanitize_dict",
"(",
"din",
")",
":",
"if",
"isinstance",
"(",
"din",
",",
"(",
"int",
",",
"str",
",",
"type",
"(",
"None",
")",
",",
"bool",
")",
")",
":",
"return",
"din",
"# native JSON types, no problem",
"elif",
"isinstance",
"(",
"din",
... | [
44,
0
] | [
61,
23
] | python | en | ['en', 'jv', 'en'] | True |
collection_path_set | (monkeypatch) | Monkey patch sys.path, insert the root of the collection folder
so that content can be imported without being fully packaged
| Monkey patch sys.path, insert the root of the collection folder
so that content can be imported without being fully packaged
| def collection_path_set(monkeypatch):
"""Monkey patch sys.path, insert the root of the collection folder
so that content can be imported without being fully packaged
"""
base_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
monkeypatch.syspath_prepend(base_fold... | [
"def",
"collection_path_set",
"(",
"monkeypatch",
")",
":",
"base_folder",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"os",
".",
"pardir",
",",
"os",... | [
65,
0
] | [
70,
44
] | python | en | ['en', 'en', 'en'] | True |
collection_import | () | These tests run assuming that the awx_collection folder is inserted
into the PATH before-hand by collection_path_set.
But all imports internally to the collection
go through this fixture so that can be changed if needed.
For instance, we could switch to fully-qualified import paths.
| These tests run assuming that the awx_collection folder is inserted
into the PATH before-hand by collection_path_set.
But all imports internally to the collection
go through this fixture so that can be changed if needed.
For instance, we could switch to fully-qualified import paths.
| def collection_import():
"""These tests run assuming that the awx_collection folder is inserted
into the PATH before-hand by collection_path_set.
But all imports internally to the collection
go through this fixture so that can be changed if needed.
For instance, we could switch to fully-qualified im... | [
"def",
"collection_import",
"(",
")",
":",
"def",
"rf",
"(",
"path",
")",
":",
"return",
"importlib",
".",
"import_module",
"(",
"path",
")",
"return",
"rf"
] | [
74,
0
] | [
85,
13
] | python | en | ['en', 'en', 'en'] | True |
silence_deprecation | () | The deprecation warnings are stored in a global variable
they will create cross-test interference. Use this to turn them off.
| The deprecation warnings are stored in a global variable
they will create cross-test interference. Use this to turn them off.
| def silence_deprecation():
"""The deprecation warnings are stored in a global variable
they will create cross-test interference. Use this to turn them off.
"""
with mock.patch('ansible.module_utils.basic.AnsibleModule.deprecate') as this_mock:
yield this_mock | [
"def",
"silence_deprecation",
"(",
")",
":",
"with",
"mock",
".",
"patch",
"(",
"'ansible.module_utils.basic.AnsibleModule.deprecate'",
")",
"as",
"this_mock",
":",
"yield",
"this_mock"
] | [
261,
0
] | [
266,
23
] | python | en | ['en', 'en', 'en'] | True |
silence_warning | () | Warnings use global variable, same as deprecations. | Warnings use global variable, same as deprecations. | def silence_warning():
"""Warnings use global variable, same as deprecations."""
with mock.patch('ansible.module_utils.basic.AnsibleModule.warn') as this_mock:
yield this_mock | [
"def",
"silence_warning",
"(",
")",
":",
"with",
"mock",
".",
"patch",
"(",
"'ansible.module_utils.basic.AnsibleModule.warn'",
")",
"as",
"this_mock",
":",
"yield",
"this_mock"
] | [
270,
0
] | [
273,
23
] | python | af | ['pt', 'af', 'en'] | False |
load_cdll | (name, macos10_16_path) | Loads a CDLL by name, falling back to known path on 10.16+ | Loads a CDLL by name, falling back to known path on 10.16+ | def load_cdll(name, macos10_16_path):
"""Loads a CDLL by name, falling back to known path on 10.16+"""
try:
# Big Sur is technically 11 but we use 10.16 due to the Big Sur
# beta being labeled as 10.16.
if version_info >= (10, 16):
path = macos10_16_path
else:
... | [
"def",
"load_cdll",
"(",
"name",
",",
"macos10_16_path",
")",
":",
"try",
":",
"# Big Sur is technically 11 but we use 10.16 due to the Big Sur",
"# beta being labeled as 10.16.",
"if",
"version_info",
">=",
"(",
"10",
",",
"16",
")",
":",
"path",
"=",
"macos10_16_path"... | [
64,
0
] | [
77,
77
] | python | en | ['en', 'en', 'en'] | True |
_clean_credentials | (credentials) |
Cleans a dictionary of credentials of potentially sensitive info before
sending to less secure functions.
Not comprehensive - intended for user_login_failed signal
|
Cleans a dictionary of credentials of potentially sensitive info before
sending to less secure functions. | def _clean_credentials(credentials):
"""
Cleans a dictionary of credentials of potentially sensitive info before
sending to less secure functions.
Not comprehensive - intended for user_login_failed signal
"""
SENSITIVE_CREDENTIALS = re.compile('api|token|key|secret|password|signature', re.I)
... | [
"def",
"_clean_credentials",
"(",
"credentials",
")",
":",
"SENSITIVE_CREDENTIALS",
"=",
"re",
".",
"compile",
"(",
"'api|token|key|secret|password|signature'",
",",
"re",
".",
"I",
")",
"CLEANSED_SUBSTITUTE",
"=",
"'********************'",
"for",
"key",
"in",
"creden... | [
42,
0
] | [
54,
22
] | python | en | ['en', 'error', 'th'] | False |
authenticate | (request=None, **credentials) |
If the given credentials are valid, return a User object.
|
If the given credentials are valid, return a User object.
| def authenticate(request=None, **credentials):
"""
If the given credentials are valid, return a User object.
"""
for backend, backend_path in _get_backends(return_tuples=True):
args = (request,)
# Does the backend accept a request argument?
try:
inspect.getcallargs(ba... | [
"def",
"authenticate",
"(",
"request",
"=",
"None",
",",
"*",
"*",
"credentials",
")",
":",
"for",
"backend",
",",
"backend_path",
"in",
"_get_backends",
"(",
"return_tuples",
"=",
"True",
")",
":",
"args",
"=",
"(",
"request",
",",
")",
"# Does the backen... | [
63,
0
] | [
110,
105
] | python | en | ['en', 'error', 'th'] | False |
login | (request, user, backend=None) |
Persist a user id and a backend in the request. This way a user doesn't
have to reauthenticate on every request. Note that data set during
the anonymous session is retained when the user logs in.
|
Persist a user id and a backend in the request. This way a user doesn't
have to reauthenticate on every request. Note that data set during
the anonymous session is retained when the user logs in.
| def login(request, user, backend=None):
"""
Persist a user id and a backend in the request. This way a user doesn't
have to reauthenticate on every request. Note that data set during
the anonymous session is retained when the user logs in.
"""
session_auth_hash = ''
if user is None:
... | [
"def",
"login",
"(",
"request",
",",
"user",
",",
"backend",
"=",
"None",
")",
":",
"session_auth_hash",
"=",
"''",
"if",
"user",
"is",
"None",
":",
"user",
"=",
"request",
".",
"user",
"if",
"hasattr",
"(",
"user",
",",
"'get_session_auth_hash'",
")",
... | [
113,
0
] | [
155,
74
] | python | en | ['en', 'error', 'th'] | False |
logout | (request) |
Removes the authenticated user's ID from the request and flushes their
session data.
|
Removes the authenticated user's ID from the request and flushes their
session data.
| def logout(request):
"""
Removes the authenticated user's ID from the request and flushes their
session data.
"""
# Dispatch the signal before the user is logged out so the receivers have a
# chance to find out *who* logged out.
user = getattr(request, 'user', None)
if hasattr(user, 'is_... | [
"def",
"logout",
"(",
"request",
")",
":",
"# Dispatch the signal before the user is logged out so the receivers have a",
"# chance to find out *who* logged out.",
"user",
"=",
"getattr",
"(",
"request",
",",
"'user'",
",",
"None",
")",
"if",
"hasattr",
"(",
"user",
",",
... | [
158,
0
] | [
180,
38
] | python | en | ['en', 'error', 'th'] | False |
get_user_model | () |
Returns the User model that is active in this project.
|
Returns the User model that is active in this project.
| def get_user_model():
"""
Returns the User model that is active in this project.
"""
try:
return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False)
except ValueError:
raise ImproperlyConfigured("AUTH_USER_MODEL must be of the form 'app_label.model_name'")
except... | [
"def",
"get_user_model",
"(",
")",
":",
"try",
":",
"return",
"django_apps",
".",
"get_model",
"(",
"settings",
".",
"AUTH_USER_MODEL",
",",
"require_ready",
"=",
"False",
")",
"except",
"ValueError",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"AUTH_USER_MODEL m... | [
183,
0
] | [
194,
9
] | python | en | ['en', 'error', 'th'] | False |
get_user | (request) |
Returns the user model instance associated with the given request session.
If no user is retrieved an instance of `AnonymousUser` is returned.
|
Returns the user model instance associated with the given request session.
If no user is retrieved an instance of `AnonymousUser` is returned.
| def get_user(request):
"""
Returns the user model instance associated with the given request session.
If no user is retrieved an instance of `AnonymousUser` is returned.
"""
from .models import AnonymousUser
user = None
try:
user_id = _get_user_session_key(request)
backend_pa... | [
"def",
"get_user",
"(",
"request",
")",
":",
"from",
".",
"models",
"import",
"AnonymousUser",
"user",
"=",
"None",
"try",
":",
"user_id",
"=",
"_get_user_session_key",
"(",
"request",
")",
"backend_path",
"=",
"request",
".",
"session",
"[",
"BACKEND_SESSION_... | [
197,
0
] | [
224,
34
] | python | en | ['en', 'error', 'th'] | False |
get_permission_codename | (action, opts) |
Returns the codename of the permission for the specified action.
|
Returns the codename of the permission for the specified action.
| def get_permission_codename(action, opts):
"""
Returns the codename of the permission for the specified action.
"""
return '%s_%s' % (action, opts.model_name) | [
"def",
"get_permission_codename",
"(",
"action",
",",
"opts",
")",
":",
"return",
"'%s_%s'",
"%",
"(",
"action",
",",
"opts",
".",
"model_name",
")"
] | [
227,
0
] | [
231,
46
] | python | en | ['en', 'error', 'th'] | False |
update_session_auth_hash | (request, user) |
Updating a user's password logs out all sessions for the user.
This function takes the current request and the updated user object from
which the new session hash will be derived and updates the session hash
appropriately to prevent a password change from logging out the session
from which the pas... |
Updating a user's password logs out all sessions for the user. | def update_session_auth_hash(request, user):
"""
Updating a user's password logs out all sessions for the user.
This function takes the current request and the updated user object from
which the new session hash will be derived and updates the session hash
appropriately to prevent a password change... | [
"def",
"update_session_auth_hash",
"(",
"request",
",",
"user",
")",
":",
"request",
".",
"session",
".",
"cycle_key",
"(",
")",
"if",
"hasattr",
"(",
"user",
",",
"'get_session_auth_hash'",
")",
"and",
"request",
".",
"user",
"==",
"user",
":",
"request",
... | [
234,
0
] | [
245,
72
] | python | en | ['en', 'error', 'th'] | False |
get_encryption_key | (field_name, pk=None, secret_key=None) |
Generate key for encrypted password based on field name,
``settings.SECRET_KEY``, and instance pk (if available).
:param pk: (optional) the primary key of the model object;
can be omitted in situations where you're encrypting a setting
that is not database-persistent (like a ... |
Generate key for encrypted password based on field name,
``settings.SECRET_KEY``, and instance pk (if available). | def get_encryption_key(field_name, pk=None, secret_key=None):
"""
Generate key for encrypted password based on field name,
``settings.SECRET_KEY``, and instance pk (if available).
:param pk: (optional) the primary key of the model object;
can be omitted in situations where you're encrypt... | [
"def",
"get_encryption_key",
"(",
"field_name",
",",
"pk",
"=",
"None",
",",
"secret_key",
"=",
"None",
")",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"h",
"=",
"hashlib",
".",
"sha512",
"(",
")",
"h",
".",
"update",
"(",
"smart_bytes",
... | [
35,
0
] | [
51,
47
] | python | en | ['en', 'error', 'th'] | False |
encrypt_field | (instance, field_name, ask=False, subfield=None, secret_key=None) |
Return content of the given instance and field name encrypted.
|
Return content of the given instance and field name encrypted.
| def encrypt_field(instance, field_name, ask=False, subfield=None, secret_key=None):
#
# ⚠️ D-D-D-DANGER ZONE ⚠️
#
# !!! PLEASE READ BEFORE USING THIS FUNCTION ANYWHERE !!!
#
# You should know that this function is used in various places throughout
# AWX for symmetric encryption - generally ... | [
"def",
"encrypt_field",
"(",
"instance",
",",
"field_name",
",",
"ask",
"=",
"False",
",",
"subfield",
"=",
"None",
",",
"secret_key",
"=",
"None",
")",
":",
"#",
"# ⚠️ D-D-D-DANGER ZONE ⚠️",
"#",
"# !!! PLEASE READ BEFORE USING THIS FUNCTION ANYWHERE !!!",
"#",
"#... | [
64,
0
] | [
121,
27
] | python | en | ['en', 'error', 'th'] | False |
decrypt_field | (instance, field_name, subfield=None, secret_key=None) |
Return content of the given instance and field name decrypted.
|
Return content of the given instance and field name decrypted.
| def decrypt_field(instance, field_name, subfield=None, secret_key=None):
"""
Return content of the given instance and field name decrypted.
"""
try:
value = instance.inputs[field_name]
except (TypeError, AttributeError):
value = getattr(instance, field_name)
except KeyError:
... | [
"def",
"decrypt_field",
"(",
"instance",
",",
"field_name",
",",
"subfield",
"=",
"None",
",",
"secret_key",
"=",
"None",
")",
":",
"try",
":",
"value",
"=",
"instance",
".",
"inputs",
"[",
"field_name",
"]",
"except",
"(",
"TypeError",
",",
"AttributeErro... | [
139,
0
] | [
169,
13
] | python | en | ['en', 'error', 'th'] | False |
encrypt_dict | (data, fields) |
Encrypts all of the dictionary values in `data` under the keys in `fields`
in-place operation on `data`
|
Encrypts all of the dictionary values in `data` under the keys in `fields`
in-place operation on `data`
| def encrypt_dict(data, fields):
"""
Encrypts all of the dictionary values in `data` under the keys in `fields`
in-place operation on `data`
"""
encrypt_fields = set(data.keys()).intersection(fields)
for key in encrypt_fields:
data[key] = encrypt_value(data[key]) | [
"def",
"encrypt_dict",
"(",
"data",
",",
"fields",
")",
":",
"encrypt_fields",
"=",
"set",
"(",
"data",
".",
"keys",
"(",
")",
")",
".",
"intersection",
"(",
"fields",
")",
"for",
"key",
"in",
"encrypt_fields",
":",
"data",
"[",
"key",
"]",
"=",
"enc... | [
172,
0
] | [
179,
44
] | python | en | ['en', 'error', 'th'] | False |
get_admin_log | (parser, token) |
Populates a template variable with the admin log for the given criteria.
Usage::
{% get_admin_log [limit] as [varname] for_user [context_var_containing_user_obj] %}
Examples::
{% get_admin_log 10 as admin_log for_user 23 %}
{% get_admin_log 10 as admin_log for_user user %}
... |
Populates a template variable with the admin log for the given criteria. | def get_admin_log(parser, token):
"""
Populates a template variable with the admin log for the given criteria.
Usage::
{% get_admin_log [limit] as [varname] for_user [context_var_containing_user_obj] %}
Examples::
{% get_admin_log 10 as admin_log for_user 23 %}
{% get_admin_l... | [
"def",
"get_admin_log",
"(",
"parser",
",",
"token",
")",
":",
"tokens",
"=",
"token",
".",
"contents",
".",
"split",
"(",
")",
"if",
"len",
"(",
"tokens",
")",
"<",
"4",
":",
"raise",
"template",
".",
"TemplateSyntaxError",
"(",
"\"'get_admin_log' stateme... | [
26,
0
] | [
58,
106
] | python | en | ['en', 'error', 'th'] | False |
auto_decode | (data) | Check a bytes string for a BOM to correctly detect the encoding
Fallback to locale.getpreferredencoding(False) like open() on Python3 | Check a bytes string for a BOM to correctly detect the encoding | def auto_decode(data):
# type: (bytes) -> Text
"""Check a bytes string for a BOM to correctly detect the encoding
Fallback to locale.getpreferredencoding(False) like open() on Python3"""
for bom, encoding in BOMS:
if data.startswith(bom):
return data[len(bom):].decode(encoding)
... | [
"def",
"auto_decode",
"(",
"data",
")",
":",
"# type: (bytes) -> Text",
"for",
"bom",
",",
"encoding",
"in",
"BOMS",
":",
"if",
"data",
".",
"startswith",
"(",
"bom",
")",
":",
"return",
"data",
"[",
"len",
"(",
"bom",
")",
":",
"]",
".",
"decode",
"... | [
23,
0
] | [
40,
5
] | python | en | ['en', 'en', 'en'] | True |
PermissionHelper.get_all_model_permissions | (self) |
Return a queryset of all Permission objects pertaining to the `model`
specified at initialisation.
|
Return a queryset of all Permission objects pertaining to the `model`
specified at initialisation.
| def get_all_model_permissions(self):
"""
Return a queryset of all Permission objects pertaining to the `model`
specified at initialisation.
"""
return Permission.objects.filter(
content_type__app_label=self.opts.app_label,
content_type__model=self.opts.mo... | [
"def",
"get_all_model_permissions",
"(",
"self",
")",
":",
"return",
"Permission",
".",
"objects",
".",
"filter",
"(",
"content_type__app_label",
"=",
"self",
".",
"opts",
".",
"app_label",
",",
"content_type__model",
"=",
"self",
".",
"opts",
".",
"model_name",... | [
19,
4
] | [
28,
9
] | python | en | ['en', 'error', 'th'] | False |
PermissionHelper.user_has_specific_permission | (self, user, perm_codename) |
Combine `perm_codename` with `self.opts.app_label` to call the provided
Django user's built-in `has_perm` method.
|
Combine `perm_codename` with `self.opts.app_label` to call the provided
Django user's built-in `has_perm` method.
| def user_has_specific_permission(self, user, perm_codename):
"""
Combine `perm_codename` with `self.opts.app_label` to call the provided
Django user's built-in `has_perm` method.
"""
return user.has_perm("%s.%s" % (self.opts.app_label, perm_codename)) | [
"def",
"user_has_specific_permission",
"(",
"self",
",",
"user",
",",
"perm_codename",
")",
":",
"return",
"user",
".",
"has_perm",
"(",
"\"%s.%s\"",
"%",
"(",
"self",
".",
"opts",
".",
"app_label",
",",
"perm_codename",
")",
")"
] | [
33,
4
] | [
39,
76
] | python | en | ['en', 'error', 'th'] | False |
PermissionHelper.user_has_any_permissions | (self, user) |
Return a boolean to indicate whether `user` has any model-wide
permissions
|
Return a boolean to indicate whether `user` has any model-wide
permissions
| def user_has_any_permissions(self, user):
"""
Return a boolean to indicate whether `user` has any model-wide
permissions
"""
for perm in self.get_all_model_permissions().values('codename'):
if self.user_has_specific_permission(user, perm['codename']):
... | [
"def",
"user_has_any_permissions",
"(",
"self",
",",
"user",
")",
":",
"for",
"perm",
"in",
"self",
".",
"get_all_model_permissions",
"(",
")",
".",
"values",
"(",
"'codename'",
")",
":",
"if",
"self",
".",
"user_has_specific_permission",
"(",
"user",
",",
"... | [
41,
4
] | [
49,
20
] | python | en | ['en', 'error', 'th'] | False |
PermissionHelper.user_can_list | (self, user) |
Return a boolean to indicate whether `user` is permitted to access the
list view for self.model
|
Return a boolean to indicate whether `user` is permitted to access the
list view for self.model
| def user_can_list(self, user):
"""
Return a boolean to indicate whether `user` is permitted to access the
list view for self.model
"""
return self.user_has_any_permissions(user) | [
"def",
"user_can_list",
"(",
"self",
",",
"user",
")",
":",
"return",
"self",
".",
"user_has_any_permissions",
"(",
"user",
")"
] | [
51,
4
] | [
56,
50
] | python | en | ['en', 'error', 'th'] | False |
PermissionHelper.user_can_create | (self, user) |
Return a boolean to indicate whether `user` is permitted to create new
instances of `self.model`
|
Return a boolean to indicate whether `user` is permitted to create new
instances of `self.model`
| def user_can_create(self, user):
"""
Return a boolean to indicate whether `user` is permitted to create new
instances of `self.model`
"""
perm_codename = self.get_perm_codename('add')
return self.user_has_specific_permission(user, perm_codename) | [
"def",
"user_can_create",
"(",
"self",
",",
"user",
")",
":",
"perm_codename",
"=",
"self",
".",
"get_perm_codename",
"(",
"'add'",
")",
"return",
"self",
".",
"user_has_specific_permission",
"(",
"user",
",",
"perm_codename",
")"
] | [
58,
4
] | [
64,
69
] | python | en | ['en', 'error', 'th'] | False |
PermissionHelper.user_can_inspect_obj | (self, user, obj) |
Return a boolean to indicate whether `user` is permitted to 'inspect'
a specific `self.model` instance.
|
Return a boolean to indicate whether `user` is permitted to 'inspect'
a specific `self.model` instance.
| def user_can_inspect_obj(self, user, obj):
"""
Return a boolean to indicate whether `user` is permitted to 'inspect'
a specific `self.model` instance.
"""
return self.inspect_view_enabled and self.user_has_any_permissions(
user) | [
"def",
"user_can_inspect_obj",
"(",
"self",
",",
"user",
",",
"obj",
")",
":",
"return",
"self",
".",
"inspect_view_enabled",
"and",
"self",
".",
"user_has_any_permissions",
"(",
"user",
")"
] | [
66,
4
] | [
72,
17
] | python | en | ['en', 'error', 'th'] | False |
PermissionHelper.user_can_edit_obj | (self, user, obj) |
Return a boolean to indicate whether `user` is permitted to 'change'
a specific `self.model` instance.
|
Return a boolean to indicate whether `user` is permitted to 'change'
a specific `self.model` instance.
| def user_can_edit_obj(self, user, obj):
"""
Return a boolean to indicate whether `user` is permitted to 'change'
a specific `self.model` instance.
"""
perm_codename = self.get_perm_codename('change')
return self.user_has_specific_permission(user, perm_codename) | [
"def",
"user_can_edit_obj",
"(",
"self",
",",
"user",
",",
"obj",
")",
":",
"perm_codename",
"=",
"self",
".",
"get_perm_codename",
"(",
"'change'",
")",
"return",
"self",
".",
"user_has_specific_permission",
"(",
"user",
",",
"perm_codename",
")"
] | [
74,
4
] | [
80,
69
] | python | en | ['en', 'error', 'th'] | False |
PermissionHelper.user_can_delete_obj | (self, user, obj) |
Return a boolean to indicate whether `user` is permitted to 'delete'
a specific `self.model` instance.
|
Return a boolean to indicate whether `user` is permitted to 'delete'
a specific `self.model` instance.
| def user_can_delete_obj(self, user, obj):
"""
Return a boolean to indicate whether `user` is permitted to 'delete'
a specific `self.model` instance.
"""
perm_codename = self.get_perm_codename('delete')
return self.user_has_specific_permission(user, perm_codename) | [
"def",
"user_can_delete_obj",
"(",
"self",
",",
"user",
",",
"obj",
")",
":",
"perm_codename",
"=",
"self",
".",
"get_perm_codename",
"(",
"'delete'",
")",
"return",
"self",
".",
"user_has_specific_permission",
"(",
"user",
",",
"perm_codename",
")"
] | [
82,
4
] | [
88,
69
] | python | en | ['en', 'error', 'th'] | False |
PagePermissionHelper.get_valid_parent_pages | (self, user) |
Identifies possible parent pages for the current user by first looking
at allowed_parent_page_models() on self.model to limit options to the
correct type of page, then checking permissions on those individual
pages to make sure we have permission to add a subpage to it.
|
Identifies possible parent pages for the current user by first looking
at allowed_parent_page_models() on self.model to limit options to the
correct type of page, then checking permissions on those individual
pages to make sure we have permission to add a subpage to it.
| def get_valid_parent_pages(self, user):
"""
Identifies possible parent pages for the current user by first looking
at allowed_parent_page_models() on self.model to limit options to the
correct type of page, then checking permissions on those individual
pages to make sure we have ... | [
"def",
"get_valid_parent_pages",
"(",
"self",
",",
"user",
")",
":",
"# Get queryset of pages where this page type can be added",
"allowed_parent_page_content_types",
"=",
"list",
"(",
"ContentType",
".",
"objects",
".",
"get_for_models",
"(",
"*",
"self",
".",
"model",
... | [
106,
4
] | [
130,
62
] | python | en | ['en', 'error', 'th'] | False |
PagePermissionHelper.user_can_list | (self, user) |
For models extending Page, permitted actions are determined by
permissions on individual objects. Rather than check for change
permissions on every object individually (which would be quite
resource intensive), we simply always allow the list view to be
viewed, and limit further... |
For models extending Page, permitted actions are determined by
permissions on individual objects. Rather than check for change
permissions on every object individually (which would be quite
resource intensive), we simply always allow the list view to be
viewed, and limit further... | def user_can_list(self, user):
"""
For models extending Page, permitted actions are determined by
permissions on individual objects. Rather than check for change
permissions on every object individually (which would be quite
resource intensive), we simply always allow the list vi... | [
"def",
"user_can_list",
"(",
"self",
",",
"user",
")",
":",
"return",
"True"
] | [
132,
4
] | [
140,
19
] | python | en | ['en', 'error', 'th'] | False |
PagePermissionHelper.user_can_create | (self, user) |
For models extending Page, whether or not a page of this type can be
added somewhere in the tree essentially determines the add permission,
rather than actual model-wide permissions
|
For models extending Page, whether or not a page of this type can be
added somewhere in the tree essentially determines the add permission,
rather than actual model-wide permissions
| def user_can_create(self, user):
"""
For models extending Page, whether or not a page of this type can be
added somewhere in the tree essentially determines the add permission,
rather than actual model-wide permissions
"""
return self.get_valid_parent_pages(user).exists() | [
"def",
"user_can_create",
"(",
"self",
",",
"user",
")",
":",
"return",
"self",
".",
"get_valid_parent_pages",
"(",
"user",
")",
".",
"exists",
"(",
")"
] | [
142,
4
] | [
148,
57
] | python | en | ['en', 'error', 'th'] | False |
write_stats_to_bed | (bed_fn, results) |
Write the results to a bed file (with a bunch of extra columns for G-test results)
|
Write the results to a bed file (with a bunch of extra columns for G-test results)
| def write_stats_to_bed(bed_fn, results):
'''
Write the results to a bed file (with a bunch of extra columns for G-test results)
'''
with open(bed_fn, 'w') as bed:
for _, chrom, pos, strand, odds_ratio, *G_test_res in results.itertuples():
G_A, G_A_p, G_B, G_B_p, G, G_p, G_fdr = G_tes... | [
"def",
"write_stats_to_bed",
"(",
"bed_fn",
",",
"results",
")",
":",
"with",
"open",
"(",
"bed_fn",
",",
"'w'",
")",
"as",
"bed",
":",
"for",
"_",
",",
"chrom",
",",
"pos",
",",
"strand",
",",
"odds_ratio",
",",
"",
"*",
"G_test_res",
"in",
"results... | [
49,
0
] | [
70,
14
] | python | en | ['en', 'error', 'th'] | False |
Polygon.__init__ | (self, *args, **kwargs) |
Initializes on an exterior ring and a sequence of holes (both
instances may be either LinearRing instances, or a tuple/list
that may be constructed into a LinearRing).
Examples of initialization, where shell, hole1, and hole2 are
valid LinearRing geometries:
>>> from dj... |
Initializes on an exterior ring and a sequence of holes (both
instances may be either LinearRing instances, or a tuple/list
that may be constructed into a LinearRing). | def __init__(self, *args, **kwargs):
"""
Initializes on an exterior ring and a sequence of holes (both
instances may be either LinearRing instances, or a tuple/list
that may be constructed into a LinearRing).
Examples of initialization, where shell, hole1, and hole2 are
... | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"args",
":",
"super",
"(",
"Polygon",
",",
"self",
")",
".",
"__init__",
"(",
"self",
".",
"_create_polygon",
"(",
"0",
",",
"None",
")",
",",
"*",
... | [
13,
4
] | [
49,
56
] | python | en | ['en', 'error', 'th'] | False |
Polygon.__iter__ | (self) | Iterates over each ring in the polygon. | Iterates over each ring in the polygon. | def __iter__(self):
"Iterates over each ring in the polygon."
for i in range(len(self)):
yield self[i] | [
"def",
"__iter__",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
")",
")",
":",
"yield",
"self",
"[",
"i",
"]"
] | [
51,
4
] | [
54,
25
] | python | en | ['en', 'en', 'en'] | True |
Polygon.__len__ | (self) | Returns the number of rings in this Polygon. | Returns the number of rings in this Polygon. | def __len__(self):
"Returns the number of rings in this Polygon."
return self.num_interior_rings + 1 | [
"def",
"__len__",
"(",
"self",
")",
":",
"return",
"self",
".",
"num_interior_rings",
"+",
"1"
] | [
56,
4
] | [
58,
42
] | python | en | ['en', 'en', 'en'] | True |
Polygon.from_bbox | (cls, bbox) | Constructs a Polygon from a bounding box (4-tuple). | Constructs a Polygon from a bounding box (4-tuple). | def from_bbox(cls, bbox):
"Constructs a Polygon from a bounding box (4-tuple)."
x0, y0, x1, y1 = bbox
for z in bbox:
if not isinstance(z, six.integer_types + (float,)):
return GEOSGeometry('POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))' %
... | [
"def",
"from_bbox",
"(",
"cls",
",",
"bbox",
")",
":",
"x0",
",",
"y0",
",",
"x1",
",",
"y1",
"=",
"bbox",
"for",
"z",
"in",
"bbox",
":",
"if",
"not",
"isinstance",
"(",
"z",
",",
"six",
".",
"integer_types",
"+",
"(",
"float",
",",
")",
")",
... | [
61,
4
] | [
68,
74
] | python | en | ['en', 'en', 'en'] | True |
Polygon._construct_ring | (self, param, msg=(
'Parameter must be a sequence of LinearRings or objects that can initialize to LinearRings')) | Helper routine for trying to construct a ring from the given parameter. | Helper routine for trying to construct a ring from the given parameter. | def _construct_ring(self, param, msg=(
'Parameter must be a sequence of LinearRings or objects that can initialize to LinearRings')):
"Helper routine for trying to construct a ring from the given parameter."
if isinstance(param, LinearRing):
return param
try:
... | [
"def",
"_construct_ring",
"(",
"self",
",",
"param",
",",
"msg",
"=",
"(",
"'Parameter must be a sequence of LinearRings or objects that can initialize to LinearRings'",
")",
")",
":",
"if",
"isinstance",
"(",
"param",
",",
"LinearRing",
")",
":",
"return",
"param",
"... | [
105,
4
] | [
114,
32
] | python | en | ['en', 'en', 'en'] | True |
Polygon._get_single_internal | (self, index) |
Returns the ring at the specified index. The first index, 0, will
always return the exterior ring. Indices > 0 will return the
interior ring at the given index (e.g., poly[1] and poly[2] would
return the first and second interior ring, respectively).
CAREFUL: Internal/Externa... |
Returns the ring at the specified index. The first index, 0, will
always return the exterior ring. Indices > 0 will return the
interior ring at the given index (e.g., poly[1] and poly[2] would
return the first and second interior ring, respectively). | def _get_single_internal(self, index):
"""
Returns the ring at the specified index. The first index, 0, will
always return the exterior ring. Indices > 0 will return the
interior ring at the given index (e.g., poly[1] and poly[2] would
return the first and second interior ring,... | [
"def",
"_get_single_internal",
"(",
"self",
",",
"index",
")",
":",
"if",
"index",
"==",
"0",
":",
"return",
"capi",
".",
"get_extring",
"(",
"self",
".",
"ptr",
")",
"else",
":",
"# Getting the interior ring, have to subtract 1 from the index.",
"return",
"capi",... | [
126,
4
] | [
142,
56
] | python | en | ['en', 'error', 'th'] | False |
Polygon.num_interior_rings | (self) | Returns the number of interior rings. | Returns the number of interior rings. | def num_interior_rings(self):
"Returns the number of interior rings."
# Getting the number of rings
return capi.get_nrings(self.ptr) | [
"def",
"num_interior_rings",
"(",
"self",
")",
":",
"# Getting the number of rings",
"return",
"capi",
".",
"get_nrings",
"(",
"self",
".",
"ptr",
")"
] | [
152,
4
] | [
155,
40
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.