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
MessagePOSTTest.test_message_to_nonexistent_stream
(self)
Sending a message to a nonexistent stream fails.
Sending a message to a nonexistent stream fails.
def test_message_to_nonexistent_stream(self) -> None: """ Sending a message to a nonexistent stream fails. """ self.login("hamlet") self.assertFalse(Stream.objects.filter(name="nonexistent_stream")) result = self.client_post( "/json/messages", { ...
[ "def", "test_message_to_nonexistent_stream", "(", "self", ")", "->", "None", ":", "self", ".", "login", "(", "\"hamlet\"", ")", "self", ".", "assertFalse", "(", "Stream", ".", "objects", ".", "filter", "(", "name", "=", "\"nonexistent_stream\"", ")", ")", "r...
[ 465, 4 ]
[ 481, 84 ]
python
en
['en', 'error', 'th']
False
MessagePOSTTest.test_message_to_nonexistent_stream_with_bad_characters
(self)
Nonexistent stream name with bad characters should be escaped properly.
Nonexistent stream name with bad characters should be escaped properly.
def test_message_to_nonexistent_stream_with_bad_characters(self) -> None: """ Nonexistent stream name with bad characters should be escaped properly. """ self.login("hamlet") self.assertFalse(Stream.objects.filter(name="""&<"'><non-existent>""")) result = self.client_post...
[ "def", "test_message_to_nonexistent_stream_with_bad_characters", "(", "self", ")", "->", "None", ":", "self", ".", "login", "(", "\"hamlet\"", ")", "self", ".", "assertFalse", "(", "Stream", ".", "objects", ".", "filter", "(", "name", "=", "\"\"\"&<\"'><non-existe...
[ 483, 4 ]
[ 501, 9 ]
python
en
['en', 'error', 'th']
False
MessagePOSTTest.test_personal_message
(self)
Sending a personal message to a valid username is successful.
Sending a personal message to a valid username is successful.
def test_personal_message(self) -> None: """ Sending a personal message to a valid username is successful. """ user_profile = self.example_user("hamlet") self.login_user(user_profile) othello = self.example_user("othello") result = self.client_post( "/...
[ "def", "test_personal_message", "(", "self", ")", "->", "None", ":", "user_profile", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "self", ".", "login_user", "(", "user_profile", ")", "othello", "=", "self", ".", "example_user", "(", "\"othello\"",...
[ 503, 4 ]
[ 553, 80 ]
python
en
['en', 'error', 'th']
False
MessagePOSTTest.test_personal_message_by_id
(self)
Sending a personal message to a valid user ID is successful.
Sending a personal message to a valid user ID is successful.
def test_personal_message_by_id(self) -> None: """ Sending a personal message to a valid user ID is successful. """ self.login("hamlet") result = self.client_post( "/json/messages", { "type": "private", "content": "Test mess...
[ "def", "test_personal_message_by_id", "(", "self", ")", "->", "None", ":", "self", ".", "login", "(", "\"hamlet\"", ")", "result", "=", "self", ".", "client_post", "(", "\"/json/messages\"", ",", "{", "\"type\"", ":", "\"private\"", ",", "\"content\"", ":", ...
[ 555, 4 ]
[ 573, 85 ]
python
en
['en', 'error', 'th']
False
MessagePOSTTest.test_group_personal_message_by_id
(self)
Sending a personal message to a valid user ID is successful.
Sending a personal message to a valid user ID is successful.
def test_group_personal_message_by_id(self) -> None: """ Sending a personal message to a valid user ID is successful. """ self.login("hamlet") result = self.client_post( "/json/messages", { "type": "private", "content": "Tes...
[ "def", "test_group_personal_message_by_id", "(", "self", ")", "->", "None", ":", "self", ".", "login", "(", "\"hamlet\"", ")", "result", "=", "self", ".", "client_post", "(", "\"/json/messages\"", ",", "{", "\"type\"", ":", "\"private\"", ",", "\"content\"", "...
[ 575, 4 ]
[ 604, 9 ]
python
en
['en', 'error', 'th']
False
MessagePOSTTest.test_personal_message_copying_self
(self)
Sending a personal message to yourself plus another user is successful, and counts as a message just to that user.
Sending a personal message to yourself plus another user is successful, and counts as a message just to that user.
def test_personal_message_copying_self(self) -> None: """ Sending a personal message to yourself plus another user is successful, and counts as a message just to that user. """ hamlet = self.example_user("hamlet") othello = self.example_user("othello") self.login_...
[ "def", "test_personal_message_copying_self", "(", "self", ")", "->", "None", ":", "hamlet", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "othello", "=", "self", ".", "example_user", "(", "\"othello\"", ")", "self", ".", "login_user", "(", "hamlet"...
[ 606, 4 ]
[ 626, 54 ]
python
en
['en', 'error', 'th']
False
MessagePOSTTest.test_personal_message_to_nonexistent_user
(self)
Sending a personal message to an invalid email returns error JSON.
Sending a personal message to an invalid email returns error JSON.
def test_personal_message_to_nonexistent_user(self) -> None: """ Sending a personal message to an invalid email returns error JSON. """ self.login("hamlet") result = self.client_post( "/json/messages", { "type": "private", "...
[ "def", "test_personal_message_to_nonexistent_user", "(", "self", ")", "->", "None", ":", "self", ".", "login", "(", "\"hamlet\"", ")", "result", "=", "self", ".", "client_post", "(", "\"/json/messages\"", ",", "{", "\"type\"", ":", "\"private\"", ",", "\"content...
[ 628, 4 ]
[ 642, 69 ]
python
en
['en', 'error', 'th']
False
MessagePOSTTest.test_personal_message_to_deactivated_user
(self)
Sending a personal message to a deactivated user returns error JSON.
Sending a personal message to a deactivated user returns error JSON.
def test_personal_message_to_deactivated_user(self) -> None: """ Sending a personal message to a deactivated user returns error JSON. """ othello = self.example_user("othello") cordelia = self.example_user("cordelia") do_deactivate_user(othello, acting_user=None) ...
[ "def", "test_personal_message_to_deactivated_user", "(", "self", ")", "->", "None", ":", "othello", "=", "self", ".", "example_user", "(", "\"othello\"", ")", "cordelia", "=", "self", ".", "example_user", "(", "\"cordelia\"", ")", "do_deactivate_user", "(", "othel...
[ 644, 4 ]
[ 673, 86 ]
python
en
['en', 'error', 'th']
False
MessagePOSTTest.test_invalid_type
(self)
Sending a message of unknown type returns error JSON.
Sending a message of unknown type returns error JSON.
def test_invalid_type(self) -> None: """ Sending a message of unknown type returns error JSON. """ self.login("hamlet") othello = self.example_user("othello") result = self.client_post( "/json/messages", { "type": "invalid type", ...
[ "def", "test_invalid_type", "(", "self", ")", "->", "None", ":", "self", ".", "login", "(", "\"hamlet\"", ")", "othello", "=", "self", ".", "example_user", "(", "\"othello\"", ")", "result", "=", "self", ".", "client_post", "(", "\"/json/messages\"", ",", ...
[ 675, 4 ]
[ 690, 62 ]
python
en
['en', 'error', 'th']
False
MessagePOSTTest.test_empty_message
(self)
Sending a message that is empty or only whitespace should fail
Sending a message that is empty or only whitespace should fail
def test_empty_message(self) -> None: """ Sending a message that is empty or only whitespace should fail """ self.login("hamlet") othello = self.example_user("othello") result = self.client_post( "/json/messages", {"type": "private", "content": " "...
[ "def", "test_empty_message", "(", "self", ")", "->", "None", ":", "self", ".", "login", "(", "\"hamlet\"", ")", "othello", "=", "self", ".", "example_user", "(", "\"othello\"", ")", "result", "=", "self", ".", "client_post", "(", "\"/json/messages\"", ",", ...
[ 692, 4 ]
[ 702, 67 ]
python
en
['en', 'error', 'th']
False
MessagePOSTTest.test_empty_string_topic
(self)
Sending a message that has empty string topic should fail
Sending a message that has empty string topic should fail
def test_empty_string_topic(self) -> None: """ Sending a message that has empty string topic should fail """ self.login("hamlet") result = self.client_post( "/json/messages", { "type": "stream", "to": "Verona", ...
[ "def", "test_empty_string_topic", "(", "self", ")", "->", "None", ":", "self", ".", "login", "(", "\"hamlet\"", ")", "result", "=", "self", ".", "client_post", "(", "\"/json/messages\"", ",", "{", "\"type\"", ":", "\"stream\"", ",", "\"to\"", ":", "\"Verona\...
[ 704, 4 ]
[ 719, 62 ]
python
en
['en', 'error', 'th']
False
MessagePOSTTest.test_missing_topic
(self)
Sending a message without topic should fail
Sending a message without topic should fail
def test_missing_topic(self) -> None: """ Sending a message without topic should fail """ self.login("hamlet") result = self.client_post( "/json/messages", {"type": "stream", "to": "Verona", "client": "test suite", "content": "Test message"}, ) ...
[ "def", "test_missing_topic", "(", "self", ")", "->", "None", ":", "self", ".", "login", "(", "\"hamlet\"", ")", "result", "=", "self", ".", "client_post", "(", "\"/json/messages\"", ",", "{", "\"type\"", ":", "\"stream\"", ",", "\"to\"", ":", "\"Verona\"", ...
[ 721, 4 ]
[ 730, 55 ]
python
en
['en', 'error', 'th']
False
MessagePOSTTest.test_invalid_message_type
(self)
Messages other than the type of "private" or "stream" are considered as invalid
Messages other than the type of "private" or "stream" are considered as invalid
def test_invalid_message_type(self) -> None: """ Messages other than the type of "private" or "stream" are considered as invalid """ self.login("hamlet") result = self.client_post( "/json/messages", { "type": "invalid", "to"...
[ "def", "test_invalid_message_type", "(", "self", ")", "->", "None", ":", "self", ".", "login", "(", "\"hamlet\"", ")", "result", "=", "self", ".", "client_post", "(", "\"/json/messages\"", ",", "{", "\"type\"", ":", "\"invalid\"", ",", "\"to\"", ":", "\"Vero...
[ 732, 4 ]
[ 747, 62 ]
python
en
['en', 'error', 'th']
False
MessagePOSTTest.test_private_message_without_recipients
(self)
Sending private message without recipients should fail
Sending private message without recipients should fail
def test_private_message_without_recipients(self) -> None: """ Sending private message without recipients should fail """ self.login("hamlet") result = self.client_post( "/json/messages", {"type": "private", "content": "Test content", "client": "test suite...
[ "def", "test_private_message_without_recipients", "(", "self", ")", "->", "None", ":", "self", ".", "login", "(", "\"hamlet\"", ")", "result", "=", "self", ".", "client_post", "(", "\"/json/messages\"", ",", "{", "\"type\"", ":", "\"private\"", ",", "\"content\"...
[ 749, 4 ]
[ 758, 70 ]
python
en
['en', 'error', 'th']
False
MessagePOSTTest.test_mirrored_huddle
(self)
Sending a mirrored huddle message works
Sending a mirrored huddle message works
def test_mirrored_huddle(self) -> None: """ Sending a mirrored huddle message works """ result = self.api_post( self.mit_user("starnine"), "/json/messages", { "type": "private", "sender": self.mit_email("sipbtest"), ...
[ "def", "test_mirrored_huddle", "(", "self", ")", "->", "None", ":", "result", "=", "self", ".", "api_post", "(", "self", ".", "mit_user", "(", "\"starnine\"", ")", ",", "\"/json/messages\"", ",", "{", "\"type\"", ":", "\"private\"", ",", "\"sender\"", ":", ...
[ 760, 4 ]
[ 778, 40 ]
python
en
['en', 'error', 'th']
False
MessagePOSTTest.test_mirrored_personal
(self)
Sending a mirrored personal message works
Sending a mirrored personal message works
def test_mirrored_personal(self) -> None: """ Sending a mirrored personal message works """ result = self.api_post( self.mit_user("starnine"), "/json/messages", { "type": "private", "sender": self.mit_email("sipbtest"), ...
[ "def", "test_mirrored_personal", "(", "self", ")", "->", "None", ":", "result", "=", "self", ".", "api_post", "(", "self", ".", "mit_user", "(", "\"starnine\"", ")", ",", "\"/json/messages\"", ",", "{", "\"type\"", ":", "\"private\"", ",", "\"sender\"", ":",...
[ 780, 4 ]
[ 796, 40 ]
python
en
['en', 'error', 'th']
False
MessagePOSTTest.test_mirrored_personal_browser
(self)
Sending a mirrored personal message via the browser should not work.
Sending a mirrored personal message via the browser should not work.
def test_mirrored_personal_browser(self) -> None: """ Sending a mirrored personal message via the browser should not work. """ user = self.mit_user("starnine") self.login_user(user) result = self.client_post( "/json/messages", { "ty...
[ "def", "test_mirrored_personal_browser", "(", "self", ")", "->", "None", ":", "user", "=", "self", ".", "mit_user", "(", "\"starnine\"", ")", "self", ".", "login_user", "(", "user", ")", "result", "=", "self", ".", "client_post", "(", "\"/json/messages\"", "...
[ 798, 4 ]
[ 815, 66 ]
python
en
['en', 'error', 'th']
False
MessagePOSTTest.test_mirrored_personal_to_someone_else
(self)
Sending a mirrored personal message to someone else is not allowed.
Sending a mirrored personal message to someone else is not allowed.
def test_mirrored_personal_to_someone_else(self) -> None: """ Sending a mirrored personal message to someone else is not allowed. """ result = self.api_post( self.mit_user("starnine"), "/api/v1/messages", { "type": "private", ...
[ "def", "test_mirrored_personal_to_someone_else", "(", "self", ")", "->", "None", ":", "result", "=", "self", ".", "api_post", "(", "self", ".", "mit_user", "(", "\"starnine\"", ")", ",", "\"/api/v1/messages\"", ",", "{", "\"type\"", ":", "\"private\"", ",", "\...
[ 817, 4 ]
[ 833, 76 ]
python
en
['en', 'error', 'th']
False
MessagePOSTTest.test_duplicated_mirrored_huddle
(self)
Sending two mirrored huddles in the row return the same ID
Sending two mirrored huddles in the row return the same ID
def test_duplicated_mirrored_huddle(self) -> None: """ Sending two mirrored huddles in the row return the same ID """ msg = { "type": "private", "sender": self.mit_email("sipbtest"), "content": "Test message", "client": "zephyr_mirror", ...
[ "def", "test_duplicated_mirrored_huddle", "(", "self", ")", "->", "None", ":", "msg", "=", "{", "\"type\"", ":", "\"private\"", ",", "\"sender\"", ":", "self", ".", "mit_email", "(", "\"sipbtest\"", ")", ",", "\"content\"", ":", "\"Test message\"", ",", "\"cli...
[ 835, 4 ]
[ 867, 98 ]
python
en
['en', 'error', 'th']
False
MessagePOSTTest.test_message_with_null_bytes
(self)
A message with null bytes in it is handled.
A message with null bytes in it is handled.
def test_message_with_null_bytes(self) -> None: """ A message with null bytes in it is handled. """ self.login("hamlet") post_data = { "type": "stream", "to": "Verona", "client": "test suite", "content": " I like null bytes \x00 in...
[ "def", "test_message_with_null_bytes", "(", "self", ")", "->", "None", ":", "self", ".", "login", "(", "\"hamlet\"", ")", "post_data", "=", "{", "\"type\"", ":", "\"stream\"", ",", "\"to\"", ":", "\"Verona\"", ",", "\"client\"", ":", "\"test suite\"", ",", "...
[ 869, 4 ]
[ 882, 77 ]
python
en
['en', 'error', 'th']
False
MessagePOSTTest.test_strip_message
(self)
A message with mixed whitespace at the end is cleaned up.
A message with mixed whitespace at the end is cleaned up.
def test_strip_message(self) -> None: """ A message with mixed whitespace at the end is cleaned up. """ self.login("hamlet") post_data = { "type": "stream", "to": "Verona", "client": "test suite", "content": " I like whitespace at ...
[ "def", "test_strip_message", "(", "self", ")", "->", "None", ":", "self", ".", "login", "(", "\"hamlet\"", ")", "post_data", "=", "{", "\"type\"", ":", "\"stream\"", ",", "\"to\"", ":", "\"Verona\"", ",", "\"client\"", ":", "\"test suite\"", ",", "\"content\...
[ 884, 4 ]
[ 899, 81 ]
python
en
['en', 'error', 'th']
False
MessagePOSTTest.test_long_message
(self)
Sending a message longer than the maximum message length succeeds but is truncated.
Sending a message longer than the maximum message length succeeds but is truncated.
def test_long_message(self) -> None: """ Sending a message longer than the maximum message length succeeds but is truncated. """ self.login("hamlet") long_message = "A" * (MAX_MESSAGE_LENGTH + 1) post_data = { "type": "stream", "to": "Veron...
[ "def", "test_long_message", "(", "self", ")", "->", "None", ":", "self", ".", "login", "(", "\"hamlet\"", ")", "long_message", "=", "\"A\"", "*", "(", "MAX_MESSAGE_LENGTH", "+", "1", ")", "post_data", "=", "{", "\"type\"", ":", "\"stream\"", ",", "\"to\"",...
[ 901, 4 ]
[ 921, 9 ]
python
en
['en', 'error', 'th']
False
MessagePOSTTest.test_long_topic
(self)
Sending a message with a topic longer than the maximum topic length succeeds, but the topic is truncated.
Sending a message with a topic longer than the maximum topic length succeeds, but the topic is truncated.
def test_long_topic(self) -> None: """ Sending a message with a topic longer than the maximum topic length succeeds, but the topic is truncated. """ self.login("hamlet") long_topic = "A" * (MAX_TOPIC_NAME_LENGTH + 1) post_data = { "type": "stream", ...
[ "def", "test_long_topic", "(", "self", ")", "->", "None", ":", "self", ".", "login", "(", "\"hamlet\"", ")", "long_topic", "=", "\"A\"", "*", "(", "MAX_TOPIC_NAME_LENGTH", "+", "1", ")", "post_data", "=", "{", "\"type\"", ":", "\"stream\"", ",", "\"to\"", ...
[ 923, 4 ]
[ 941, 94 ]
python
en
['en', 'error', 'th']
False
StreamMessagesTest.assert_stream_message
( self, stream_name: str, topic_name: str = "test topic", content: str = "test content" )
Check that messages sent to a stream reach all subscribers to that stream.
Check that messages sent to a stream reach all subscribers to that stream.
def assert_stream_message( self, stream_name: str, topic_name: str = "test topic", content: str = "test content" ) -> None: """ Check that messages sent to a stream reach all subscribers to that stream. """ realm = get_realm("zulip") subscribers = self.users_subscribe...
[ "def", "assert_stream_message", "(", "self", ",", "stream_name", ":", "str", ",", "topic_name", ":", "str", "=", "\"test topic\"", ",", "content", ":", "str", "=", "\"test content\"", ")", "->", "None", ":", "realm", "=", "get_realm", "(", "\"zulip\"", ")", ...
[ 1417, 4 ]
[ 1464, 95 ]
python
en
['en', 'error', 'th']
False
StreamMessagesTest.test_performance
(self)
This test is part of the automated test suite, but it is more intended as an aid to measuring the performance of do_send_messages() with consistent data setup across different commits. You can modify the values below and run just this test, and then comment out the prin...
This test is part of the automated test suite, but it is more intended as an aid to measuring the performance of do_send_messages() with consistent data setup across different commits. You can modify the values below and run just this test, and then comment out the prin...
def test_performance(self) -> None: """ This test is part of the automated test suite, but it is more intended as an aid to measuring the performance of do_send_messages() with consistent data setup across different commits. You can modify the values below and run just t...
[ "def", "test_performance", "(", "self", ")", "->", "None", ":", "num_messages", "=", "2", "num_extra_users", "=", "10", "sender", "=", "self", ".", "example_user", "(", "\"cordelia\"", ")", "realm", "=", "sender", ".", "realm", "message_content", "=", "\"wha...
[ 1466, 4 ]
[ 1524, 72 ]
python
en
['en', 'error', 'th']
False
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\"", ")" ]
[ 1852, 4 ]
[ 1857, 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\"...
[ 1859, 4 ]
[ 1875, 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...
[ 1908, 4 ]
[ 1931, 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...
[ 1933, 4 ]
[ 1963, 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...
[ 1965, 4 ]
[ 1973, 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", ...
[ 1975, 4 ]
[ 1993, 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", ".",...
[ 1995, 4 ]
[ 2004, 9 ]
python
en
['en', 'error', 'th']
False
CheckMessageTest.test_bot_pm_feature
(self)
We send a PM to a bot's owner if their bot sends a message to an unsubscribed stream
We send a PM to a bot's owner if their bot sends a message to an unsubscribed stream
def test_bot_pm_feature(self) -> None: """We send a PM to a bot's owner if their bot sends a message to an unsubscribed stream""" parent = self.example_user("othello") bot = do_create_user( email="othello-bot@zulip.com", password="", realm=parent.realm...
[ "def", "test_bot_pm_feature", "(", "self", ")", "->", "None", ":", "parent", "=", "self", ".", "example_user", "(", "\"othello\"", ")", "bot", "=", "do_create_user", "(", "email", "=", "\"othello-bot@zulip.com\"", ",", "password", "=", "\"\"", ",", "realm", ...
[ 2442, 4 ]
[ 2492, 91 ]
python
en
['en', 'en', 'en']
True
hop_skip_jump_attack
( model_fn, x, norm, y_target=None, image_target=None, initial_num_evals=100, max_num_evals=10000, stepsize_search="geometric_progression", num_iterations=64, gamma=1.0, constraint=2, batch_size=128, verbose=True, clip_min=0, clip_max=1, )
PyTorch implementation of HopSkipJumpAttack. HopSkipJumpAttack was originally proposed by Chen, Jordan and Wainwright. It is a decision-based attack that requires access to output labels of a model alone. Paper link: https://arxiv.org/abs/1904.02144 At a high level, this attack is an iterative ...
PyTorch implementation of HopSkipJumpAttack. HopSkipJumpAttack was originally proposed by Chen, Jordan and Wainwright. It is a decision-based attack that requires access to output labels of a model alone. Paper link: https://arxiv.org/abs/1904.02144 At a high level, this attack is an iterative ...
def hop_skip_jump_attack( model_fn, x, norm, y_target=None, image_target=None, initial_num_evals=100, max_num_evals=10000, stepsize_search="geometric_progression", num_iterations=64, gamma=1.0, constraint=2, batch_size=128, verbose=True, clip_min=0, clip_max=1...
[ "def", "hop_skip_jump_attack", "(", "model_fn", ",", "x", ",", "norm", ",", "y_target", "=", "None", ",", "image_target", "=", "None", ",", "initial_num_evals", "=", "100", ",", "max_num_evals", "=", "10000", ",", "stepsize_search", "=", "\"geometric_progression...
[ 7, 0 ]
[ 212, 30 ]
python
en
['en', 'error', 'th']
False
compute_distance
(x_ori, x_pert, constraint=2)
Compute the distance between two images.
Compute the distance between two images.
def compute_distance(x_ori, x_pert, constraint=2): """ Compute the distance between two images. """ if constraint == 2: dist = torch.norm(x_ori - x_pert, p=2) elif constraint == np.inf: dist = torch.max(torch.abs(x_ori - x_pert)) return dist
[ "def", "compute_distance", "(", "x_ori", ",", "x_pert", ",", "constraint", "=", "2", ")", ":", "if", "constraint", "==", "2", ":", "dist", "=", "torch", ".", "norm", "(", "x_ori", "-", "x_pert", ",", "p", "=", "2", ")", "elif", "constraint", "==", ...
[ 215, 0 ]
[ 221, 15 ]
python
en
['en', 'en', 'en']
True
approximate_gradient
( decision_function, sample, num_evals, delta, constraint, shape, clip_min, clip_max )
Gradient direction estimation
Gradient direction estimation
def approximate_gradient( decision_function, sample, num_evals, delta, constraint, shape, clip_min, clip_max ): """ Gradient direction estimation """ # Generate random vectors. noise_shape = [num_evals] + list(shape) if constraint == 2: rv = torch.randn(noise_shape) elif constraint == np...
[ "def", "approximate_gradient", "(", "decision_function", ",", "sample", ",", "num_evals", ",", "delta", ",", "constraint", ",", "shape", ",", "clip_min", ",", "clip_max", ")", ":", "# Generate random vectors.", "noise_shape", "=", "[", "num_evals", "]", "+", "li...
[ 224, 0 ]
[ 258, 16 ]
python
fr
['fr', 'fr', 'en']
True
project
(original_image, perturbed_images, alphas, shape, constraint)
Projection onto given l2 / linf balls in a batch.
Projection onto given l2 / linf balls in a batch.
def project(original_image, perturbed_images, alphas, shape, constraint): """ Projection onto given l2 / linf balls in a batch. """ alphas = alphas.view((alphas.shape[0],) + (1,) * (len(shape) - 1)) if constraint == 2: projected = (1 - alphas) * original_image + alphas * perturbed_images elif co...
[ "def", "project", "(", "original_image", ",", "perturbed_images", ",", "alphas", ",", "shape", ",", "constraint", ")", ":", "alphas", "=", "alphas", ".", "view", "(", "(", "alphas", ".", "shape", "[", "0", "]", ",", ")", "+", "(", "1", ",", ")", "*...
[ 261, 0 ]
[ 270, 20 ]
python
en
['en', 'en', 'en']
True
binary_search_batch
( original_image, perturbed_images, decision_function, shape, constraint, theta )
Binary search to approach the boundary.
Binary search to approach the boundary.
def binary_search_batch( original_image, perturbed_images, decision_function, shape, constraint, theta ): """ Binary search to approach the boundary. """ # Compute distance between each of perturbed image and original image. dists_post_update = torch.stack( [ compute_distance(origin...
[ "def", "binary_search_batch", "(", "original_image", ",", "perturbed_images", ",", "decision_function", ",", "shape", ",", "constraint", ",", "theta", ")", ":", "# Compute distance between each of perturbed image and original image.", "dists_post_update", "=", "torch", ".", ...
[ 273, 0 ]
[ 321, 26 ]
python
en
['en', 'en', 'en']
True
initialize
(decision_function, sample, shape, clip_min, clip_max)
Efficient Implementation of BlendedUniformNoiseAttack in Foolbox.
Efficient Implementation of BlendedUniformNoiseAttack in Foolbox.
def initialize(decision_function, sample, shape, clip_min, clip_max): """ Efficient Implementation of BlendedUniformNoiseAttack in Foolbox. """ success = 0 num_evals = 0 # Find a misclassified random noise. while True: random_noise = clip_min + torch.rand(shape).to(sample.device) * ...
[ "def", "initialize", "(", "decision_function", ",", "sample", ",", "shape", ",", "clip_min", ",", "clip_max", ")", ":", "success", "=", "0", "num_evals", "=", "0", "# Find a misclassified random noise.", "while", "True", ":", "random_noise", "=", "clip_min", "+"...
[ 324, 0 ]
[ 358, 25 ]
python
en
['en', 'error', 'th']
False
geometric_progression_for_stepsize
( x, update, dist, decision_function, current_iteration )
Geometric progression to search for stepsize. Keep decreasing stepsize by half until reaching the desired side of the boundary.
Geometric progression to search for stepsize. Keep decreasing stepsize by half until reaching the desired side of the boundary.
def geometric_progression_for_stepsize( x, update, dist, decision_function, current_iteration ): """Geometric progression to search for stepsize. Keep decreasing stepsize by half until reaching the desired side of the boundary. """ epsilon = dist / np.sqrt(current_iteration) while True: ...
[ "def", "geometric_progression_for_stepsize", "(", "x", ",", "update", ",", "dist", ",", "decision_function", ",", "current_iteration", ")", ":", "epsilon", "=", "dist", "/", "np", ".", "sqrt", "(", "current_iteration", ")", "while", "True", ":", "updated", "="...
[ 361, 0 ]
[ 377, 18 ]
python
en
['en', 'en', 'en']
True
select_delta
( dist_post_update, current_iteration, clip_max, clip_min, d, theta, constraint )
Choose the delta at the scale of distance between x and perturbed sample.
Choose the delta at the scale of distance between x and perturbed sample.
def select_delta( dist_post_update, current_iteration, clip_max, clip_min, d, theta, constraint ): """ Choose the delta at the scale of distance between x and perturbed sample. """ if current_iteration == 1: delta = 0.1 * (clip_max - clip_min) else: if constraint == 2: ...
[ "def", "select_delta", "(", "dist_post_update", ",", "current_iteration", ",", "clip_max", ",", "clip_min", ",", "d", ",", "theta", ",", "constraint", ")", ":", "if", "current_iteration", "==", "1", ":", "delta", "=", "0.1", "*", "(", "clip_max", "-", "cli...
[ 380, 0 ]
[ 395, 16 ]
python
en
['en', 'error', 'th']
False
lookup
(code, _cache={})
Lookup an error code or class code and return its symbolic name. Raise `KeyError` if the code is not found.
Lookup an error code or class code and return its symbolic name.
def lookup(code, _cache={}): """Lookup an error code or class code and return its symbolic name. Raise `KeyError` if the code is not found. """ if _cache: return _cache[code] # Generate the lookup map at first usage. tmp = {} for k, v in globals().items(): if isinstance(v, ...
[ "def", "lookup", "(", "code", ",", "_cache", "=", "{", "}", ")", ":", "if", "_cache", ":", "return", "_cache", "[", "code", "]", "# Generate the lookup map at first usage.", "tmp", "=", "{", "}", "for", "k", ",", "v", "in", "globals", "(", ")", ".", ...
[ 33, 0 ]
[ 52, 23 ]
python
en
['en', 'en', 'en']
True
inject_into_urllib3
()
Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.
Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.
def inject_into_urllib3(): "Monkey-patch urllib3 with PyOpenSSL-backed SSL-support." _validate_dependencies_met() util.SSLContext = PyOpenSSLContext util.ssl_.SSLContext = PyOpenSSLContext util.HAS_SNI = HAS_SNI util.ssl_.HAS_SNI = HAS_SNI util.IS_PYOPENSSL = True util.ssl_.IS_PYOPENSS...
[ "def", "inject_into_urllib3", "(", ")", ":", "_validate_dependencies_met", "(", ")", "util", ".", "SSLContext", "=", "PyOpenSSLContext", "util", ".", "ssl_", ".", "SSLContext", "=", "PyOpenSSLContext", "util", ".", "HAS_SNI", "=", "HAS_SNI", "util", ".", "ssl_",...
[ 114, 0 ]
[ 124, 33 ]
python
en
['en', 'en', 'en']
True
extract_from_urllib3
()
Undo monkey-patching by :func:`inject_into_urllib3`.
Undo monkey-patching by :func:`inject_into_urllib3`.
def extract_from_urllib3(): "Undo monkey-patching by :func:`inject_into_urllib3`." util.SSLContext = orig_util_SSLContext util.ssl_.SSLContext = orig_util_SSLContext util.HAS_SNI = orig_util_HAS_SNI util.ssl_.HAS_SNI = orig_util_HAS_SNI util.IS_PYOPENSSL = False util.ssl_.IS_PYOPENSSL = Fal...
[ "def", "extract_from_urllib3", "(", ")", ":", "util", ".", "SSLContext", "=", "orig_util_SSLContext", "util", ".", "ssl_", ".", "SSLContext", "=", "orig_util_SSLContext", "util", ".", "HAS_SNI", "=", "orig_util_HAS_SNI", "util", ".", "ssl_", ".", "HAS_SNI", "=",...
[ 127, 0 ]
[ 135, 34 ]
python
en
['en', 'ny', 'sw']
False
_validate_dependencies_met
()
Verifies that PyOpenSSL's package-level dependencies have been met. Throws `ImportError` if they are not met.
Verifies that PyOpenSSL's package-level dependencies have been met. Throws `ImportError` if they are not met.
def _validate_dependencies_met(): """ Verifies that PyOpenSSL's package-level dependencies have been met. Throws `ImportError` if they are not met. """ # Method added in `cryptography==1.1`; not available in older versions from cryptography.x509.extensions import Extensions if getattr(Exten...
[ "def", "_validate_dependencies_met", "(", ")", ":", "# Method added in `cryptography==1.1`; not available in older versions", "from", "cryptography", ".", "x509", ".", "extensions", "import", "Extensions", "if", "getattr", "(", "Extensions", ",", "\"get_extension_for_class\"", ...
[ 138, 0 ]
[ 161, 9 ]
python
en
['en', 'error', 'th']
False
_dnsname_to_stdlib
(name)
Converts a dNSName SubjectAlternativeName field to the form used by the standard library on the given Python version. Cryptography produces a dNSName as a unicode string that was idna-decoded from ASCII bytes. We need to idna-encode that string to get it back, and then on Python 3 we also need to ...
Converts a dNSName SubjectAlternativeName field to the form used by the standard library on the given Python version.
def _dnsname_to_stdlib(name): """ Converts a dNSName SubjectAlternativeName field to the form used by the standard library on the given Python version. Cryptography produces a dNSName as a unicode string that was idna-decoded from ASCII bytes. We need to idna-encode that string to get it back, and ...
[ "def", "_dnsname_to_stdlib", "(", "name", ")", ":", "def", "idna_encode", "(", "name", ")", ":", "\"\"\"\n Borrowed wholesale from the Python Cryptography Project. It turns out\n that we can't just safely call `idna.encode`: it can explode for\n wildcard names. This avoi...
[ 164, 0 ]
[ 204, 15 ]
python
en
['en', 'error', 'th']
False
get_subj_alt_name
(peer_cert)
Given an PyOpenSSL certificate, provides all the subject alternative names.
Given an PyOpenSSL certificate, provides all the subject alternative names.
def get_subj_alt_name(peer_cert): """ Given an PyOpenSSL certificate, provides all the subject alternative names. """ # Pass the cert to cryptography, which has much better APIs for this. if hasattr(peer_cert, "to_cryptography"): cert = peer_cert.to_cryptography() else: # This is...
[ "def", "get_subj_alt_name", "(", "peer_cert", ")", ":", "# Pass the cert to cryptography, which has much better APIs for this.", "if", "hasattr", "(", "peer_cert", ",", "\"to_cryptography\"", ")", ":", "cert", "=", "peer_cert", ".", "to_cryptography", "(", ")", "else", ...
[ 207, 0 ]
[ 258, 16 ]
python
en
['en', 'error', 'th']
False
DynamicLayoutHandler.all
(self)
Returns all layout objects of first level of depth
Returns all layout objects of first level of depth
def all(self): """ Returns all layout objects of first level of depth """ self._check_layout() return LayoutSlice(self.layout, slice(0, len(self.layout.fields), 1))
[ "def", "all", "(", "self", ")", ":", "self", ".", "_check_layout", "(", ")", "return", "LayoutSlice", "(", "self", ".", "layout", ",", "slice", "(", "0", ",", "len", "(", "self", ".", "layout", ".", "fields", ")", ",", "1", ")", ")" ]
[ 21, 4 ]
[ 26, 77 ]
python
en
['en', 'ja', 'th']
False
DynamicLayoutHandler.filter
(self, *LayoutClasses, **kwargs)
Returns a LayoutSlice pointing to layout objects of type `LayoutClass`
Returns a LayoutSlice pointing to layout objects of type `LayoutClass`
def filter(self, *LayoutClasses, **kwargs): """ Returns a LayoutSlice pointing to layout objects of type `LayoutClass` """ self._check_layout() max_level = kwargs.pop("max_level", 0) greedy = kwargs.pop("greedy", False) filtered_layout_objects = self.layout...
[ "def", "filter", "(", "self", ",", "*", "LayoutClasses", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_check_layout", "(", ")", "max_level", "=", "kwargs", ".", "pop", "(", "\"max_level\"", ",", "0", ")", "greedy", "=", "kwargs", ".", "pop", "(",...
[ 28, 4 ]
[ 37, 64 ]
python
en
['en', 'ja', 'th']
False
DynamicLayoutHandler.filter_by_widget
(self, widget_type)
Returns a LayoutSlice pointing to fields with widgets of `widget_type`
Returns a LayoutSlice pointing to fields with widgets of `widget_type`
def filter_by_widget(self, widget_type): """ Returns a LayoutSlice pointing to fields with widgets of `widget_type` """ self._check_layout_and_form() layout_field_names = self.layout.get_field_names() # Let's filter all fields with widgets like widget_type ...
[ "def", "filter_by_widget", "(", "self", ",", "widget_type", ")", ":", "self", ".", "_check_layout_and_form", "(", ")", "layout_field_names", "=", "self", ".", "layout", ".", "get_field_names", "(", ")", "# Let's filter all fields with widgets like widget_type\r", "filte...
[ 39, 4 ]
[ 52, 56 ]
python
en
['en', 'ja', 'th']
False
DynamicLayoutHandler.exclude_by_widget
(self, widget_type)
Returns a LayoutSlice pointing to fields with widgets NOT matching `widget_type`
Returns a LayoutSlice pointing to fields with widgets NOT matching `widget_type`
def exclude_by_widget(self, widget_type): """ Returns a LayoutSlice pointing to fields with widgets NOT matching `widget_type` """ self._check_layout_and_form() layout_field_names = self.layout.get_field_names() # Let's exclude all fields with widgets like widget_...
[ "def", "exclude_by_widget", "(", "self", ",", "widget_type", ")", ":", "self", ".", "_check_layout_and_form", "(", ")", "layout_field_names", "=", "self", ".", "layout", ".", "get_field_names", "(", ")", "# Let's exclude all fields with widgets like widget_type\r", "fil...
[ 54, 4 ]
[ 67, 56 ]
python
en
['en', 'ja', 'th']
False
DynamicLayoutHandler.__getitem__
(self, key)
Return a LayoutSlice that makes changes affect the current instance of the layout and not a copy.
Return a LayoutSlice that makes changes affect the current instance of the layout and not a copy.
def __getitem__(self, key): """ Return a LayoutSlice that makes changes affect the current instance of the layout and not a copy. """ # when key is a string containing the field name if isinstance(key, str): # Django templates access FormHelper attribut...
[ "def", "__getitem__", "(", "self", ",", "key", ")", ":", "# when key is a string containing the field name\r", "if", "isinstance", "(", "key", ",", "str", ")", ":", "# Django templates access FormHelper attributes using dictionary [] operator\r", "# This could be a helper['form_i...
[ 69, 4 ]
[ 92, 44 ]
python
en
['en', 'ja', 'th']
False
FormHelper.render_layout
(self, form, context, template_pack=TEMPLATE_PACK)
Returns safe html of the rendering of the layout
Returns safe html of the rendering of the layout
def render_layout(self, form, context, template_pack=TEMPLATE_PACK): """ Returns safe html of the rendering of the layout """ form.rendered_fields = set() form.crispy_field_template = self.field_template # This renders the specified Layout strictly html =...
[ "def", "render_layout", "(", "self", ",", "form", ",", "context", ",", "template_pack", "=", "TEMPLATE_PACK", ")", ":", "form", ".", "rendered_fields", "=", "set", "(", ")", "form", ".", "crispy_field_template", "=", "self", ".", "field_template", "# This rend...
[ 292, 4 ]
[ 314, 30 ]
python
en
['en', 'ja', 'th']
False
FormHelper.get_attributes
(self, template_pack=TEMPLATE_PACK)
Used by crispy_forms_tags to get helper attributes
Used by crispy_forms_tags to get helper attributes
def get_attributes(self, template_pack=TEMPLATE_PACK): # noqa: C901 """ Used by crispy_forms_tags to get helper attributes """ items = { "disable_csrf": self.disable_csrf, "error_text_inline": self.error_text_inline, "field_class": self.field_c...
[ "def", "get_attributes", "(", "self", ",", "template_pack", "=", "TEMPLATE_PACK", ")", ":", "# noqa: C901\r", "items", "=", "{", "\"disable_csrf\"", ":", "self", ".", "disable_csrf", ",", "\"error_text_inline\"", ":", "self", ".", "error_text_inline", ",", "\"fiel...
[ 316, 4 ]
[ 387, 20 ]
python
en
['en', 'ja', 'th']
False
SelectRelatedTests.create_tree
(self, stringtree)
Helper to create a complete tree.
Helper to create a complete tree.
def create_tree(self, stringtree): """ Helper to create a complete tree. """ names = stringtree.split() models = [Domain, Kingdom, Phylum, Klass, Order, Family, Genus, Species] assert len(names) == len(models), (names, models) parent = None for name, mode...
[ "def", "create_tree", "(", "self", ",", "stringtree", ")", ":", "names", "=", "stringtree", ".", "split", "(", ")", "models", "=", "[", "Domain", ",", "Kingdom", ",", "Phylum", ",", "Klass", ",", "Order", ",", "Family", ",", "Genus", ",", "Species", ...
[ 9, 4 ]
[ 26, 24 ]
python
en
['en', 'error', 'th']
False
SelectRelatedTests.test_access_fks_without_select_related
(self)
Normally, accessing FKs doesn't fill in related objects
Normally, accessing FKs doesn't fill in related objects
def test_access_fks_without_select_related(self): """ Normally, accessing FKs doesn't fill in related objects """ with self.assertNumQueries(8): fly = Species.objects.get(name="melanogaster") domain = fly.genus.family.order.klass.phylum.kingdom.domain ...
[ "def", "test_access_fks_without_select_related", "(", "self", ")", ":", "with", "self", ".", "assertNumQueries", "(", "8", ")", ":", "fly", "=", "Species", ".", "objects", ".", "get", "(", "name", "=", "\"melanogaster\"", ")", "domain", "=", "fly", ".", "g...
[ 40, 4 ]
[ 47, 54 ]
python
en
['en', 'error', 'th']
False
SelectRelatedTests.test_access_fks_with_select_related
(self)
A select_related() call will fill in those related objects without any extra queries
A select_related() call will fill in those related objects without any extra queries
def test_access_fks_with_select_related(self): """ A select_related() call will fill in those related objects without any extra queries """ with self.assertNumQueries(1): person = Species.objects.select_related('genus__family__order__klass__phylum__kingdom__domain').g...
[ "def", "test_access_fks_with_select_related", "(", "self", ")", ":", "with", "self", ".", "assertNumQueries", "(", "1", ")", ":", "person", "=", "Species", ".", "objects", ".", "select_related", "(", "'genus__family__order__klass__phylum__kingdom__domain'", ")", ".", ...
[ 49, 4 ]
[ 57, 54 ]
python
en
['en', 'error', 'th']
False
SelectRelatedTests.test_list_without_select_related
(self)
select_related() also of course applies to entire lists, not just items. This test verifies the expected behavior without select_related.
select_related() also of course applies to entire lists, not just items. This test verifies the expected behavior without select_related.
def test_list_without_select_related(self): """ select_related() also of course applies to entire lists, not just items. This test verifies the expected behavior without select_related. """ with self.assertNumQueries(9): world = Species.objects.all() famil...
[ "def", "test_list_without_select_related", "(", "self", ")", ":", "with", "self", ".", "assertNumQueries", "(", "9", ")", ":", "world", "=", "Species", ".", "objects", ".", "all", "(", ")", "families", "=", "[", "o", ".", "genus", ".", "family", ".", "...
[ 59, 4 ]
[ 72, 14 ]
python
en
['en', 'error', 'th']
False
SelectRelatedTests.test_list_with_select_related
(self)
select_related() also of course applies to entire lists, not just items. This test verifies the expected behavior with select_related.
select_related() also of course applies to entire lists, not just items. This test verifies the expected behavior with select_related.
def test_list_with_select_related(self): """ select_related() also of course applies to entire lists, not just items. This test verifies the expected behavior with select_related. """ with self.assertNumQueries(1): world = Species.objects.all().select_related() ...
[ "def", "test_list_with_select_related", "(", "self", ")", ":", "with", "self", ".", "assertNumQueries", "(", "1", ")", ":", "world", "=", "Species", ".", "objects", ".", "all", "(", ")", ".", "select_related", "(", ")", "families", "=", "[", "o", ".", ...
[ 74, 4 ]
[ 87, 14 ]
python
en
['en', 'error', 'th']
False
SelectRelatedTests.test_list_with_depth
(self)
Passing a relationship field lookup specifier to select_related() will stop the descent at a particular level. This can be used on lists as well.
Passing a relationship field lookup specifier to select_related() will stop the descent at a particular level. This can be used on lists as well.
def test_list_with_depth(self): """ Passing a relationship field lookup specifier to select_related() will stop the descent at a particular level. This can be used on lists as well. """ with self.assertNumQueries(5): world = Species.objects.all().select_relate...
[ "def", "test_list_with_depth", "(", "self", ")", ":", "with", "self", ".", "assertNumQueries", "(", "5", ")", ":", "world", "=", "Species", ".", "objects", ".", "all", "(", ")", ".", "select_related", "(", "'genus__family'", ")", "orders", "=", "[", "o",...
[ 89, 4 ]
[ 99, 65 ]
python
en
['en', 'error', 'th']
False
SelectRelatedTests.test_certain_fields
(self)
The optional fields passed to select_related() control which related models we pull in. This allows for smaller queries. In this case, we explicitly say to select the 'genus' and 'genus.family' models, leading to the same number of queries as before.
The optional fields passed to select_related() control which related models we pull in. This allows for smaller queries.
def test_certain_fields(self): """ The optional fields passed to select_related() control which related models we pull in. This allows for smaller queries. In this case, we explicitly say to select the 'genus' and 'genus.family' models, leading to the same number of queries as b...
[ "def", "test_certain_fields", "(", "self", ")", ":", "with", "self", ".", "assertNumQueries", "(", "1", ")", ":", "world", "=", "Species", ".", "objects", ".", "select_related", "(", "'genus__family'", ")", "families", "=", "[", "o", ".", "genus", ".", "...
[ 107, 4 ]
[ 119, 73 ]
python
en
['en', 'error', 'th']
False
SelectRelatedTests.test_more_certain_fields
(self)
In this case, we explicitly say to select the 'genus' and 'genus.family' models, leading to the same number of queries as before.
In this case, we explicitly say to select the 'genus' and 'genus.family' models, leading to the same number of queries as before.
def test_more_certain_fields(self): """ In this case, we explicitly say to select the 'genus' and 'genus.family' models, leading to the same number of queries as before. """ with self.assertNumQueries(2): world = Species.objects.filter(genus__name='Amanita')\ ...
[ "def", "test_more_certain_fields", "(", "self", ")", ":", "with", "self", ".", "assertNumQueries", "(", "2", ")", ":", "world", "=", "Species", ".", "objects", ".", "filter", "(", "genus__name", "=", "'Amanita'", ")", ".", "select_related", "(", "'genus__fam...
[ 121, 4 ]
[ 130, 52 ]
python
en
['en', 'error', 'th']
False
_contains_egg_info
( s, _egg_info_re=re.compile(r'([a-z0-9_.]+)-([a-z0-9_.!+-]+)', re.I))
Determine whether the string looks like an egg_info. :param s: The string to parse. E.g. foo-2.1
Determine whether the string looks like an egg_info.
def _contains_egg_info( s, _egg_info_re=re.compile(r'([a-z0-9_.]+)-([a-z0-9_.!+-]+)', re.I)): # type: (str, Pattern[str]) -> bool """Determine whether the string looks like an egg_info. :param s: The string to parse. E.g. foo-2.1 """ return bool(_egg_info_re.search(s))
[ "def", "_contains_egg_info", "(", "s", ",", "_egg_info_re", "=", "re", ".", "compile", "(", "r'([a-z0-9_.]+)-([a-z0-9_.!+-]+)'", ",", "re", ".", "I", ")", ")", ":", "# type: (str, Pattern[str]) -> bool", "return", "bool", "(", "_egg_info_re", ".", "search", "(", ...
[ 37, 0 ]
[ 44, 39 ]
python
en
['en', 'en', 'en']
True
_should_build
( req, # type: InstallRequirement need_wheel, # type: bool check_binary_allowed, # type: BinaryAllowedPredicate )
Return whether an InstallRequirement should be built into a wheel.
Return whether an InstallRequirement should be built into a wheel.
def _should_build( req, # type: InstallRequirement need_wheel, # type: bool check_binary_allowed, # type: BinaryAllowedPredicate ): # type: (...) -> bool """Return whether an InstallRequirement should be built into a wheel.""" if req.constraint: # never build requirements that are mer...
[ "def", "_should_build", "(", "req", ",", "# type: InstallRequirement", "need_wheel", ",", "# type: bool", "check_binary_allowed", ",", "# type: BinaryAllowedPredicate", ")", ":", "# type: (...) -> bool", "if", "req", ".", "constraint", ":", "# never build requirements that ar...
[ 47, 0 ]
[ 89, 15 ]
python
en
['en', 'en', 'en']
True
_should_cache
( req, # type: InstallRequirement )
Return whether a built InstallRequirement can be stored in the persistent wheel cache, assuming the wheel cache is available, and _should_build() has determined a wheel needs to be built.
Return whether a built InstallRequirement can be stored in the persistent wheel cache, assuming the wheel cache is available, and _should_build() has determined a wheel needs to be built.
def _should_cache( req, # type: InstallRequirement ): # type: (...) -> Optional[bool] """ Return whether a built InstallRequirement can be stored in the persistent wheel cache, assuming the wheel cache is available, and _should_build() has determined a wheel needs to be built. """ if no...
[ "def", "_should_cache", "(", "req", ",", "# type: InstallRequirement", ")", ":", "# type: (...) -> Optional[bool]", "if", "not", "should_build_for_install_command", "(", "req", ",", "check_binary_allowed", "=", "_always_true", ")", ":", "# never cache if pip install would not...
[ 111, 0 ]
[ 143, 16 ]
python
en
['en', 'error', 'th']
False
_get_cache_dir
( req, # type: InstallRequirement wheel_cache, # type: WheelCache )
Return the persistent or temporary cache directory where the built wheel need to be stored.
Return the persistent or temporary cache directory where the built wheel need to be stored.
def _get_cache_dir( req, # type: InstallRequirement wheel_cache, # type: WheelCache ): # type: (...) -> str """Return the persistent or temporary cache directory where the built wheel need to be stored. """ cache_available = bool(wheel_cache.cache_dir) if cache_available and _should_ca...
[ "def", "_get_cache_dir", "(", "req", ",", "# type: InstallRequirement", "wheel_cache", ",", "# type: WheelCache", ")", ":", "# type: (...) -> str", "cache_available", "=", "bool", "(", "wheel_cache", ".", "cache_dir", ")", "if", "cache_available", "and", "_should_cache"...
[ 146, 0 ]
[ 159, 20 ]
python
en
['en', 'en', 'en']
True
_build_one
( req, # type: InstallRequirement output_dir, # type: str build_options, # type: List[str] global_options, # type: List[str] )
Build one wheel. :return: The filename of the built wheel, or None if the build failed.
Build one wheel.
def _build_one( req, # type: InstallRequirement output_dir, # type: str build_options, # type: List[str] global_options, # type: List[str] ): # type: (...) -> Optional[str] """Build one wheel. :return: The filename of the built wheel, or None if the build failed. """ try: ...
[ "def", "_build_one", "(", "req", ",", "# type: InstallRequirement", "output_dir", ",", "# type: str", "build_options", ",", "# type: List[str]", "global_options", ",", "# type: List[str]", ")", ":", "# type: (...) -> Optional[str]", "try", ":", "ensure_dir", "(", "output_...
[ 167, 0 ]
[ 191, 9 ]
python
en
['en', 'sr', 'en']
True
build
( requirements, # type: Iterable[InstallRequirement] wheel_cache, # type: WheelCache build_options, # type: List[str] global_options, # type: List[str] )
Build wheels. :return: The list of InstallRequirement that succeeded to build and the list of InstallRequirement that failed to build.
Build wheels.
def build( requirements, # type: Iterable[InstallRequirement] wheel_cache, # type: WheelCache build_options, # type: List[str] global_options, # type: List[str] ): # type: (...) -> BuildResult """Build wheels. :return: The list of InstallRequirement that succeeded to build and t...
[ "def", "build", "(", "requirements", ",", "# type: Iterable[InstallRequirement]", "wheel_cache", ",", "# type: WheelCache", "build_options", ",", "# type: List[str]", "global_options", ",", "# type: List[str]", ")", ":", "# type: (...) -> BuildResult", "if", "not", "requireme...
[ 259, 0 ]
[ 308, 42 ]
python
en
['en', 'sr', 'en']
False
Filter.__init__
(self, source, require_matching_tags=True)
Creates a Filter :arg source: the source token stream :arg require_matching_tags: whether or not to require matching tags
Creates a Filter
def __init__(self, source, require_matching_tags=True): """Creates a Filter :arg source: the source token stream :arg require_matching_tags: whether or not to require matching tags """ super(Filter, self).__init__(source) self.require_matching_tags = require_matching_t...
[ "def", "__init__", "(", "self", ",", "source", ",", "require_matching_tags", "=", "True", ")", ":", "super", "(", "Filter", ",", "self", ")", ".", "__init__", "(", "source", ")", "self", ".", "require_matching_tags", "=", "require_matching_tags" ]
[ 17, 4 ]
[ 26, 58 ]
python
en
['en', 'gl', 'en']
True
xframe_options_deny
(view_func)
Modifies a view function so its response has the X-Frame-Options HTTP header set to 'DENY' as long as the response doesn't already have that header set. e.g. @xframe_options_deny def some_view(request): ...
Modifies a view function so its response has the X-Frame-Options HTTP header set to 'DENY' as long as the response doesn't already have that header set.
def xframe_options_deny(view_func): """ Modifies a view function so its response has the X-Frame-Options HTTP header set to 'DENY' as long as the response doesn't already have that header set. e.g. @xframe_options_deny def some_view(request): ... """ def wrapped_view(*args...
[ "def", "xframe_options_deny", "(", "view_func", ")", ":", "def", "wrapped_view", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "resp", "=", "view_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "resp", ".", "get", "(", "'X-Frame-O...
[ 5, 0 ]
[ 23, 78 ]
python
en
['en', 'error', 'th']
False
xframe_options_sameorigin
(view_func)
Modifies a view function so its response has the X-Frame-Options HTTP header set to 'SAMEORIGIN' as long as the response doesn't already have that header set. e.g. @xframe_options_sameorigin def some_view(request): ...
Modifies a view function so its response has the X-Frame-Options HTTP header set to 'SAMEORIGIN' as long as the response doesn't already have that header set.
def xframe_options_sameorigin(view_func): """ Modifies a view function so its response has the X-Frame-Options HTTP header set to 'SAMEORIGIN' as long as the response doesn't already have that header set. e.g. @xframe_options_sameorigin def some_view(request): ... """ def ...
[ "def", "xframe_options_sameorigin", "(", "view_func", ")", ":", "def", "wrapped_view", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "resp", "=", "view_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "resp", ".", "get", "(", "'X-F...
[ 26, 0 ]
[ 44, 78 ]
python
en
['en', 'error', 'th']
False
xframe_options_exempt
(view_func)
Modifies a view function by setting a response variable that instructs XFrameOptionsMiddleware to NOT set the X-Frame-Options HTTP header. e.g. @xframe_options_exempt def some_view(request): ...
Modifies a view function by setting a response variable that instructs XFrameOptionsMiddleware to NOT set the X-Frame-Options HTTP header.
def xframe_options_exempt(view_func): """ Modifies a view function by setting a response variable that instructs XFrameOptionsMiddleware to NOT set the X-Frame-Options HTTP header. e.g. @xframe_options_exempt def some_view(request): ... """ def wrapped_view(*args, **kwargs): ...
[ "def", "xframe_options_exempt", "(", "view_func", ")", ":", "def", "wrapped_view", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "resp", "=", "view_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "resp", ".", "xframe_options_exempt", "=", ...
[ 47, 0 ]
[ 63, 78 ]
python
en
['en', 'error', 'th']
False
tokenize
(sql, encoding=None)
Tokenize sql. Tokenize *sql* using the :class:`Lexer` and return a 2-tuple stream of ``(token type, value)`` items.
Tokenize sql.
def tokenize(sql, encoding=None): """Tokenize sql. Tokenize *sql* using the :class:`Lexer` and return a 2-tuple stream of ``(token type, value)`` items. """ return Lexer().get_tokens(sql, encoding)
[ "def", "tokenize", "(", "sql", ",", "encoding", "=", "None", ")", ":", "return", "Lexer", "(", ")", ".", "get_tokens", "(", "sql", ",", "encoding", ")" ]
[ 75, 0 ]
[ 81, 44 ]
python
nl
['nl', 'sl', 'tr']
False
Lexer.get_tokens
(text, encoding=None)
Return an iterable of (tokentype, value) pairs generated from `text`. If `unfiltered` is set to `True`, the filtering mechanism is bypassed even if filters are defined. Also preprocess the text, i.e. expand tabs and strip it if wanted and applies registered filters. Sp...
Return an iterable of (tokentype, value) pairs generated from `text`. If `unfiltered` is set to `True`, the filtering mechanism is bypassed even if filters are defined.
def get_tokens(text, encoding=None): """ Return an iterable of (tokentype, value) pairs generated from `text`. If `unfiltered` is set to `True`, the filtering mechanism is bypassed even if filters are defined. Also preprocess the text, i.e. expand tabs and strip it if wa...
[ "def", "get_tokens", "(", "text", ",", "encoding", "=", "None", ")", ":", "if", "isinstance", "(", "text", ",", "file_types", ")", ":", "text", "=", "text", ".", "read", "(", ")", "if", "isinstance", "(", "text", ",", "text_type", ")", ":", "pass", ...
[ 27, 4 ]
[ 72, 40 ]
python
en
['en', 'error', 'th']
False
batch_indices
(batch_nb, data_length, batch_size)
This helper function computes a batch start and end index :param batch_nb: the batch number :param data_length: the total length of the data being parsed by batches :param batch_size: the number of inputs in each batch :return: pair of (start, end) indices
This helper function computes a batch start and end index :param batch_nb: the batch number :param data_length: the total length of the data being parsed by batches :param batch_size: the number of inputs in each batch :return: pair of (start, end) indices
def batch_indices(batch_nb, data_length, batch_size): """ This helper function computes a batch start and end index :param batch_nb: the batch number :param data_length: the total length of the data being parsed by batches :param batch_size: the number of inputs in each batch :return: pair of (s...
[ "def", "batch_indices", "(", "batch_nb", ",", "data_length", ",", "batch_size", ")", ":", "# Batch start and end index", "start", "=", "int", "(", "batch_nb", "*", "batch_size", ")", "end", "=", "int", "(", "(", "batch_nb", "+", "1", ")", "*", "batch_size", ...
[ 75, 0 ]
[ 94, 21 ]
python
en
['en', 'error', 'th']
False
other_classes
(nb_classes, class_ind)
Returns a list of class indices excluding the class indexed by class_ind :param nb_classes: number of classes in the task :param class_ind: the class index to be omitted :return: list of class indices excluding the class indexed by class_ind
Returns a list of class indices excluding the class indexed by class_ind :param nb_classes: number of classes in the task :param class_ind: the class index to be omitted :return: list of class indices excluding the class indexed by class_ind
def other_classes(nb_classes, class_ind): """ Returns a list of class indices excluding the class indexed by class_ind :param nb_classes: number of classes in the task :param class_ind: the class index to be omitted :return: list of class indices excluding the class indexed by class_ind """ ...
[ "def", "other_classes", "(", "nb_classes", ",", "class_ind", ")", ":", "if", "class_ind", "<", "0", "or", "class_ind", ">=", "nb_classes", ":", "error_str", "=", "\"class_ind must be within the range (0, nb_classes - 1)\"", "raise", "ValueError", "(", "error_str", ")"...
[ 97, 0 ]
[ 111, 29 ]
python
en
['en', 'error', 'th']
False
to_categorical
(y, nb_classes, num_classes=None)
Converts a class vector (integers) to binary class matrix. This is adapted from the Keras function with the same name. :param y: class vector to be converted into a matrix (integers from 0 to nb_classes). :param nb_classes: nb_classes: total number of classes. :param num_classses: dep...
Converts a class vector (integers) to binary class matrix. This is adapted from the Keras function with the same name. :param y: class vector to be converted into a matrix (integers from 0 to nb_classes). :param nb_classes: nb_classes: total number of classes. :param num_classses: dep...
def to_categorical(y, nb_classes, num_classes=None): """ Converts a class vector (integers) to binary class matrix. This is adapted from the Keras function with the same name. :param y: class vector to be converted into a matrix (integers from 0 to nb_classes). :param nb_classes: nb_cl...
[ "def", "to_categorical", "(", "y", ",", "nb_classes", ",", "num_classes", "=", "None", ")", ":", "if", "num_classes", "is", "not", "None", ":", "if", "nb_classes", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Should not specify both nb_classes and it...
[ 114, 0 ]
[ 140, 22 ]
python
en
['en', 'error', 'th']
False
random_targets
(gt, nb_classes)
Take in an array of correct labels and randomly select a different label for each label in the array. This is typically used to randomly select a target class in targeted adversarial examples attacks (i.e., when the search algorithm takes in both a source class and target class to compute the adver...
Take in an array of correct labels and randomly select a different label for each label in the array. This is typically used to randomly select a target class in targeted adversarial examples attacks (i.e., when the search algorithm takes in both a source class and target class to compute the adver...
def random_targets(gt, nb_classes): """ Take in an array of correct labels and randomly select a different label for each label in the array. This is typically used to randomly select a target class in targeted adversarial examples attacks (i.e., when the search algorithm takes in both a source clas...
[ "def", "random_targets", "(", "gt", ",", "nb_classes", ")", ":", "# If the ground truth labels are encoded as one-hot, convert to labels.", "if", "len", "(", "gt", ".", "shape", ")", "==", "2", ":", "gt", "=", "np", ".", "argmax", "(", "gt", ",", "axis", "=", ...
[ 143, 0 ]
[ 180, 17 ]
python
en
['en', 'error', 'th']
False
pair_visual
(*args, **kwargs)
Deprecation wrapper
Deprecation wrapper
def pair_visual(*args, **kwargs): """Deprecation wrapper""" warnings.warn( "`pair_visual` has moved to `cleverhans.plot.pyplot_image`. " "cleverhans.utils.pair_visual may be removed on or after " "2019-04-24." ) from cleverhans.plot.pyplot_image import pair_visual as new_pair_vis...
[ "def", "pair_visual", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "\"`pair_visual` has moved to `cleverhans.plot.pyplot_image`. \"", "\"cleverhans.utils.pair_visual may be removed on or after \"", "\"2019-04-24.\"", ")", "from", "cleverh...
[ 183, 0 ]
[ 192, 43 ]
python
en
['en', 'pt', 'en']
False
grid_visual
(*args, **kwargs)
Deprecation wrapper
Deprecation wrapper
def grid_visual(*args, **kwargs): """Deprecation wrapper""" warnings.warn( "`grid_visual` has moved to `cleverhans.plot.pyplot_image`. " "cleverhans.utils.grid_visual may be removed on or after " "2019-04-24." ) from cleverhans.plot.pyplot_image import grid_visual as new_grid_vis...
[ "def", "grid_visual", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "\"`grid_visual` has moved to `cleverhans.plot.pyplot_image`. \"", "\"cleverhans.utils.grid_visual may be removed on or after \"", "\"2019-04-24.\"", ")", "from", "cleverh...
[ 195, 0 ]
[ 204, 43 ]
python
en
['en', 'pt', 'en']
False
get_logits_over_interval
(*args, **kwargs)
Deprecation wrapper
Deprecation wrapper
def get_logits_over_interval(*args, **kwargs): """Deprecation wrapper""" warnings.warn( "`get_logits_over_interval` has moved to " "`cleverhans.plot.pyplot_image`. " "cleverhans.utils.get_logits_over_interval may be removed on " "or after 2019-04-24." ) # pylint:disable=l...
[ "def", "get_logits_over_interval", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "\"`get_logits_over_interval` has moved to \"", "\"`cleverhans.plot.pyplot_image`. \"", "\"cleverhans.utils.get_logits_over_interval may be removed on \"", "\"or ...
[ 207, 0 ]
[ 220, 56 ]
python
en
['en', 'pt', 'en']
False
linear_extrapolation_plot
(*args, **kwargs)
Deprecation wrapper
Deprecation wrapper
def linear_extrapolation_plot(*args, **kwargs): """Deprecation wrapper""" warnings.warn( "`linear_extrapolation_plot` has moved to " "`cleverhans.plot.pyplot_image`. " "cleverhans.utils.linear_extrapolation_plot may be removed on " "or after 2019-04-24." ) # pylint:disabl...
[ "def", "linear_extrapolation_plot", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "\"`linear_extrapolation_plot` has moved to \"", "\"`cleverhans.plot.pyplot_image`. \"", "\"cleverhans.utils.linear_extrapolation_plot may be removed on \"", "\"...
[ 223, 0 ]
[ 236, 57 ]
python
en
['en', 'pt', 'en']
False
set_log_level
(level, name="cleverhans")
Sets the threshold for the cleverhans logger to level :param level: the logger threshold. You can find values here: https://docs.python.org/2/library/logging.html#levels :param name: the name used for the cleverhans logger
Sets the threshold for the cleverhans logger to level :param level: the logger threshold. You can find values here: https://docs.python.org/2/library/logging.html#levels :param name: the name used for the cleverhans logger
def set_log_level(level, name="cleverhans"): """ Sets the threshold for the cleverhans logger to level :param level: the logger threshold. You can find values here: https://docs.python.org/2/library/logging.html#levels :param name: the name used for the cleverhans logger """ lo...
[ "def", "set_log_level", "(", "level", ",", "name", "=", "\"cleverhans\"", ")", ":", "logging", ".", "getLogger", "(", "name", ")", ".", "setLevel", "(", "level", ")" ]
[ 239, 0 ]
[ 246, 43 ]
python
en
['en', 'error', 'th']
False
get_log_level
(name="cleverhans")
Gets the current threshold for the cleverhans logger :param name: the name used for the cleverhans logger
Gets the current threshold for the cleverhans logger :param name: the name used for the cleverhans logger
def get_log_level(name="cleverhans"): """ Gets the current threshold for the cleverhans logger :param name: the name used for the cleverhans logger """ return logging.getLogger(name).getEffectiveLevel()
[ "def", "get_log_level", "(", "name", "=", "\"cleverhans\"", ")", ":", "return", "logging", ".", "getLogger", "(", "name", ")", ".", "getEffectiveLevel", "(", ")" ]
[ 249, 0 ]
[ 254, 54 ]
python
en
['en', 'error', 'th']
False
create_logger
(name)
Create a logger object with the given name. If this is the first time that we call this method, then initialize the formatter.
Create a logger object with the given name.
def create_logger(name): """ Create a logger object with the given name. If this is the first time that we call this method, then initialize the formatter. """ base = logging.getLogger("cleverhans") if len(base.handlers) == 0: ch = logging.StreamHandler() formatter = logging...
[ "def", "create_logger", "(", "name", ")", ":", "base", "=", "logging", ".", "getLogger", "(", "\"cleverhans\"", ")", "if", "len", "(", "base", ".", "handlers", ")", "==", "0", ":", "ch", "=", "logging", ".", "StreamHandler", "(", ")", "formatter", "=",...
[ 279, 0 ]
[ 295, 15 ]
python
en
['en', 'error', 'th']
False
deterministic_dict
(normal_dict)
Returns a version of `normal_dict` whose iteration order is always the same
Returns a version of `normal_dict` whose iteration order is always the same
def deterministic_dict(normal_dict): """ Returns a version of `normal_dict` whose iteration order is always the same """ out = OrderedDict() for key in sorted(normal_dict.keys()): out[key] = normal_dict[key] return out
[ "def", "deterministic_dict", "(", "normal_dict", ")", ":", "out", "=", "OrderedDict", "(", ")", "for", "key", "in", "sorted", "(", "normal_dict", ".", "keys", "(", ")", ")", ":", "out", "[", "key", "]", "=", "normal_dict", "[", "key", "]", "return", ...
[ 298, 0 ]
[ 305, 14 ]
python
en
['en', 'error', 'th']
False
ordered_union
(l1, l2)
Return the union of l1 and l2, with a deterministic ordering. (Union of python sets does not necessarily have a consisten iteration order) :param l1: list of items :param l2: list of items :returns: list containing one copy of each item that is in l1 or in l2
Return the union of l1 and l2, with a deterministic ordering. (Union of python sets does not necessarily have a consisten iteration order) :param l1: list of items :param l2: list of items :returns: list containing one copy of each item that is in l1 or in l2
def ordered_union(l1, l2): """ Return the union of l1 and l2, with a deterministic ordering. (Union of python sets does not necessarily have a consisten iteration order) :param l1: list of items :param l2: list of items :returns: list containing one copy of each item that is in l1 or in l2 ...
[ "def", "ordered_union", "(", "l1", ",", "l2", ")", ":", "out", "=", "[", "]", "for", "e", "in", "l1", "+", "l2", ":", "if", "e", "not", "in", "out", ":", "out", ".", "append", "(", "e", ")", "return", "out" ]
[ 308, 0 ]
[ 321, 14 ]
python
en
['en', 'error', 'th']
False
safe_zip
(*args)
like zip but with these properties: - returns a list, rather than an iterator. This is the old Python2 zip behavior. - a guarantee that all arguments are the same length. (normal zip silently drops entries to make them the same length)
like zip but with these properties: - returns a list, rather than an iterator. This is the old Python2 zip behavior. - a guarantee that all arguments are the same length. (normal zip silently drops entries to make them the same length)
def safe_zip(*args): """like zip but with these properties: - returns a list, rather than an iterator. This is the old Python2 zip behavior. - a guarantee that all arguments are the same length. (normal zip silently drops entries to make them the same length) """ length = len(args[0]) if not...
[ "def", "safe_zip", "(", "*", "args", ")", ":", "length", "=", "len", "(", "args", "[", "0", "]", ")", "if", "not", "all", "(", "len", "(", "arg", ")", "==", "length", "for", "arg", "in", "args", ")", ":", "raise", "ValueError", "(", "\"Lengths of...
[ 324, 0 ]
[ 335, 27 ]
python
en
['en', 'en', 'en']
True
shell_call
(command, **kwargs)
Calls shell command with argument substitution. Args: command: command represented as a list. Each element of the list is one token of the command. For example "cp a b" becomes ['cp', 'a', 'b'] If any element of the list looks like '${NAME}' then it will be replaced by value from **kw...
Calls shell command with argument substitution.
def shell_call(command, **kwargs): """Calls shell command with argument substitution. Args: command: command represented as a list. Each element of the list is one token of the command. For example "cp a b" becomes ['cp', 'a', 'b'] If any element of the list looks like '${NAME}' then it w...
[ "def", "shell_call", "(", "command", ",", "*", "*", "kwargs", ")", ":", "# Regular expression to find instances of '${NAME}' in a string", "CMD_VARIABLE_RE", "=", "re", ".", "compile", "(", "\"^\\\\$\\\\{(\\\\w+)\\\\}$\"", ")", "command", "=", "list", "(", "command", ...
[ 338, 0 ]
[ 373, 43 ]
python
en
['en', 'en', 'en']
True
deep_copy
(numpy_dict)
Returns a copy of a dictionary whose values are numpy arrays. Copies their values rather than copying references to them.
Returns a copy of a dictionary whose values are numpy arrays. Copies their values rather than copying references to them.
def deep_copy(numpy_dict): """ Returns a copy of a dictionary whose values are numpy arrays. Copies their values rather than copying references to them. """ out = {} for key in numpy_dict: out[key] = numpy_dict[key].copy() return out
[ "def", "deep_copy", "(", "numpy_dict", ")", ":", "out", "=", "{", "}", "for", "key", "in", "numpy_dict", ":", "out", "[", "key", "]", "=", "numpy_dict", "[", "key", "]", ".", "copy", "(", ")", "return", "out" ]
[ 376, 0 ]
[ 384, 14 ]
python
en
['en', 'error', 'th']
False
_save
(im, fp, tile, bufsize=0)
Helper to save image based on tile list :param im: Image object. :param fp: File object. :param tile: Tile list. :param bufsize: Optional buffer size
Helper to save image based on tile list
def _save(im, fp, tile, bufsize=0): """Helper to save image based on tile list :param im: Image object. :param fp: File object. :param tile: Tile list. :param bufsize: Optional buffer size """ im.load() if not hasattr(im, "encoderconfig"): im.encoderconfig = () tile.sort(ke...
[ "def", "_save", "(", "im", ",", "fp", ",", "tile", ",", "bufsize", "=", "0", ")", ":", "im", ".", "load", "(", ")", "if", "not", "hasattr", "(", "im", ",", "\"encoderconfig\"", ")", ":", "im", ".", "encoderconfig", "=", "(", ")", "tile", ".", "...
[ 483, 0 ]
[ 542, 18 ]
python
en
['en', 'da', 'en']
True
_safe_read
(fp, size)
Reads large blocks in a safe way. Unlike fp.read(n), this function doesn't trust the user. If the requested size is larger than SAFEBLOCK, the file is read block by block. :param fp: File handle. Must implement a <b>read</b> method. :param size: Number of bytes to read. :returns: A string c...
Reads large blocks in a safe way. Unlike fp.read(n), this function doesn't trust the user. If the requested size is larger than SAFEBLOCK, the file is read block by block.
def _safe_read(fp, size): """ Reads large blocks in a safe way. Unlike fp.read(n), this function doesn't trust the user. If the requested size is larger than SAFEBLOCK, the file is read block by block. :param fp: File handle. Must implement a <b>read</b> method. :param size: Number of bytes ...
[ "def", "_safe_read", "(", "fp", ",", "size", ")", ":", "if", "size", "<=", "0", ":", "return", "b\"\"", "if", "size", "<=", "SAFEBLOCK", ":", "return", "fp", ".", "read", "(", "size", ")", "data", "=", "[", "]", "while", "size", ">", "0", ":", ...
[ 545, 0 ]
[ 566, 25 ]
python
en
['en', 'error', 'th']
False
ImageFile.verify
(self)
Check file integrity
Check file integrity
def verify(self): """Check file integrity""" # raise exception if something's wrong. must be called # directly after open, and closes file when finished. if self._exclusive_fp: self.fp.close() self.fp = None
[ "def", "verify", "(", "self", ")", ":", "# raise exception if something's wrong. must be called", "# directly after open, and closes file when finished.", "if", "self", ".", "_exclusive_fp", ":", "self", ".", "fp", ".", "close", "(", ")", "self", ".", "fp", "=", "Non...
[ 140, 4 ]
[ 147, 22 ]
python
en
['en', 'en', 'en']
True
ImageFile.load
(self)
Load image data based on tile list
Load image data based on tile list
def load(self): """Load image data based on tile list""" if self.tile is None: raise OSError("cannot load this image") pixel = Image.Image.load(self) if not self.tile: return pixel self.map = None use_mmap = self.filename and len(self.tile) == 1...
[ "def", "load", "(", "self", ")", ":", "if", "self", ".", "tile", "is", "None", ":", "raise", "OSError", "(", "\"cannot load this image\"", ")", "pixel", "=", "Image", ".", "Image", ".", "load", "(", "self", ")", "if", "not", "self", ".", "tile", ":",...
[ 149, 4 ]
[ 281, 37 ]
python
en
['en', 'da', 'en']
True
StubImageFile._load
(self)
(Hook) Find actual image loader.
(Hook) Find actual image loader.
def _load(self): """(Hook) Find actual image loader.""" raise NotImplementedError("StubImageFile subclass must implement _load")
[ "def", "_load", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "\"StubImageFile subclass must implement _load\"", ")" ]
[ 339, 4 ]
[ 341, 80 ]
python
en
['en', 'da', 'en']
True
Parser.reset
(self)
(Consumer) Reset the parser. Note that you can only call this method immediately after you've created a parser; parser instances cannot be reused.
(Consumer) Reset the parser. Note that you can only call this method immediately after you've created a parser; parser instances cannot be reused.
def reset(self): """ (Consumer) Reset the parser. Note that you can only call this method immediately after you've created a parser; parser instances cannot be reused. """ assert self.data is None, "cannot reuse parsers"
[ "def", "reset", "(", "self", ")", ":", "assert", "self", ".", "data", "is", "None", ",", "\"cannot reuse parsers\"" ]
[ 357, 4 ]
[ 363, 56 ]
python
en
['en', 'error', 'th']
False
Parser.feed
(self, data)
(Consumer) Feed data to the parser. :param data: A string buffer. :exception OSError: If the parser failed to parse the image file.
(Consumer) Feed data to the parser.
def feed(self, data): """ (Consumer) Feed data to the parser. :param data: A string buffer. :exception OSError: If the parser failed to parse the image file. """ # collect data if self.finished: return if self.data is None: self....
[ "def", "feed", "(", "self", ",", "data", ")", ":", "# collect data", "if", "self", ".", "finished", ":", "return", "if", "self", ".", "data", "is", "None", ":", "self", ".", "data", "=", "data", "else", ":", "self", ".", "data", "=", "self", ".", ...
[ 365, 4 ]
[ 443, 31 ]
python
en
['en', 'error', 'th']
False
Parser.close
(self)
(Consumer) Close the stream. :returns: An image object. :exception OSError: If the parser failed to parse the image file either because it cannot be identified or cannot be decoded.
(Consumer) Close the stream.
def close(self): """ (Consumer) Close the stream. :returns: An image object. :exception OSError: If the parser failed to parse the image file either because it cannot be identified or cannot be decoded. """ # finish...
[ "def", "close", "(", "self", ")", ":", "# finish decoding", "if", "self", ".", "decoder", ":", "# get rid of what's left in the buffers", "self", ".", "feed", "(", "b\"\"", ")", "self", ".", "data", "=", "self", ".", "decoder", "=", "None", "if", "not", "s...
[ 451, 4 ]
[ 477, 25 ]
python
en
['en', 'error', 'th']
False
PyDecoder.init
(self, args)
Override to perform decoder specific initialization :param args: Array of args items from the tile entry :returns: None
Override to perform decoder specific initialization
def init(self, args): """ Override to perform decoder specific initialization :param args: Array of args items from the tile entry :returns: None """ self.args = args
[ "def", "init", "(", "self", ",", "args", ")", ":", "self", ".", "args", "=", "args" ]
[ 597, 4 ]
[ 604, 24 ]
python
en
['en', 'error', 'th']
False
PyDecoder.decode
(self, buffer)
Override to perform the decoding process. :param buffer: A bytes object with the data to be decoded. :returns: A tuple of (bytes consumed, errcode). If finished with decoding return <0 for the bytes consumed. Err codes are from `ERRORS`
Override to perform the decoding process.
def decode(self, buffer): """ Override to perform the decoding process. :param buffer: A bytes object with the data to be decoded. :returns: A tuple of (bytes consumed, errcode). If finished with decoding return <0 for the bytes consumed. Err codes are from `ERRO...
[ "def", "decode", "(", "self", ",", "buffer", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 610, 4 ]
[ 619, 35 ]
python
en
['en', 'error', 'th']
False