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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
process_long_term_idle_users | (
slack_data_dir: str,
users: List[ZerverFieldsT],
slack_user_id_to_zulip_user_id: SlackToZulipUserIDT,
added_channels: AddedChannelsT,
added_mpims: AddedMPIMsT,
dm_members: DMMembersT,
zerver_userprofile: List[ZerverFieldsT],
) | Algorithmically, we treat users who have sent at least 10 messages
or have sent a message within the last 60 days as active.
Everyone else is treated as long-term idle, which means they will
have a slightly slower first page load when coming back to
Zulip.
| Algorithmically, we treat users who have sent at least 10 messages
or have sent a message within the last 60 days as active.
Everyone else is treated as long-term idle, which means they will
have a slightly slower first page load when coming back to
Zulip.
| def process_long_term_idle_users(
slack_data_dir: str,
users: List[ZerverFieldsT],
slack_user_id_to_zulip_user_id: SlackToZulipUserIDT,
added_channels: AddedChannelsT,
added_mpims: AddedMPIMsT,
dm_members: DMMembersT,
zerver_userprofile: List[ZerverFieldsT],
) -> Set[int]:
"""Algorithmic... | [
"def",
"process_long_term_idle_users",
"(",
"slack_data_dir",
":",
"str",
",",
"users",
":",
"List",
"[",
"ZerverFieldsT",
"]",
",",
"slack_user_id_to_zulip_user_id",
":",
"SlackToZulipUserIDT",
",",
"added_channels",
":",
"AddedChannelsT",
",",
"added_mpims",
":",
"A... | [
604,
0
] | [
657,
25
] | python | en | ['en', 'en', 'en'] | True |
convert_slack_workspace_messages | (
slack_data_dir: str,
users: List[ZerverFieldsT],
realm_id: int,
slack_user_id_to_zulip_user_id: SlackToZulipUserIDT,
slack_recipient_name_to_zulip_recipient_id: SlackToZulipRecipientT,
added_channels: AddedChannelsT,
added_mpims: AddedMPIMsT,
dm_members: DMMembersT,
realm: ZerverFi... |
Returns:
1. reactions, which is a list of the reactions
2. uploads, which is a list of uploads to be mapped in uploads records.json
3. attachment, which is a list of the attachments
|
Returns:
1. reactions, which is a list of the reactions
2. uploads, which is a list of uploads to be mapped in uploads records.json
3. attachment, which is a list of the attachments
| def convert_slack_workspace_messages(
slack_data_dir: str,
users: List[ZerverFieldsT],
realm_id: int,
slack_user_id_to_zulip_user_id: SlackToZulipUserIDT,
slack_recipient_name_to_zulip_recipient_id: SlackToZulipRecipientT,
added_channels: AddedChannelsT,
added_mpims: AddedMPIMsT,
dm_memb... | [
"def",
"convert_slack_workspace_messages",
"(",
"slack_data_dir",
":",
"str",
",",
"users",
":",
"List",
"[",
"ZerverFieldsT",
"]",
",",
"realm_id",
":",
"int",
",",
"slack_user_id_to_zulip_user_id",
":",
"SlackToZulipUserIDT",
",",
"slack_recipient_name_to_zulip_recipien... | [
660,
0
] | [
750,
60
] | python | en | ['en', 'error', 'th'] | False |
get_messages_iterator | (
slack_data_dir: str,
added_channels: Dict[str, Any],
added_mpims: AddedMPIMsT,
dm_members: DMMembersT,
) | This function is an iterator that returns all the messages across
all Slack channels, in order by timestamp. It's important to
not read all the messages into memory at once, because for
large imports that can OOM kill. | This function is an iterator that returns all the messages across
all Slack channels, in order by timestamp. It's important to
not read all the messages into memory at once, because for
large imports that can OOM kill. | def get_messages_iterator(
slack_data_dir: str,
added_channels: Dict[str, Any],
added_mpims: AddedMPIMsT,
dm_members: DMMembersT,
) -> Iterator[ZerverFieldsT]:
"""This function is an iterator that returns all the messages across
all Slack channels, in order by timestamp. It's important to
n... | [
"def",
"get_messages_iterator",
"(",
"slack_data_dir",
":",
"str",
",",
"added_channels",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"added_mpims",
":",
"AddedMPIMsT",
",",
"dm_members",
":",
"DMMembersT",
",",
")",
"->",
"Iterator",
"[",
"ZerverFieldsT",
... | [
753,
0
] | [
799,
70
] | python | en | ['en', 'en', 'en'] | True |
channel_message_to_zerver_message | (
realm_id: int,
users: List[ZerverFieldsT],
slack_user_id_to_zulip_user_id: SlackToZulipUserIDT,
slack_recipient_name_to_zulip_recipient_id: SlackToZulipRecipientT,
all_messages: List[ZerverFieldsT],
zerver_realmemoji: List[ZerverFieldsT],
subscriber_map: Dict[int, Set[int]],
added_chan... |
Returns:
1. zerver_message, which is a list of the messages
2. zerver_usermessage, which is a list of the usermessages
3. zerver_attachment, which is a list of the attachments
4. uploads_list, which is a list of uploads to be mapped in uploads records.json
5. reaction_list, which is a list of a... |
Returns:
1. zerver_message, which is a list of the messages
2. zerver_usermessage, which is a list of the usermessages
3. zerver_attachment, which is a list of the attachments
4. uploads_list, which is a list of uploads to be mapped in uploads records.json
5. reaction_list, which is a list of a... | def channel_message_to_zerver_message(
realm_id: int,
users: List[ZerverFieldsT],
slack_user_id_to_zulip_user_id: SlackToZulipUserIDT,
slack_recipient_name_to_zulip_recipient_id: SlackToZulipRecipientT,
all_messages: List[ZerverFieldsT],
zerver_realmemoji: List[ZerverFieldsT],
subscriber_map... | [
"def",
"channel_message_to_zerver_message",
"(",
"realm_id",
":",
"int",
",",
"users",
":",
"List",
"[",
"ZerverFieldsT",
"]",
",",
"slack_user_id_to_zulip_user_id",
":",
"SlackToZulipUserIDT",
",",
"slack_recipient_name_to_zulip_recipient_id",
":",
"SlackToZulipRecipientT",
... | [
802,
0
] | [
971,
93
] | python | en | ['en', 'error', 'th'] | False |
always_want | (msg_type: str) |
This function is used as a helper in
fetch_initial_state_data, when the user passes
in None for event_types, and we want to fetch
info for every event type. Defining this at module
level makes it easier to mock.
|
This function is used as a helper in
fetch_initial_state_data, when the user passes
in None for event_types, and we want to fetch
info for every event type. Defining this at module
level makes it easier to mock.
| def always_want(msg_type: str) -> bool:
"""
This function is used as a helper in
fetch_initial_state_data, when the user passes
in None for event_types, and we want to fetch
info for every event type. Defining this at module
level makes it easier to mock.
"""
return True | [
"def",
"always_want",
"(",
"msg_type",
":",
"str",
")",
"->",
"bool",
":",
"return",
"True"
] | [
85,
0
] | [
93,
15
] | python | en | ['en', 'error', 'th'] | False |
fetch_initial_state_data | (
user_profile: Optional[UserProfile],
*,
realm: Optional[Realm] = None,
event_types: Optional[Iterable[str]] = None,
queue_id: Optional[str] = "",
client_gravatar: bool = False,
user_avatar_url_field_optional: bool = False,
slim_presence: bool = False,
include_subscribers: bool = Tr... | When `event_types` is None, fetches the core data powering the
web app's `page_params` and `/api/v1/register` (for mobile/terminal
apps). Can also fetch a subset as determined by `event_types`.
The user_profile=None code path is used for logged-out public
access to streams with is_web_public=True.
... | When `event_types` is None, fetches the core data powering the
web app's `page_params` and `/api/v1/register` (for mobile/terminal
apps). Can also fetch a subset as determined by `event_types`. | def fetch_initial_state_data(
user_profile: Optional[UserProfile],
*,
realm: Optional[Realm] = None,
event_types: Optional[Iterable[str]] = None,
queue_id: Optional[str] = "",
client_gravatar: bool = False,
user_avatar_url_field_optional: bool = False,
slim_presence: bool = False,
in... | [
"def",
"fetch_initial_state_data",
"(",
"user_profile",
":",
"Optional",
"[",
"UserProfile",
"]",
",",
"*",
",",
"realm",
":",
"Optional",
"[",
"Realm",
"]",
"=",
"None",
",",
"event_types",
":",
"Optional",
"[",
"Iterable",
"[",
"str",
"]",
"]",
"=",
"N... | [
96,
0
] | [
487,
16
] | python | en | ['en', 'en', 'en'] | True |
post_process_state | (
user_profile: Optional[UserProfile], ret: Dict[str, Any], notification_settings_null: bool
) |
NOTE:
Below is an example of post-processing initial state data AFTER we
apply events. For large payloads like `unread_msgs`, it's helpful
to have an intermediate data structure that is easy to manipulate
with O(1)-type operations as we apply events.
Then, only at the end, we put it in the f... |
NOTE: | def post_process_state(
user_profile: Optional[UserProfile], ret: Dict[str, Any], notification_settings_null: bool
) -> None:
"""
NOTE:
Below is an example of post-processing initial state data AFTER we
apply events. For large payloads like `unread_msgs`, it's helpful
to have an intermediate d... | [
"def",
"post_process_state",
"(",
"user_profile",
":",
"Optional",
"[",
"UserProfile",
"]",
",",
"ret",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"notification_settings_null",
":",
"bool",
")",
"->",
"None",
":",
"if",
"\"raw_unread_msgs\"",
"in",
"ret"... | [
1183,
0
] | [
1243,
13
] | python | en | ['en', 'error', 'th'] | False |
getmsg | (f, extra_ns=None, must_pass=False) | Rewrite the assertions in f, run it, and get the failure message. | Rewrite the assertions in f, run it, and get the failure message. | def getmsg(f, extra_ns=None, must_pass=False):
"""Rewrite the assertions in f, run it, and get the failure message."""
src = '\n'.join(_pytest._code.Code(f).source().lines)
mod = rewrite(src)
code = compile(mod, "<test>", "exec")
ns = {}
if extra_ns is not None:
ns.update(extra_ns)
p... | [
"def",
"getmsg",
"(",
"f",
",",
"extra_ns",
"=",
"None",
",",
"must_pass",
"=",
"False",
")",
":",
"src",
"=",
"'\\n'",
".",
"join",
"(",
"_pytest",
".",
"_code",
".",
"Code",
"(",
"f",
")",
".",
"source",
"(",
")",
".",
"lines",
")",
"mod",
"=... | [
39,
0
] | [
60,
55
] | python | en | ['en', 'en', 'en'] | True |
TestRewriteOnImport.test_remember_rewritten_modules | (self, pytestconfig, testdir, monkeypatch) |
AssertionRewriteHook should remember rewritten modules so it
doesn't give false positives (#2005).
|
AssertionRewriteHook should remember rewritten modules so it
doesn't give false positives (#2005).
| def test_remember_rewritten_modules(self, pytestconfig, testdir, monkeypatch):
"""
AssertionRewriteHook should remember rewritten modules so it
doesn't give false positives (#2005).
"""
monkeypatch.syspath_prepend(testdir.tmpdir)
testdir.makepyfile(test_remember_rewritten... | [
"def",
"test_remember_rewritten_modules",
"(",
"self",
",",
"pytestconfig",
",",
"testdir",
",",
"monkeypatch",
")",
":",
"monkeypatch",
".",
"syspath_prepend",
"(",
"testdir",
".",
"tmpdir",
")",
"testdir",
".",
"makepyfile",
"(",
"test_remember_rewritten_modules",
... | [
704,
4
] | [
718,
29
] | python | en | ['en', 'error', 'th'] | False |
TestRewriteOnImport.test_rewrite_future_imports | (self, testdir) | Test that rewritten modules don't inherit the __future__ flags
from the assertrewrite module.
assertion.rewrite imports __future__.division (and others), so
ensure rewritten modules don't inherit those flags.
The test below will fail if __future__.division is enabled
| Test that rewritten modules don't inherit the __future__ flags
from the assertrewrite module. | def test_rewrite_future_imports(self, testdir):
"""Test that rewritten modules don't inherit the __future__ flags
from the assertrewrite module.
assertion.rewrite imports __future__.division (and others), so
ensure rewritten modules don't inherit those flags.
The test below wil... | [
"def",
"test_rewrite_future_imports",
"(",
"self",
",",
"testdir",
")",
":",
"testdir",
".",
"makepyfile",
"(",
"'''\n def test():\n x = 1 / 2\n assert type(x) is int\n '''",
")",
"result",
"=",
"testdir",
".",
"runpytest",
"(",
... | [
750,
4
] | [
765,
30
] | python | en | ['en', 'en', 'en'] | True |
TestAssertionRewriteHookDetails.test_resources_provider_for_loader | (self, testdir) |
Attempts to load resources from a package should succeed normally,
even when the AssertionRewriteHook is used to load the modules.
See #366 for details.
|
Attempts to load resources from a package should succeed normally,
even when the AssertionRewriteHook is used to load the modules. | def test_resources_provider_for_loader(self, testdir):
"""
Attempts to load resources from a package should succeed normally,
even when the AssertionRewriteHook is used to load the modules.
See #366 for details.
"""
pytest.importorskip("pkg_resources")
testdir.m... | [
"def",
"test_resources_provider_for_loader",
"(",
"self",
",",
"testdir",
")",
":",
"pytest",
".",
"importorskip",
"(",
"\"pkg_resources\"",
")",
"testdir",
".",
"mkpydir",
"(",
"'testpkg'",
")",
"contents",
"=",
"{",
"'testpkg/test_pkg'",
":",
"\"\"\"\n ... | [
859,
4
] | [
887,
40
] | python | en | ['en', 'error', 'th'] | False |
TestAssertionRewriteHookDetails.test_read_pyc | (self, tmpdir) |
Ensure that the `_read_pyc` can properly deal with corrupted pyc files.
In those circumstances it should just give up instead of generating
an exception that is propagated to the caller.
|
Ensure that the `_read_pyc` can properly deal with corrupted pyc files.
In those circumstances it should just give up instead of generating
an exception that is propagated to the caller.
| def test_read_pyc(self, tmpdir):
"""
Ensure that the `_read_pyc` can properly deal with corrupted pyc files.
In those circumstances it should just give up instead of generating
an exception that is propagated to the caller.
"""
import py_compile
from _pytest.asser... | [
"def",
"test_read_pyc",
"(",
"self",
",",
"tmpdir",
")",
":",
"import",
"py_compile",
"from",
"_pytest",
".",
"assertion",
".",
"rewrite",
"import",
"_read_pyc",
"source",
"=",
"tmpdir",
".",
"join",
"(",
"'source.py'",
")",
"pyc",
"=",
"source",
"+",
"'c'... | [
889,
4
] | [
909,
50
] | python | en | ['en', 'error', 'th'] | False |
TestAssertionRewriteHookDetails.test_get_data_support | (self, testdir) | Implement optional PEP302 api (#808).
| Implement optional PEP302 api (#808).
| def test_get_data_support(self, testdir):
"""Implement optional PEP302 api (#808).
"""
path = testdir.mkpydir("foo")
path.join("test_foo.py").write(_pytest._code.Source("""
class Test(object):
def test_foo(self):
import pkgutil
... | [
"def",
"test_get_data_support",
"(",
"self",
",",
"testdir",
")",
":",
"path",
"=",
"testdir",
".",
"mkpydir",
"(",
"\"foo\"",
")",
"path",
".",
"join",
"(",
"\"test_foo.py\"",
")",
".",
"write",
"(",
"_pytest",
".",
"_code",
".",
"Source",
"(",
"\"\"\"\... | [
935,
4
] | [
948,
49
] | python | en | ['en', 'ceb', 'en'] | True |
ensure_no_empty_passwords | (apps: StateApps, schema_editor: DatabaseSchemaEditor) | With CVE-2019-18933, it was possible for certain users created
using social login (e.g. Google/GitHub auth) to have the empty
string as their password in the Zulip database, rather than
Django's "unusable password" (i.e. no password at all). This was a
serious security issue for organizations with both... | With CVE-2019-18933, it was possible for certain users created
using social login (e.g. Google/GitHub auth) to have the empty
string as their password in the Zulip database, rather than
Django's "unusable password" (i.e. no password at all). This was a
serious security issue for organizations with both... | def ensure_no_empty_passwords(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
"""With CVE-2019-18933, it was possible for certain users created
using social login (e.g. Google/GitHub auth) to have the empty
string as their password in the Zulip database, rather than
Django's "unusable pas... | [
"def",
"ensure_no_empty_passwords",
"(",
"apps",
":",
"StateApps",
",",
"schema_editor",
":",
"DatabaseSchemaEditor",
")",
"->",
"None",
":",
"UserProfile",
"=",
"apps",
".",
"get_model",
"(",
"\"zerver\"",
",",
"\"UserProfile\"",
")",
"RealmAuditLog",
"=",
"apps"... | [
17,
0
] | [
211,
13
] | python | en | ['en', 'en', 'en'] | True |
make_setuptools_shim_args | (
setup_py_path, # type: str
global_options=None, # type: Sequence[str]
no_user_config=False, # type: bool
unbuffered_output=False # type: bool
) |
Get setuptools command arguments with shim wrapped setup file invocation.
:param setup_py_path: The path to setup.py to be wrapped.
:param global_options: Additional global options.
:param no_user_config: If True, disables personal user configuration.
:param unbuffered_output: If True, adds the un... |
Get setuptools command arguments with shim wrapped setup file invocation. | def make_setuptools_shim_args(
setup_py_path, # type: str
global_options=None, # type: Sequence[str]
no_user_config=False, # type: bool
unbuffered_output=False # type: bool
):
# type: (...) -> List[str]
"""
Get setuptools command arguments with shim wrapped setup file invocation.
:p... | [
"def",
"make_setuptools_shim_args",
"(",
"setup_py_path",
",",
"# type: str",
"global_options",
"=",
"None",
",",
"# type: Sequence[str]",
"no_user_config",
"=",
"False",
",",
"# type: bool",
"unbuffered_output",
"=",
"False",
"# type: bool",
")",
":",
"# type: (...) -> L... | [
22,
0
] | [
46,
15
] | python | en | ['en', 'error', 'th'] | False |
Security.xml | (self) |
Get xml representation of the object.
@return: The root node.
@rtype: L{Element}
|
Get xml representation of the object.
| def xml(self):
"""
Get xml representation of the object.
@return: The root node.
@rtype: L{Element}
"""
root = Element('Security', ns=wssens)
root.set('mustUnderstand', str(self.mustUnderstand).lower())
for t in self.tokens:
root.append(t.xml()... | [
"def",
"xml",
"(",
"self",
")",
":",
"root",
"=",
"Element",
"(",
"'Security'",
",",
"ns",
"=",
"wssens",
")",
"root",
".",
"set",
"(",
"'mustUnderstand'",
",",
"str",
"(",
"self",
".",
"mustUnderstand",
")",
".",
"lower",
"(",
")",
")",
"for",
"t"... | [
70,
4
] | [
80,
19
] | python | en | ['en', 'error', 'th'] | False |
UsernameToken.__init__ | (self, username=None, password=None) |
@param username: A username.
@type username: str
@param password: A password.
@type password: str
| def __init__(self, username=None, password=None):
"""
@param username: A username.
@type username: str
@param password: A password.
@type password: str
"""
Token.__init__(self)
self.username = username
self.password = password
self.nonce = ... | [
"def",
"__init__",
"(",
"self",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"Token",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"username",
"=",
"username",
"self",
".",
"password",
"=",
"password",
"self",
".",
"nonce",
... | [
116,
4
] | [
127,
27
] | python | en | ['en', 'error', 'th'] | False | |
UsernameToken.setnonce | (self, text=None) |
Set I{nonce} which is arbitraty set of bytes to prevent
reply attacks.
@param text: The nonce text value.
Generated when I{None}.
@type text: str
|
Set I{nonce} which is arbitraty set of bytes to prevent
reply attacks.
| def setnonce(self, text=None):
"""
Set I{nonce} which is arbitraty set of bytes to prevent
reply attacks.
@param text: The nonce text value.
Generated when I{None}.
@type text: str
"""
if text is None:
s = []
s.append(self.usern... | [
"def",
"setnonce",
"(",
"self",
",",
"text",
"=",
"None",
")",
":",
"if",
"text",
"is",
"None",
":",
"s",
"=",
"[",
"]",
"s",
".",
"append",
"(",
"self",
".",
"username",
")",
"s",
".",
"append",
"(",
"self",
".",
"password",
")",
"s",
".",
"... | [
129,
4
] | [
146,
29
] | python | en | ['en', 'error', 'th'] | False |
UsernameToken.setcreated | (self, dt=None) |
Set I{created}.
@param dt: The created date & time.
Set as datetime.utc() when I{None}.
@type dt: L{datetime}
|
Set I{created}.
| def setcreated(self, dt=None):
"""
Set I{created}.
@param dt: The created date & time.
Set as datetime.utc() when I{None}.
@type dt: L{datetime}
"""
if dt is None:
self.created = Token.utc()
else:
self.created = dt | [
"def",
"setcreated",
"(",
"self",
",",
"dt",
"=",
"None",
")",
":",
"if",
"dt",
"is",
"None",
":",
"self",
".",
"created",
"=",
"Token",
".",
"utc",
"(",
")",
"else",
":",
"self",
".",
"created",
"=",
"dt"
] | [
148,
4
] | [
158,
29
] | python | en | ['en', 'error', 'th'] | False |
UsernameToken.xml | (self) |
Get xml representation of the object.
@return: The root node.
@rtype: L{Element}
|
Get xml representation of the object.
| def xml(self):
"""
Get xml representation of the object.
@return: The root node.
@rtype: L{Element}
"""
root = Element('UsernameToken', ns=wssens)
u = Element('Username', ns=wssens)
u.setText(self.username)
root.append(u)
p = Element('Passw... | [
"def",
"xml",
"(",
"self",
")",
":",
"root",
"=",
"Element",
"(",
"'UsernameToken'",
",",
"ns",
"=",
"wssens",
")",
"u",
"=",
"Element",
"(",
"'Username'",
",",
"ns",
"=",
"wssens",
")",
"u",
".",
"setText",
"(",
"self",
".",
"username",
")",
"root... | [
161,
4
] | [
182,
19
] | python | en | ['en', 'error', 'th'] | False |
Timestamp.__init__ | (self, validity=90) |
@param validity: The time in seconds.
@type validity: int
| def __init__(self, validity=90):
"""
@param validity: The time in seconds.
@type validity: int
"""
Token.__init__(self)
self.created = Token.utc()
self.expires = self.created + timedelta(seconds=validity) | [
"def",
"__init__",
"(",
"self",
",",
"validity",
"=",
"90",
")",
":",
"Token",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"created",
"=",
"Token",
".",
"utc",
"(",
")",
"self",
".",
"expires",
"=",
"self",
".",
"created",
"+",
"timedelta",
"("... | [
194,
4
] | [
201,
65
] | python | en | ['en', 'error', 'th'] | False | |
Literal.validate | (self, result, spec) | Validate that the result has the correct structure. | Validate that the result has the correct structure. | def validate(self, result, spec): # noqa Yes, it's too complex.
"""Validate that the result has the correct structure."""
if spec is None:
# None matches anything.
return
if isinstance(spec, dict):
if not isinstance(result, dict):
raise ValueE... | [
"def",
"validate",
"(",
"self",
",",
"result",
",",
"spec",
")",
":",
"# noqa Yes, it's too complex.",
"if",
"spec",
"is",
"None",
":",
"# None matches anything.",
"return",
"if",
"isinstance",
"(",
"spec",
",",
"dict",
")",
":",
"if",
"not",
"isinstance",
"... | [
116,
4
] | [
153,
76
] | python | en | ['en', 'en', 'en'] | True |
Literal.update | (self, result, spec) | Replace elements with results of calling callables. | Replace elements with results of calling callables. | def update(self, result, spec):
"""Replace elements with results of calling callables."""
if isinstance(spec, dict):
if spec:
spec_value = next(iter(spec.values()))
for key, value in result.items():
result[key] = self.update(value, spec_val... | [
"def",
"update",
"(",
"self",
",",
"result",
",",
"spec",
")",
":",
"if",
"isinstance",
"(",
"spec",
",",
"dict",
")",
":",
"if",
"spec",
":",
"spec_value",
"=",
"next",
"(",
"iter",
"(",
"spec",
".",
"values",
"(",
")",
")",
")",
"for",
"key",
... | [
155,
4
] | [
171,
21
] | python | en | ['en', 'en', 'en'] | True |
create_question | (question_text, days) |
Create a question with the given `question_text` and published the
given number of `days` offset to now (negative for questions published
in the past, positive for questions that have yet to be published).
|
Create a question with the given `question_text` and published the
given number of `days` offset to now (negative for questions published
in the past, positive for questions that have yet to be published).
| def create_question(question_text, days):
"""
Create a question with the given `question_text` and published the
given number of `days` offset to now (negative for questions published
in the past, positive for questions that have yet to be published).
"""
time = timezone.now() + datetime.timedel... | [
"def",
"create_question",
"(",
"question_text",
",",
"days",
")",
":",
"time",
"=",
"timezone",
".",
"now",
"(",
")",
"+",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"days",
")",
"return",
"Question",
".",
"objects",
".",
"create",
"(",
"question_te... | [
38,
0
] | [
45,
78
] | python | en | ['en', 'error', 'th'] | False |
QuestionModelTests.test_was_published_recently_with_future_question | (self) |
was_published_recently() returns False for questions whose pub_date
is in the future.
|
was_published_recently() returns False for questions whose pub_date
is in the future.
| def test_was_published_recently_with_future_question(self):
"""
was_published_recently() returns False for questions whose pub_date
is in the future.
"""
time = timezone.now() + datetime.timedelta(days=30)
future_question = Question(pub_date=time)
self.assertIs(fu... | [
"def",
"test_was_published_recently_with_future_question",
"(",
"self",
")",
":",
"time",
"=",
"timezone",
".",
"now",
"(",
")",
"+",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"30",
")",
"future_question",
"=",
"Question",
"(",
"pub_date",
"=",
"time",
... | [
11,
4
] | [
18,
70
] | python | en | ['en', 'error', 'th'] | False |
QuestionModelTests.test_was_published_recently_with_old_question | (self) |
was_published_recently() returns False for questions whose pub_date
is older than 1 day.
|
was_published_recently() returns False for questions whose pub_date
is older than 1 day.
| def test_was_published_recently_with_old_question(self):
"""
was_published_recently() returns False for questions whose pub_date
is older than 1 day.
"""
time = timezone.now() - datetime.timedelta(days=1, seconds=1)
old_question = Question(pub_date=time)
self.asse... | [
"def",
"test_was_published_recently_with_old_question",
"(",
"self",
")",
":",
"time",
"=",
"timezone",
".",
"now",
"(",
")",
"-",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"1",
",",
"seconds",
"=",
"1",
")",
"old_question",
"=",
"Question",
"(",
"pu... | [
20,
4
] | [
27,
67
] | python | en | ['en', 'error', 'th'] | False |
QuestionModelTests.test_was_published_recently_with_recent_question | (self) |
was_published_recently() returns True for questions whose pub_date
is within the last day.
|
was_published_recently() returns True for questions whose pub_date
is within the last day.
| def test_was_published_recently_with_recent_question(self):
"""
was_published_recently() returns True for questions whose pub_date
is within the last day.
"""
time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59)
recent_question = Question(pub_date=... | [
"def",
"test_was_published_recently_with_recent_question",
"(",
"self",
")",
":",
"time",
"=",
"timezone",
".",
"now",
"(",
")",
"-",
"datetime",
".",
"timedelta",
"(",
"hours",
"=",
"23",
",",
"minutes",
"=",
"59",
",",
"seconds",
"=",
"59",
")",
"recent_... | [
29,
4
] | [
36,
69
] | python | en | ['en', 'error', 'th'] | False |
QuestionIndexViewTests.test_no_questions | (self) |
If no questions exist, an appropriate message is displayed.
|
If no questions exist, an appropriate message is displayed.
| def test_no_questions(self):
"""
If no questions exist, an appropriate message is displayed.
"""
response = self.client.get(reverse('polls:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "No polls are available.")
self.assertQuer... | [
"def",
"test_no_questions",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"get",
"(",
"reverse",
"(",
"'polls:index'",
")",
")",
"self",
".",
"assertEqual",
"(",
"response",
".",
"status_code",
",",
"200",
")",
"self",
".",
"assertC... | [
48,
4
] | [
55,
78
] | python | en | ['en', 'error', 'th'] | False |
QuestionIndexViewTests.test_past_question | (self) |
Questions with a pub_date in the past are displayed on the
index page.
|
Questions with a pub_date in the past are displayed on the
index page.
| def test_past_question(self):
"""
Questions with a pub_date in the past are displayed on the
index page.
"""
create_question(question_text="Past question.", days=-30)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response... | [
"def",
"test_past_question",
"(",
"self",
")",
":",
"create_question",
"(",
"question_text",
"=",
"\"Past question.\"",
",",
"days",
"=",
"-",
"30",
")",
"response",
"=",
"self",
".",
"client",
".",
"get",
"(",
"reverse",
"(",
"'polls:index'",
")",
")",
"s... | [
57,
4
] | [
67,
9
] | python | en | ['en', 'error', 'th'] | False |
QuestionIndexViewTests.test_future_question | (self) |
Questions with a pub_date in the future aren't displayed on
the index page.
|
Questions with a pub_date in the future aren't displayed on
the index page.
| def test_future_question(self):
"""
Questions with a pub_date in the future aren't displayed on
the index page.
"""
create_question(question_text="Future question.", days=30)
response = self.client.get(reverse('polls:index'))
self.assertContains(response, "No poll... | [
"def",
"test_future_question",
"(",
"self",
")",
":",
"create_question",
"(",
"question_text",
"=",
"\"Future question.\"",
",",
"days",
"=",
"30",
")",
"response",
"=",
"self",
".",
"client",
".",
"get",
"(",
"reverse",
"(",
"'polls:index'",
")",
")",
"self... | [
69,
4
] | [
77,
78
] | python | en | ['en', 'error', 'th'] | False |
QuestionIndexViewTests.test_future_question_and_past_question | (self) |
Even if both past and future questions exist, only past questions
are displayed.
|
Even if both past and future questions exist, only past questions
are displayed.
| def test_future_question_and_past_question(self):
"""
Even if both past and future questions exist, only past questions
are displayed.
"""
create_question(question_text="Past question.", days=-30)
create_question(question_text="Future question.", days=30)
response... | [
"def",
"test_future_question_and_past_question",
"(",
"self",
")",
":",
"create_question",
"(",
"question_text",
"=",
"\"Past question.\"",
",",
"days",
"=",
"-",
"30",
")",
"create_question",
"(",
"question_text",
"=",
"\"Future question.\"",
",",
"days",
"=",
"30"... | [
79,
4
] | [
90,
9
] | python | en | ['en', 'error', 'th'] | False |
QuestionIndexViewTests.test_two_past_questions | (self) |
The questions index page may display multiple questions.
|
The questions index page may display multiple questions.
| def test_two_past_questions(self):
"""
The questions index page may display multiple questions.
"""
create_question(question_text="Past question 1.", days=-30)
create_question(question_text="Past question 2.", days=-5)
response = self.client.get(reverse('polls:index'))
... | [
"def",
"test_two_past_questions",
"(",
"self",
")",
":",
"create_question",
"(",
"question_text",
"=",
"\"Past question 1.\"",
",",
"days",
"=",
"-",
"30",
")",
"create_question",
"(",
"question_text",
"=",
"\"Past question 2.\"",
",",
"days",
"=",
"-",
"5",
")"... | [
92,
4
] | [
102,
9
] | python | en | ['en', 'error', 'th'] | False |
QuestionDetailViewTests.test_future_question | (self) |
The detail view of a question with a pub_date in the future
returns a 404 not found.
|
The detail view of a question with a pub_date in the future
returns a 404 not found.
| def test_future_question(self):
"""
The detail view of a question with a pub_date in the future
returns a 404 not found.
"""
future_question = create_question(question_text='Future question.', days=5)
url = reverse('polls:detail', args=(future_question.id,))
respo... | [
"def",
"test_future_question",
"(",
"self",
")",
":",
"future_question",
"=",
"create_question",
"(",
"question_text",
"=",
"'Future question.'",
",",
"days",
"=",
"5",
")",
"url",
"=",
"reverse",
"(",
"'polls:detail'",
",",
"args",
"=",
"(",
"future_question",
... | [
105,
4
] | [
113,
51
] | python | en | ['en', 'error', 'th'] | False |
QuestionDetailViewTests.test_past_question | (self) |
The detail view of a question with a pub_date in the past
displays the question's text.
|
The detail view of a question with a pub_date in the past
displays the question's text.
| def test_past_question(self):
"""
The detail view of a question with a pub_date in the past
displays the question's text.
"""
past_question = create_question(question_text='Past Question.', days=-5)
url = reverse('polls:detail', args=(past_question.id,))
response ... | [
"def",
"test_past_question",
"(",
"self",
")",
":",
"past_question",
"=",
"create_question",
"(",
"question_text",
"=",
"'Past Question.'",
",",
"days",
"=",
"-",
"5",
")",
"url",
"=",
"reverse",
"(",
"'polls:detail'",
",",
"args",
"=",
"(",
"past_question",
... | [
115,
4
] | [
123,
66
] | python | en | ['en', 'error', 'th'] | False |
sanitize_input | (input_str_list) | r"""Replace all instances of 'weird' characters and spaces in string elements of a input_str_list sequence with '_'.
Examples:
[a/?, b\\t, c] --> [a__, b_, c]
Args:
input_str_list (list/iterable): list of strings
Returns:
list: list of newly created strings
| r"""Replace all instances of 'weird' characters and spaces in string elements of a input_str_list sequence with '_'. | def sanitize_input(input_str_list):
r"""Replace all instances of 'weird' characters and spaces in string elements of a input_str_list sequence with '_'.
Examples:
[a/?, b\\t, c] --> [a__, b_, c]
Args:
input_str_list (list/iterable): list of strings
Returns:
list: list of newly... | [
"def",
"sanitize_input",
"(",
"input_str_list",
")",
":",
"p",
"=",
"r'[\"/\\\\.,?!:;\\n\\t\\r\\a\\f\\v\\b \\{\\}\\[\\]\\(\\)]'",
"new_input",
"=",
"[",
"re",
".",
"sub",
"(",
"p",
",",
"\"_\"",
",",
"x",
")",
"for",
"x",
"in",
"input_str_list",
"]",
"return",
... | [
7,
0
] | [
21,
20
] | python | en | ['en', 'en', 'en'] | True |
sanitize_keys_in_dict | (dictionary) | Sanitize keys in a dictionary so they are JS friendly.
All keys in a dictionary are converted to strings and they are sanitized from any 'weird' characters present.
Args:
dictionary (dict): dictionary
Returns:
dict: new dict with sanitized keys
| Sanitize keys in a dictionary so they are JS friendly. | def sanitize_keys_in_dict(dictionary):
"""Sanitize keys in a dictionary so they are JS friendly.
All keys in a dictionary are converted to strings and they are sanitized from any 'weird' characters present.
Args:
dictionary (dict): dictionary
Returns:
dict: new dict with sanitized key... | [
"def",
"sanitize_keys_in_dict",
"(",
"dictionary",
")",
":",
"old_keys",
"=",
"list",
"(",
"dictionary",
".",
"keys",
"(",
")",
")",
"new_keys",
"=",
"sanitize_input",
"(",
"[",
"str",
"(",
"key",
")",
"for",
"key",
"in",
"old_keys",
"]",
")",
"new_dict"... | [
24,
0
] | [
41,
19
] | python | en | ['en', 'en', 'en'] | True |
calculate_numerical_bins | (series) | Calculate how many bins in a histogram should there be for a provided numerical series.
Method used to calculate it is 'Freedman-Diaconis rule' -
https://en.wikipedia.org/wiki/Freedman%E2%80%93Diaconis_rule . If the calculated result doesn't make sense (e.g. is
higher than the number of rows or is 0 or low... | Calculate how many bins in a histogram should there be for a provided numerical series. | def calculate_numerical_bins(series):
"""Calculate how many bins in a histogram should there be for a provided numerical series.
Method used to calculate it is 'Freedman-Diaconis rule' -
https://en.wikipedia.org/wiki/Freedman%E2%80%93Diaconis_rule . If the calculated result doesn't make sense (e.g. is
... | [
"def",
"calculate_numerical_bins",
"(",
"series",
")",
":",
"n",
"=",
"series",
".",
"size",
"iqr",
"=",
"series",
".",
"quantile",
"(",
"0.75",
")",
"-",
"series",
".",
"quantile",
"(",
"0.25",
")",
"bins",
"=",
"(",
"series",
".",
"max",
"(",
")",
... | [
44,
0
] | [
71,
15
] | python | en | ['en', 'en', 'en'] | True |
modify_histogram_edges | (edges, interval_percentage=0.005) | Modify edges calculated by np.histogram by adding little space between them.
numpy.histogram method computes bin_edges of a histogram and a default way to use them is to define
left_edges = edges[:-1]; right_edges = edges[1:] and provide that to BarPlot Visualization. However, that method
does not provide ... | Modify edges calculated by np.histogram by adding little space between them. | def modify_histogram_edges(edges, interval_percentage=0.005):
"""Modify edges calculated by np.histogram by adding little space between them.
numpy.histogram method computes bin_edges of a histogram and a default way to use them is to define
left_edges = edges[:-1]; right_edges = edges[1:] and provide that... | [
"def",
"modify_histogram_edges",
"(",
"edges",
",",
"interval_percentage",
"=",
"0.005",
")",
":",
"# Adding space between the edges to visualize the data properly",
"interval",
"=",
"(",
"max",
"(",
"edges",
")",
"-",
"min",
"(",
"edges",
")",
")",
"*",
"interval_p... | [
74,
0
] | [
95,
34
] | python | en | ['en', 'en', 'en'] | True |
sort_strings | (list_of_strings) | Return sorted list of strings in an ascending order by treating every string as if it would start with an
uppercase letter.
Examples:
[toast2, Test3, Toast, test33] --> [Test3, test33, Toast, toast2]
Args:
list_of_strings (list): list of string elements
Returns:
list: sorted l... | Return sorted list of strings in an ascending order by treating every string as if it would start with an
uppercase letter. | def sort_strings(list_of_strings):
"""Return sorted list of strings in an ascending order by treating every string as if it would start with an
uppercase letter.
Examples:
[toast2, Test3, Toast, test33] --> [Test3, test33, Toast, toast2]
Args:
list_of_strings (list): list of string ele... | [
"def",
"sort_strings",
"(",
"list_of_strings",
")",
":",
"return",
"sorted",
"(",
"list_of_strings",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"upper",
"(",
")",
")"
] | [
98,
0
] | [
111,
59
] | python | en | ['en', 'en', 'en'] | True |
reverse_sorting_order | (str_name) | Return False if str_name ends with one of the err_strings suffixes. Otherwise, return True.
Negation was introduced as the function is used to determine the order of the sorting depending on scoring
function name: if scoring ends with "_error" or "_loss", it means that lower score is better. If it doesn't,
... | Return False if str_name ends with one of the err_strings suffixes. Otherwise, return True. | def reverse_sorting_order(str_name):
"""Return False if str_name ends with one of the err_strings suffixes. Otherwise, return True.
Negation was introduced as the function is used to determine the order of the sorting depending on scoring
function name: if scoring ends with "_error" or "_loss", it means th... | [
"def",
"reverse_sorting_order",
"(",
"str_name",
")",
":",
"err_strings",
"=",
"(",
"\"_error\"",
",",
"\"_loss\"",
")",
"return",
"not",
"str_name",
".",
"endswith",
"(",
"err_strings",
")"
] | [
114,
0
] | [
129,
45
] | python | en | ['en', 'en', 'en'] | True |
obj_name | (obj) | Return __name__ property of obj and if it's not defined, return it from obj's Parent Class.
Args:
obj (object): object
Returns:
str: __name__ of the object or it's Class
| Return __name__ property of obj and if it's not defined, return it from obj's Parent Class. | def obj_name(obj):
"""Return __name__ property of obj and if it's not defined, return it from obj's Parent Class.
Args:
obj (object): object
Returns:
str: __name__ of the object or it's Class
"""
try:
obj_str = obj.__name__
except AttributeError:
obj_str = type(... | [
"def",
"obj_name",
"(",
"obj",
")",
":",
"try",
":",
"obj_str",
"=",
"obj",
".",
"__name__",
"except",
"AttributeError",
":",
"obj_str",
"=",
"type",
"(",
"obj",
")",
".",
"__name__",
"return",
"obj_str"
] | [
132,
0
] | [
145,
18
] | python | en | ['en', 'en', 'en'] | True |
append_description | (text, parsed_html) | r"""Encompass in <span> HTML tag and append provided text to the end of provided parsed_html and return the
created tag.
Additionally, every \\n in text is replaced with <br> HTML tag.
Args:
text (str): text string
parsed_html (bs4.BeautifulSoup): HTML text parsed with BeautifulSoup4
... | r"""Encompass in <span> HTML tag and append provided text to the end of provided parsed_html and return the
created tag. | def append_description(text, parsed_html):
r"""Encompass in <span> HTML tag and append provided text to the end of provided parsed_html and return the
created tag.
Additionally, every \\n in text is replaced with <br> HTML tag.
Args:
text (str): text string
parsed_html (bs4.BeautifulSo... | [
"def",
"append_description",
"(",
"text",
",",
"parsed_html",
")",
":",
"new_tag",
"=",
"parsed_html",
".",
"new_tag",
"(",
"\"span\"",
")",
"lines",
"=",
"text",
".",
"split",
"(",
"\"\\n\"",
")",
"new_tag",
".",
"string",
"=",
"lines",
"[",
"0",
"]",
... | [
148,
0
] | [
169,
18
] | python | en | ['en', 'en', 'en'] | True |
series_to_dict | (series) | r"""Return dictionary constructed from pandas.Series where keys are indexes of Series and values are respective
string values from the array, but every instance of ', ' string is replaced with \\n.
Args:
series (pandas.Series): Series
Returns:
dict: dictionary with changed strings in value... | r"""Return dictionary constructed from pandas.Series where keys are indexes of Series and values are respective
string values from the array, but every instance of ', ' string is replaced with \\n. | def series_to_dict(series):
r"""Return dictionary constructed from pandas.Series where keys are indexes of Series and values are respective
string values from the array, but every instance of ', ' string is replaced with \\n.
Args:
series (pandas.Series): Series
Returns:
dict: dictiona... | [
"def",
"series_to_dict",
"(",
"series",
")",
":",
"dictionary",
"=",
"series",
".",
"to_dict",
"(",
")",
"dict_str",
"=",
"{",
"key",
":",
"str",
"(",
"item_str",
")",
"[",
"1",
":",
"-",
"1",
"]",
".",
"replace",
"(",
"\", \"",
",",
"\"\\n\"",
")"... | [
172,
0
] | [
184,
19
] | python | en | ['en', 'en', 'en'] | True |
replace_duplicate_str | (duplicate_list_of_str) | Replace every duplicate instance of string element in duplicate_list_of_str with new string indicating which
duplicate element it is. Return unchanged duplicate_list_of_str if there are no duplicates.
Examples:
[a, b, a, b, c, a] --> [a #1, b #1, a #2, b #2, c, a #3] \n
[a, b] --> [a, b]
A... | Replace every duplicate instance of string element in duplicate_list_of_str with new string indicating which
duplicate element it is. Return unchanged duplicate_list_of_str if there are no duplicates. | def replace_duplicate_str(duplicate_list_of_str):
"""Replace every duplicate instance of string element in duplicate_list_of_str with new string indicating which
duplicate element it is. Return unchanged duplicate_list_of_str if there are no duplicates.
Examples:
[a, b, a, b, c, a] --> [a #1, b #1,... | [
"def",
"replace_duplicate_str",
"(",
"duplicate_list_of_str",
")",
":",
"if",
"len",
"(",
"set",
"(",
"duplicate_list_of_str",
")",
")",
"!=",
"len",
"(",
"duplicate_list_of_str",
")",
":",
"base_cnt",
"=",
"Counter",
"(",
"duplicate_list_of_str",
")",
"item_cnt",... | [
187,
0
] | [
216,
36
] | python | en | ['en', 'en', 'en'] | True |
assess_models_names | (model_tuples) | Replace first element of a tuple in a sequence of tuples with its appropriate obj_name and additionally check
if the name is duplicated across other first elements of tuples and replace if it's the case.
Args:
model_tuples ({list, sequence}): sequence of 2-item tuples (object, value)
Returns:
... | Replace first element of a tuple in a sequence of tuples with its appropriate obj_name and additionally check
if the name is duplicated across other first elements of tuples and replace if it's the case. | def assess_models_names(model_tuples):
"""Replace first element of a tuple in a sequence of tuples with its appropriate obj_name and additionally check
if the name is duplicated across other first elements of tuples and replace if it's the case.
Args:
model_tuples ({list, sequence}): sequence of 2-... | [
"def",
"assess_models_names",
"(",
"model_tuples",
")",
":",
"models",
"=",
"[",
"obj_name",
"(",
"tp",
"[",
"0",
"]",
")",
"for",
"tp",
"in",
"model_tuples",
"]",
"new_names",
"=",
"replace_duplicate_str",
"(",
"models",
")",
"new_tuple",
"=",
"[",
"(",
... | [
219,
0
] | [
232,
20
] | python | en | ['en', 'en', 'en'] | True |
make_pandas_data | (data, desired_pandas_class) | Transform provided data object into a desired pandas class instance.
data can be provided as either scipy.csr_matrix, numpy.ndarray, instance of desired_pandas_class or any other object
that can be fed directly into a construction call of desired_pandas_class
(e.g. dict in pd.DataFrame(data=your_dict)).
... | Transform provided data object into a desired pandas class instance. | def make_pandas_data(data, desired_pandas_class):
"""Transform provided data object into a desired pandas class instance.
data can be provided as either scipy.csr_matrix, numpy.ndarray, instance of desired_pandas_class or any other object
that can be fed directly into a construction call of desired_pandas_... | [
"def",
"make_pandas_data",
"(",
"data",
",",
"desired_pandas_class",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"csr_matrix",
")",
":",
"X_arr",
"=",
"data",
".",
"toarray",
"(",
")",
"if",
"desired_pandas_class",
"==",
"pd",
".",
"Series",
":",
"# sp... | [
235,
0
] | [
281,
19
] | python | en | ['es', 'en', 'en'] | True |
read_pkg_file | (self, file) | Reads the metadata values from a file object. | Reads the metadata values from a file object. | def read_pkg_file(self, file):
"""Reads the metadata values from a file object."""
msg = message_from_file(file)
def _read_field(name):
value = msg[name]
if value == 'UNKNOWN':
return None
return value
def _read_list(name):
values = msg.get_all(name, None)
... | [
"def",
"read_pkg_file",
"(",
"self",
",",
"file",
")",
":",
"msg",
"=",
"message_from_file",
"(",
"file",
")",
"def",
"_read_field",
"(",
"name",
")",
":",
"value",
"=",
"msg",
"[",
"name",
"]",
"if",
"value",
"==",
"'UNKNOWN'",
":",
"return",
"None",
... | [
67,
0
] | [
117,
29
] | python | en | ['en', 'en', 'en'] | True |
write_pkg_file | (self, file) | Write the PKG-INFO format data to a file object.
| Write the PKG-INFO format data to a file object.
| def write_pkg_file(self, file):
"""Write the PKG-INFO format data to a file object.
"""
version = self.get_metadata_version()
def write_field(key, value):
file.write("%s: %s\n" % (key, value))
write_field('Metadata-Version', str(version))
write_field('Name', self.get_name())
write_... | [
"def",
"write_pkg_file",
"(",
"self",
",",
"file",
")",
":",
"version",
"=",
"self",
".",
"get_metadata_version",
"(",
")",
"def",
"write_field",
"(",
"key",
",",
"value",
")",
":",
"file",
".",
"write",
"(",
"\"%s: %s\\n\"",
"%",
"(",
"key",
",",
"val... | [
121,
0
] | [
190,
48
] | python | en | ['en', 'en', 'en'] | True |
assert_string_list | (dist, attr, value) | Verify that value is a string list | Verify that value is a string list | def assert_string_list(dist, attr, value):
"""Verify that value is a string list"""
try:
# verify that value is a list or tuple to exclude unordered
# or single-use iterables
assert isinstance(value, (list, tuple))
# verify that elements of value are strings
assert ''.joi... | [
"def",
"assert_string_list",
"(",
"dist",
",",
"attr",
",",
"value",
")",
":",
"try",
":",
"# verify that value is a list or tuple to exclude unordered",
"# or single-use iterables",
"assert",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
"# ... | [
207,
0
] | [
218,
16
] | python | en | ['en', 'en', 'en'] | True |
check_nsp | (dist, attr, value) | Verify that namespace packages are valid | Verify that namespace packages are valid | def check_nsp(dist, attr, value):
"""Verify that namespace packages are valid"""
ns_packages = value
assert_string_list(dist, attr, ns_packages)
for nsp in ns_packages:
if not dist.has_contents_for(nsp):
raise DistutilsSetupError(
"Distribution contains no modules or ... | [
"def",
"check_nsp",
"(",
"dist",
",",
"attr",
",",
"value",
")",
":",
"ns_packages",
"=",
"value",
"assert_string_list",
"(",
"dist",
",",
"attr",
",",
"ns_packages",
")",
"for",
"nsp",
"in",
"ns_packages",
":",
"if",
"not",
"dist",
".",
"has_contents_for"... | [
221,
0
] | [
236,
13
] | python | en | ['en', 'en', 'en'] | True |
check_extras | (dist, attr, value) | Verify that extras_require mapping is valid | Verify that extras_require mapping is valid | def check_extras(dist, attr, value):
"""Verify that extras_require mapping is valid"""
try:
list(itertools.starmap(_check_extra, value.items()))
except (TypeError, ValueError, AttributeError) as e:
raise DistutilsSetupError(
"'extras_require' must be a dictionary whose values are... | [
"def",
"check_extras",
"(",
"dist",
",",
"attr",
",",
"value",
")",
":",
"try",
":",
"list",
"(",
"itertools",
".",
"starmap",
"(",
"_check_extra",
",",
"value",
".",
"items",
"(",
")",
")",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
",",
"A... | [
239,
0
] | [
248,
16
] | python | en | ['en', 'en', 'en'] | True |
assert_bool | (dist, attr, value) | Verify that value is True, False, 0, or 1 | Verify that value is True, False, 0, or 1 | def assert_bool(dist, attr, value):
"""Verify that value is True, False, 0, or 1"""
if bool(value) != value:
tmpl = "{attr!r} must be a boolean value (got {value!r})"
raise DistutilsSetupError(tmpl.format(attr=attr, value=value)) | [
"def",
"assert_bool",
"(",
"dist",
",",
"attr",
",",
"value",
")",
":",
"if",
"bool",
"(",
"value",
")",
"!=",
"value",
":",
"tmpl",
"=",
"\"{attr!r} must be a boolean value (got {value!r})\"",
"raise",
"DistutilsSetupError",
"(",
"tmpl",
".",
"format",
"(",
"... | [
258,
0
] | [
262,
70
] | python | en | ['en', 'en', 'en'] | True |
check_requirements | (dist, attr, value) | Verify that install_requires is a valid requirements list | Verify that install_requires is a valid requirements list | def check_requirements(dist, attr, value):
"""Verify that install_requires is a valid requirements list"""
try:
list(pkg_resources.parse_requirements(value))
if isinstance(value, (dict, set)):
raise TypeError("Unordered types are not allowed")
except (TypeError, ValueError) as er... | [
"def",
"check_requirements",
"(",
"dist",
",",
"attr",
",",
"value",
")",
":",
"try",
":",
"list",
"(",
"pkg_resources",
".",
"parse_requirements",
"(",
"value",
")",
")",
"if",
"isinstance",
"(",
"value",
",",
"(",
"dict",
",",
"set",
")",
")",
":",
... | [
265,
0
] | [
278,
20
] | python | en | ['en', 'en', 'en'] | True |
check_specifier | (dist, attr, value) | Verify that value is a valid version specifier | Verify that value is a valid version specifier | def check_specifier(dist, attr, value):
"""Verify that value is a valid version specifier"""
try:
packaging.specifiers.SpecifierSet(value)
except packaging.specifiers.InvalidSpecifier as error:
tmpl = (
"{attr!r} must be a string "
"containing valid version specifiers... | [
"def",
"check_specifier",
"(",
"dist",
",",
"attr",
",",
"value",
")",
":",
"try",
":",
"packaging",
".",
"specifiers",
".",
"SpecifierSet",
"(",
"value",
")",
"except",
"packaging",
".",
"specifiers",
".",
"InvalidSpecifier",
"as",
"error",
":",
"tmpl",
"... | [
281,
0
] | [
292,
20
] | python | en | ['en', 'en', 'en'] | True |
check_entry_points | (dist, attr, value) | Verify that entry_points map is parseable | Verify that entry_points map is parseable | def check_entry_points(dist, attr, value):
"""Verify that entry_points map is parseable"""
try:
pkg_resources.EntryPoint.parse_map(value)
except ValueError as e:
raise DistutilsSetupError(e) from e | [
"def",
"check_entry_points",
"(",
"dist",
",",
"attr",
",",
"value",
")",
":",
"try",
":",
"pkg_resources",
".",
"EntryPoint",
".",
"parse_map",
"(",
"value",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",
"DistutilsSetupError",
"(",
"e",
")",
"from... | [
295,
0
] | [
300,
43
] | python | en | ['en', 'en', 'en'] | True |
check_package_data | (dist, attr, value) | Verify that value is a dictionary of package names to glob lists | Verify that value is a dictionary of package names to glob lists | def check_package_data(dist, attr, value):
"""Verify that value is a dictionary of package names to glob lists"""
if not isinstance(value, dict):
raise DistutilsSetupError(
"{!r} must be a dictionary mapping package names to lists of "
"string wildcard patterns".format(attr))
... | [
"def",
"check_package_data",
"(",
"dist",
",",
"attr",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"raise",
"DistutilsSetupError",
"(",
"\"{!r} must be a dictionary mapping package names to lists of \"",
"\"string wildcard pat... | [
308,
0
] | [
320,
71
] | python | en | ['en', 'en', 'en'] | True |
Distribution._finalize_requires | (self) |
Set `metadata.python_requires` and fix environment markers
in `install_requires` and `extras_require`.
|
Set `metadata.python_requires` and fix environment markers
in `install_requires` and `extras_require`.
| def _finalize_requires(self):
"""
Set `metadata.python_requires` and fix environment markers
in `install_requires` and `extras_require`.
"""
if getattr(self, 'python_requires', None):
self.metadata.python_requires = self.python_requires
if getattr(self, 'extr... | [
"def",
"_finalize_requires",
"(",
"self",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"'python_requires'",
",",
"None",
")",
":",
"self",
".",
"metadata",
".",
"python_requires",
"=",
"self",
".",
"python_requires",
"if",
"getattr",
"(",
"self",
",",
"'ex... | [
474,
4
] | [
492,
49
] | python | en | ['en', 'error', 'th'] | False |
Distribution._convert_extras_requirements | (self) |
Convert requirements in `extras_require` of the form
`"extra": ["barbazquux; {marker}"]` to
`"extra:{marker}": ["barbazquux"]`.
|
Convert requirements in `extras_require` of the form
`"extra": ["barbazquux; {marker}"]` to
`"extra:{marker}": ["barbazquux"]`.
| def _convert_extras_requirements(self):
"""
Convert requirements in `extras_require` of the form
`"extra": ["barbazquux; {marker}"]` to
`"extra:{marker}": ["barbazquux"]`.
"""
spec_ext_reqs = getattr(self, 'extras_require', None) or {}
self._tmp_extras_require = d... | [
"def",
"_convert_extras_requirements",
"(",
"self",
")",
":",
"spec_ext_reqs",
"=",
"getattr",
"(",
"self",
",",
"'extras_require'",
",",
"None",
")",
"or",
"{",
"}",
"self",
".",
"_tmp_extras_require",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"section",
... | [
494,
4
] | [
507,
68
] | python | en | ['en', 'error', 'th'] | False |
Distribution._suffix_for | (req) |
For a requirement, return the 'extras_require' suffix for
that requirement.
|
For a requirement, return the 'extras_require' suffix for
that requirement.
| def _suffix_for(req):
"""
For a requirement, return the 'extras_require' suffix for
that requirement.
"""
return ':' + str(req.marker) if req.marker else '' | [
"def",
"_suffix_for",
"(",
"req",
")",
":",
"return",
"':'",
"+",
"str",
"(",
"req",
".",
"marker",
")",
"if",
"req",
".",
"marker",
"else",
"''"
] | [
510,
4
] | [
515,
58
] | python | en | ['en', 'error', 'th'] | False |
Distribution._move_install_requirements_markers | (self) |
Move requirements in `install_requires` that are using environment
markers `extras_require`.
|
Move requirements in `install_requires` that are using environment
markers `extras_require`.
| def _move_install_requirements_markers(self):
"""
Move requirements in `install_requires` that are using environment
markers `extras_require`.
"""
# divide the install_requires into two sets, simple ones still
# handled by install_requires and more complex ones handled
... | [
"def",
"_move_install_requirements_markers",
"(",
"self",
")",
":",
"# divide the install_requires into two sets, simple ones still",
"# handled by install_requires and more complex ones handled",
"# by extras_require.",
"def",
"is_simple_req",
"(",
"req",
")",
":",
"return",
"not",
... | [
517,
4
] | [
541,
9
] | python | en | ['en', 'error', 'th'] | False |
Distribution._clean_req | (self, req) |
Given a Requirement, remove environment markers and return it.
|
Given a Requirement, remove environment markers and return it.
| def _clean_req(self, req):
"""
Given a Requirement, remove environment markers and return it.
"""
req.marker = None
return req | [
"def",
"_clean_req",
"(",
"self",
",",
"req",
")",
":",
"req",
".",
"marker",
"=",
"None",
"return",
"req"
] | [
543,
4
] | [
548,
18
] | python | en | ['en', 'error', 'th'] | False |
Distribution._parse_config_files | (self, filenames=None) |
Adapted from distutils.dist.Distribution.parse_config_files,
this method provides the same functionality in subtly-improved
ways.
|
Adapted from distutils.dist.Distribution.parse_config_files,
this method provides the same functionality in subtly-improved
ways.
| def _parse_config_files(self, filenames=None):
"""
Adapted from distutils.dist.Distribution.parse_config_files,
this method provides the same functionality in subtly-improved
ways.
"""
from configparser import ConfigParser
# Ignore install directory options if we... | [
"def",
"_parse_config_files",
"(",
"self",
",",
"filenames",
"=",
"None",
")",
":",
"from",
"configparser",
"import",
"ConfigParser",
"# Ignore install directory options if we have a venv",
"if",
"sys",
".",
"prefix",
"!=",
"sys",
".",
"base_prefix",
":",
"ignore_opti... | [
550,
4
] | [
610,
56
] | python | en | ['en', 'error', 'th'] | False |
Distribution._set_command_options | (self, command_obj, option_dict=None) |
Set the options for 'command_obj' from 'option_dict'. Basically
this means copying elements of a dictionary ('option_dict') to
attributes of an instance ('command').
'command_obj' must be a Command instance. If 'option_dict' is not
supplied, uses the standard option dictionar... |
Set the options for 'command_obj' from 'option_dict'. Basically
this means copying elements of a dictionary ('option_dict') to
attributes of an instance ('command'). | def _set_command_options(self, command_obj, option_dict=None):
"""
Set the options for 'command_obj' from 'option_dict'. Basically
this means copying elements of a dictionary ('option_dict') to
attributes of an instance ('command').
'command_obj' must be a Command instance. If... | [
"def",
"_set_command_options",
"(",
"self",
",",
"command_obj",
",",
"option_dict",
"=",
"None",
")",
":",
"command_name",
"=",
"command_obj",
".",
"get_command_name",
"(",
")",
"if",
"option_dict",
"is",
"None",
":",
"option_dict",
"=",
"self",
".",
"get_opti... | [
612,
4
] | [
657,
52
] | python | en | ['en', 'error', 'th'] | False |
Distribution.parse_config_files | (self, filenames=None, ignore_option_errors=False) | Parses configuration files from various levels
and loads configuration.
| Parses configuration files from various levels
and loads configuration. | def parse_config_files(self, filenames=None, ignore_option_errors=False):
"""Parses configuration files from various levels
and loads configuration.
"""
self._parse_config_files(filenames=filenames)
parse_configuration(self, self.command_options,
ign... | [
"def",
"parse_config_files",
"(",
"self",
",",
"filenames",
"=",
"None",
",",
"ignore_option_errors",
"=",
"False",
")",
":",
"self",
".",
"_parse_config_files",
"(",
"filenames",
"=",
"filenames",
")",
"parse_configuration",
"(",
"self",
",",
"self",
".",
"co... | [
659,
4
] | [
668,
33
] | python | en | ['en', 'en', 'en'] | True |
Distribution.fetch_build_eggs | (self, requires) | Resolve pre-setup requirements | Resolve pre-setup requirements | def fetch_build_eggs(self, requires):
"""Resolve pre-setup requirements"""
resolved_dists = pkg_resources.working_set.resolve(
pkg_resources.parse_requirements(requires),
installer=self.fetch_build_egg,
replace_conflicting=True,
)
for dist in resolved_... | [
"def",
"fetch_build_eggs",
"(",
"self",
",",
"requires",
")",
":",
"resolved_dists",
"=",
"pkg_resources",
".",
"working_set",
".",
"resolve",
"(",
"pkg_resources",
".",
"parse_requirements",
"(",
"requires",
")",
",",
"installer",
"=",
"self",
".",
"fetch_build... | [
670,
4
] | [
679,
29
] | python | en | ['en', 'en', 'en'] | True |
Distribution.finalize_options | (self) |
Allow plugins to apply arbitrary operations to the
distribution. Each hook may optionally define a 'order'
to influence the order of execution. Smaller numbers
go first and the default is 0.
|
Allow plugins to apply arbitrary operations to the
distribution. Each hook may optionally define a 'order'
to influence the order of execution. Smaller numbers
go first and the default is 0.
| def finalize_options(self):
"""
Allow plugins to apply arbitrary operations to the
distribution. Each hook may optionally define a 'order'
to influence the order of execution. Smaller numbers
go first and the default is 0.
"""
group = 'setuptools.finalize_distribu... | [
"def",
"finalize_options",
"(",
"self",
")",
":",
"group",
"=",
"'setuptools.finalize_distribution_options'",
"def",
"by_order",
"(",
"hook",
")",
":",
"return",
"getattr",
"(",
"hook",
",",
"'order'",
",",
"0",
")",
"eps",
"=",
"map",
"(",
"lambda",
"e",
... | [
681,
4
] | [
694,
20
] | python | en | ['en', 'error', 'th'] | False |
Distribution.fetch_build_egg | (self, req) | Fetch an egg needed for building | Fetch an egg needed for building | def fetch_build_egg(self, req):
"""Fetch an egg needed for building"""
from setuptools.installer import fetch_build_egg
return fetch_build_egg(self, req) | [
"def",
"fetch_build_egg",
"(",
"self",
",",
"req",
")",
":",
"from",
"setuptools",
".",
"installer",
"import",
"fetch_build_egg",
"return",
"fetch_build_egg",
"(",
"self",
",",
"req",
")"
] | [
728,
4
] | [
731,
41
] | python | en | ['en', 'en', 'en'] | True |
Distribution.get_command_class | (self, command) | Pluggable version of get_command_class() | Pluggable version of get_command_class() | def get_command_class(self, command):
"""Pluggable version of get_command_class()"""
if command in self.cmdclass:
return self.cmdclass[command]
eps = pkg_resources.iter_entry_points('distutils.commands', command)
for ep in eps:
ep.require(installer=self.fetch_bui... | [
"def",
"get_command_class",
"(",
"self",
",",
"command",
")",
":",
"if",
"command",
"in",
"self",
".",
"cmdclass",
":",
"return",
"self",
".",
"cmdclass",
"[",
"command",
"]",
"eps",
"=",
"pkg_resources",
".",
"iter_entry_points",
"(",
"'distutils.commands'",
... | [
733,
4
] | [
744,
65
] | python | en | ['en', 'en', 'en'] | True |
Distribution.include | (self, **attrs) | Add items to distribution that are named in keyword arguments
For example, 'dist.include(py_modules=["x"])' would add 'x' to
the distribution's 'py_modules' attribute, if it was not already
there.
Currently, this method only supports inclusion for attributes that are
lists or t... | Add items to distribution that are named in keyword arguments | def include(self, **attrs):
"""Add items to distribution that are named in keyword arguments
For example, 'dist.include(py_modules=["x"])' would add 'x' to
the distribution's 'py_modules' attribute, if it was not already
there.
Currently, this method only supports inclusion for... | [
"def",
"include",
"(",
"self",
",",
"*",
"*",
"attrs",
")",
":",
"for",
"k",
",",
"v",
"in",
"attrs",
".",
"items",
"(",
")",
":",
"include",
"=",
"getattr",
"(",
"self",
",",
"'_include_'",
"+",
"k",
",",
"None",
")",
"if",
"include",
":",
"in... | [
762,
4
] | [
782,
40
] | python | en | ['en', 'en', 'en'] | True |
Distribution.exclude_package | (self, package) | Remove packages, modules, and extensions in named package | Remove packages, modules, and extensions in named package | def exclude_package(self, package):
"""Remove packages, modules, and extensions in named package"""
pfx = package + '.'
if self.packages:
self.packages = [
p for p in self.packages
if p != package and not p.startswith(pfx)
]
if se... | [
"def",
"exclude_package",
"(",
"self",
",",
"package",
")",
":",
"pfx",
"=",
"package",
"+",
"'.'",
"if",
"self",
".",
"packages",
":",
"self",
".",
"packages",
"=",
"[",
"p",
"for",
"p",
"in",
"self",
".",
"packages",
"if",
"p",
"!=",
"package",
"... | [
784,
4
] | [
804,
13
] | python | en | ['en', 'en', 'en'] | True |
Distribution.has_contents_for | (self, package) | Return true if 'exclude_package(package)' would do something | Return true if 'exclude_package(package)' would do something | def has_contents_for(self, package):
"""Return true if 'exclude_package(package)' would do something"""
pfx = package + '.'
for p in self.iter_distribution_names():
if p == package or p.startswith(pfx):
return True | [
"def",
"has_contents_for",
"(",
"self",
",",
"package",
")",
":",
"pfx",
"=",
"package",
"+",
"'.'",
"for",
"p",
"in",
"self",
".",
"iter_distribution_names",
"(",
")",
":",
"if",
"p",
"==",
"package",
"or",
"p",
".",
"startswith",
"(",
"pfx",
")",
"... | [
806,
4
] | [
813,
27
] | python | en | ['en', 'en', 'en'] | True |
Distribution._exclude_misc | (self, name, value) | Handle 'exclude()' for list/tuple attrs without a special handler | Handle 'exclude()' for list/tuple attrs without a special handler | def _exclude_misc(self, name, value):
"""Handle 'exclude()' for list/tuple attrs without a special handler"""
if not isinstance(value, sequence):
raise DistutilsSetupError(
"%s: setting must be a list or tuple (%r)" % (name, value)
)
try:
old =... | [
"def",
"_exclude_misc",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"sequence",
")",
":",
"raise",
"DistutilsSetupError",
"(",
"\"%s: setting must be a list or tuple (%r)\"",
"%",
"(",
"name",
",",
"value",
"... | [
815,
4
] | [
832,
76
] | python | en | ['en', 'en', 'en'] | True |
Distribution._include_misc | (self, name, value) | Handle 'include()' for list/tuple attrs without a special handler | Handle 'include()' for list/tuple attrs without a special handler | def _include_misc(self, name, value):
"""Handle 'include()' for list/tuple attrs without a special handler"""
if not isinstance(value, sequence):
raise DistutilsSetupError(
"%s: setting must be a list (%r)" % (name, value)
)
try:
old = getattr... | [
"def",
"_include_misc",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"sequence",
")",
":",
"raise",
"DistutilsSetupError",
"(",
"\"%s: setting must be a list (%r)\"",
"%",
"(",
"name",
",",
"value",
")",
")"... | [
834,
4
] | [
855,
42
] | python | en | ['en', 'en', 'en'] | True |
Distribution.exclude | (self, **attrs) | Remove items from distribution that are named in keyword arguments
For example, 'dist.exclude(py_modules=["x"])' would remove 'x' from
the distribution's 'py_modules' attribute. Excluding packages uses
the 'exclude_package()' method, so all of the package's contained
packages, modules,... | Remove items from distribution that are named in keyword arguments | def exclude(self, **attrs):
"""Remove items from distribution that are named in keyword arguments
For example, 'dist.exclude(py_modules=["x"])' would remove 'x' from
the distribution's 'py_modules' attribute. Excluding packages uses
the 'exclude_package()' method, so all of the package... | [
"def",
"exclude",
"(",
"self",
",",
"*",
"*",
"attrs",
")",
":",
"for",
"k",
",",
"v",
"in",
"attrs",
".",
"items",
"(",
")",
":",
"exclude",
"=",
"getattr",
"(",
"self",
",",
"'_exclude_'",
"+",
"k",
",",
"None",
")",
"if",
"exclude",
":",
"ex... | [
857,
4
] | [
878,
40
] | python | en | ['en', 'en', 'en'] | True |
Distribution.get_cmdline_options | (self) | Return a '{cmd: {opt:val}}' map of all command-line options
Option names are all long, but do not include the leading '--', and
contain dashes rather than underscores. If the option doesn't take
an argument (e.g. '--quiet'), the 'val' is 'None'.
Note that options provided by config fi... | Return a '{cmd: {opt:val}}' map of all command-line options | def get_cmdline_options(self):
"""Return a '{cmd: {opt:val}}' map of all command-line options
Option names are all long, but do not include the leading '--', and
contain dashes rather than underscores. If the option doesn't take
an argument (e.g. '--quiet'), the 'val' is 'None'.
... | [
"def",
"get_cmdline_options",
"(",
"self",
")",
":",
"d",
"=",
"{",
"}",
"for",
"cmd",
",",
"opts",
"in",
"self",
".",
"command_options",
".",
"items",
"(",
")",
":",
"for",
"opt",
",",
"(",
"src",
",",
"val",
")",
"in",
"opts",
".",
"items",
"("... | [
913,
4
] | [
951,
16
] | python | en | ['en', 'en', 'en'] | True |
Distribution.iter_distribution_names | (self) | Yield all packages, modules, and extension names in distribution | Yield all packages, modules, and extension names in distribution | def iter_distribution_names(self):
"""Yield all packages, modules, and extension names in distribution"""
for pkg in self.packages or ():
yield pkg
for module in self.py_modules or ():
yield module
for ext in self.ext_modules or ():
if isinstance(ex... | [
"def",
"iter_distribution_names",
"(",
"self",
")",
":",
"for",
"pkg",
"in",
"self",
".",
"packages",
"or",
"(",
")",
":",
"yield",
"pkg",
"for",
"module",
"in",
"self",
".",
"py_modules",
"or",
"(",
")",
":",
"yield",
"module",
"for",
"ext",
"in",
"... | [
953,
4
] | [
969,
22
] | python | en | ['en', 'en', 'en'] | True |
Distribution.handle_display_options | (self, option_order) | If there were any non-global "display-only" options
(--help-commands or the metadata display options) on the command
line, display the requested info and return true; else return
false.
| If there were any non-global "display-only" options
(--help-commands or the metadata display options) on the command
line, display the requested info and return true; else return
false.
| def handle_display_options(self, option_order):
"""If there were any non-global "display-only" options
(--help-commands or the metadata display options) on the command
line, display the requested info and return true; else return
false.
"""
import sys
if self.hel... | [
"def",
"handle_display_options",
"(",
"self",
",",
"option_order",
")",
":",
"import",
"sys",
"if",
"self",
".",
"help_commands",
":",
"return",
"_Distribution",
".",
"handle_display_options",
"(",
"self",
",",
"option_order",
")",
"# Stdout may be StringIO (e.g. in t... | [
971,
4
] | [
1003,
79
] | python | en | ['en', 'en', 'en'] | True |
_infer_return_type | (*args) | Look at the type of all args and divine their implied return type. | Look at the type of all args and divine their implied return type. | def _infer_return_type(*args):
"""Look at the type of all args and divine their implied return type."""
return_type = None
for arg in args:
if arg is None:
continue
if isinstance(arg, bytes):
if return_type is str:
raise TypeError("Can't mix bytes and ... | [
"def",
"_infer_return_type",
"(",
"*",
"args",
")",
":",
"return_type",
"=",
"None",
"for",
"arg",
"in",
"args",
":",
"if",
"arg",
"is",
"None",
":",
"continue",
"if",
"isinstance",
"(",
"arg",
",",
"bytes",
")",
":",
"if",
"return_type",
"is",
"str",
... | [
96,
0
] | [
114,
22
] | python | en | ['en', 'en', 'en'] | True |
_sanitize_params | (prefix, suffix, dir) | Common parameter processing for most APIs in this module. | Common parameter processing for most APIs in this module. | def _sanitize_params(prefix, suffix, dir):
"""Common parameter processing for most APIs in this module."""
output_type = _infer_return_type(prefix, suffix, dir)
if suffix is None:
suffix = output_type()
if prefix is None:
if output_type is str:
prefix = template
else:... | [
"def",
"_sanitize_params",
"(",
"prefix",
",",
"suffix",
",",
"dir",
")",
":",
"output_type",
"=",
"_infer_return_type",
"(",
"prefix",
",",
"suffix",
",",
"dir",
")",
"if",
"suffix",
"is",
"None",
":",
"suffix",
"=",
"output_type",
"(",
")",
"if",
"pref... | [
117,
0
] | [
132,
43
] | python | en | ['en', 'en', 'en'] | True |
_candidate_tempdir_list | () | Generate a list of candidate temporary directories which
_get_default_tempdir will try. | Generate a list of candidate temporary directories which
_get_default_tempdir will try. | def _candidate_tempdir_list():
"""Generate a list of candidate temporary directories which
_get_default_tempdir will try."""
dirlist = []
# First, try the environment.
for envname in 'TMPDIR', 'TEMP', 'TMP':
dirname = _os.getenv(envname)
if dirname: dirlist.append(dirname)
# F... | [
"def",
"_candidate_tempdir_list",
"(",
")",
":",
"dirlist",
"=",
"[",
"]",
"# First, try the environment.",
"for",
"envname",
"in",
"'TMPDIR'",
",",
"'TEMP'",
",",
"'TMP'",
":",
"dirname",
"=",
"_os",
".",
"getenv",
"(",
"envname",
")",
"if",
"dirname",
":",... | [
162,
0
] | [
187,
18
] | python | en | ['en', 'en', 'en'] | True |
_get_default_tempdir | () | Calculate the default directory to use for temporary files.
This routine should be called exactly once.
We determine whether or not a candidate temp dir is usable by
trying to create and write to a file in that directory. If this
is successful, the test file is deleted. To prevent denial of
servi... | Calculate the default directory to use for temporary files.
This routine should be called exactly once. | def _get_default_tempdir():
"""Calculate the default directory to use for temporary files.
This routine should be called exactly once.
We determine whether or not a candidate temp dir is usable by
trying to create and write to a file in that directory. If this
is successful, the test file is delet... | [
"def",
"_get_default_tempdir",
"(",
")",
":",
"namer",
"=",
"_RandomNameSequence",
"(",
")",
"dirlist",
"=",
"_candidate_tempdir_list",
"(",
")",
"for",
"dir",
"in",
"dirlist",
":",
"if",
"dir",
"!=",
"_os",
".",
"curdir",
":",
"dir",
"=",
"_os",
".",
"p... | [
189,
0
] | [
232,
36
] | python | en | ['en', 'en', 'en'] | True |
_get_candidate_names | () | Common setup sequence for all user-callable interfaces. | Common setup sequence for all user-callable interfaces. | def _get_candidate_names():
"""Common setup sequence for all user-callable interfaces."""
global _name_sequence
if _name_sequence is None:
_once_lock.acquire()
try:
if _name_sequence is None:
_name_sequence = _RandomNameSequence()
finally:
_on... | [
"def",
"_get_candidate_names",
"(",
")",
":",
"global",
"_name_sequence",
"if",
"_name_sequence",
"is",
"None",
":",
"_once_lock",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"_name_sequence",
"is",
"None",
":",
"_name_sequence",
"=",
"_RandomNameSequence",
"(",... | [
236,
0
] | [
247,
25
] | python | en | ['en', 'en', 'en'] | True |
_mkstemp_inner | (dir, pre, suf, flags, output_type) | Code common to mkstemp, TemporaryFile, and NamedTemporaryFile. | Code common to mkstemp, TemporaryFile, and NamedTemporaryFile. | def _mkstemp_inner(dir, pre, suf, flags, output_type):
"""Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
names = _get_candidate_names()
if output_type is bytes:
names = map(_os.fsencode, names)
for seq in range(TMP_MAX):
name = next(names)
file = _os.path.joi... | [
"def",
"_mkstemp_inner",
"(",
"dir",
",",
"pre",
",",
"suf",
",",
"flags",
",",
"output_type",
")",
":",
"names",
"=",
"_get_candidate_names",
"(",
")",
"if",
"output_type",
"is",
"bytes",
":",
"names",
"=",
"map",
"(",
"_os",
".",
"fsencode",
",",
"na... | [
250,
0
] | [
275,
64
] | python | en | ['en', 'en', 'en'] | True |
gettempprefix | () | The default prefix for temporary directories. | The default prefix for temporary directories. | def gettempprefix():
"""The default prefix for temporary directories."""
return template | [
"def",
"gettempprefix",
"(",
")",
":",
"return",
"template"
] | [
280,
0
] | [
282,
19
] | python | en | ['en', 'en', 'en'] | True |
gettempprefixb | () | The default prefix for temporary directories as bytes. | The default prefix for temporary directories as bytes. | def gettempprefixb():
"""The default prefix for temporary directories as bytes."""
return _os.fsencode(gettempprefix()) | [
"def",
"gettempprefixb",
"(",
")",
":",
"return",
"_os",
".",
"fsencode",
"(",
"gettempprefix",
"(",
")",
")"
] | [
284,
0
] | [
286,
40
] | python | en | ['en', 'en', 'en'] | True |
gettempdir | () | Accessor for tempfile.tempdir. | Accessor for tempfile.tempdir. | def gettempdir():
"""Accessor for tempfile.tempdir."""
global tempdir
if tempdir is None:
_once_lock.acquire()
try:
if tempdir is None:
tempdir = _get_default_tempdir()
finally:
_once_lock.release()
return tempdir | [
"def",
"gettempdir",
"(",
")",
":",
"global",
"tempdir",
"if",
"tempdir",
"is",
"None",
":",
"_once_lock",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"tempdir",
"is",
"None",
":",
"tempdir",
"=",
"_get_default_tempdir",
"(",
")",
"finally",
":",
"_once_... | [
290,
0
] | [
300,
18
] | python | en | ['en', 'gl', 'en'] | True |
gettempdirb | () | A bytes version of tempfile.gettempdir(). | A bytes version of tempfile.gettempdir(). | def gettempdirb():
"""A bytes version of tempfile.gettempdir()."""
return _os.fsencode(gettempdir()) | [
"def",
"gettempdirb",
"(",
")",
":",
"return",
"_os",
".",
"fsencode",
"(",
"gettempdir",
"(",
")",
")"
] | [
302,
0
] | [
304,
37
] | python | en | ['en', 'gl', 'en'] | True |
mkstemp | (suffix=None, prefix=None, dir=None, text=False) | User-callable function to create and return a unique temporary
file. The return value is a pair (fd, name) where fd is the
file descriptor returned by os.open, and name is the filename.
If 'suffix' is not None, the file name will end with that suffix,
otherwise there will be no suffix.
If 'prefix... | User-callable function to create and return a unique temporary
file. The return value is a pair (fd, name) where fd is the
file descriptor returned by os.open, and name is the filename. | def mkstemp(suffix=None, prefix=None, dir=None, text=False):
"""User-callable function to create and return a unique temporary
file. The return value is a pair (fd, name) where fd is the
file descriptor returned by os.open, and name is the filename.
If 'suffix' is not None, the file name will end with... | [
"def",
"mkstemp",
"(",
"suffix",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"dir",
"=",
"None",
",",
"text",
"=",
"False",
")",
":",
"prefix",
",",
"suffix",
",",
"dir",
",",
"output_type",
"=",
"_sanitize_params",
"(",
"prefix",
",",
"suffix",
",... | [
306,
0
] | [
343,
66
] | python | en | ['en', 'en', 'en'] | True |
mkdtemp | (suffix=None, prefix=None, dir=None) | User-callable function to create and return a unique temporary
directory. The return value is the pathname of the directory.
Arguments are as for mkstemp, except that the 'text' argument is
not accepted.
The directory is readable, writable, and searchable only by the
creating user.
Caller is... | User-callable function to create and return a unique temporary
directory. The return value is the pathname of the directory. | def mkdtemp(suffix=None, prefix=None, dir=None):
"""User-callable function to create and return a unique temporary
directory. The return value is the pathname of the directory.
Arguments are as for mkstemp, except that the 'text' argument is
not accepted.
The directory is readable, writable, and ... | [
"def",
"mkdtemp",
"(",
"suffix",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"dir",
"=",
"None",
")",
":",
"prefix",
",",
"suffix",
",",
"dir",
",",
"output_type",
"=",
"_sanitize_params",
"(",
"prefix",
",",
"suffix",
",",
"dir",
")",
"names",
"="... | [
346,
0
] | [
383,
69
] | python | en | ['en', 'en', 'en'] | True |
mktemp | (suffix="", prefix=template, dir=None) | User-callable function to return a unique temporary file name. The
file is not created.
Arguments are similar to mkstemp, except that the 'text' argument is
not accepted, and suffix=None, prefix=None and bytes file names are not
supported.
THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file... | User-callable function to return a unique temporary file name. The
file is not created. | def mktemp(suffix="", prefix=template, dir=None):
"""User-callable function to return a unique temporary file name. The
file is not created.
Arguments are similar to mkstemp, except that the 'text' argument is
not accepted, and suffix=None, prefix=None and bytes file names are not
supported.
... | [
"def",
"mktemp",
"(",
"suffix",
"=",
"\"\"",
",",
"prefix",
"=",
"template",
",",
"dir",
"=",
"None",
")",
":",
"## from warnings import warn as _warn",
"## _warn(\"mktemp is a potential security risk to your program\",",
"## RuntimeWarning, stacklevel=2)",
"if",... | [
385,
0
] | [
414,
63
] | python | en | ['en', 'en', 'en'] | True |
NamedTemporaryFile | (mode='w+b', buffering=-1, encoding=None,
newline=None, suffix=None, prefix=None,
dir=None, delete=True) | Create and return a temporary file.
Arguments:
'prefix', 'suffix', 'dir' -- as for mkstemp.
'mode' -- the mode argument to io.open (default "w+b").
'buffering' -- the buffer size argument to io.open (default -1).
'encoding' -- the encoding argument to io.open (default None)
'newline' -- the newl... | Create and return a temporary file.
Arguments:
'prefix', 'suffix', 'dir' -- as for mkstemp.
'mode' -- the mode argument to io.open (default "w+b").
'buffering' -- the buffer size argument to io.open (default -1).
'encoding' -- the encoding argument to io.open (default None)
'newline' -- the newl... | def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None,
newline=None, suffix=None, prefix=None,
dir=None, delete=True):
"""Create and return a temporary file.
Arguments:
'prefix', 'suffix', 'dir' -- as for mkstemp.
'mode' -- the mode argument to io.o... | [
"def",
"NamedTemporaryFile",
"(",
"mode",
"=",
"'w+b'",
",",
"buffering",
"=",
"-",
"1",
",",
"encoding",
"=",
"None",
",",
"newline",
"=",
"None",
",",
"suffix",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"dir",
"=",
"None",
",",
"delete",
"=",
... | [
523,
0
] | [
559,
13
] | python | en | ['en', 'en', 'en'] | True |
_TemporaryFileWrapper.close | (self) |
Close the temporary file, possibly deleting it.
|
Close the temporary file, possibly deleting it.
| def close(self):
"""
Close the temporary file, possibly deleting it.
"""
self._closer.close() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"_closer",
".",
"close",
"(",
")"
] | [
506,
4
] | [
510,
28
] | python | en | ['en', 'error', 'th'] | False |
_wrapped_include | (arg) | Convert the old 3-tuple arg for include() into the new format.
The argument "arg" should be a tuple with 3 elements:
(pattern_list, app_namespace, instance_namespace)
Prior to Django 2.0, django.urls.conf.include() accepts 3-tuple arg
(urlconf, namespace, app_name), but it was droppped in Django 2.0.
... | Convert the old 3-tuple arg for include() into the new format. | def _wrapped_include(arg):
"""Convert the old 3-tuple arg for include() into the new format.
The argument "arg" should be a tuple with 3 elements:
(pattern_list, app_namespace, instance_namespace)
Prior to Django 2.0, django.urls.conf.include() accepts 3-tuple arg
(urlconf, namespace, app_name), b... | [
"def",
"_wrapped_include",
"(",
"arg",
")",
":",
"pattern_list",
",",
"app_namespace",
",",
"instance_namespace",
"=",
"arg",
"return",
"include",
"(",
"(",
"pattern_list",
",",
"app_namespace",
")",
",",
"namespace",
"=",
"instance_namespace",
")"
] | [
94,
0
] | [
109,
79
] | python | en | ['en', 'en', 'en'] | True |
Registry._register | (self, cls) | Registers the given class.
If the specified class is already registered then it is ignored.
| Registers the given class. | def _register(self, cls):
"""Registers the given class.
If the specified class is already registered then it is ignored.
"""
if not inspect.isclass(cls):
raise ValueError('Only classes may be registered.')
elif not issubclass(cls, self._registerable_class):
... | [
"def",
"_register",
"(",
"self",
",",
"cls",
")",
":",
"if",
"not",
"inspect",
".",
"isclass",
"(",
"cls",
")",
":",
"raise",
"ValueError",
"(",
"'Only classes may be registered.'",
")",
"elif",
"not",
"issubclass",
"(",
"cls",
",",
"self",
".",
"_register... | [
193,
4
] | [
208,
34
] | python | en | ['en', 'en', 'en'] | True |
Registry._unregister | (self, cls) | Unregisters the given class.
If the specified class isn't registered, ``NotRegistered`` will
be raised.
| Unregisters the given class. | def _unregister(self, cls):
"""Unregisters the given class.
If the specified class isn't registered, ``NotRegistered`` will
be raised.
"""
if not issubclass(cls, self._registerable_class):
raise ValueError('Only %s classes or subclasses may be '
... | [
"def",
"_unregister",
"(",
"self",
",",
"cls",
")",
":",
"if",
"not",
"issubclass",
"(",
"cls",
",",
"self",
".",
"_registerable_class",
")",
":",
"raise",
"ValueError",
"(",
"'Only %s classes or subclasses may be '",
"'unregistered.'",
"%",
"self",
".",
"_regis... | [
210,
4
] | [
225,
19
] | python | en | ['en', 'en', 'en'] | True |
Panel.get_absolute_url | (self) | Returns the default URL for this panel.
The default URL is defined as the URL pattern with ``name="index"`` in
the URLconf for this panel.
| Returns the default URL for this panel. | def get_absolute_url(self):
"""Returns the default URL for this panel.
The default URL is defined as the URL pattern with ``name="index"`` in
the URLconf for this panel.
"""
try:
return reverse('horizon:%s:%s:%s' % (self._registered_with.slug,
... | [
"def",
"get_absolute_url",
"(",
"self",
")",
":",
"try",
":",
"return",
"reverse",
"(",
"'horizon:%s:%s:%s'",
"%",
"(",
"self",
".",
"_registered_with",
".",
"slug",
",",
"self",
".",
"slug",
",",
"self",
".",
"index_url_name",
")",
")",
"except",
"Excepti... | [
320,
4
] | [
335,
17
] | python | en | ['en', 'en', 'en'] | True |
Dashboard.get_panel | (self, panel) | Returns the Panel instance registered with this dashboard. | Returns the Panel instance registered with this dashboard. | def get_panel(self, panel):
"""Returns the Panel instance registered with this dashboard."""
return self._registered(panel) | [
"def",
"get_panel",
"(",
"self",
",",
"panel",
")",
":",
"return",
"self",
".",
"_registered",
"(",
"panel",
")"
] | [
496,
4
] | [
498,
38
] | python | en | ['en', 'en', 'en'] | True |
Dashboard.get_panels | (self) | Returns the Panel instances registered with this dashboard in order.
Panel grouping information is not included.
| Returns the Panel instances registered with this dashboard in order. | def get_panels(self):
"""Returns the Panel instances registered with this dashboard in order.
Panel grouping information is not included.
"""
all_panels = []
panel_groups = self.get_panel_groups()
for panel_group in panel_groups.values():
all_panels.extend(pa... | [
"def",
"get_panels",
"(",
"self",
")",
":",
"all_panels",
"=",
"[",
"]",
"panel_groups",
"=",
"self",
".",
"get_panel_groups",
"(",
")",
"for",
"panel_group",
"in",
"panel_groups",
".",
"values",
"(",
")",
":",
"all_panels",
".",
"extend",
"(",
"panel_grou... | [
500,
4
] | [
509,
25
] | python | en | ['en', 'en', 'en'] | True |
Dashboard.get_panel_group | (self, slug) | Returns the specified :class:~horizon.PanelGroup.
Returns None if not registered.
| Returns the specified :class:~horizon.PanelGroup. | def get_panel_group(self, slug):
"""Returns the specified :class:~horizon.PanelGroup.
Returns None if not registered.
"""
return self._panel_groups.get(slug) | [
"def",
"get_panel_group",
"(",
"self",
",",
"slug",
")",
":",
"return",
"self",
".",
"_panel_groups",
".",
"get",
"(",
"slug",
")"
] | [
511,
4
] | [
516,
43
] | python | en | ['en', 'en', 'en'] | True |
Dashboard.get_absolute_url | (self) | Returns the default URL for this dashboard.
The default URL is defined as the URL pattern with ``name="index"``
in the URLconf for the :class:`~horizon.Panel` specified by
:attr:`~horizon.Dashboard.default_panel`.
| Returns the default URL for this dashboard. | def get_absolute_url(self):
"""Returns the default URL for this dashboard.
The default URL is defined as the URL pattern with ``name="index"``
in the URLconf for the :class:`~horizon.Panel` specified by
:attr:`~horizon.Dashboard.default_panel`.
"""
try:
retur... | [
"def",
"get_absolute_url",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_registered",
"(",
"self",
".",
"default_panel",
")",
".",
"get_absolute_url",
"(",
")",
"except",
"Exception",
":",
"# Logging here since this will often be called in a template",
... | [
539,
4
] | [
552,
17
] | 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.