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
DecoratorFromMiddlewareTests.test_callable_process_view_middleware
(self)
Test a middleware that implements process_view, operating on a callable class.
Test a middleware that implements process_view, operating on a callable class.
def test_callable_process_view_middleware(self): """ Test a middleware that implements process_view, operating on a callable class. """ class_process_view(self.rf.get('/'))
[ "def", "test_callable_process_view_middleware", "(", "self", ")", ":", "class_process_view", "(", "self", ".", "rf", ".", "get", "(", "'/'", ")", ")" ]
[ 59, 4 ]
[ 63, 44 ]
python
en
['en', 'error', 'th']
False
DecoratorFromMiddlewareTests.test_full_dec_normal
(self)
Test that all methods of middleware are called for normal HttpResponses
Test that all methods of middleware are called for normal HttpResponses
def test_full_dec_normal(self): """ Test that all methods of middleware are called for normal HttpResponses """ @full_dec def normal_view(request): t = Template("Hello world") return HttpResponse(t.render(Context({}))) request = self.rf.get('/') ...
[ "def", "test_full_dec_normal", "(", "self", ")", ":", "@", "full_dec", "def", "normal_view", "(", "request", ")", ":", "t", "=", "Template", "(", "\"Hello world\"", ")", "return", "HttpResponse", "(", "t", ".", "render", "(", "Context", "(", "{", "}", ")...
[ 65, 4 ]
[ 81, 76 ]
python
en
['en', 'error', 'th']
False
DecoratorFromMiddlewareTests.test_full_dec_templateresponse
(self)
Test that all methods of middleware are called for TemplateResponses in the right sequence.
Test that all methods of middleware are called for TemplateResponses in the right sequence.
def test_full_dec_templateresponse(self): """ Test that all methods of middleware are called for TemplateResponses in the right sequence. """ @full_dec def template_response_view(request): t = Template("Hello world") return TemplateResponse(reques...
[ "def", "test_full_dec_templateresponse", "(", "self", ")", ":", "@", "full_dec", "def", "template_response_view", "(", "request", ")", ":", "t", "=", "Template", "(", "\"Hello world\"", ")", "return", "TemplateResponse", "(", "request", ",", "t", ",", "{", "}"...
[ 83, 4 ]
[ 108, 74 ]
python
en
['en', 'error', 'th']
False
ogrinfo
(data_source, num_features=10)
Walks the available layers in the supplied `data_source`, displaying the fields for the first `num_features` features.
Walks the available layers in the supplied `data_source`, displaying the fields for the first `num_features` features.
def ogrinfo(data_source, num_features=10): """ Walks the available layers in the supplied `data_source`, displaying the fields for the first `num_features` features. """ # Checking the parameters. if isinstance(data_source, str): data_source = DataSource(data_source) elif isinstance...
[ "def", "ogrinfo", "(", "data_source", ",", "num_features", "=", "10", ")", ":", "# Checking the parameters.", "if", "isinstance", "(", "data_source", ",", "str", ")", ":", "data_source", "=", "DataSource", "(", "data_source", ")", "elif", "isinstance", "(", "d...
[ 10, 0 ]
[ 50, 29 ]
python
en
['en', 'error', 'th']
False
SessionStore.save
(self, must_create=False)
Saves the current session data to the database. If 'must_create' is True, a database error will be raised if the saving operation doesn't create a *new* entry (as opposed to possibly updating an existing entry).
Saves the current session data to the database. If 'must_create' is True, a database error will be raised if the saving operation doesn't create a *new* entry (as opposed to possibly updating an existing entry).
def save(self, must_create=False): """ Saves the current session data to the database. If 'must_create' is True, a database error will be raised if the saving operation doesn't create a *new* entry (as opposed to possibly updating an existing entry). """ obj = Ses...
[ "def", "save", "(", "self", ",", "must_create", "=", "False", ")", ":", "obj", "=", "Session", "(", "session_key", "=", "self", ".", "_get_or_create_session_key", "(", ")", ",", "session_data", "=", "self", ".", "encode", "(", "self", ".", "_get_session", ...
[ 48, 4 ]
[ 67, 17 ]
python
en
['en', 'error', 'th']
False
modernize_apns_payload
(data: Dict[str, Any])
Take a payload in an unknown Zulip version's format, and return in current format.
Take a payload in an unknown Zulip version's format, and return in current format.
def modernize_apns_payload(data: Dict[str, Any]) -> Dict[str, Any]: """Take a payload in an unknown Zulip version's format, and return in current format.""" # TODO this isn't super robust as is -- if a buggy remote server # sends a malformed payload, we are likely to raise an exception. if "message_ids"...
[ "def", "modernize_apns_payload", "(", "data", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "# TODO this isn't super robust as is -- if a buggy remote server", "# sends a malformed payload, we are likely to raise an exception...
[ 86, 0 ]
[ 109, 19 ]
python
en
['en', 'en', 'en']
True
parse_gcm_options
(options: Dict[str, Any], data: Dict[str, Any])
Parse GCM options, supplying defaults, and raising an error if invalid. The options permitted here form part of the Zulip notification bouncer's API. They are: `priority`: Passed through to GCM; see upstream doc linked below. Zulip servers should always set this; when unset, we guess a value...
Parse GCM options, supplying defaults, and raising an error if invalid.
def parse_gcm_options(options: Dict[str, Any], data: Dict[str, Any]) -> str: """ Parse GCM options, supplying defaults, and raising an error if invalid. The options permitted here form part of the Zulip notification bouncer's API. They are: `priority`: Passed through to GCM; see upstream doc link...
[ "def", "parse_gcm_options", "(", "options", ":", "Dict", "[", "str", ",", "Any", "]", ",", "data", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "str", ":", "priority", "=", "options", ".", "pop", "(", "\"priority\"", ",", "None", ")", "if",...
[ 245, 0 ]
[ 287, 19 ]
python
en
['en', 'error', 'th']
False
send_android_push_notification
( devices: List[DeviceToken], data: Dict[str, Any], options: Dict[str, Any], remote: bool = False )
Send a GCM message to the given devices. See https://firebase.google.com/docs/cloud-messaging/http-server-ref for the GCM upstream API which this talks to. data: The JSON object (decoded) to send as the 'data' parameter of the GCM message. options: Additional options to control the GCM me...
Send a GCM message to the given devices.
def send_android_push_notification( devices: List[DeviceToken], data: Dict[str, Any], options: Dict[str, Any], remote: bool = False ) -> None: """ Send a GCM message to the given devices. See https://firebase.google.com/docs/cloud-messaging/http-server-ref for the GCM upstream API which this talks ...
[ "def", "send_android_push_notification", "(", "devices", ":", "List", "[", "DeviceToken", "]", ",", "data", ":", "Dict", "[", "str", ",", "Any", "]", ",", "options", ":", "Dict", "[", "str", ",", "Any", "]", ",", "remote", ":", "bool", "=", "False", ...
[ 291, 0 ]
[ 378, 83 ]
python
en
['en', 'error', 'th']
False
push_notifications_enabled
()
True just if this server has configured a way to send push notifications.
True just if this server has configured a way to send push notifications.
def push_notifications_enabled() -> bool: """True just if this server has configured a way to send push notifications.""" if ( uses_notification_bouncer() and settings.ZULIP_ORG_KEY is not None and settings.ZULIP_ORG_ID is not None ): # nocoverage # We have the needed config...
[ "def", "push_notifications_enabled", "(", ")", "->", "bool", ":", "if", "(", "uses_notification_bouncer", "(", ")", "and", "settings", ".", "ZULIP_ORG_KEY", "is", "not", "None", "and", "settings", ".", "ZULIP_ORG_ID", "is", "not", "None", ")", ":", "# nocovera...
[ 517, 0 ]
[ 538, 16 ]
python
en
['en', 'en', 'en']
True
get_gcm_alert
(message: Message)
Determine what alert string to display based on the missed messages.
Determine what alert string to display based on the missed messages.
def get_gcm_alert(message: Message) -> str: """ Determine what alert string to display based on the missed messages. """ sender_str = message.sender.full_name if message.recipient.type == Recipient.HUDDLE and message.trigger == "private_message": return f"New private group message from {send...
[ "def", "get_gcm_alert", "(", "message", ":", "Message", ")", "->", "str", ":", "sender_str", "=", "message", ".", "sender", ".", "full_name", "if", "message", ".", "recipient", ".", "type", "==", "Recipient", ".", "HUDDLE", "and", "message", ".", "trigger"...
[ 553, 0 ]
[ 567, 100 ]
python
en
['en', 'error', 'th']
False
get_base_payload
(user_profile: UserProfile)
Common fields for all notification payloads.
Common fields for all notification payloads.
def get_base_payload(user_profile: UserProfile) -> Dict[str, Any]: """Common fields for all notification payloads.""" data: Dict[str, Any] = {} # These will let the app support logging into multiple realms and servers. data["server"] = settings.EXTERNAL_HOST data["realm_id"] = user_profile.realm.id...
[ "def", "get_base_payload", "(", "user_profile", ":", "UserProfile", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "data", ":", "Dict", "[", "str", ",", "Any", "]", "=", "{", "}", "# These will let the app support logging into multiple realms and servers.", ...
[ 648, 0 ]
[ 658, 15 ]
python
en
['en', 'en', 'en']
True
get_message_payload
(user_profile: UserProfile, message: Message)
Common fields for `message` payloads, for all platforms.
Common fields for `message` payloads, for all platforms.
def get_message_payload(user_profile: UserProfile, message: Message) -> Dict[str, Any]: """Common fields for `message` payloads, for all platforms.""" data = get_base_payload(user_profile) # `sender_id` is preferred, but some existing versions use `sender_email`. data["sender_id"] = message.sender.id ...
[ "def", "get_message_payload", "(", "user_profile", ":", "UserProfile", ",", "message", ":", "Message", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "data", "=", "get_base_payload", "(", "user_profile", ")", "# `sender_id` is preferred, but some existing vers...
[ 661, 0 ]
[ 679, 15 ]
python
en
['en', 'en', 'en']
True
get_apns_alert_title
(message: Message)
On an iOS notification, this is the first bolded line.
On an iOS notification, this is the first bolded line.
def get_apns_alert_title(message: Message) -> str: """ On an iOS notification, this is the first bolded line. """ if message.recipient.type == Recipient.HUDDLE: recipients = get_display_recipient(message.recipient) assert isinstance(recipients, list) return ", ".join(sorted(r["fu...
[ "def", "get_apns_alert_title", "(", "message", ":", "Message", ")", "->", "str", ":", "if", "message", ".", "recipient", ".", "type", "==", "Recipient", ".", "HUDDLE", ":", "recipients", "=", "get_display_recipient", "(", "message", ".", "recipient", ")", "a...
[ 682, 0 ]
[ 693, 35 ]
python
en
['en', 'error', 'th']
False
get_apns_alert_subtitle
(message: Message)
On an iOS notification, this is the second bolded line.
On an iOS notification, this is the second bolded line.
def get_apns_alert_subtitle(message: Message) -> str: """ On an iOS notification, this is the second bolded line. """ if message.trigger == "mentioned": return _("{full_name} mentioned you:").format(full_name=message.sender.full_name) elif message.trigger == "wildcard_mentioned": ret...
[ "def", "get_apns_alert_subtitle", "(", "message", ":", "Message", ")", "->", "str", ":", "if", "message", ".", "trigger", "==", "\"mentioned\"", ":", "return", "_", "(", "\"{full_name} mentioned you:\"", ")", ".", "format", "(", "full_name", "=", "message", "....
[ 696, 0 ]
[ 707, 41 ]
python
en
['en', 'error', 'th']
False
get_message_payload_apns
(user_profile: UserProfile, message: Message)
A `message` payload for iOS, via APNs.
A `message` payload for iOS, via APNs.
def get_message_payload_apns(user_profile: UserProfile, message: Message) -> Dict[str, Any]: """A `message` payload for iOS, via APNs.""" zulip_data = get_message_payload(user_profile, message) zulip_data.update( message_ids=[message.id], ) assert message.rendered_content is not None co...
[ "def", "get_message_payload_apns", "(", "user_profile", ":", "UserProfile", ",", "message", ":", "Message", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "zulip_data", "=", "get_message_payload", "(", "user_profile", ",", "message", ")", "zulip_data", "...
[ 738, 0 ]
[ 757, 20 ]
python
en
['en', 'en', 'en']
True
get_message_payload_gcm
( user_profile: UserProfile, message: Message, )
A `message` payload + options, for Android via GCM/FCM.
A `message` payload + options, for Android via GCM/FCM.
def get_message_payload_gcm( user_profile: UserProfile, message: Message, ) -> Tuple[Dict[str, Any], Dict[str, Any]]: """A `message` payload + options, for Android via GCM/FCM.""" data = get_message_payload(user_profile, message) assert message.rendered_content is not None content, truncated = t...
[ "def", "get_message_payload_gcm", "(", "user_profile", ":", "UserProfile", ",", "message", ":", "Message", ",", ")", "->", "Tuple", "[", "Dict", "[", "str", ",", "Any", "]", ",", "Dict", "[", "str", ",", "Any", "]", "]", ":", "data", "=", "get_message_...
[ 760, 0 ]
[ 779, 28 ]
python
en
['en', 'en', 'en']
True
get_remove_payload_gcm
( user_profile: UserProfile, message_ids: List[int], )
A `remove` payload + options, for Android via GCM/FCM.
A `remove` payload + options, for Android via GCM/FCM.
def get_remove_payload_gcm( user_profile: UserProfile, message_ids: List[int], ) -> Tuple[Dict[str, Any], Dict[str, Any]]: """A `remove` payload + options, for Android via GCM/FCM.""" gcm_payload = get_base_payload(user_profile) gcm_payload.update( event="remove", zulip_message_ids="...
[ "def", "get_remove_payload_gcm", "(", "user_profile", ":", "UserProfile", ",", "message_ids", ":", "List", "[", "int", "]", ",", ")", "->", "Tuple", "[", "Dict", "[", "str", ",", "Any", "]", ",", "Dict", "[", "str", ",", "Any", "]", "]", ":", "gcm_pa...
[ 782, 0 ]
[ 796, 35 ]
python
en
['en', 'en', 'en']
True
handle_remove_push_notification
(user_profile_id: int, message_ids: List[int])
This should be called when a message that previously had a mobile push notification executed is read. This triggers a push to the mobile app, when the message is read on the server, to remove the message from the notification.
This should be called when a message that previously had a mobile push notification executed is read. This triggers a push to the mobile app, when the message is read on the server, to remove the message from the notification.
def handle_remove_push_notification(user_profile_id: int, message_ids: List[int]) -> None: """This should be called when a message that previously had a mobile push notification executed is read. This triggers a push to the mobile app, when the message is read on the server, to remove the message from ...
[ "def", "handle_remove_push_notification", "(", "user_profile_id", ":", "int", ",", "message_ids", ":", "List", "[", "int", "]", ")", "->", "None", ":", "user_profile", "=", "get_user_profile_by_id", "(", "user_profile_id", ")", "message_ids", "=", "bulk_access_messa...
[ 812, 0 ]
[ 840, 89 ]
python
en
['en', 'en', 'en']
True
handle_push_notification
(user_profile_id: int, missed_message: Dict[str, Any])
missed_message is the event received by the zerver.worker.queue_processors.PushNotificationWorker.consume function.
missed_message is the event received by the zerver.worker.queue_processors.PushNotificationWorker.consume function.
def handle_push_notification(user_profile_id: int, missed_message: Dict[str, Any]) -> None: """ missed_message is the event received by the zerver.worker.queue_processors.PushNotificationWorker.consume function. """ if not push_notifications_enabled(): return user_profile = get_user_prof...
[ "def", "handle_push_notification", "(", "user_profile_id", ":", "int", ",", "missed_message", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "None", ":", "if", "not", "push_notifications_enabled", "(", ")", ":", "return", "user_profile", "=", "get_user_p...
[ 844, 0 ]
[ 918, 77 ]
python
en
['en', 'error', 'th']
False
with_metaclass
(meta, *bases)
Create a base class with a metaclass.
Create a base class with a metaclass.
def with_metaclass(meta, *bases): # type: (Type[Any], Tuple[Type[Any], ...]) -> Any """ Create a base class with a metaclass. """ # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual me...
[ "def", "with_metaclass", "(", "meta", ",", "*", "bases", ")", ":", "# type: (Type[Any], Tuple[Type[Any], ...]) -> Any", "# This requires a bit of explanation: the basic idea is to make a dummy", "# metaclass for one level of class instantiation that replaces itself with", "# the actual metac...
[ 24, 0 ]
[ 37, 61 ]
python
en
['en', 'error', 'th']
False
TestCaseFixtureLoadingTests.testClassFixtures
(self)
Check that test case has installed 3 fixture objects
Check that test case has installed 3 fixture objects
def testClassFixtures(self): "Check that test case has installed 3 fixture objects" self.assertEqual(Article.objects.count(), 3) self.assertQuerysetEqual(Article.objects.all(), [ '<Article: Django conquers world!>', '<Article: Copyright is fine the way it is>', ...
[ "def", "testClassFixtures", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "Article", ".", "objects", ".", "count", "(", ")", ",", "3", ")", "self", ".", "assertQuerysetEqual", "(", "Article", ".", "objects", ".", "all", "(", ")", ",", "[", ...
[ 17, 4 ]
[ 24, 10 ]
python
en
['en', 'en', 'en']
True
SubclassTestCaseFixtureLoadingTests.testClassFixtures
(self)
Check that there were no fixture objects installed
Check that there were no fixture objects installed
def testClassFixtures(self): "Check that there were no fixture objects installed" self.assertEqual(Article.objects.count(), 0)
[ "def", "testClassFixtures", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "Article", ".", "objects", ".", "count", "(", ")", ",", "0", ")" ]
[ 33, 4 ]
[ 35, 52 ]
python
en
['en', 'en', 'en']
True
FixtureLoadingTests.test_loaddata_error_message
(self)
Verifies that loading a fixture which contains an invalid object outputs an error message which contains the pk of the object that triggered the error.
Verifies that loading a fixture which contains an invalid object outputs an error message which contains the pk of the object that triggered the error.
def test_loaddata_error_message(self): """ Verifies that loading a fixture which contains an invalid object outputs an error message which contains the pk of the object that triggered the error. """ # MySQL needs a little prodding to reject invalid data. # This wo...
[ "def", "test_loaddata_error_message", "(", "self", ")", ":", "# MySQL needs a little prodding to reject invalid data.", "# This won't affect other tests because the database connection", "# is closed at the end of each test.", "if", "connection", ".", "vendor", "==", "'mysql'", ":", ...
[ 333, 4 ]
[ 346, 89 ]
python
en
['en', 'error', 'th']
False
FixtureLoadingTests.test_loaddata_app_option
(self)
Verifies that the --app option works.
Verifies that the --app option works.
def test_loaddata_app_option(self): """ Verifies that the --app option works. """ with warnings.catch_warnings(): # Ignore: No fixture named ... warnings.filterwarnings("ignore", category=UserWarning) management.call_command('loaddata', 'db_fixture_1',...
[ "def", "test_loaddata_app_option", "(", "self", ")", ":", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "# Ignore: No fixture named ...", "warnings", ".", "filterwarnings", "(", "\"ignore\"", ",", "category", "=", "UserWarning", ")", "management", ".", ...
[ 348, 4 ]
[ 360, 10 ]
python
en
['en', 'error', 'th']
False
rgb
(r, g, b, a=255)
(Internal) Turns an RGB color into a Qt compatible color integer.
(Internal) Turns an RGB color into a Qt compatible color integer.
def rgb(r, g, b, a=255): """(Internal) Turns an RGB color into a Qt compatible color integer.""" # use qRgb to pack the colors, and then turn the resulting long # into a negative integer with the same bitpattern. return qRgba(r, g, b, a) & 0xFFFFFFFF
[ "def", "rgb", "(", "r", ",", "g", ",", "b", ",", "a", "=", "255", ")", ":", "# use qRgb to pack the colors, and then turn the resulting long", "# into a negative integer with the same bitpattern.", "return", "qRgba", "(", "r", ",", "g", ",", "b", ",", "a", ")", ...
[ 45, 0 ]
[ 49, 41 ]
python
en
['en', 'ca', 'en']
True
fromqimage
(im)
:param im: A PIL Image object, or a file name (given either as Python string or a PyQt string object)
:param im: A PIL Image object, or a file name (given either as Python string or a PyQt string object)
def fromqimage(im): """ :param im: A PIL Image object, or a file name (given either as Python string or a PyQt string object) """ buffer = QBuffer() buffer.open(QIODevice.ReadWrite) # preserve alpha channel with png # otherwise ppm is more friendly with Image.open if im.hasAlphaChann...
[ "def", "fromqimage", "(", "im", ")", ":", "buffer", "=", "QBuffer", "(", ")", "buffer", ".", "open", "(", "QIODevice", ".", "ReadWrite", ")", "# preserve alpha channel with png", "# otherwise ppm is more friendly with Image.open", "if", "im", ".", "hasAlphaChannel", ...
[ 52, 0 ]
[ 71, 24 ]
python
en
['en', 'error', 'th']
False
align8to32
(bytes, width, mode)
converts each scanline of data from 8 bit to 32 bit aligned
converts each scanline of data from 8 bit to 32 bit aligned
def align8to32(bytes, width, mode): """ converts each scanline of data from 8 bit to 32 bit aligned """ bits_per_pixel = {"1": 1, "L": 8, "P": 8}[mode] # calculate bytes per line and the extra padding if needed bits_per_line = bits_per_pixel * width full_bytes_per_line, remaining_bits_per_...
[ "def", "align8to32", "(", "bytes", ",", "width", ",", "mode", ")", ":", "bits_per_pixel", "=", "{", "\"1\"", ":", "1", ",", "\"L\"", ":", "8", ",", "\"P\"", ":", "8", "}", "[", "mode", "]", "# calculate bytes per line and the extra padding if needed", "bits_...
[ 88, 0 ]
[ 113, 29 ]
python
en
['en', 'error', 'th']
False
SortedDictTests.test_overwrite_ordering
(self)
Overwriting an item keeps its place.
Overwriting an item keeps its place.
def test_overwrite_ordering(self): """ Overwriting an item keeps its place. """ self.d1[1] = 'ONE' self.assertEqual(list(six.itervalues(self.d1)), ['seven', 'ONE', 'nine'])
[ "def", "test_overwrite_ordering", "(", "self", ")", ":", "self", ".", "d1", "[", "1", "]", "=", "'ONE'", "self", ".", "assertEqual", "(", "list", "(", "six", ".", "itervalues", "(", "self", ".", "d1", ")", ")", ",", "[", "'seven'", ",", "'ONE'", ",...
[ 33, 4 ]
[ 36, 81 ]
python
en
['en', 'en', 'en']
True
SortedDictTests.test_append_items
(self)
New items go to the end.
New items go to the end.
def test_append_items(self): """ New items go to the end. """ self.d1[0] = 'nil' self.assertEqual(list(six.iterkeys(self.d1)), [7, 1, 9, 0])
[ "def", "test_append_items", "(", "self", ")", ":", "self", ".", "d1", "[", "0", "]", "=", "'nil'", "self", ".", "assertEqual", "(", "list", "(", "six", ".", "iterkeys", "(", "self", ".", "d1", ")", ")", ",", "[", "7", ",", "1", ",", "9", ",", ...
[ 38, 4 ]
[ 41, 67 ]
python
en
['en', 'en', 'en']
True
SortedDictTests.test_delete_and_insert
(self)
Deleting an item, then inserting the same key again will place it at the end.
Deleting an item, then inserting the same key again will place it at the end.
def test_delete_and_insert(self): """ Deleting an item, then inserting the same key again will place it at the end. """ del self.d2[7] self.assertEqual(list(six.iterkeys(self.d2)), [1, 9, 0]) self.d2[7] = 'lucky number 7' self.assertEqual(list(six.iterkeys...
[ "def", "test_delete_and_insert", "(", "self", ")", ":", "del", "self", ".", "d2", "[", "7", "]", "self", ".", "assertEqual", "(", "list", "(", "six", ".", "iterkeys", "(", "self", ".", "d2", ")", ")", ",", "[", "1", ",", "9", ",", "0", "]", ")"...
[ 43, 4 ]
[ 51, 67 ]
python
en
['en', 'error', 'th']
False
SortedDictTests.test_init_keys
(self)
Initialising a SortedDict with two keys will just take the first one. A real dict will actually take the second value so we will too, but we'll keep the ordering from the first key found.
Initialising a SortedDict with two keys will just take the first one.
def test_init_keys(self): """ Initialising a SortedDict with two keys will just take the first one. A real dict will actually take the second value so we will too, but we'll keep the ordering from the first key found. """ tuples = ((2, 'two'), (1, 'one'), (2, 'second-two...
[ "def", "test_init_keys", "(", "self", ")", ":", "tuples", "=", "(", "(", "2", ",", "'two'", ")", ",", "(", "1", ",", "'one'", ")", ",", "(", "2", ",", "'second-two'", ")", ")", "d", "=", "SortedDict", "(", "tuples", ")", "self", ".", "assertEqual...
[ 66, 4 ]
[ 82, 72 ]
python
en
['en', 'error', 'th']
False
MergeDictTests.test_mergedict_merges_multivaluedict
(self)
MergeDict can merge MultiValueDicts
MergeDict can merge MultiValueDicts
def test_mergedict_merges_multivaluedict(self): """ MergeDict can merge MultiValueDicts """ multi1 = MultiValueDict({'key1': ['value1'], 'key2': ['value2', 'value3']}) multi2 = MultiValueDict({'key2': ['value4'], 'key4': ['value...
[ "def", "test_mergedict_merges_multivaluedict", "(", "self", ")", ":", "multi1", "=", "MultiValueDict", "(", "{", "'key1'", ":", "[", "'value1'", "]", ",", "'key2'", ":", "[", "'value2'", ",", "'value3'", "]", "}", ")", "multi2", "=", "MultiValueDict", "(", ...
[ 159, 4 ]
[ 191, 9 ]
python
en
['en', 'en', 'en']
True
MergeDictTests.test_key_error
(self)
Test that the message of KeyError contains the missing key name.
Test that the message of KeyError contains the missing key name.
def test_key_error(self): """ Test that the message of KeyError contains the missing key name. """ d1 = MergeDict({'key1': 42}) with six.assertRaisesRegex(self, KeyError, 'key2'): d1['key2']
[ "def", "test_key_error", "(", "self", ")", ":", "d1", "=", "MergeDict", "(", "{", "'key1'", ":", "42", "}", ")", "with", "six", ".", "assertRaisesRegex", "(", "self", ",", "KeyError", ",", "'key2'", ")", ":", "d1", "[", "'key2'", "]" ]
[ 199, 4 ]
[ 205, 22 ]
python
en
['en', 'error', 'th']
False
response_chunks
(response, chunk_size=CONTENT_CHUNK_SIZE)
Given a requests Response, provide the data chunks.
Given a requests Response, provide the data chunks.
def response_chunks(response, chunk_size=CONTENT_CHUNK_SIZE): # type: (Response, int) -> Iterator[bytes] """Given a requests Response, provide the data chunks. """ try: # Special case for urllib3. for chunk in response.raw.stream( chunk_size, # We use decode_conte...
[ "def", "response_chunks", "(", "response", ",", "chunk_size", "=", "CONTENT_CHUNK_SIZE", ")", ":", "# type: (Response, int) -> Iterator[bytes]", "try", ":", "# Special case for urllib3.", "for", "chunk", "in", "response", ".", "raw", ".", "stream", "(", "chunk_size", ...
[ 8, 0 ]
[ 47, 23 ]
python
en
['en', 'en', 'en']
True
ResNetTF._stride_arr
(self, stride)
Map a stride scalar to the stride array for tf.nn.conv2d.
Map a stride scalar to the stride array for tf.nn.conv2d.
def _stride_arr(self, stride): """Map a stride scalar to the stride array for tf.nn.conv2d.""" return [1, stride, stride, 1]
[ "def", "_stride_arr", "(", "self", ",", "stride", ")", ":", "return", "[", "1", ",", "stride", ",", "stride", ",", "1", "]" ]
[ 81, 4 ]
[ 83, 37 ]
python
en
['en', 'en', 'en']
True
ResNetTF._build_model
(self, x)
Build the core model within the graph.
Build the core model within the graph.
def _build_model(self, x): """Build the core model within the graph.""" with tf.variable_scope("init"): x = self._conv("init_conv", x, 3, x.shape[3], 16, self._stride_arr(1)) strides = [1, 2, 2] activate_before_residual = [True, False, False] if self.hps.use_bottlene...
[ "def", "_build_model", "(", "self", ",", "x", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"init\"", ")", ":", "x", "=", "self", ".", "_conv", "(", "\"init_conv\"", ",", "x", ",", "3", ",", "x", ".", "shape", "[", "3", "]", ",", "16", ...
[ 85, 4 ]
[ 152, 34 ]
python
en
['en', 'en', 'en']
True
ResNetTF.build_cost
(self, labels, logits)
Build the graph for cost from the logits if logits are provided. If predictions are provided, logits are extracted from the operation.
Build the graph for cost from the logits if logits are provided. If predictions are provided, logits are extracted from the operation.
def build_cost(self, labels, logits): """ Build the graph for cost from the logits if logits are provided. If predictions are provided, logits are extracted from the operation. """ op = logits.op if "softmax" in str(op).lower(): (logits,) = op.inputs ...
[ "def", "build_cost", "(", "self", ",", "labels", ",", "logits", ")", ":", "op", "=", "logits", ".", "op", "if", "\"softmax\"", "in", "str", "(", "op", ")", ".", "lower", "(", ")", ":", "(", "logits", ",", ")", "=", "op", ".", "inputs", "with", ...
[ 154, 4 ]
[ 169, 19 ]
python
en
['en', 'error', 'th']
False
ResNetTF.build_train_op_from_cost
(self, cost)
Build training specific ops for the graph.
Build training specific ops for the graph.
def build_train_op_from_cost(self, cost): """Build training specific ops for the graph.""" self.lrn_rate = tf.constant(self.hps.lrn_rate, tf.float32, name="learning_rate") self.momentum = tf.constant(self.hps.momentum, tf.float32, name="momentum") trainable_variables = tf.trainable_vari...
[ "def", "build_train_op_from_cost", "(", "self", ",", "cost", ")", ":", "self", ".", "lrn_rate", "=", "tf", ".", "constant", "(", "self", ".", "hps", ".", "lrn_rate", ",", "tf", ".", "float32", ",", "name", "=", "\"learning_rate\"", ")", "self", ".", "m...
[ 171, 4 ]
[ 197, 23 ]
python
en
['en', 'en', 'en']
True
ResNetTF._layer_norm
(self, name, x)
Layer normalization.
Layer normalization.
def _layer_norm(self, name, x): """Layer normalization.""" if self.init_layers: bn = LayerNorm() bn.name = name self.layers += [bn] else: bn = self.layers[self.layer_idx] self.layer_idx += 1 bn.device_name = self.device_name ...
[ "def", "_layer_norm", "(", "self", ",", "name", ",", "x", ")", ":", "if", "self", ".", "init_layers", ":", "bn", "=", "LayerNorm", "(", ")", "bn", ".", "name", "=", "name", "self", ".", "layers", "+=", "[", "bn", "]", "else", ":", "bn", "=", "s...
[ 199, 4 ]
[ 211, 16 ]
python
en
['es', 'en', 'en']
False
ResNetTF._residual
( self, x, in_filter, out_filter, stride, activate_before_residual=False )
Residual unit with 2 sub layers.
Residual unit with 2 sub layers.
def _residual( self, x, in_filter, out_filter, stride, activate_before_residual=False ): """Residual unit with 2 sub layers.""" if activate_before_residual: with tf.variable_scope("shared_activation"): x = self._layer_norm("init_bn", x) x = self._r...
[ "def", "_residual", "(", "self", ",", "x", ",", "in_filter", ",", "out_filter", ",", "stride", ",", "activate_before_residual", "=", "False", ")", ":", "if", "activate_before_residual", ":", "with", "tf", ".", "variable_scope", "(", "\"shared_activation\"", ")",...
[ 213, 4 ]
[ 250, 16 ]
python
en
['en', 'en', 'en']
True
ResNetTF._bottleneck_residual
( self, x, in_filter, out_filter, stride, activate_before_residual=False )
Bottleneck residual unit with 3 sub layers.
Bottleneck residual unit with 3 sub layers.
def _bottleneck_residual( self, x, in_filter, out_filter, stride, activate_before_residual=False ): """Bottleneck residual unit with 3 sub layers.""" if activate_before_residual: with tf.variable_scope("common_bn_relu"): x = self._layer_norm("init_bn", x) ...
[ "def", "_bottleneck_residual", "(", "self", ",", "x", ",", "in_filter", ",", "out_filter", ",", "stride", ",", "activate_before_residual", "=", "False", ")", ":", "if", "activate_before_residual", ":", "with", "tf", ".", "variable_scope", "(", "\"common_bn_relu\""...
[ 252, 4 ]
[ 285, 16 ]
python
en
['en', 'en', 'en']
True
ResNetTF._decay
(self)
L2 weight decay loss.
L2 weight decay loss.
def _decay(self): """L2 weight decay loss.""" if self.decay_cost is not None: return self.decay_cost costs = [] if self.device_name is None: for var in tf.trainable_variables(): if var.op.name.find(r"DW") > 0: costs.append(tf.n...
[ "def", "_decay", "(", "self", ")", ":", "if", "self", ".", "decay_cost", "is", "not", "None", ":", "return", "self", ".", "decay_cost", "costs", "=", "[", "]", "if", "self", ".", "device_name", "is", "None", ":", "for", "var", "in", "tf", ".", "tra...
[ 287, 4 ]
[ 304, 30 ]
python
en
['oc', 'en', 'en']
True
ResNetTF._conv
(self, name, x, filter_size, in_filters, out_filters, strides)
Convolution.
Convolution.
def _conv(self, name, x, filter_size, in_filters, out_filters, strides): """Convolution.""" if self.init_layers: conv = Conv2DnGPU( out_filters, (filter_size, filter_size), strides[1:3], "SAME", w_name="DW", ...
[ "def", "_conv", "(", "self", ",", "name", ",", "x", ",", "filter_size", ",", "in_filters", ",", "out_filters", ",", "strides", ")", ":", "if", "self", ".", "init_layers", ":", "conv", "=", "Conv2DnGPU", "(", "out_filters", ",", "(", "filter_size", ",", ...
[ 306, 4 ]
[ 323, 28 ]
python
en
['en', 'it', 'en']
False
ResNetTF._relu
(self, x, leakiness=0.0)
Relu, with optional leaky support.
Relu, with optional leaky support.
def _relu(self, x, leakiness=0.0): """Relu, with optional leaky support.""" return tf.where(tf.less(x, 0.0), leakiness * x, x, name="leaky_relu")
[ "def", "_relu", "(", "self", ",", "x", ",", "leakiness", "=", "0.0", ")", ":", "return", "tf", ".", "where", "(", "tf", ".", "less", "(", "x", ",", "0.0", ")", ",", "leakiness", "*", "x", ",", "x", ",", "name", "=", "\"leaky_relu\"", ")" ]
[ 325, 4 ]
[ 327, 77 ]
python
en
['en', 'en', 'en']
True
ResNetTF._fully_connected
(self, x, out_dim)
FullyConnected layer for final output.
FullyConnected layer for final output.
def _fully_connected(self, x, out_dim): """FullyConnected layer for final output.""" if self.init_layers: fc = LinearnGPU(out_dim, w_name="DW") fc.name = "logits" self.layers += [fc] else: fc = self.layers[self.layer_idx] self.layer_idx...
[ "def", "_fully_connected", "(", "self", ",", "x", ",", "out_dim", ")", ":", "if", "self", ".", "init_layers", ":", "fc", "=", "LinearnGPU", "(", "out_dim", ",", "w_name", "=", "\"DW\"", ")", "fc", ".", "name", "=", "\"logits\"", "self", ".", "layers", ...
[ 329, 4 ]
[ 340, 26 ]
python
en
['en', 'en', 'en']
True
ReverseLookupTests.test_reverse_field_name_disallowed
(self)
If a related_name is given you can't use the field name instead
If a related_name is given you can't use the field name instead
def test_reverse_field_name_disallowed(self): """ If a related_name is given you can't use the field name instead """ self.assertRaises(FieldError, Poll.objects.get, choice__name__exact="This is the answer")
[ "def", "test_reverse_field_name_disallowed", "(", "self", ")", ":", "self", ".", "assertRaises", "(", "FieldError", ",", "Poll", ".", "objects", ".", "get", ",", "choice__name__exact", "=", "\"This is the answer\"", ")" ]
[ 46, 4 ]
[ 51, 53 ]
python
en
['en', 'error', 'th']
False
common_context
(user: UserProfile)
Common context used for things like outgoing emails that don't have a request.
Common context used for things like outgoing emails that don't have a request.
def common_context(user: UserProfile) -> Dict[str, Any]: """Common context used for things like outgoing emails that don't have a request. """ return { "realm_uri": user.realm.uri, "realm_name": user.realm.name, "root_domain_uri": settings.ROOT_DOMAIN_URI, "external_uri_s...
[ "def", "common_context", "(", "user", ":", "UserProfile", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "return", "{", "\"realm_uri\"", ":", "user", ".", "realm", ".", "uri", ",", "\"realm_name\"", ":", "user", ".", "realm", ".", "name", ",", ...
[ 31, 0 ]
[ 42, 5 ]
python
en
['en', 'en', 'en']
True
zulip_default_context
(request: HttpRequest)
Context available to all Zulip Jinja2 templates that have a request passed in. Designed to provide the long list of variables at the bottom of this function in a wide range of situations: logged-in or logged-out, subdomains or not, etc. The main variable in the below is whether we know what realm the ...
Context available to all Zulip Jinja2 templates that have a request passed in. Designed to provide the long list of variables at the bottom of this function in a wide range of situations: logged-in or logged-out, subdomains or not, etc.
def zulip_default_context(request: HttpRequest) -> Dict[str, Any]: """Context available to all Zulip Jinja2 templates that have a request passed in. Designed to provide the long list of variables at the bottom of this function in a wide range of situations: logged-in or logged-out, subdomains or not, e...
[ "def", "zulip_default_context", "(", "request", ":", "HttpRequest", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "realm", "=", "get_realm_from_request", "(", "request", ")", "if", "realm", "is", "None", ":", "realm_uri", "=", "settings", ".", "ROOT...
[ 68, 0 ]
[ 169, 18 ]
python
en
['en', 'en', 'en']
True
SpatiaLiteOperations.spatial_version
(self)
Determine the version of the SpatiaLite library.
Determine the version of the SpatiaLite library.
def spatial_version(self): """Determine the version of the SpatiaLite library.""" try: version = self.spatialite_version_tuple()[1:] except Exception as exc: raise ImproperlyConfigured( 'Cannot determine the SpatiaLite version for the "%s" database. ' ...
[ "def", "spatial_version", "(", "self", ")", ":", "try", ":", "version", "=", "self", ".", "spatialite_version_tuple", "(", ")", "[", "1", ":", "]", "except", "Exception", "as", "exc", ":", "raise", "ImproperlyConfigured", "(", "'Cannot determine the SpatiaLite v...
[ 87, 4 ]
[ 100, 22 ]
python
en
['en', 'en', 'en']
True
SpatiaLiteOperations.convert_extent
(self, box)
Convert the polygon data received from SpatiaLite to min/max values.
Convert the polygon data received from SpatiaLite to min/max values.
def convert_extent(self, box): """ Convert the polygon data received from SpatiaLite to min/max values. """ if box is None: return None shell = GEOSGeometry(box).shell xmin, ymin = shell[0][:2] xmax, ymax = shell[2][:2] return (xmin, ymin, xmax...
[ "def", "convert_extent", "(", "self", ",", "box", ")", ":", "if", "box", "is", "None", ":", "return", "None", "shell", "=", "GEOSGeometry", "(", "box", ")", ".", "shell", "xmin", ",", "ymin", "=", "shell", "[", "0", "]", "[", ":", "2", "]", "xmax...
[ 102, 4 ]
[ 111, 39 ]
python
en
['en', 'error', 'th']
False
SpatiaLiteOperations.geo_db_type
(self, f)
Return None because geometry columns are added via the `AddGeometryColumn` stored procedure on SpatiaLite.
Return None because geometry columns are added via the `AddGeometryColumn` stored procedure on SpatiaLite.
def geo_db_type(self, f): """ Return None because geometry columns are added via the `AddGeometryColumn` stored procedure on SpatiaLite. """ return None
[ "def", "geo_db_type", "(", "self", ",", "f", ")", ":", "return", "None" ]
[ 113, 4 ]
[ 118, 19 ]
python
en
['en', 'error', 'th']
False
SpatiaLiteOperations.get_distance
(self, f, value, lookup_type)
Return the distance parameters for the given geometry field, lookup value, and lookup type.
Return the distance parameters for the given geometry field, lookup value, and lookup type.
def get_distance(self, f, value, lookup_type): """ Return the distance parameters for the given geometry field, lookup value, and lookup type. """ if not value: return [] value = value[0] if isinstance(value, Distance): if f.geodetic(self.c...
[ "def", "get_distance", "(", "self", ",", "f", ",", "value", ",", "lookup_type", ")", ":", "if", "not", "value", ":", "return", "[", "]", "value", "=", "value", "[", "0", "]", "if", "isinstance", "(", "value", ",", "Distance", ")", ":", "if", "f", ...
[ 120, 4 ]
[ 140, 27 ]
python
en
['en', 'error', 'th']
False
SpatiaLiteOperations._get_spatialite_func
(self, func)
Helper routine for calling SpatiaLite functions and returning their result. Any error occurring in this method should be handled by the caller.
Helper routine for calling SpatiaLite functions and returning their result. Any error occurring in this method should be handled by the caller.
def _get_spatialite_func(self, func): """ Helper routine for calling SpatiaLite functions and returning their result. Any error occurring in this method should be handled by the caller. """ cursor = self.connection._cursor() try: cursor.execute('SELECT...
[ "def", "_get_spatialite_func", "(", "self", ",", "func", ")", ":", "cursor", "=", "self", ".", "connection", ".", "_cursor", "(", ")", "try", ":", "cursor", ".", "execute", "(", "'SELECT %s'", "%", "func", ")", "row", "=", "cursor", ".", "fetchone", "(...
[ 142, 4 ]
[ 154, 21 ]
python
en
['en', 'error', 'th']
False
SpatiaLiteOperations.geos_version
(self)
Return the version of GEOS used by SpatiaLite as a string.
Return the version of GEOS used by SpatiaLite as a string.
def geos_version(self): "Return the version of GEOS used by SpatiaLite as a string." return self._get_spatialite_func('geos_version()')
[ "def", "geos_version", "(", "self", ")", ":", "return", "self", ".", "_get_spatialite_func", "(", "'geos_version()'", ")" ]
[ 156, 4 ]
[ 158, 58 ]
python
en
['en', 'en', 'en']
True
SpatiaLiteOperations.proj4_version
(self)
Return the version of the PROJ.4 library used by SpatiaLite.
Return the version of the PROJ.4 library used by SpatiaLite.
def proj4_version(self): "Return the version of the PROJ.4 library used by SpatiaLite." return self._get_spatialite_func('proj4_version()')
[ "def", "proj4_version", "(", "self", ")", ":", "return", "self", ".", "_get_spatialite_func", "(", "'proj4_version()'", ")" ]
[ 160, 4 ]
[ 162, 59 ]
python
en
['en', 'en', 'en']
True
SpatiaLiteOperations.lwgeom_version
(self)
Return the version of LWGEOM library used by SpatiaLite.
Return the version of LWGEOM library used by SpatiaLite.
def lwgeom_version(self): """Return the version of LWGEOM library used by SpatiaLite.""" return self._get_spatialite_func('lwgeom_version()')
[ "def", "lwgeom_version", "(", "self", ")", ":", "return", "self", ".", "_get_spatialite_func", "(", "'lwgeom_version()'", ")" ]
[ 164, 4 ]
[ 166, 60 ]
python
en
['en', 'en', 'en']
True
SpatiaLiteOperations.spatialite_version
(self)
Return the SpatiaLite library version as a string.
Return the SpatiaLite library version as a string.
def spatialite_version(self): "Return the SpatiaLite library version as a string." return self._get_spatialite_func('spatialite_version()')
[ "def", "spatialite_version", "(", "self", ")", ":", "return", "self", ".", "_get_spatialite_func", "(", "'spatialite_version()'", ")" ]
[ 168, 4 ]
[ 170, 64 ]
python
en
['en', 'en', 'en']
True
SpatiaLiteOperations.spatialite_version_tuple
(self)
Return the SpatiaLite version as a tuple (version string, major, minor, subminor).
Return the SpatiaLite version as a tuple (version string, major, minor, subminor).
def spatialite_version_tuple(self): """ Return the SpatiaLite version as a tuple (version string, major, minor, subminor). """ version = self.spatialite_version() return (version,) + get_version_tuple(version)
[ "def", "spatialite_version_tuple", "(", "self", ")", ":", "version", "=", "self", ".", "spatialite_version", "(", ")", "return", "(", "version", ",", ")", "+", "get_version_tuple", "(", "version", ")" ]
[ 172, 4 ]
[ 178, 54 ]
python
en
['en', 'error', 'th']
False
SpatiaLiteOperations.spatial_aggregate_name
(self, agg_name)
Return the spatial aggregate SQL template and function for the given Aggregate instance.
Return the spatial aggregate SQL template and function for the given Aggregate instance.
def spatial_aggregate_name(self, agg_name): """ Return the spatial aggregate SQL template and function for the given Aggregate instance. """ agg_name = 'unionagg' if agg_name.lower() == 'union' else agg_name.lower() return getattr(self, agg_name)
[ "def", "spatial_aggregate_name", "(", "self", ",", "agg_name", ")", ":", "agg_name", "=", "'unionagg'", "if", "agg_name", ".", "lower", "(", ")", "==", "'union'", "else", "agg_name", ".", "lower", "(", ")", "return", "getattr", "(", "self", ",", "agg_name"...
[ 180, 4 ]
[ 186, 38 ]
python
en
['en', 'error', 'th']
False
AdminEmailHandler.format_subject
(self, subject)
Escape CR and LF characters, and limit length. RFC 2822's hard limit is 998 characters per line. So, minus "Subject: " the actual subject must be no longer than 989 characters.
Escape CR and LF characters, and limit length. RFC 2822's hard limit is 998 characters per line. So, minus "Subject: " the actual subject must be no longer than 989 characters.
def format_subject(self, subject): """ Escape CR and LF characters, and limit length. RFC 2822's hard limit is 998 characters per line. So, minus "Subject: " the actual subject must be no longer than 989 characters. """ formatted_subject = subject.replace('\n', '\\n').rep...
[ "def", "format_subject", "(", "self", ",", "subject", ")", ":", "formatted_subject", "=", "subject", ".", "replace", "(", "'\\n'", ",", "'\\\\n'", ")", ".", "replace", "(", "'\\r'", ",", "'\\\\r'", ")", "return", "formatted_subject", "[", ":", "989", "]" ]
[ 136, 4 ]
[ 143, 38 ]
python
en
['en', 'error', 'th']
False
getInnerText
(node)
Get all the inner text of a DOM node (recursively).
Get all the inner text of a DOM node (recursively).
def getInnerText(node): """ Get all the inner text of a DOM node (recursively). """ # inspired by http://mail.python.org/pipermail/xml-sig/2005-March/011022.html inner_text = [] for child in node.childNodes: if child.nodeType == child.TEXT_NODE or child.nodeType == child.CDATA_SECTION_NO...
[ "def", "getInnerText", "(", "node", ")", ":", "# inspired by http://mail.python.org/pipermail/xml-sig/2005-March/011022.html", "inner_text", "=", "[", "]", "for", "child", "in", "node", ".", "childNodes", ":", "if", "child", ".", "nodeType", "==", "child", ".", "TEX...
[ 286, 0 ]
[ 299, 30 ]
python
en
['en', 'error', 'th']
False
Serializer.start_serialization
(self)
Start serialization -- open the XML document and the root element.
Start serialization -- open the XML document and the root element.
def start_serialization(self): """ Start serialization -- open the XML document and the root element. """ self.xml = SimplerXMLGenerator(self.stream, self.options.get("encoding", settings.DEFAULT_CHARSET)) self.xml.startDocument() self.xml.startElement("django-objects", {...
[ "def", "start_serialization", "(", "self", ")", ":", "self", ".", "xml", "=", "SimplerXMLGenerator", "(", "self", ".", "stream", ",", "self", ".", "options", ".", "get", "(", "\"encoding\"", ",", "settings", ".", "DEFAULT_CHARSET", ")", ")", "self", ".", ...
[ 26, 4 ]
[ 32, 67 ]
python
en
['en', 'error', 'th']
False
Serializer.end_serialization
(self)
End serialization -- end the document.
End serialization -- end the document.
def end_serialization(self): """ End serialization -- end the document. """ self.indent(0) self.xml.endElement("django-objects") self.xml.endDocument()
[ "def", "end_serialization", "(", "self", ")", ":", "self", ".", "indent", "(", "0", ")", "self", ".", "xml", ".", "endElement", "(", "\"django-objects\"", ")", "self", ".", "xml", ".", "endDocument", "(", ")" ]
[ 34, 4 ]
[ 40, 30 ]
python
en
['en', 'error', 'th']
False
Serializer.start_object
(self, obj)
Called as each object is handled.
Called as each object is handled.
def start_object(self, obj): """ Called as each object is handled. """ if not hasattr(obj, "_meta"): raise base.SerializationError("Non-model object (%s) encountered during serialization" % type(obj)) self.indent(1) attrs = {"model": smart_text(obj._meta)} ...
[ "def", "start_object", "(", "self", ",", "obj", ")", ":", "if", "not", "hasattr", "(", "obj", ",", "\"_meta\"", ")", ":", "raise", "base", ".", "SerializationError", "(", "\"Non-model object (%s) encountered during serialization\"", "%", "type", "(", "obj", ")",...
[ 42, 4 ]
[ 56, 46 ]
python
en
['en', 'error', 'th']
False
Serializer.end_object
(self, obj)
Called after handling all fields for an object.
Called after handling all fields for an object.
def end_object(self, obj): """ Called after handling all fields for an object. """ self.indent(1) self.xml.endElement("object")
[ "def", "end_object", "(", "self", ",", "obj", ")", ":", "self", ".", "indent", "(", "1", ")", "self", ".", "xml", ".", "endElement", "(", "\"object\"", ")" ]
[ 58, 4 ]
[ 63, 37 ]
python
en
['en', 'error', 'th']
False
Serializer.handle_field
(self, obj, field)
Called to handle each field on an object (except for ForeignKeys and ManyToManyFields)
Called to handle each field on an object (except for ForeignKeys and ManyToManyFields)
def handle_field(self, obj, field): """ Called to handle each field on an object (except for ForeignKeys and ManyToManyFields) """ self.indent(2) self.xml.startElement("field", { "name": field.name, "type": field.get_internal_type() }) ...
[ "def", "handle_field", "(", "self", ",", "obj", ",", "field", ")", ":", "self", ".", "indent", "(", "2", ")", "self", ".", "xml", ".", "startElement", "(", "\"field\"", ",", "{", "\"name\"", ":", "field", ".", "name", ",", "\"type\"", ":", "field", ...
[ 65, 4 ]
[ 82, 36 ]
python
en
['en', 'error', 'th']
False
Serializer.handle_fk_field
(self, obj, field)
Called to handle a ForeignKey (we need to treat them slightly differently from regular fields).
Called to handle a ForeignKey (we need to treat them slightly differently from regular fields).
def handle_fk_field(self, obj, field): """ Called to handle a ForeignKey (we need to treat them slightly differently from regular fields). """ self._start_relational_field(field) related_att = getattr(obj, field.get_attname()) if related_att is not None: ...
[ "def", "handle_fk_field", "(", "self", ",", "obj", ",", "field", ")", ":", "self", ".", "_start_relational_field", "(", "field", ")", "related_att", "=", "getattr", "(", "obj", ",", "field", ".", "get_attname", "(", ")", ")", "if", "related_att", "is", "...
[ 84, 4 ]
[ 105, 36 ]
python
en
['en', 'error', 'th']
False
Serializer.handle_m2m_field
(self, obj, field)
Called to handle a ManyToManyField. Related objects are only serialized as references to the object's PK (i.e. the related *data* is not dumped, just the relation).
Called to handle a ManyToManyField. Related objects are only serialized as references to the object's PK (i.e. the related *data* is not dumped, just the relation).
def handle_m2m_field(self, obj, field): """ Called to handle a ManyToManyField. Related objects are only serialized as references to the object's PK (i.e. the related *data* is not dumped, just the relation). """ if field.rel.through._meta.auto_created: self._...
[ "def", "handle_m2m_field", "(", "self", ",", "obj", ",", "field", ")", ":", "if", "field", ".", "rel", ".", "through", ".", "_meta", ".", "auto_created", ":", "self", ".", "_start_relational_field", "(", "field", ")", "if", "self", ".", "use_natural_foreig...
[ 107, 4 ]
[ 134, 40 ]
python
en
['en', 'error', 'th']
False
Serializer._start_relational_field
(self, field)
Helper to output the <field> element for relational fields
Helper to output the <field> element for relational fields
def _start_relational_field(self, field): """ Helper to output the <field> element for relational fields """ self.indent(2) self.xml.startElement("field", { "name": field.name, "rel": field.rel.__class__.__name__, "to": smart_text(field.rel.to....
[ "def", "_start_relational_field", "(", "self", ",", "field", ")", ":", "self", ".", "indent", "(", "2", ")", "self", ".", "xml", ".", "startElement", "(", "\"field\"", ",", "{", "\"name\"", ":", "field", ".", "name", ",", "\"rel\"", ":", "field", ".", ...
[ 136, 4 ]
[ 145, 10 ]
python
en
['en', 'error', 'th']
False
Deserializer._make_parser
(self)
Create a hardened XML parser (no custom/external entities).
Create a hardened XML parser (no custom/external entities).
def _make_parser(self): """Create a hardened XML parser (no custom/external entities).""" return DefusedExpatParser()
[ "def", "_make_parser", "(", "self", ")", ":", "return", "DefusedExpatParser", "(", ")" ]
[ 159, 4 ]
[ 161, 35 ]
python
en
['en', 'af', 'en']
True
Deserializer._handle_object
(self, node)
Convert an <object> node to a DeserializedObject.
Convert an <object> node to a DeserializedObject.
def _handle_object(self, node): """ Convert an <object> node to a DeserializedObject. """ # Look up the model using the model loading mechanism. If this fails, # bail. Model = self._get_model_from_node(node, "model") # Start building a data dictionary from the ob...
[ "def", "_handle_object", "(", "self", ",", "node", ")", ":", "# Look up the model using the model loading mechanism. If this fails,", "# bail.", "Model", "=", "self", ".", "_get_model_from_node", "(", "node", ",", "\"model\"", ")", "# Start building a data dictionary from the...
[ 170, 4 ]
[ 219, 53 ]
python
en
['en', 'error', 'th']
False
Deserializer._handle_fk_field_node
(self, node, field)
Handle a <field> node for a ForeignKey
Handle a <field> node for a ForeignKey
def _handle_fk_field_node(self, node, field): """ Handle a <field> node for a ForeignKey """ # Check if there is a child node named 'None', returning None if so. if node.getElementsByTagName('None'): return None else: if hasattr(field.rel.to._defau...
[ "def", "_handle_fk_field_node", "(", "self", ",", "node", ",", "field", ")", ":", "# Check if there is a child node named 'None', returning None if so.", "if", "node", ".", "getElementsByTagName", "(", "'None'", ")", ":", "return", "None", "else", ":", "if", "hasattr"...
[ 221, 4 ]
[ 247, 96 ]
python
en
['en', 'error', 'th']
False
Deserializer._handle_m2m_field_node
(self, node, field)
Handle a <field> node for a ManyToManyField.
Handle a <field> node for a ManyToManyField.
def _handle_m2m_field_node(self, node, field): """ Handle a <field> node for a ManyToManyField. """ if hasattr(field.rel.to._default_manager, 'get_by_natural_key'): def m2m_convert(n): keys = n.getElementsByTagName('natural') if keys: ...
[ "def", "_handle_m2m_field_node", "(", "self", ",", "node", ",", "field", ")", ":", "if", "hasattr", "(", "field", ".", "rel", ".", "to", ".", "_default_manager", ",", "'get_by_natural_key'", ")", ":", "def", "m2m_convert", "(", "n", ")", ":", "keys", "="...
[ 249, 4 ]
[ 266, 76 ]
python
en
['en', 'error', 'th']
False
Deserializer._get_model_from_node
(self, node, attr)
Helper to look up a model from a <object model=...> or a <field rel=... to=...> node.
Helper to look up a model from a <object model=...> or a <field rel=... to=...> node.
def _get_model_from_node(self, node, attr): """ Helper to look up a model from a <object model=...> or a <field rel=... to=...> node. """ model_identifier = node.getAttribute(attr) if not model_identifier: raise base.DeserializationError( "<%s>...
[ "def", "_get_model_from_node", "(", "self", ",", "node", ",", "attr", ")", ":", "model_identifier", "=", "node", ".", "getAttribute", "(", "attr", ")", "if", "not", "model_identifier", ":", "raise", "base", ".", "DeserializationError", "(", "\"<%s> node is missi...
[ 268, 4 ]
[ 283, 52 ]
python
en
['en', 'error', 'th']
False
MaxConfidence.generate
(self, x, **kwargs)
Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: Keyword arguments for the base attacker
Generate symbolic graph for adversarial examples and return.
def generate(self, x, **kwargs): """ Generate symbolic graph for adversarial examples and return. :param x: The model's symbolic inputs. :param kwargs: Keyword arguments for the base attacker """ assert self.parse_params(**kwargs) labels, _nb_classes = self.get_...
[ "def", "generate", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "assert", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "labels", ",", "_nb_classes", "=", "self", ".", "get_or_guess_labels", "(", "x", ",", "kwargs", ")", "ad...
[ 41, 4 ]
[ 53, 20 ]
python
en
['en', 'error', 'th']
False
MaxConfidence.attack
(self, x, true_y)
Runs the untargeted attack. :param x: The input :param true_y: The correct label for `x`. This attack aims to produce misclassification.
Runs the untargeted attack. :param x: The input :param true_y: The correct label for `x`. This attack aims to produce misclassification.
def attack(self, x, true_y): """ Runs the untargeted attack. :param x: The input :param true_y: The correct label for `x`. This attack aims to produce misclassification. """ adv_x_cls = [] prob_cls = [] m = tf.shape(x)[0] true_y_idx = tf.argmax(tru...
[ "def", "attack", "(", "self", ",", "x", ",", "true_y", ")", ":", "adv_x_cls", "=", "[", "]", "prob_cls", "=", "[", "]", "m", "=", "tf", ".", "shape", "(", "x", ")", "[", "0", "]", "true_y_idx", "=", "tf", ".", "argmax", "(", "true_y", ",", "a...
[ 65, 4 ]
[ 111, 18 ]
python
en
['en', 'error', 'th']
False
MaxConfidence.attack_class
(self, x, target_y)
Run the attack on a specific target class. :param x: tf Tensor. The input example. :param target_y: tf Tensor. The attacker's desired target class. Returns: A targeted adversarial example, intended to be classified as the target class.
Run the attack on a specific target class. :param x: tf Tensor. The input example. :param target_y: tf Tensor. The attacker's desired target class. Returns: A targeted adversarial example, intended to be classified as the target class.
def attack_class(self, x, target_y): """ Run the attack on a specific target class. :param x: tf Tensor. The input example. :param target_y: tf Tensor. The attacker's desired target class. Returns: A targeted adversarial example, intended to be classified as the target ...
[ "def", "attack_class", "(", "self", ",", "x", ",", "target_y", ")", ":", "adv", "=", "self", ".", "base_attacker", ".", "generate", "(", "x", ",", "y_target", "=", "target_y", ",", "*", "*", "self", ".", "params", ")", "return", "adv" ]
[ 113, 4 ]
[ 122, 18 ]
python
en
['en', 'error', 'th']
False
isnamedtuple
(x)
Utility to check whether something is a named tuple Since a namedtuple is basically a tuple with some additional metadata, we can't just do an `isinstance` check Based on https://stackoverflow.com/questions/2166818/how-to-check-if-an-object-is-an-instance-of-a-namedtuple/2166841#2166841
Utility to check whether something is a named tuple Since a namedtuple is basically a tuple with some additional metadata, we can't just do an `isinstance` check Based on https://stackoverflow.com/questions/2166818/how-to-check-if-an-object-is-an-instance-of-a-namedtuple/2166841#2166841
def isnamedtuple(x): """ Utility to check whether something is a named tuple Since a namedtuple is basically a tuple with some additional metadata, we can't just do an `isinstance` check Based on https://stackoverflow.com/questions/2166818/how-to-check-if-an-object-is-an-instance-of-a-namedtuple/2166841...
[ "def", "isnamedtuple", "(", "x", ")", ":", "t", "=", "type", "(", "x", ")", "b", "=", "t", ".", "__bases__", "# Named tuples are tuple subclasses", "if", "len", "(", "b", ")", "!=", "1", "or", "b", "[", "0", "]", "!=", "tuple", ":", "return", "Fals...
[ 32, 0 ]
[ 51, 41 ]
python
en
['en', 'error', 'th']
False
TorchScriptNeuropodExecutor.__init__
(self, neuropod_path, visible_gpu=0, load_custom_ops=True)
Load a TorchScript neuropod :param neuropod_path: The path to a TorchScript neuropod package :param visible_gpu: The index of the GPU that this Neuropod should run on (if any). This is either `None` or a nonnegative integer. Setting this ...
Load a TorchScript neuropod
def __init__(self, neuropod_path, visible_gpu=0, load_custom_ops=True): """ Load a TorchScript neuropod :param neuropod_path: The path to a TorchScript neuropod package :param visible_gpu: The index of the GPU that this Neuropod should run on (if any). ...
[ "def", "__init__", "(", "self", ",", "neuropod_path", ",", "visible_gpu", "=", "0", ",", "load_custom_ops", "=", "True", ")", ":", "super", "(", "TorchScriptNeuropodExecutor", ",", "self", ")", ".", "__init__", "(", "neuropod_path", ")", "self", ".", "visibl...
[ 59, 4 ]
[ 96, 48 ]
python
en
['en', 'error', 'th']
False
TorchScriptNeuropodExecutor._get_torch_device
(self, target_device)
Get a concrete device (e.g. `cuda:0` or `cpu`) given a target (e.g. `CPU` or `GPU`)
Get a concrete device (e.g. `cuda:0` or `cpu`) given a target (e.g. `CPU` or `GPU`)
def _get_torch_device(self, target_device): """ Get a concrete device (e.g. `cuda:0` or `cpu`) given a target (e.g. `CPU` or `GPU`) """ if self.visible_gpu is None or not torch.cuda.is_available(): # No matter what the target device is, we don't have a choice other ...
[ "def", "_get_torch_device", "(", "self", ",", "target_device", ")", ":", "if", "self", ".", "visible_gpu", "is", "None", "or", "not", "torch", ".", "cuda", ".", "is_available", "(", ")", ":", "# No matter what the target device is, we don't have a choice other", "# ...
[ 98, 4 ]
[ 113, 70 ]
python
en
['en', 'error', 'th']
False
TorchScriptNeuropodExecutor.forward
(self, inputs)
Run inference using the specifed inputs. :param inputs: A dict mapping input names to values. This must match the input spec in the neuropod config for the loaded model. Ex: {'x1': np.array([5]), 'x2': np.array([6])} ...
Run inference using the specifed inputs.
def forward(self, inputs): """ Run inference using the specifed inputs. :param inputs: A dict mapping input names to values. This must match the input spec in the neuropod config for the loaded model. Ex: {'x1': np.array([5]), 'x2': n...
[ "def", "forward", "(", "self", ",", "inputs", ")", ":", "# Convert the inputs to torch tensors and move to the appropriate device", "converted_inputs", "=", "{", "}", "for", "k", ",", "v", "in", "inputs", ".", "items", "(", ")", ":", "# Get the target device for this ...
[ 115, 4 ]
[ 197, 27 ]
python
en
['en', 'error', 'th']
False
get_keywords
()
Get the keywords needed to look up the version information.
Get the keywords needed to look up the version information.
def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keyword...
[ "def", "get_keywords", "(", ")", ":", "# these strings will be replaced by git during git-archive.", "# setup.py/versioneer.py will grep for the variable names, so they must", "# each be defined on a line of their own. _version.py will just call", "# get_keywords().", "git_refnames", "=", "\"$...
[ 18, 0 ]
[ 28, 19 ]
python
en
['en', 'en', 'en']
True
get_config
()
Create, populate and return the VersioneerConfig() object.
Create, populate and return the VersioneerConfig() object.
def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "pep440" cfg.tag_prefix = "" cfg.parentdir_prefix = "None" cfg.versio...
[ "def", "get_config", "(", ")", ":", "# these strings are filled in when 'setup.py versioneer' creates", "# _version.py", "cfg", "=", "VersioneerConfig", "(", ")", "cfg", ".", "VCS", "=", "\"git\"", "cfg", ".", "style", "=", "\"pep440\"", "cfg", ".", "tag_prefix", "=...
[ 35, 0 ]
[ 46, 14 ]
python
en
['en', 'en', 'en']
True
register_vcs_handler
(vcs, method)
Decorator to mark a method as the handler for a particular VCS.
Decorator to mark a method as the handler for a particular VCS.
def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f retur...
[ "def", "register_vcs_handler", "(", "vcs", ",", "method", ")", ":", "# decorator", "def", "decorate", "(", "f", ")", ":", "\"\"\"Store f in HANDLERS[vcs][method].\"\"\"", "if", "vcs", "not", "in", "HANDLERS", ":", "HANDLERS", "[", "vcs", "]", "=", "{", "}", ...
[ 57, 0 ]
[ 67, 19 ]
python
en
['en', 'en', 'en']
True
run_command
(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None)
Call the given command(s).
Call the given command(s).
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just...
[ "def", "run_command", "(", "commands", ",", "args", ",", "cwd", "=", "None", ",", "verbose", "=", "False", ",", "hide_stderr", "=", "False", ",", "env", "=", "None", ")", ":", "assert", "isinstance", "(", "commands", ",", "list", ")", "p", "=", "None...
[ 70, 0 ]
[ 106, 31 ]
python
en
['en', 'en', 'en']
True
versions_from_parentdir
(parentdir_prefix, root, verbose)
Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory
Try to determine the version from the parent directory name.
def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an ap...
[ "def", "versions_from_parentdir", "(", "parentdir_prefix", ",", "root", ",", "verbose", ")", ":", "rootdirs", "=", "[", "]", "for", "i", "in", "range", "(", "3", ")", ":", "dirname", "=", "os", ".", "path", ".", "basename", "(", "root", ")", "if", "d...
[ 109, 0 ]
[ 137, 70 ]
python
en
['en', 'en', 'en']
True
git_get_keywords
(versionfile_abs)
Extract version information from the given file.
Extract version information from the given file.
def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from...
[ "def", "git_get_keywords", "(", "versionfile_abs", ")", ":", "# the code embedded in _version.py can just fetch the value of these", "# keywords. When used from setup.py, we don't want to import _version.py,", "# so we do it with a regexp instead. This function is not used from", "# _version.py.",...
[ 141, 0 ]
[ 166, 19 ]
python
en
['en', 'en', 'en']
True
git_versions_from_keywords
(keywords, tag_prefix, verbose)
Get version information from git keywords.
Get version information from git keywords.
def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%cI", which expands to an ISO-8601 -compli...
[ "def", "git_versions_from_keywords", "(", "keywords", ",", "tag_prefix", ",", "verbose", ")", ":", "if", "not", "keywords", ":", "raise", "NotThisMethod", "(", "\"no keywords at all, weird\"", ")", "date", "=", "keywords", ".", "get", "(", "\"date\"", ")", "if",...
[ 170, 0 ]
[ 228, 5 ]
python
en
['en', 'da', 'en']
True
git_pieces_from_vcs
(tag_prefix, root, verbose, run_command=run_command)
Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree.
Get version from 'git describe' in the root of the source tree.
def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meani...
[ "def", "git_pieces_from_vcs", "(", "tag_prefix", ",", "root", ",", "verbose", ",", "run_command", "=", "run_command", ")", ":", "GITS", "=", "[", "\"git\"", "]", "if", "sys", ".", "platform", "==", "\"win32\"", ":", "GITS", "=", "[", "\"git.cmd\"", ",", ...
[ 232, 0 ]
[ 329, 17 ]
python
en
['en', 'en', 'en']
True
plus_or_dot
(pieces)
Return a + if we don't already have one, else return a .
Return a + if we don't already have one, else return a .
def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+"
[ "def", "plus_or_dot", "(", "pieces", ")", ":", "if", "\"+\"", "in", "pieces", ".", "get", "(", "\"closest-tag\"", ",", "\"\"", ")", ":", "return", "\".\"", "return", "\"+\"" ]
[ 332, 0 ]
[ 336, 14 ]
python
en
['en', 'en', 'en']
True
render_pep440
(pieces)
Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
Build up version string, with post-release "local version identifier".
def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHE...
[ "def", "render_pep440", "(", "pieces", ")", ":", "if", "pieces", "[", "\"closest-tag\"", "]", ":", "rendered", "=", "pieces", "[", "\"closest-tag\"", "]", "if", "pieces", "[", "\"distance\"", "]", "or", "pieces", "[", "\"dirty\"", "]", ":", "rendered", "+=...
[ 339, 0 ]
[ 360, 19 ]
python
en
['en', 'en', 'en']
True
render_pep440_pre
(pieces)
TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE
TAG[.post.devDISTANCE] -- No -dirty.
def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exce...
[ "def", "render_pep440_pre", "(", "pieces", ")", ":", "if", "pieces", "[", "\"closest-tag\"", "]", ":", "rendered", "=", "pieces", "[", "\"closest-tag\"", "]", "if", "pieces", "[", "\"distance\"", "]", ":", "rendered", "+=", "\".post.dev%d\"", "%", "pieces", ...
[ 363, 0 ]
[ 376, 19 ]
python
en
['en', 'en', 'pt']
True
render_pep440_post
(pieces)
TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0]
TAG[.postDISTANCE[.dev0]+gHEX] .
def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[...
[ "def", "render_pep440_post", "(", "pieces", ")", ":", "if", "pieces", "[", "\"closest-tag\"", "]", ":", "rendered", "=", "pieces", "[", "\"closest-tag\"", "]", "if", "pieces", "[", "\"distance\"", "]", "or", "pieces", "[", "\"dirty\"", "]", ":", "rendered", ...
[ 379, 0 ]
[ 403, 19 ]
python
cy
['en', 'cy', 'hi']
False
render_pep440_old
(pieces)
TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0]
TAG[.postDISTANCE[.dev0]] .
def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pie...
[ "def", "render_pep440_old", "(", "pieces", ")", ":", "if", "pieces", "[", "\"closest-tag\"", "]", ":", "rendered", "=", "pieces", "[", "\"closest-tag\"", "]", "if", "pieces", "[", "\"distance\"", "]", "or", "pieces", "[", "\"dirty\"", "]", ":", "rendered", ...
[ 406, 0 ]
[ 425, 19 ]
python
en
['en', 'mt', 'hi']
False
render_git_describe
(pieces)
TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix)
TAG[-DISTANCE-gHEX][-dirty].
def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered +=...
[ "def", "render_git_describe", "(", "pieces", ")", ":", "if", "pieces", "[", "\"closest-tag\"", "]", ":", "rendered", "=", "pieces", "[", "\"closest-tag\"", "]", "if", "pieces", "[", "\"distance\"", "]", ":", "rendered", "+=", "\"-%d-g%s\"", "%", "(", "pieces...
[ 428, 0 ]
[ 445, 19 ]
python
en
['en', 'en', 'en']
False
render_git_describe_long
(pieces)
TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix)
TAG-DISTANCE-gHEX[-dirty].
def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] ...
[ "def", "render_git_describe_long", "(", "pieces", ")", ":", "if", "pieces", "[", "\"closest-tag\"", "]", ":", "rendered", "=", "pieces", "[", "\"closest-tag\"", "]", "rendered", "+=", "\"-%d-g%s\"", "%", "(", "pieces", "[", "\"distance\"", "]", ",", "pieces", ...
[ 448, 0 ]
[ 465, 19 ]
python
en
['en', 'en', 'pt']
False
render
(pieces, style)
Render the given version pieces into the requested style.
Render the given version pieces into the requested style.
def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return { "version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None, ...
[ "def", "render", "(", "pieces", ",", "style", ")", ":", "if", "pieces", "[", "\"error\"", "]", ":", "return", "{", "\"version\"", ":", "\"unknown\"", ",", "\"full-revisionid\"", ":", "pieces", ".", "get", "(", "\"long\"", ")", ",", "\"dirty\"", ":", "Non...
[ 468, 0 ]
[ 503, 5 ]
python
en
['en', 'en', 'en']
True
get_versions
()
Get version information or return default if unable to do so.
Get version information or return default if unable to do so.
def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which #...
[ "def", "get_versions", "(", ")", ":", "# I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have", "# __file__, we can work backwards from there to the root. Some", "# py2exe/bbfreeze/non-CPython implementations don't do __file__, in which", "# case we can only use expanded keywords....
[ 506, 0 ]
[ 555, 5 ]
python
en
['it', 'en', 'en']
True
trim_docstring
(docstring)
Uniformly trim leading/trailing whitespace from docstrings. Based on https://www.python.org/dev/peps/pep-0257/#handling-docstring-indentation
Uniformly trim leading/trailing whitespace from docstrings.
def trim_docstring(docstring): """ Uniformly trim leading/trailing whitespace from docstrings. Based on https://www.python.org/dev/peps/pep-0257/#handling-docstring-indentation """ if not docstring or not docstring.strip(): return '' # Convert tabs to spaces and split into lines lin...
[ "def", "trim_docstring", "(", "docstring", ")", ":", "if", "not", "docstring", "or", "not", "docstring", ".", "strip", "(", ")", ":", "return", "''", "# Convert tabs to spaces and split into lines", "lines", "=", "docstring", ".", "expandtabs", "(", ")", ".", ...
[ 25, 0 ]
[ 37, 37 ]
python
en
['en', 'error', 'th']
False
parse_docstring
(docstring)
Parse out the parts of a docstring. Return (title, body, metadata).
Parse out the parts of a docstring. Return (title, body, metadata).
def parse_docstring(docstring): """ Parse out the parts of a docstring. Return (title, body, metadata). """ docstring = trim_docstring(docstring) parts = re.split(r'\n{2,}', docstring) title = parts[0] if len(parts) == 1: body = '' metadata = {} else: parser = He...
[ "def", "parse_docstring", "(", "docstring", ")", ":", "docstring", "=", "trim_docstring", "(", "docstring", ")", "parts", "=", "re", ".", "split", "(", "r'\\n{2,}'", ",", "docstring", ")", "title", "=", "parts", "[", "0", "]", "if", "len", "(", "parts", ...
[ 40, 0 ]
[ 63, 32 ]
python
en
['en', 'error', 'th']
False