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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
MicroPy.create_stubs | (self, port, verbose=False) | Create and add stubs from Pyboard.
Args:
port (str): Port of Pyboard
Returns:
Stub: generated stub
| Create and add stubs from Pyboard. | def create_stubs(self, port, verbose=False):
"""Create and add stubs from Pyboard.
Args:
port (str): Port of Pyboard
Returns:
Stub: generated stub
"""
self.log.title(f"Connecting to Pyboard @ $[{port}]")
try:
pyb = utils.PyboardWrapp... | [
"def",
"create_stubs",
"(",
"self",
",",
"port",
",",
"verbose",
"=",
"False",
")",
":",
"self",
".",
"log",
".",
"title",
"(",
"f\"Connecting to Pyboard @ $[{port}]\"",
")",
"try",
":",
"pyb",
"=",
"utils",
".",
"PyboardWrapper",
"(",
"port",
",",
"verbos... | [
83,
4
] | [
127,
19
] | python | en | ['en', 'en', 'en'] | True |
KMLSitemap._build_kml_sources | (self, sources) |
Goes through the given sources and returns a 3-tuple of
the application label, module name, and field name of every
GeometryField encountered in the sources.
If no sources are provided, then all models.
|
Goes through the given sources and returns a 3-tuple of
the application label, module name, and field name of every
GeometryField encountered in the sources. | def _build_kml_sources(self, sources):
"""
Goes through the given sources and returns a 3-tuple of
the application label, module name, and field name of every
GeometryField encountered in the sources.
If no sources are provided, then all models.
"""
kml_sources =... | [
"def",
"_build_kml_sources",
"(",
"self",
",",
"sources",
")",
":",
"kml_sources",
"=",
"[",
"]",
"if",
"sources",
"is",
"None",
":",
"sources",
"=",
"apps",
".",
"get_models",
"(",
")",
"for",
"source",
"in",
"sources",
":",
"if",
"isinstance",
"(",
"... | [
18,
4
] | [
42,
26
] | python | en | ['en', 'error', 'th'] | False |
KMLSitemap.get_urls | (self, page=1, site=None, protocol=None) |
This method is overrridden so the appropriate `geo_format` attribute
is placed on each URL element.
|
This method is overrridden so the appropriate `geo_format` attribute
is placed on each URL element.
| def get_urls(self, page=1, site=None, protocol=None):
"""
This method is overrridden so the appropriate `geo_format` attribute
is placed on each URL element.
"""
urls = Sitemap.get_urls(self, page=page, site=site, protocol=protocol)
for url in urls:
url['geo_f... | [
"def",
"get_urls",
"(",
"self",
",",
"page",
"=",
"1",
",",
"site",
"=",
"None",
",",
"protocol",
"=",
"None",
")",
":",
"urls",
"=",
"Sitemap",
".",
"get_urls",
"(",
"self",
",",
"page",
"=",
"page",
",",
"site",
"=",
"site",
",",
"protocol",
"=... | [
44,
4
] | [
52,
19
] | python | en | ['en', 'error', 'th'] | False |
save_dt | (obj, attr, dt, orig_tz="UTC") |
Sets given field in an object to a DateTime object with or without
a time zone converted into UTC time zone from given time zone
If there is no time zone on the given DateTime, orig_tz will be used
|
Sets given field in an object to a DateTime object with or without
a time zone converted into UTC time zone from given time zone | def save_dt(obj, attr, dt, orig_tz="UTC"):
"""
Sets given field in an object to a DateTime object with or without
a time zone converted into UTC time zone from given time zone
If there is no time zone on the given DateTime, orig_tz will be used
"""
if dt.tzinfo:
arr = arrow.get(dt).to("... | [
"def",
"save_dt",
"(",
"obj",
",",
"attr",
",",
"dt",
",",
"orig_tz",
"=",
"\"UTC\"",
")",
":",
"if",
"dt",
".",
"tzinfo",
":",
"arr",
"=",
"arrow",
".",
"get",
"(",
"dt",
")",
".",
"to",
"(",
"\"UTC\"",
")",
"else",
":",
"arr",
"=",
"arrow",
... | [
24,
0
] | [
35,
36
] | python | en | ['en', 'error', 'th'] | False |
is_valid_time_slot | (time, time_slot_duration, opening_time) |
Check if given time is correctly aligned with time slots.
:type time: datetime.datetime
:type time_slot_duration: datetime.timedelta
:type opening_time: datetime.datetime
:rtype: bool
|
Check if given time is correctly aligned with time slots. | def is_valid_time_slot(time, time_slot_duration, opening_time):
"""
Check if given time is correctly aligned with time slots.
:type time: datetime.datetime
:type time_slot_duration: datetime.timedelta
:type opening_time: datetime.datetime
:rtype: bool
"""
return not ((time - opening_tim... | [
"def",
"is_valid_time_slot",
"(",
"time",
",",
"time_slot_duration",
",",
"opening_time",
")",
":",
"return",
"not",
"(",
"(",
"time",
"-",
"opening_time",
")",
"%",
"time_slot_duration",
")"
] | [
72,
0
] | [
81,
59
] | python | en | ['en', 'error', 'th'] | False |
humanize_duration | (duration) |
Return the given duration in a localized humanized form.
Examples: "2 hours 30 minutes", "1 hour", "30 minutes"
:type duration: datetime.timedelta
:rtype: str
|
Return the given duration in a localized humanized form. | def humanize_duration(duration):
"""
Return the given duration in a localized humanized form.
Examples: "2 hours 30 minutes", "1 hour", "30 minutes"
:type duration: datetime.timedelta
:rtype: str
"""
hours = duration.days * 24 + duration.seconds // 3600
mins = duration.seconds // 60 % ... | [
"def",
"humanize_duration",
"(",
"duration",
")",
":",
"hours",
"=",
"duration",
".",
"days",
"*",
"24",
"+",
"duration",
".",
"seconds",
"//",
"3600",
"mins",
"=",
"duration",
".",
"seconds",
"//",
"60",
"%",
"60",
"hours_string",
"=",
"ungettext",
"(",... | [
84,
0
] | [
97,
62
] | python | en | ['en', 'error', 'th'] | False |
generate_reservation_xlsx | (reservations) |
Return reservations in Excel xlsx format
The parameter is expected to be a list of dicts with fields:
* unit: unit name str
* resource: resource name str
* begin: begin time datetime
* end: end time datetime
* staff_event: is staff event bool
* user: user email str (optiona... |
Return reservations in Excel xlsx format | def generate_reservation_xlsx(reservations):
"""
Return reservations in Excel xlsx format
The parameter is expected to be a list of dicts with fields:
* unit: unit name str
* resource: resource name str
* begin: begin time datetime
* end: end time datetime
* staff_event: is st... | [
"def",
"generate_reservation_xlsx",
"(",
"reservations",
")",
":",
"from",
"resources",
".",
"models",
"import",
"Reservation",
",",
"RESERVATION_EXTRA_FIELDS",
"output",
"=",
"io",
".",
"BytesIO",
"(",
")",
"workbook",
"=",
"xlsxwriter",
".",
"Workbook",
"(",
"... | [
120,
0
] | [
177,
28
] | python | en | ['en', 'error', 'th'] | False |
build_reservations_ical_file | (reservations) |
Return iCalendar file containing given reservations
|
Return iCalendar file containing given reservations
| def build_reservations_ical_file(reservations):
"""
Return iCalendar file containing given reservations
"""
cal = Calendar()
for reservation in reservations:
event = Event()
begin_utc = timezone.localtime(reservation.begin, timezone.utc)
end_utc = timezone.localtime(reservat... | [
"def",
"build_reservations_ical_file",
"(",
"reservations",
")",
":",
"cal",
"=",
"Calendar",
"(",
")",
"for",
"reservation",
"in",
"reservations",
":",
"event",
"=",
"Event",
"(",
")",
"begin_utc",
"=",
"timezone",
".",
"localtime",
"(",
"reservation",
".",
... | [
228,
0
] | [
247,
24
] | python | en | ['en', 'error', 'th'] | False |
build_ical_feed_url | (ical_token, request) |
Return iCal feed url for given token without query parameters
|
Return iCal feed url for given token without query parameters
| def build_ical_feed_url(ical_token, request):
"""
Return iCal feed url for given token without query parameters
"""
url = reverse('ical-feed', kwargs={'ical_token': ical_token}, request=request)
return url[:url.find('?')] | [
"def",
"build_ical_feed_url",
"(",
"ical_token",
",",
"request",
")",
":",
"url",
"=",
"reverse",
"(",
"'ical-feed'",
",",
"kwargs",
"=",
"{",
"'ical_token'",
":",
"ical_token",
"}",
",",
"request",
"=",
"request",
")",
"return",
"url",
"[",
":",
"url",
... | [
250,
0
] | [
256,
30
] | python | en | ['en', 'error', 'th'] | False |
get_translated_field_count | (image_formset=None) |
Serve a count of how many fields are possible to translate with the translate
buttons in the UI. The image formset is passed as a parameter since it can hold
a number of forms with fields which can be translated.
:param image_formset: formset holding images
:return: dictionary of all languages as ... |
Serve a count of how many fields are possible to translate with the translate
buttons in the UI. The image formset is passed as a parameter since it can hold
a number of forms with fields which can be translated. | def get_translated_field_count(image_formset=None):
"""
Serve a count of how many fields are possible to translate with the translate
buttons in the UI. The image formset is passed as a parameter since it can hold
a number of forms with fields which can be translated.
:param image_formset: formset ... | [
"def",
"get_translated_field_count",
"(",
"image_formset",
"=",
"None",
")",
":",
"resource_form_data",
"=",
"ResourceForm",
".",
"Meta",
".",
"translated_fields",
"translated_fields",
"=",
"resource_form_data",
"lang_num",
"=",
"{",
"}",
"if",
"translated_fields",
":... | [
382,
0
] | [
402,
19
] | python | en | ['en', 'error', 'th'] | False |
DatabaseSchemaEditor._alter_field_type_workaround | (self, model, old_field, new_field) |
Oracle refuses to change from some type to other type.
What we need to do instead is:
- Add a nullable version of the desired field with a temporary name. If
the new column is an auto field, then the temporary column can't be
nullable.
- Update the table to transfer ... |
Oracle refuses to change from some type to other type.
What we need to do instead is:
- Add a nullable version of the desired field with a temporary name. If
the new column is an auto field, then the temporary column can't be
nullable.
- Update the table to transfer ... | def _alter_field_type_workaround(self, model, old_field, new_field):
"""
Oracle refuses to change from some type to other type.
What we need to do instead is:
- Add a nullable version of the desired field with a temporary name. If
the new column is an auto field, then the tempo... | [
"def",
"_alter_field_type_workaround",
"(",
"self",
",",
"model",
",",
"old_field",
",",
"new_field",
")",
":",
"# Make a new field that's like the new one but with a temporary",
"# column name.",
"new_temp_field",
"=",
"copy",
".",
"deepcopy",
"(",
"new_field",
")",
"new... | [
78,
4
] | [
122,
61
] | python | en | ['en', 'error', 'th'] | False |
DatabaseSchemaEditor.normalize_name | (self, name) |
Get the properly shortened and uppercased identifier as returned by
quote_name() but without the quotes.
|
Get the properly shortened and uppercased identifier as returned by
quote_name() but without the quotes.
| def normalize_name(self, name):
"""
Get the properly shortened and uppercased identifier as returned by
quote_name() but without the quotes.
"""
nn = self.quote_name(name)
if nn[0] == '"' and nn[-1] == '"':
nn = nn[1:-1]
return nn | [
"def",
"normalize_name",
"(",
"self",
",",
"name",
")",
":",
"nn",
"=",
"self",
".",
"quote_name",
"(",
"name",
")",
"if",
"nn",
"[",
"0",
"]",
"==",
"'\"'",
"and",
"nn",
"[",
"-",
"1",
"]",
"==",
"'\"'",
":",
"nn",
"=",
"nn",
"[",
"1",
":",
... | [
124,
4
] | [
132,
17
] | python | en | ['en', 'error', 'th'] | False |
DatabaseSchemaEditor._generate_temp_name | (self, for_name) | Generate temporary names for workarounds that need temp columns. | Generate temporary names for workarounds that need temp columns. | def _generate_temp_name(self, for_name):
"""Generate temporary names for workarounds that need temp columns."""
suffix = hex(hash(for_name)).upper()[1:]
return self.normalize_name(for_name + "_" + suffix) | [
"def",
"_generate_temp_name",
"(",
"self",
",",
"for_name",
")",
":",
"suffix",
"=",
"hex",
"(",
"hash",
"(",
"for_name",
")",
")",
".",
"upper",
"(",
")",
"[",
"1",
":",
"]",
"return",
"self",
".",
"normalize_name",
"(",
"for_name",
"+",
"\"_\"",
"+... | [
134,
4
] | [
137,
59
] | python | en | ['en', 'en', 'en'] | True |
TarIO.__init__ | (self, tarfile, file) |
Create file object.
:param tarfile: Name of TAR file.
:param file: Name of member file.
|
Create file object. | def __init__(self, tarfile, file):
"""
Create file object.
:param tarfile: Name of TAR file.
:param file: Name of member file.
"""
self.fh = open(tarfile, "rb")
while True:
s = self.fh.read(512)
if len(s) != 512:
raise OS... | [
"def",
"__init__",
"(",
"self",
",",
"tarfile",
",",
"file",
")",
":",
"self",
".",
"fh",
"=",
"open",
"(",
"tarfile",
",",
"\"rb\"",
")",
"while",
"True",
":",
"s",
"=",
"self",
".",
"fh",
".",
"read",
"(",
"512",
")",
"if",
"len",
"(",
"s",
... | [
24,
4
] | [
54,
55
] | python | en | ['en', 'error', 'th'] | False |
XmlDeserializerSecurityTests.test_no_dtd | (self) |
The XML deserializer shouldn't allow a DTD.
This is the most straightforward way to prevent all entity definitions
and avoid both external entities and entity-expansion attacks.
|
The XML deserializer shouldn't allow a DTD. | def test_no_dtd(self):
"""
The XML deserializer shouldn't allow a DTD.
This is the most straightforward way to prevent all entity definitions
and avoid both external entities and entity-expansion attacks.
"""
xml = '<?xml version="1.0" standalone="no"?><!DOCTYPE example... | [
"def",
"test_no_dtd",
"(",
"self",
")",
":",
"xml",
"=",
"'<?xml version=\"1.0\" standalone=\"no\"?><!DOCTYPE example SYSTEM \"http://example.com/example.dtd\">'",
"with",
"self",
".",
"assertRaises",
"(",
"DTDForbidden",
")",
":",
"next",
"(",
"serializers",
".",
"deserial... | [
591,
4
] | [
601,
53
] | python | en | ['en', 'error', 'th'] | False |
SessionMiddleware.process_response | (self, request, response) |
If request.session was modified, or if the configuration is to save the
session every time, save the changes and set a session cookie or delete
the session cookie if the session has been emptied.
|
If request.session was modified, or if the configuration is to save the
session every time, save the changes and set a session cookie or delete
the session cookie if the session has been emptied.
| def process_response(self, request, response):
"""
If request.session was modified, or if the configuration is to save the
session every time, save the changes and set a session cookie or delete
the session cookie if the session has been emptied.
"""
try:
acce... | [
"def",
"process_response",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"try",
":",
"accessed",
"=",
"request",
".",
"session",
".",
"accessed",
"modified",
"=",
"request",
".",
"session",
".",
"modified",
"empty",
"=",
"request",
".",
"session"... | [
17,
4
] | [
55,
23
] | python | en | ['en', 'error', 'th'] | False |
_check_middleware_classes | (app_configs=None, **kwargs) |
Checks if the user has *not* overridden the ``MIDDLEWARE_CLASSES`` setting &
warns them about the global default changes.
|
Checks if the user has *not* overridden the ``MIDDLEWARE_CLASSES`` setting &
warns them about the global default changes.
| def _check_middleware_classes(app_configs=None, **kwargs):
"""
Checks if the user has *not* overridden the ``MIDDLEWARE_CLASSES`` setting &
warns them about the global default changes.
"""
from django.conf import settings
# MIDDLEWARE_CLASSES is overridden by default by startproject. If users
... | [
"def",
"_check_middleware_classes",
"(",
"app_configs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"# MIDDLEWARE_CLASSES is overridden by default by startproject. If users",
"# have removed this override then we'll warn ... | [
12,
0
] | [
35,
17
] | python | en | ['en', 'error', 'th'] | False |
get_connection | (backend=None, fail_silently=False, **kwds) | Load an email backend and return an instance of it.
If backend is None (default), use settings.EMAIL_BACKEND.
Both fail_silently and other keyword arguments are used in the
constructor of the backend.
| Load an email backend and return an instance of it. | def get_connection(backend=None, fail_silently=False, **kwds):
"""Load an email backend and return an instance of it.
If backend is None (default), use settings.EMAIL_BACKEND.
Both fail_silently and other keyword arguments are used in the
constructor of the backend.
"""
klass = import_string(b... | [
"def",
"get_connection",
"(",
"backend",
"=",
"None",
",",
"fail_silently",
"=",
"False",
",",
"*",
"*",
"kwds",
")",
":",
"klass",
"=",
"import_string",
"(",
"backend",
"or",
"settings",
".",
"EMAIL_BACKEND",
")",
"return",
"klass",
"(",
"fail_silently",
... | [
25,
0
] | [
34,
53
] | python | en | ['en', 'en', 'en'] | True |
send_mail | (subject, message, from_email, recipient_list,
fail_silently=False, auth_user=None, auth_password=None,
connection=None, html_message=None) |
Easy wrapper for sending a single message to a recipient list. All members
of the recipient list will see the other recipients in the 'To' field.
If auth_user is None, use the EMAIL_HOST_USER setting.
If auth_password is None, use the EMAIL_HOST_PASSWORD setting.
Note: The API for this method is ... |
Easy wrapper for sending a single message to a recipient list. All members
of the recipient list will see the other recipients in the 'To' field. | def send_mail(subject, message, from_email, recipient_list,
fail_silently=False, auth_user=None, auth_password=None,
connection=None, html_message=None):
"""
Easy wrapper for sending a single message to a recipient list. All members
of the recipient list will see the other recipi... | [
"def",
"send_mail",
"(",
"subject",
",",
"message",
",",
"from_email",
",",
"recipient_list",
",",
"fail_silently",
"=",
"False",
",",
"auth_user",
"=",
"None",
",",
"auth_password",
"=",
"None",
",",
"connection",
"=",
"None",
",",
"html_message",
"=",
"Non... | [
37,
0
] | [
59,
22
] | python | en | ['en', 'error', 'th'] | False |
send_mass_mail | (datatuple, fail_silently=False, auth_user=None,
auth_password=None, connection=None) |
Given a datatuple of (subject, message, from_email, recipient_list), send
each message to each recipient list. Return the number of emails sent.
If from_email is None, use the DEFAULT_FROM_EMAIL setting.
If auth_user and auth_password are set, use them to log in.
If auth_user is None, use the EMAI... |
Given a datatuple of (subject, message, from_email, recipient_list), send
each message to each recipient list. Return the number of emails sent. | def send_mass_mail(datatuple, fail_silently=False, auth_user=None,
auth_password=None, connection=None):
"""
Given a datatuple of (subject, message, from_email, recipient_list), send
each message to each recipient list. Return the number of emails sent.
If from_email is None, use the... | [
"def",
"send_mass_mail",
"(",
"datatuple",
",",
"fail_silently",
"=",
"False",
",",
"auth_user",
"=",
"None",
",",
"auth_password",
"=",
"None",
",",
"connection",
"=",
"None",
")",
":",
"connection",
"=",
"connection",
"or",
"get_connection",
"(",
"username",... | [
62,
0
] | [
85,
45
] | python | en | ['en', 'error', 'th'] | False |
mail_admins | (subject, message, fail_silently=False, connection=None,
html_message=None) | Send a message to the admins, as defined by the ADMINS setting. | Send a message to the admins, as defined by the ADMINS setting. | def mail_admins(subject, message, fail_silently=False, connection=None,
html_message=None):
"""Send a message to the admins, as defined by the ADMINS setting."""
if not settings.ADMINS:
return
if not all(isinstance(a, (list, tuple)) and len(a) == 2 for a in settings.ADMINS):
... | [
"def",
"mail_admins",
"(",
"subject",
",",
"message",
",",
"fail_silently",
"=",
"False",
",",
"connection",
"=",
"None",
",",
"html_message",
"=",
"None",
")",
":",
"if",
"not",
"settings",
".",
"ADMINS",
":",
"return",
"if",
"not",
"all",
"(",
"isinsta... | [
88,
0
] | [
102,
42
] | python | en | ['en', 'en', 'en'] | True |
mail_managers | (subject, message, fail_silently=False, connection=None,
html_message=None) | Send a message to the managers, as defined by the MANAGERS setting. | Send a message to the managers, as defined by the MANAGERS setting. | def mail_managers(subject, message, fail_silently=False, connection=None,
html_message=None):
"""Send a message to the managers, as defined by the MANAGERS setting."""
if not settings.MANAGERS:
return
if not all(isinstance(a, (list, tuple)) and len(a) == 2 for a in settings.MANAGER... | [
"def",
"mail_managers",
"(",
"subject",
",",
"message",
",",
"fail_silently",
"=",
"False",
",",
"connection",
"=",
"None",
",",
"html_message",
"=",
"None",
")",
":",
"if",
"not",
"settings",
".",
"MANAGERS",
":",
"return",
"if",
"not",
"all",
"(",
"isi... | [
105,
0
] | [
119,
42
] | python | en | ['en', 'en', 'en'] | True |
check_cs_op | (result, func, cargs) | Check the status code of a coordinate sequence operation. | Check the status code of a coordinate sequence operation. | def check_cs_op(result, func, cargs):
"Check the status code of a coordinate sequence operation."
if result == 0:
raise GEOSException('Could not set value on coordinate sequence')
else:
return result | [
"def",
"check_cs_op",
"(",
"result",
",",
"func",
",",
"cargs",
")",
":",
"if",
"result",
"==",
"0",
":",
"raise",
"GEOSException",
"(",
"'Could not set value on coordinate sequence'",
")",
"else",
":",
"return",
"result"
] | [
9,
0
] | [
14,
21
] | python | en | ['en', 'en', 'en'] | True |
check_cs_get | (result, func, cargs) | Check the coordinate sequence retrieval. | Check the coordinate sequence retrieval. | def check_cs_get(result, func, cargs):
"Check the coordinate sequence retrieval."
check_cs_op(result, func, cargs)
# Object in by reference, return its value.
return last_arg_byref(cargs) | [
"def",
"check_cs_get",
"(",
"result",
",",
"func",
",",
"cargs",
")",
":",
"check_cs_op",
"(",
"result",
",",
"func",
",",
"cargs",
")",
"# Object in by reference, return its value.",
"return",
"last_arg_byref",
"(",
"cargs",
")"
] | [
17,
0
] | [
21,
32
] | python | en | ['en', 'en', 'en'] | True |
MigrationOptimizer.optimize | (self, operations, app_label=None) |
Main optimization entry point. Pass in a list of Operation instances,
get out a new list of Operation instances.
Unfortunately, due to the scope of the optimization (two combinable
operations might be separated by several hundred others), this can't be
done as a peephole optimi... |
Main optimization entry point. Pass in a list of Operation instances,
get out a new list of Operation instances. | def optimize(self, operations, app_label=None):
"""
Main optimization entry point. Pass in a list of Operation instances,
get out a new list of Operation instances.
Unfortunately, due to the scope of the optimization (two combinable
operations might be separated by several hundr... | [
"def",
"optimize",
"(",
"self",
",",
"operations",
",",
"app_label",
"=",
"None",
")",
":",
"# Internal tracking variable for test assertions about # of loops",
"self",
".",
"_iterations",
"=",
"0",
"while",
"True",
":",
"result",
"=",
"self",
".",
"optimize_inner",... | [
11,
4
] | [
38,
31
] | python | en | ['en', 'error', 'th'] | False |
MigrationOptimizer.optimize_inner | (self, operations, app_label=None) | Inner optimization loop. | Inner optimization loop. | def optimize_inner(self, operations, app_label=None):
"""Inner optimization loop."""
new_operations = []
for i, operation in enumerate(operations):
right = True # Should we reduce on the right or on the left.
# Compare it to each operation after it
for j, oth... | [
"def",
"optimize_inner",
"(",
"self",
",",
"operations",
",",
"app_label",
"=",
"None",
")",
":",
"new_operations",
"=",
"[",
"]",
"for",
"i",
",",
"operation",
"in",
"enumerate",
"(",
"operations",
")",
":",
"right",
"=",
"True",
"# Should we reduce on the ... | [
40,
4
] | [
69,
29
] | python | af | ['es', 'af', 'en'] | False |
parse_args | () | Parses command line arguments. | Parses command line arguments. | def parse_args():
"""Parses command line arguments."""
parser = argparse.ArgumentParser(description="Tool to run attacks and defenses.")
parser.add_argument("--attacks_dir", required=True, help="Location of all attacks.")
parser.add_argument(
"--targeted_attacks_dir",
required=True,
... | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Tool to run attacks and defenses.\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--attacks_dir\"",
",",
"required",
"=",
"True",
",",
"help",
"=",
... | [
15,
0
] | [
56,
30
] | python | en | ['en', 'fr', 'en'] | True |
read_submissions_from_directory | (dirname, use_gpu) | Scans directory and read all submissions.
Args:
dirname: directory to scan.
use_gpu: whether submissions should use GPU. This argument is
used to pick proper Docker container for each submission and create
instance of Attack or Defense class.
Returns:
List with submissions (s... | Scans directory and read all submissions. | def read_submissions_from_directory(dirname, use_gpu):
"""Scans directory and read all submissions.
Args:
dirname: directory to scan.
use_gpu: whether submissions should use GPU. This argument is
used to pick proper Docker container for each submission and create
instance of Attack ... | [
"def",
"read_submissions_from_directory",
"(",
"dirname",
",",
"use_gpu",
")",
":",
"result",
"=",
"[",
"]",
"for",
"sub_dir",
"in",
"os",
".",
"listdir",
"(",
"dirname",
")",
":",
"submission_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
"... | [
147,
0
] | [
184,
17
] | python | en | ['en', 'en', 'en'] | True |
load_defense_output | (filename) | Loads output of defense from given file. | Loads output of defense from given file. | def load_defense_output(filename):
"""Loads output of defense from given file."""
result = {}
with open(filename) as f:
for row in csv.reader(f):
try:
image_filename = row[0]
if image_filename.endswith(".png") or image_filename.endswith(".jpg"):
... | [
"def",
"load_defense_output",
"(",
"filename",
")",
":",
"result",
"=",
"{",
"}",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"for",
"row",
"in",
"csv",
".",
"reader",
"(",
"f",
")",
":",
"try",
":",
"image_filename",
"=",
"row",
"[",
"0"... | [
363,
0
] | [
376,
17
] | python | en | ['en', 'en', 'en'] | True |
compute_and_save_scores_and_ranking | (
attacks_output,
defenses_output,
dataset_meta,
output_dir,
save_all_classification=False,
) | Computes scores and ranking and saves it.
Args:
attacks_output: output of attacks, instance of AttacksOutput class.
defenses_output: outputs of defenses. Dictionary of dictionaries, key in
outer dictionary is name of the defense, key of inner dictionary is
name of the image, value of in... | Computes scores and ranking and saves it. | def compute_and_save_scores_and_ranking(
attacks_output,
defenses_output,
dataset_meta,
output_dir,
save_all_classification=False,
):
"""Computes scores and ranking and saves it.
Args:
attacks_output: output of attacks, instance of AttacksOutput class.
defenses_output: outputs o... | [
"def",
"compute_and_save_scores_and_ranking",
"(",
"attacks_output",
",",
"defenses_output",
",",
"dataset_meta",
",",
"output_dir",
",",
"save_all_classification",
"=",
"False",
",",
")",
":",
"def",
"write_ranking",
"(",
"filename",
",",
"header",
",",
"names",
",... | [
379,
0
] | [
552,
21
] | python | en | ['en', 'en', 'en'] | True |
main | () | Run all attacks against all defenses and compute results. | Run all attacks against all defenses and compute results. | def main():
"""Run all attacks against all defenses and compute results."""
args = parse_args()
attacks_output_dir = os.path.join(args.intermediate_results_dir, "attacks_output")
targeted_attacks_output_dir = os.path.join(
args.intermediate_results_dir, "targeted_attacks_output"
)
defens... | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"parse_args",
"(",
")",
"attacks_output_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"args",
".",
"intermediate_results_dir",
",",
"\"attacks_output\"",
")",
"targeted_attacks_output_dir",
"=",
"os",
".",
"path",
... | [
555,
0
] | [
641,
5
] | python | en | ['en', 'en', 'en'] | True |
Submission.__init__ | (self, directory, container, entry_point, use_gpu) | Initializes instance of Submission class.
Args:
directory: location of the submission.
container: URL of Docker container which should be used to run submission.
entry_point: entry point script, which invokes submission.
use_gpu: whether to use Docker with GPU or not.
... | Initializes instance of Submission class. | def __init__(self, directory, container, entry_point, use_gpu):
"""Initializes instance of Submission class.
Args:
directory: location of the submission.
container: URL of Docker container which should be used to run submission.
entry_point: entry point script, which invok... | [
"def",
"__init__",
"(",
"self",
",",
"directory",
",",
"container",
",",
"entry_point",
",",
"use_gpu",
")",
":",
"self",
".",
"name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"directory",
")",
"self",
".",
"directory",
"=",
"directory",
"self",
"... | [
62,
4
] | [
75,
30
] | python | en | ['en', 'en', 'en'] | True |
Submission.docker_binary | (self) | Returns appropriate Docker binary to use. | Returns appropriate Docker binary to use. | def docker_binary(self):
"""Returns appropriate Docker binary to use."""
return "nvidia-docker" if self.use_gpu else "docker" | [
"def",
"docker_binary",
"(",
"self",
")",
":",
"return",
"\"nvidia-docker\"",
"if",
"self",
".",
"use_gpu",
"else",
"\"docker\""
] | [
77,
4
] | [
79,
60
] | python | en | ['en', 'fy', 'en'] | True |
Attack.run | (self, input_dir, output_dir, epsilon) | Runs attack inside Docker.
Args:
input_dir: directory with input (dataset).
output_dir: directory where output (adversarial images) should be written.
epsilon: maximum allowed size of adversarial perturbation,
should be in range [0, 255].
| Runs attack inside Docker. | def run(self, input_dir, output_dir, epsilon):
"""Runs attack inside Docker.
Args:
input_dir: directory with input (dataset).
output_dir: directory where output (adversarial images) should be written.
epsilon: maximum allowed size of adversarial perturbation,
s... | [
"def",
"run",
"(",
"self",
",",
"input_dir",
",",
"output_dir",
",",
"epsilon",
")",
":",
"print",
"(",
"\"Running attack \"",
",",
"self",
".",
"name",
")",
"cmd",
"=",
"[",
"self",
".",
"docker_binary",
"(",
")",
",",
"\"run\"",
",",
"\"-v\"",
",",
... | [
85,
4
] | [
113,
28
] | python | en | ['en', 'sv', 'en'] | True |
Defense.run | (self, input_dir, output_dir) | Runs defense inside Docker.
Args:
input_dir: directory with input (adversarial images).
output_dir: directory to write output (classification result).
| Runs defense inside Docker. | def run(self, input_dir, output_dir):
"""Runs defense inside Docker.
Args:
input_dir: directory with input (adversarial images).
output_dir: directory to write output (classification result).
"""
print("Running defense ", self.name)
cmd = [
self.d... | [
"def",
"run",
"(",
"self",
",",
"input_dir",
",",
"output_dir",
")",
":",
"print",
"(",
"\"Running defense \"",
",",
"self",
".",
"name",
")",
"cmd",
"=",
"[",
"self",
".",
"docker_binary",
"(",
")",
",",
"\"run\"",
",",
"\"-v\"",
",",
"\"{0}:/input_imag... | [
119,
4
] | [
144,
28
] | python | en | ['fr', 'sv', 'en'] | False |
AttacksOutput.__init__ | (
self,
dataset_dir,
attacks_output_dir,
targeted_attacks_output_dir,
all_adv_examples_dir,
epsilon,
) | Initializes instance of AttacksOutput class.
Args:
dataset_dir: location of the dataset.
attacks_output_dir: where to write results of attacks.
targeted_attacks_output_dir: where to write results of targeted attacks.
all_adv_examples_dir: directory to copy all adversaria... | Initializes instance of AttacksOutput class. | def __init__(
self,
dataset_dir,
attacks_output_dir,
targeted_attacks_output_dir,
all_adv_examples_dir,
epsilon,
):
"""Initializes instance of AttacksOutput class.
Args:
dataset_dir: location of the dataset.
attacks_output_dir: whe... | [
"def",
"__init__",
"(",
"self",
",",
"dataset_dir",
",",
"attacks_output_dir",
",",
"targeted_attacks_output_dir",
",",
"all_adv_examples_dir",
",",
"epsilon",
",",
")",
":",
"self",
".",
"attacks_output_dir",
"=",
"attacks_output_dir",
"self",
".",
"targeted_attacks_... | [
190,
4
] | [
217,
43
] | python | en | ['en', 'en', 'en'] | True |
AttacksOutput._load_dataset_clipping | (self, dataset_dir, epsilon) | Helper method which loads dataset and determines clipping range.
Args:
dataset_dir: location of the dataset.
epsilon: maximum allowed size of adversarial perturbation.
| Helper method which loads dataset and determines clipping range. | def _load_dataset_clipping(self, dataset_dir, epsilon):
"""Helper method which loads dataset and determines clipping range.
Args:
dataset_dir: location of the dataset.
epsilon: maximum allowed size of adversarial perturbation.
"""
self.dataset_max_clip = {}
s... | [
"def",
"_load_dataset_clipping",
"(",
"self",
",",
"dataset_dir",
",",
"epsilon",
")",
":",
"self",
".",
"dataset_max_clip",
"=",
"{",
"}",
"self",
".",
"dataset_min_clip",
"=",
"{",
"}",
"self",
".",
"_dataset_image_count",
"=",
"0",
"for",
"fname",
"in",
... | [
219,
4
] | [
243,
13
] | python | en | ['en', 'en', 'en'] | True |
AttacksOutput.clip_and_copy_attack_outputs | (self, attack_name, is_targeted) | Clips results of attack and copy it to directory with all images.
Args:
attack_name: name of the attack.
is_targeted: if True then attack is targeted, otherwise non-targeted.
| Clips results of attack and copy it to directory with all images. | def clip_and_copy_attack_outputs(self, attack_name, is_targeted):
"""Clips results of attack and copy it to directory with all images.
Args:
attack_name: name of the attack.
is_targeted: if True then attack is targeted, otherwise non-targeted.
"""
if is_targeted:
... | [
"def",
"clip_and_copy_attack_outputs",
"(",
"self",
",",
"attack_name",
",",
"is_targeted",
")",
":",
"if",
"is_targeted",
":",
"self",
".",
"_targeted_attack_names",
".",
"add",
"(",
"attack_name",
")",
"else",
":",
"self",
".",
"_attack_names",
".",
"add",
"... | [
245,
4
] | [
289,
13
] | python | en | ['en', 'en', 'en'] | True |
AttacksOutput.attack_names | (self) | Returns list of all non-targeted attacks. | Returns list of all non-targeted attacks. | def attack_names(self):
"""Returns list of all non-targeted attacks."""
return self._attack_names | [
"def",
"attack_names",
"(",
"self",
")",
":",
"return",
"self",
".",
"_attack_names"
] | [
292,
4
] | [
294,
33
] | python | en | ['en', 'en', 'en'] | True |
AttacksOutput.targeted_attack_names | (self) | Returns list of all targeted attacks. | Returns list of all targeted attacks. | def targeted_attack_names(self):
"""Returns list of all targeted attacks."""
return self._targeted_attack_names | [
"def",
"targeted_attack_names",
"(",
"self",
")",
":",
"return",
"self",
".",
"_targeted_attack_names"
] | [
297,
4
] | [
299,
42
] | python | en | ['en', 'en', 'en'] | True |
AttacksOutput.attack_image_count | (self) | Returns number of all images generated by non-targeted attacks. | Returns number of all images generated by non-targeted attacks. | def attack_image_count(self):
"""Returns number of all images generated by non-targeted attacks."""
return self._attack_image_count | [
"def",
"attack_image_count",
"(",
"self",
")",
":",
"return",
"self",
".",
"_attack_image_count"
] | [
302,
4
] | [
304,
39
] | python | en | ['en', 'en', 'en'] | True |
AttacksOutput.dataset_image_count | (self) | Returns number of all images in the dataset. | Returns number of all images in the dataset. | def dataset_image_count(self):
"""Returns number of all images in the dataset."""
return self._dataset_image_count | [
"def",
"dataset_image_count",
"(",
"self",
")",
":",
"return",
"self",
".",
"_dataset_image_count"
] | [
307,
4
] | [
309,
40
] | python | en | ['en', 'en', 'en'] | True |
AttacksOutput.targeted_attack_image_count | (self) | Returns number of all images generated by targeted attacks. | Returns number of all images generated by targeted attacks. | def targeted_attack_image_count(self):
"""Returns number of all images generated by targeted attacks."""
return self._targeted_attack_image_count | [
"def",
"targeted_attack_image_count",
"(",
"self",
")",
":",
"return",
"self",
".",
"_targeted_attack_image_count"
] | [
312,
4
] | [
314,
48
] | python | en | ['en', 'en', 'en'] | True |
AttacksOutput.image_by_base_filename | (self, filename) | Returns information about image based on it's filename. | Returns information about image based on it's filename. | def image_by_base_filename(self, filename):
"""Returns information about image based on it's filename."""
return self._output_to_attack_mapping[filename] | [
"def",
"image_by_base_filename",
"(",
"self",
",",
"filename",
")",
":",
"return",
"self",
".",
"_output_to_attack_mapping",
"[",
"filename",
"]"
] | [
316,
4
] | [
318,
55
] | python | en | ['en', 'en', 'en'] | True |
DatasetMetadata.__init__ | (self, filename) | Initializes instance of DatasetMetadata. | Initializes instance of DatasetMetadata. | def __init__(self, filename):
"""Initializes instance of DatasetMetadata."""
self._true_labels = {}
self._target_classes = {}
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
try:
row_idx_image_id = header_row.... | [
"def",
"__init__",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"_true_labels",
"=",
"{",
"}",
"self",
".",
"_target_classes",
"=",
"{",
"}",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"reader",
"=",
"csv",
".",
"reader",
"(",
"f... | [
324,
4
] | [
346,
71
] | python | en | ['en', 'zu', 'en'] | True |
DatasetMetadata.get_true_label | (self, image_id) | Returns true label for image with given ID. | Returns true label for image with given ID. | def get_true_label(self, image_id):
"""Returns true label for image with given ID."""
return self._true_labels[image_id] | [
"def",
"get_true_label",
"(",
"self",
",",
"image_id",
")",
":",
"return",
"self",
".",
"_true_labels",
"[",
"image_id",
"]"
] | [
348,
4
] | [
350,
42
] | python | en | ['en', 'en', 'en'] | True |
DatasetMetadata.get_target_class | (self, image_id) | Returns target class for image with given ID. | Returns target class for image with given ID. | def get_target_class(self, image_id):
"""Returns target class for image with given ID."""
return self._target_classes[image_id] | [
"def",
"get_target_class",
"(",
"self",
",",
"image_id",
")",
":",
"return",
"self",
".",
"_target_classes",
"[",
"image_id",
"]"
] | [
352,
4
] | [
354,
45
] | python | en | ['en', 'en', 'en'] | True |
DatasetMetadata.save_target_classes | (self, filename) | Saves target classed for all dataset images into given file. | Saves target classed for all dataset images into given file. | def save_target_classes(self, filename):
"""Saves target classed for all dataset images into given file."""
with open(filename, "w") as f:
for k, v in self._target_classes.items():
f.write("{0}.png,{1}\n".format(k, v)) | [
"def",
"save_target_classes",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"\"w\"",
")",
"as",
"f",
":",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_target_classes",
".",
"items",
"(",
")",
":",
"f",
".",
"write",
"(... | [
356,
4
] | [
360,
53
] | python | en | ['en', 'en', 'en'] | True |
LutBuilder._string_permute | (self, pattern, permutation) | string_permute takes a pattern and a permutation and returns the
string permuted according to the permutation list.
| string_permute takes a pattern and a permutation and returns the
string permuted according to the permutation list.
| def _string_permute(self, pattern, permutation):
"""string_permute takes a pattern and a permutation and returns the
string permuted according to the permutation list.
"""
assert len(permutation) == 9
return "".join(pattern[p] for p in permutation) | [
"def",
"_string_permute",
"(",
"self",
",",
"pattern",
",",
"permutation",
")",
":",
"assert",
"len",
"(",
"permutation",
")",
"==",
"9",
"return",
"\"\"",
".",
"join",
"(",
"pattern",
"[",
"p",
"]",
"for",
"p",
"in",
"permutation",
")"
] | [
98,
4
] | [
103,
55
] | python | en | ['en', 'en', 'en'] | True |
LutBuilder._pattern_permute | (self, basic_pattern, options, basic_result) | pattern_permute takes a basic pattern and its result and clones
the pattern according to the modifications described in the $options
parameter. It returns a list of all cloned patterns. | pattern_permute takes a basic pattern and its result and clones
the pattern according to the modifications described in the $options
parameter. It returns a list of all cloned patterns. | def _pattern_permute(self, basic_pattern, options, basic_result):
"""pattern_permute takes a basic pattern and its result and clones
the pattern according to the modifications described in the $options
parameter. It returns a list of all cloned patterns."""
patterns = [(basic_pattern, ba... | [
"def",
"_pattern_permute",
"(",
"self",
",",
"basic_pattern",
",",
"options",
",",
"basic_result",
")",
":",
"patterns",
"=",
"[",
"(",
"basic_pattern",
",",
"basic_result",
")",
"]",
"# rotations",
"if",
"\"4\"",
"in",
"options",
":",
"res",
"=",
"patterns"... | [
105,
4
] | [
133,
23
] | python | en | ['en', 'en', 'en'] | True |
LutBuilder.build_lut | (self) | Compile all patterns into a morphology lut.
TBD :Build based on (file) morphlut:modify_lut
| Compile all patterns into a morphology lut. | def build_lut(self):
"""Compile all patterns into a morphology lut.
TBD :Build based on (file) morphlut:modify_lut
"""
self.build_default_lut()
patterns = []
# Parse and create symmetries of the patterns strings
for p in self.patterns:
m = re.search(... | [
"def",
"build_lut",
"(",
"self",
")",
":",
"self",
".",
"build_default_lut",
"(",
")",
"patterns",
"=",
"[",
"]",
"# Parse and create symmetries of the patterns strings",
"for",
"p",
"in",
"self",
".",
"patterns",
":",
"m",
"=",
"re",
".",
"search",
"(",
"r\... | [
135,
4
] | [
175,
23
] | python | en | ['en', 'en', 'en'] | True |
MorphOp.__init__ | (self, lut=None, op_name=None, patterns=None) | Create a binary morphological operator | Create a binary morphological operator | def __init__(self, lut=None, op_name=None, patterns=None):
"""Create a binary morphological operator"""
self.lut = lut
if op_name is not None:
self.lut = LutBuilder(op_name=op_name).build_lut()
elif patterns is not None:
self.lut = LutBuilder(patterns=patterns).bu... | [
"def",
"__init__",
"(",
"self",
",",
"lut",
"=",
"None",
",",
"op_name",
"=",
"None",
",",
"patterns",
"=",
"None",
")",
":",
"self",
".",
"lut",
"=",
"lut",
"if",
"op_name",
"is",
"not",
"None",
":",
"self",
".",
"lut",
"=",
"LutBuilder",
"(",
"... | [
181,
4
] | [
187,
64
] | python | en | ['en', 'ig', 'en'] | True |
MorphOp.apply | (self, image) | Run a single morphological operation on an image
Returns a tuple of the number of changed pixels and the
morphed image | Run a single morphological operation on an image | def apply(self, image):
"""Run a single morphological operation on an image
Returns a tuple of the number of changed pixels and the
morphed image"""
if self.lut is None:
raise Exception("No operator loaded")
if image.mode != "L":
raise Exception("Image m... | [
"def",
"apply",
"(",
"self",
",",
"image",
")",
":",
"if",
"self",
".",
"lut",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"No operator loaded\"",
")",
"if",
"image",
".",
"mode",
"!=",
"\"L\"",
":",
"raise",
"Exception",
"(",
"\"Image must be binary, ... | [
189,
4
] | [
201,
30
] | python | en | ['en', 'en', 'en'] | True |
MorphOp.match | (self, image) | Get a list of coordinates matching the morphological operation on
an image.
Returns a list of tuples of (x,y) coordinates
of all matching pixels. See :ref:`coordinate-system`. | Get a list of coordinates matching the morphological operation on
an image. | def match(self, image):
"""Get a list of coordinates matching the morphological operation on
an image.
Returns a list of tuples of (x,y) coordinates
of all matching pixels. See :ref:`coordinate-system`."""
if self.lut is None:
raise Exception("No operator loaded")
... | [
"def",
"match",
"(",
"self",
",",
"image",
")",
":",
"if",
"self",
".",
"lut",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"No operator loaded\"",
")",
"if",
"image",
".",
"mode",
"!=",
"\"L\"",
":",
"raise",
"Exception",
"(",
"\"Image must be binary, ... | [
203,
4
] | [
214,
64
] | python | en | ['en', 'en', 'en'] | True |
MorphOp.get_on_pixels | (self, image) | Get a list of all turned on pixels in a binary image
Returns a list of tuples of (x,y) coordinates
of all matching pixels. See :ref:`coordinate-system`. | Get a list of all turned on pixels in a binary image | def get_on_pixels(self, image):
"""Get a list of all turned on pixels in a binary image
Returns a list of tuples of (x,y) coordinates
of all matching pixels. See :ref:`coordinate-system`."""
if image.mode != "L":
raise Exception("Image must be binary, meaning it must use mo... | [
"def",
"get_on_pixels",
"(",
"self",
",",
"image",
")",
":",
"if",
"image",
".",
"mode",
"!=",
"\"L\"",
":",
"raise",
"Exception",
"(",
"\"Image must be binary, meaning it must use mode L\"",
")",
"return",
"_imagingmorph",
".",
"get_on_pixels",
"(",
"image",
".",... | [
216,
4
] | [
224,
55
] | python | en | ['en', 'en', 'en'] | True |
MorphOp.load_lut | (self, filename) | Load an operator from an mrl file | Load an operator from an mrl file | def load_lut(self, filename):
"""Load an operator from an mrl file"""
with open(filename, "rb") as f:
self.lut = bytearray(f.read())
if len(self.lut) != LUT_SIZE:
self.lut = None
raise Exception("Wrong size operator file!") | [
"def",
"load_lut",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"as",
"f",
":",
"self",
".",
"lut",
"=",
"bytearray",
"(",
"f",
".",
"read",
"(",
")",
")",
"if",
"len",
"(",
"self",
".",
"lut",
")... | [
226,
4
] | [
233,
56
] | python | en | ['en', 'en', 'en'] | True |
MorphOp.save_lut | (self, filename) | Save an operator to an mrl file | Save an operator to an mrl file | def save_lut(self, filename):
"""Save an operator to an mrl file"""
if self.lut is None:
raise Exception("No operator loaded")
with open(filename, "wb") as f:
f.write(self.lut) | [
"def",
"save_lut",
"(",
"self",
",",
"filename",
")",
":",
"if",
"self",
".",
"lut",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"No operator loaded\"",
")",
"with",
"open",
"(",
"filename",
",",
"\"wb\"",
")",
"as",
"f",
":",
"f",
".",
"write",
... | [
235,
4
] | [
240,
29
] | python | en | ['en', 'en', 'en'] | True |
MorphOp.set_lut | (self, lut) | Set the lut from an external source | Set the lut from an external source | def set_lut(self, lut):
"""Set the lut from an external source"""
self.lut = lut | [
"def",
"set_lut",
"(",
"self",
",",
"lut",
")",
":",
"self",
".",
"lut",
"=",
"lut"
] | [
242,
4
] | [
244,
22
] | python | en | ['en', 'lb', 'en'] | True |
dumps | (obj, key=None, salt='django.core.signing', serializer=JSONSerializer, compress=False) |
Returns URL-safe, sha1 signed base64 compressed JSON string. If key is
None, settings.SECRET_KEY is used instead.
If compress is True (not the default) checks if compressing using zlib can
save some space. Prepends a '.' to signify compression. This is included
in the signature, to protect against... |
Returns URL-safe, sha1 signed base64 compressed JSON string. If key is
None, settings.SECRET_KEY is used instead. | def dumps(obj, key=None, salt='django.core.signing', serializer=JSONSerializer, compress=False):
"""
Returns URL-safe, sha1 signed base64 compressed JSON string. If key is
None, settings.SECRET_KEY is used instead.
If compress is True (not the default) checks if compressing using zlib can
save some... | [
"def",
"dumps",
"(",
"obj",
",",
"key",
"=",
"None",
",",
"salt",
"=",
"'django.core.signing'",
",",
"serializer",
"=",
"JSONSerializer",
",",
"compress",
"=",
"False",
")",
":",
"data",
"=",
"serializer",
"(",
")",
".",
"dumps",
"(",
"obj",
")",
"# Fl... | [
94,
0
] | [
124,
56
] | python | en | ['en', 'error', 'th'] | False |
loads | (s, key=None, salt='django.core.signing', serializer=JSONSerializer, max_age=None) |
Reverse of dumps(), raises BadSignature if signature fails.
The serializer is expected to accept a bytestring.
|
Reverse of dumps(), raises BadSignature if signature fails. | def loads(s, key=None, salt='django.core.signing', serializer=JSONSerializer, max_age=None):
"""
Reverse of dumps(), raises BadSignature if signature fails.
The serializer is expected to accept a bytestring.
"""
# TimestampSigner.unsign always returns unicode but base64 and zlib
# compression o... | [
"def",
"loads",
"(",
"s",
",",
"key",
"=",
"None",
",",
"salt",
"=",
"'django.core.signing'",
",",
"serializer",
"=",
"JSONSerializer",
",",
"max_age",
"=",
"None",
")",
":",
"# TimestampSigner.unsign always returns unicode but base64 and zlib",
"# compression operate o... | [
127,
0
] | [
144,
35
] | python | en | ['en', 'error', 'th'] | False |
TimestampSigner.unsign | (self, value, max_age=None) |
Retrieve original value and check it wasn't signed more
than max_age seconds ago.
|
Retrieve original value and check it wasn't signed more
than max_age seconds ago.
| def unsign(self, value, max_age=None):
"""
Retrieve original value and check it wasn't signed more
than max_age seconds ago.
"""
result = super(TimestampSigner, self).unsign(value)
value, timestamp = result.rsplit(self.sep, 1)
timestamp = baseconv.base62.decode(ti... | [
"def",
"unsign",
"(",
"self",
",",
"value",
",",
"max_age",
"=",
"None",
")",
":",
"result",
"=",
"super",
"(",
"TimestampSigner",
",",
"self",
")",
".",
"unsign",
"(",
"value",
")",
"value",
",",
"timestamp",
"=",
"result",
".",
"rsplit",
"(",
"self... | [
185,
4
] | [
199,
20
] | python | en | ['en', 'error', 'th'] | False |
MomentumIterativeMethod.__init__ | (self, model, sess=None, dtypestr="float32", **kwargs) |
Create a MomentumIterativeMethod instance.
Note: the model parameter should be an instance of the
cleverhans.model.Model abstraction provided by CleverHans.
|
Create a MomentumIterativeMethod instance.
Note: the model parameter should be an instance of the
cleverhans.model.Model abstraction provided by CleverHans.
| def __init__(self, model, sess=None, dtypestr="float32", **kwargs):
"""
Create a MomentumIterativeMethod instance.
Note: the model parameter should be an instance of the
cleverhans.model.Model abstraction provided by CleverHans.
"""
super(MomentumIterativeMethod, self)._... | [
"def",
"__init__",
"(",
"self",
",",
"model",
",",
"sess",
"=",
"None",
",",
"dtypestr",
"=",
"\"float32\"",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"MomentumIterativeMethod",
",",
"self",
")",
".",
"__init__",
"(",
"model",
",",
"sess",
",",
... | [
28,
4
] | [
50,
9
] | python | en | ['en', 'error', 'th'] | False |
MomentumIterativeMethod.generate | (self, x, **kwargs) |
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: Keyword arguments. See `parse_params` for documentation.
|
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. See `parse_params` for documentation.
"""
# Parse and save attack-specific parameters
assert... | [
"def",
"generate",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"# Parse and save attack-specific parameters",
"assert",
"self",
".",
"parse_params",
"(",
"*",
"*",
"kwargs",
")",
"asserts",
"=",
"[",
"]",
"# If a data range was specified, check that ... | [
52,
4
] | [
138,
20
] | python | en | ['en', 'error', 'th'] | False |
MomentumIterativeMethod.parse_params | (
self,
eps=0.3,
eps_iter=0.06,
nb_iter=10,
y=None,
ord=np.inf,
decay_factor=1.0,
clip_min=None,
clip_max=None,
y_target=None,
sanity_checks=True,
**kwargs
) |
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
Attack-specific parameters:
:param eps: (optional float) maximum distortion of adversarial example
compared to original input
:param eps_iter: (optional ... |
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes. | def parse_params(
self,
eps=0.3,
eps_iter=0.06,
nb_iter=10,
y=None,
ord=np.inf,
decay_factor=1.0,
clip_min=None,
clip_max=None,
y_target=None,
sanity_checks=True,
**kwargs
):
"""
Take in a dictionary of p... | [
"def",
"parse_params",
"(",
"self",
",",
"eps",
"=",
"0.3",
",",
"eps_iter",
"=",
"0.06",
",",
"nb_iter",
"=",
"10",
",",
"y",
"=",
"None",
",",
"ord",
"=",
"np",
".",
"inf",
",",
"decay_factor",
"=",
"1.0",
",",
"clip_min",
"=",
"None",
",",
"cl... | [
140,
4
] | [
198,
19
] | python | en | ['en', 'error', 'th'] | False |
JsonableError.msg_format | () | Override in subclasses. Gets the items in `data_fields` as format args.
This should return (a translation of) a string literal.
The reason it's not simply a class attribute is to allow
translation to work.
| Override in subclasses. Gets the items in `data_fields` as format args. | def msg_format() -> str:
"""Override in subclasses. Gets the items in `data_fields` as format args.
This should return (a translation of) a string literal.
The reason it's not simply a class attribute is to allow
translation to work.
"""
# Secretly this gets one more fo... | [
"def",
"msg_format",
"(",
")",
"->",
"str",
":",
"# Secretly this gets one more format arg not in `data_fields`: `_msg`.",
"# That's for the sake of the `JsonableError` base logic itself, for",
"# the simplest form of use where we just get a plain message string",
"# at construction time.",
"r... | [
106,
4
] | [
117,
23
] | python | en | ['en', 'en', 'en'] | True |
ascii_lower | (string) | r"""Transform (only) ASCII letters to lower case: A-Z is mapped to a-z.
:param string: An Unicode string.
:returns: A new Unicode string.
This is used for `ASCII case-insensitive
<http://encoding.spec.whatwg.org/#ascii-case-insensitive>`_
matching of encoding labels.
The same matching is also ... | r"""Transform (only) ASCII letters to lower case: A-Z is mapped to a-z. | def ascii_lower(string):
r"""Transform (only) ASCII letters to lower case: A-Z is mapped to a-z.
:param string: An Unicode string.
:returns: A new Unicode string.
This is used for `ASCII case-insensitive
<http://encoding.spec.whatwg.org/#ascii-case-insensitive>`_
matching of encoding labels.
... | [
"def",
"ascii_lower",
"(",
"string",
")",
":",
"# This turns out to be faster than unicode.translate()",
"return",
"string",
".",
"encode",
"(",
"'utf8'",
")",
".",
"lower",
"(",
")",
".",
"decode",
"(",
"'utf8'",
")"
] | [
34,
0
] | [
57,
55
] | python | en | ['en', 'en', 'en'] | True |
lookup | (label) |
Look for an encoding by its label.
This is the spec’s `get an encoding
<http://encoding.spec.whatwg.org/#concept-encoding-get>`_ algorithm.
Supported labels are listed there.
:param label: A string.
:returns:
An :class:`Encoding` object, or :obj:`None` for an unknown label.
|
Look for an encoding by its label.
This is the spec’s `get an encoding
<http://encoding.spec.whatwg.org/#concept-encoding-get>`_ algorithm.
Supported labels are listed there. | def lookup(label):
"""
Look for an encoding by its label.
This is the spec’s `get an encoding
<http://encoding.spec.whatwg.org/#concept-encoding-get>`_ algorithm.
Supported labels are listed there.
:param label: A string.
:returns:
An :class:`Encoding` object, or :obj:`None` for an ... | [
"def",
"lookup",
"(",
"label",
")",
":",
"# Only strip ASCII whitespace: U+0009, U+000A, U+000C, U+000D, and U+0020.",
"label",
"=",
"ascii_lower",
"(",
"label",
".",
"strip",
"(",
"'\\t\\n\\f\\r '",
")",
")",
"name",
"=",
"LABELS",
".",
"get",
"(",
"label",
")",
... | [
60,
0
] | [
87,
19
] | python | en | ['en', 'error', 'th'] | False |
_get_encoding | (encoding_or_label) |
Accept either an encoding object or label.
:param encoding: An :class:`Encoding` object or a label string.
:returns: An :class:`Encoding` object.
:raises: :exc:`~exceptions.LookupError` for an unknown label.
|
Accept either an encoding object or label. | def _get_encoding(encoding_or_label):
"""
Accept either an encoding object or label.
:param encoding: An :class:`Encoding` object or a label string.
:returns: An :class:`Encoding` object.
:raises: :exc:`~exceptions.LookupError` for an unknown label.
"""
if hasattr(encoding_or_label, 'codec... | [
"def",
"_get_encoding",
"(",
"encoding_or_label",
")",
":",
"if",
"hasattr",
"(",
"encoding_or_label",
",",
"'codec_info'",
")",
":",
"return",
"encoding_or_label",
"encoding",
"=",
"lookup",
"(",
"encoding_or_label",
")",
"if",
"encoding",
"is",
"None",
":",
"r... | [
90,
0
] | [
105,
19
] | python | en | ['en', 'error', 'th'] | False |
decode | (input, fallback_encoding, errors='replace') |
Decode a single string.
:param input: A byte string
:param fallback_encoding:
An :class:`Encoding` object or a label string.
The encoding to use if :obj:`input` does note have a BOM.
:param errors: Type of error handling. See :func:`codecs.register`.
:raises: :exc:`~exceptions.Look... |
Decode a single string. | def decode(input, fallback_encoding, errors='replace'):
"""
Decode a single string.
:param input: A byte string
:param fallback_encoding:
An :class:`Encoding` object or a label string.
The encoding to use if :obj:`input` does note have a BOM.
:param errors: Type of error handling. S... | [
"def",
"decode",
"(",
"input",
",",
"fallback_encoding",
",",
"errors",
"=",
"'replace'",
")",
":",
"# Fail early if `encoding` is an invalid label.",
"fallback_encoding",
"=",
"_get_encoding",
"(",
"fallback_encoding",
")",
"bom_encoding",
",",
"input",
"=",
"_detect_b... | [
138,
0
] | [
157,
65
] | python | en | ['en', 'error', 'th'] | False |
_detect_bom | (input) | Return (bom_encoding, input), with any BOM removed from the input. | Return (bom_encoding, input), with any BOM removed from the input. | def _detect_bom(input):
"""Return (bom_encoding, input), with any BOM removed from the input."""
if input.startswith(b'\xFF\xFE'):
return _UTF16LE, input[2:]
if input.startswith(b'\xFE\xFF'):
return _UTF16BE, input[2:]
if input.startswith(b'\xEF\xBB\xBF'):
return UTF8, input[3:]
... | [
"def",
"_detect_bom",
"(",
"input",
")",
":",
"if",
"input",
".",
"startswith",
"(",
"b'\\xFF\\xFE'",
")",
":",
"return",
"_UTF16LE",
",",
"input",
"[",
"2",
":",
"]",
"if",
"input",
".",
"startswith",
"(",
"b'\\xFE\\xFF'",
")",
":",
"return",
"_UTF16BE"... | [
160,
0
] | [
168,
22
] | python | en | ['en', 'en', 'en'] | True |
encode | (input, encoding=UTF8, errors='strict') |
Encode a single string.
:param input: An Unicode string.
:param encoding: An :class:`Encoding` object or a label string.
:param errors: Type of error handling. See :func:`codecs.register`.
:raises: :exc:`~exceptions.LookupError` for an unknown encoding label.
:return: A byte string.
|
Encode a single string. | def encode(input, encoding=UTF8, errors='strict'):
"""
Encode a single string.
:param input: An Unicode string.
:param encoding: An :class:`Encoding` object or a label string.
:param errors: Type of error handling. See :func:`codecs.register`.
:raises: :exc:`~exceptions.LookupError` for an unkn... | [
"def",
"encode",
"(",
"input",
",",
"encoding",
"=",
"UTF8",
",",
"errors",
"=",
"'strict'",
")",
":",
"return",
"_get_encoding",
"(",
"encoding",
")",
".",
"codec_info",
".",
"encode",
"(",
"input",
",",
"errors",
")",
"[",
"0",
"]"
] | [
171,
0
] | [
182,
70
] | python | en | ['en', 'error', 'th'] | False |
iter_decode | (input, fallback_encoding, errors='replace') |
"Pull"-based decoder.
:param input:
An iterable of byte strings.
The input is first consumed just enough to determine the encoding
based on the precense of a BOM,
then consumed on demand when the return value is.
:param fallback_encoding:
An :class:`Encoding` objec... |
"Pull"-based decoder. | def iter_decode(input, fallback_encoding, errors='replace'):
"""
"Pull"-based decoder.
:param input:
An iterable of byte strings.
The input is first consumed just enough to determine the encoding
based on the precense of a BOM,
then consumed on demand when the return value ... | [
"def",
"iter_decode",
"(",
"input",
",",
"fallback_encoding",
",",
"errors",
"=",
"'replace'",
")",
":",
"decoder",
"=",
"IncrementalDecoder",
"(",
"fallback_encoding",
",",
"errors",
")",
"generator",
"=",
"_iter_decode_generator",
"(",
"input",
",",
"decoder",
... | [
185,
0
] | [
210,
30
] | python | en | ['en', 'error', 'th'] | False |
_iter_decode_generator | (input, decoder) | Return a generator that first yields the :obj:`Encoding`,
then yields output chukns as Unicode strings.
| Return a generator that first yields the :obj:`Encoding`,
then yields output chukns as Unicode strings. | def _iter_decode_generator(input, decoder):
"""Return a generator that first yields the :obj:`Encoding`,
then yields output chukns as Unicode strings.
"""
decode = decoder.decode
input = iter(input)
for chunck in input:
output = decode(chunck)
if output:
assert decod... | [
"def",
"_iter_decode_generator",
"(",
"input",
",",
"decoder",
")",
":",
"decode",
"=",
"decoder",
".",
"decode",
"input",
"=",
"iter",
"(",
"input",
")",
"for",
"chunck",
"in",
"input",
":",
"output",
"=",
"decode",
"(",
"chunck",
")",
"if",
"output",
... | [
213,
0
] | [
242,
20
] | python | en | ['en', 'en', 'en'] | True |
iter_encode | (input, encoding=UTF8, errors='strict') |
“Pull”-based encoder.
:param input: An iterable of Unicode strings.
:param encoding: An :class:`Encoding` object or a label string.
:param errors: Type of error handling. See :func:`codecs.register`.
:raises: :exc:`~exceptions.LookupError` for an unknown encoding label.
:returns: An iterable o... |
“Pull”-based encoder. | def iter_encode(input, encoding=UTF8, errors='strict'):
"""
“Pull”-based encoder.
:param input: An iterable of Unicode strings.
:param encoding: An :class:`Encoding` object or a label string.
:param errors: Type of error handling. See :func:`codecs.register`.
:raises: :exc:`~exceptions.LookupEr... | [
"def",
"iter_encode",
"(",
"input",
",",
"encoding",
"=",
"UTF8",
",",
"errors",
"=",
"'strict'",
")",
":",
"# Fail early if `encoding` is an invalid label.",
"encode",
"=",
"IncrementalEncoder",
"(",
"encoding",
",",
"errors",
")",
".",
"encode",
"return",
"_iter... | [
245,
0
] | [
258,
48
] | python | en | ['en', 'error', 'th'] | False |
IncrementalDecoder.decode | (self, input, final=False) | Decode one chunk of the input.
:param input: A byte string.
:param final:
Indicate that no more input is available.
Must be :obj:`True` if this is the last call.
:returns: An Unicode string.
| Decode one chunk of the input. | def decode(self, input, final=False):
"""Decode one chunk of the input.
:param input: A byte string.
:param final:
Indicate that no more input is available.
Must be :obj:`True` if this is the last call.
:returns: An Unicode string.
"""
decoder = ... | [
"def",
"decode",
"(",
"self",
",",
"input",
",",
"final",
"=",
"False",
")",
":",
"decoder",
"=",
"self",
".",
"_decoder",
"if",
"decoder",
"is",
"not",
"None",
":",
"return",
"decoder",
"(",
"input",
",",
"final",
")",
"input",
"=",
"self",
".",
"... | [
294,
4
] | [
319,
36
] | python | en | ['en', 'en', 'en'] | True |
install_given_reqs | (
to_install, # type: List[InstallRequirement]
install_options, # type: List[str]
global_options=(), # type: Sequence[str]
*args, # type: Any
**kwargs # type: Any
) |
Install everything in the given list.
(to be called after having downloaded and unpacked the packages)
|
Install everything in the given list. | def install_given_reqs(
to_install, # type: List[InstallRequirement]
install_options, # type: List[str]
global_options=(), # type: Sequence[str]
*args, # type: Any
**kwargs # type: Any
):
# type: (...) -> List[InstallationResult]
"""
Install everything in the given list.
(to be... | [
"def",
"install_given_reqs",
"(",
"to_install",
",",
"# type: List[InstallRequirement]",
"install_options",
",",
"# type: List[str]",
"global_options",
"=",
"(",
")",
",",
"# type: Sequence[str]",
"*",
"args",
",",
"# type: Any",
"*",
"*",
"kwargs",
"# type: Any",
")",
... | [
35,
0
] | [
91,
20
] | python | en | ['en', 'error', 'th'] | False |
fix_duplicate_attachments | (apps: StateApps, schema_editor: DatabaseSchemaEditor) | Migration 0041 had a bug, where if multiple messages referenced the
same attachment, rather than creating a single attachment object
for all of them, we would incorrectly create one for each message.
This results in exceptions looking up the Attachment object
corresponding to a file that was used in mul... | Migration 0041 had a bug, where if multiple messages referenced the
same attachment, rather than creating a single attachment object
for all of them, we would incorrectly create one for each message.
This results in exceptions looking up the Attachment object
corresponding to a file that was used in mul... | def fix_duplicate_attachments(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
"""Migration 0041 had a bug, where if multiple messages referenced the
same attachment, rather than creating a single attachment object
for all of them, we would incorrectly create one for each message.
This res... | [
"def",
"fix_duplicate_attachments",
"(",
"apps",
":",
"StateApps",
",",
"schema_editor",
":",
"DatabaseSchemaEditor",
")",
"->",
"None",
":",
"Attachment",
"=",
"apps",
".",
"get_model",
"(",
"\"zerver\"",
",",
"\"Attachment\"",
")",
"# Loop through all groups of Atta... | [
7,
0
] | [
41,
22
] | python | en | ['en', 'en', 'en'] | True |
get_neighbors | (row, col) | Returns the coordinates of the neighbors. | Returns the coordinates of the neighbors. | def get_neighbors(row, col):
""" Returns the coordinates of the neighbors. """
return [(row - 1, col - 1), (row - 1, col), (row - 1, col + 1),
(row, col - 1), (row, col + 1),
(row + 1, col - 1), (row + 1, col), (row + 1, col + 1)] | [
"def",
"get_neighbors",
"(",
"row",
",",
"col",
")",
":",
"return",
"[",
"(",
"row",
"-",
"1",
",",
"col",
"-",
"1",
")",
",",
"(",
"row",
"-",
"1",
",",
"col",
")",
",",
"(",
"row",
"-",
"1",
",",
"col",
"+",
"1",
")",
",",
"(",
"row",
... | [
1,
0
] | [
5,
67
] | python | en | ['en', 'en', 'en'] | True |
OptimizerTests.optimize | (self, operations) |
Handy shortcut for getting results + number of loops
|
Handy shortcut for getting results + number of loops
| def optimize(self, operations):
"""
Handy shortcut for getting results + number of loops
"""
optimizer = MigrationOptimizer()
return optimizer.optimize(operations), optimizer._iterations | [
"def",
"optimize",
"(",
"self",
",",
"operations",
")",
":",
"optimizer",
"=",
"MigrationOptimizer",
"(",
")",
"return",
"optimizer",
".",
"optimize",
"(",
"operations",
")",
",",
"optimizer",
".",
"_iterations"
] | [
13,
4
] | [
18,
68
] | python | en | ['en', 'error', 'th'] | False |
OptimizerTests.test_operation_equality | (self) |
Tests the equality operator on lists of operations.
If this is broken, then the optimizer will get stuck in an
infinite loop, so it's kind of important.
|
Tests the equality operator on lists of operations.
If this is broken, then the optimizer will get stuck in an
infinite loop, so it's kind of important.
| def test_operation_equality(self):
"""
Tests the equality operator on lists of operations.
If this is broken, then the optimizer will get stuck in an
infinite loop, so it's kind of important.
"""
self.assertEqual(
[migrations.DeleteModel("Test")],
... | [
"def",
"test_operation_equality",
"(",
"self",
")",
":",
"self",
".",
"assertEqual",
"(",
"[",
"migrations",
".",
"DeleteModel",
"(",
"\"Test\"",
")",
"]",
",",
"[",
"migrations",
".",
"DeleteModel",
"(",
"\"Test\"",
")",
"]",
",",
")",
"self",
".",
"ass... | [
28,
4
] | [
57,
9
] | python | en | ['en', 'error', 'th'] | False |
OptimizerTests.test_single | (self) |
Tests that the optimizer does nothing on a single operation,
and that it does it in just one pass.
|
Tests that the optimizer does nothing on a single operation,
and that it does it in just one pass.
| def test_single(self):
"""
Tests that the optimizer does nothing on a single operation,
and that it does it in just one pass.
"""
self.assertOptimizesTo(
[migrations.DeleteModel("Foo")],
[migrations.DeleteModel("Foo")],
exact=1,
) | [
"def",
"test_single",
"(",
"self",
")",
":",
"self",
".",
"assertOptimizesTo",
"(",
"[",
"migrations",
".",
"DeleteModel",
"(",
"\"Foo\"",
")",
"]",
",",
"[",
"migrations",
".",
"DeleteModel",
"(",
"\"Foo\"",
")",
"]",
",",
"exact",
"=",
"1",
",",
")"
... | [
59,
4
] | [
68,
9
] | python | en | ['en', 'error', 'th'] | False |
OptimizerTests.test_create_delete_model | (self) |
CreateModel and DeleteModel should collapse into nothing.
|
CreateModel and DeleteModel should collapse into nothing.
| def test_create_delete_model(self):
"""
CreateModel and DeleteModel should collapse into nothing.
"""
self.assertOptimizesTo(
[
migrations.CreateModel("Foo", [("name", models.CharField(max_length=255))]),
migrations.DeleteModel("Foo"),
... | [
"def",
"test_create_delete_model",
"(",
"self",
")",
":",
"self",
".",
"assertOptimizesTo",
"(",
"[",
"migrations",
".",
"CreateModel",
"(",
"\"Foo\"",
",",
"[",
"(",
"\"name\"",
",",
"models",
".",
"CharField",
"(",
"max_length",
"=",
"255",
")",
")",
"]"... | [
70,
4
] | [
80,
9
] | python | en | ['en', 'error', 'th'] | False |
OptimizerTests.test_create_rename_model | (self) |
CreateModel should absorb RenameModels.
|
CreateModel should absorb RenameModels.
| def test_create_rename_model(self):
"""
CreateModel should absorb RenameModels.
"""
self.assertOptimizesTo(
[
migrations.CreateModel("Foo", [("name", models.CharField(max_length=255))]),
migrations.RenameModel("Foo", "Bar"),
],
... | [
"def",
"test_create_rename_model",
"(",
"self",
")",
":",
"self",
".",
"assertOptimizesTo",
"(",
"[",
"migrations",
".",
"CreateModel",
"(",
"\"Foo\"",
",",
"[",
"(",
"\"name\"",
",",
"models",
".",
"CharField",
"(",
"max_length",
"=",
"255",
")",
")",
"]"... | [
82,
4
] | [
94,
9
] | python | en | ['en', 'error', 'th'] | False |
OptimizerTests.test_rename_model_self | (self) |
RenameModels should absorb themselves.
|
RenameModels should absorb themselves.
| def test_rename_model_self(self):
"""
RenameModels should absorb themselves.
"""
self.assertOptimizesTo(
[
migrations.RenameModel("Foo", "Baa"),
migrations.RenameModel("Baa", "Bar"),
],
[
migrations.Renam... | [
"def",
"test_rename_model_self",
"(",
"self",
")",
":",
"self",
".",
"assertOptimizesTo",
"(",
"[",
"migrations",
".",
"RenameModel",
"(",
"\"Foo\"",
",",
"\"Baa\"",
")",
",",
"migrations",
".",
"RenameModel",
"(",
"\"Baa\"",
",",
"\"Bar\"",
")",
",",
"]",
... | [
96,
4
] | [
108,
9
] | python | en | ['en', 'error', 'th'] | False |
OptimizerTests.test_create_alter_delete_model | (self) |
CreateModel, AlterModelTable, AlterUniqueTogether, and DeleteModel should collapse into nothing.
|
CreateModel, AlterModelTable, AlterUniqueTogether, and DeleteModel should collapse into nothing.
| def test_create_alter_delete_model(self):
"""
CreateModel, AlterModelTable, AlterUniqueTogether, and DeleteModel should collapse into nothing.
"""
self.assertOptimizesTo(
[
migrations.CreateModel("Foo", [("name", models.CharField(max_length=255))]),
... | [
"def",
"test_create_alter_delete_model",
"(",
"self",
")",
":",
"self",
".",
"assertOptimizesTo",
"(",
"[",
"migrations",
".",
"CreateModel",
"(",
"\"Foo\"",
",",
"[",
"(",
"\"name\"",
",",
"models",
".",
"CharField",
"(",
"max_length",
"=",
"255",
")",
")",... | [
110,
4
] | [
122,
9
] | python | en | ['en', 'error', 'th'] | False |
OptimizerTests.test_optimize_through_create | (self) |
We should be able to optimize away create/delete through a create or delete
of a different model, but only if the create operation does not mention the model
at all.
|
We should be able to optimize away create/delete through a create or delete
of a different model, but only if the create operation does not mention the model
at all.
| def test_optimize_through_create(self):
"""
We should be able to optimize away create/delete through a create or delete
of a different model, but only if the create operation does not mention the model
at all.
"""
# These should work
self.assertOptimizesTo(
... | [
"def",
"test_optimize_through_create",
"(",
"self",
")",
":",
"# These should work",
"self",
".",
"assertOptimizesTo",
"(",
"[",
"migrations",
".",
"CreateModel",
"(",
"\"Foo\"",
",",
"[",
"(",
"\"name\"",
",",
"models",
".",
"CharField",
"(",
"max_length",
"=",... | [
124,
4
] | [
184,
9
] | python | en | ['en', 'error', 'th'] | False |
OptimizerTests.test_create_model_add_field | (self) |
AddField should optimize into CreateModel.
|
AddField should optimize into CreateModel.
| def test_create_model_add_field(self):
"""
AddField should optimize into CreateModel.
"""
self.assertOptimizesTo(
[
migrations.CreateModel("Foo", [("name", models.CharField(max_length=255))]),
migrations.AddField("Foo", "age", models.IntegerFie... | [
"def",
"test_create_model_add_field",
"(",
"self",
")",
":",
"self",
".",
"assertOptimizesTo",
"(",
"[",
"migrations",
".",
"CreateModel",
"(",
"\"Foo\"",
",",
"[",
"(",
"\"name\"",
",",
"models",
".",
"CharField",
"(",
"max_length",
"=",
"255",
")",
")",
... | [
186,
4
] | [
201,
9
] | python | en | ['en', 'error', 'th'] | False |
OptimizerTests.test_create_model_add_field_not_through_fk | (self) |
AddField should NOT optimize into CreateModel if it's an FK to a model
that's between them.
|
AddField should NOT optimize into CreateModel if it's an FK to a model
that's between them.
| def test_create_model_add_field_not_through_fk(self):
"""
AddField should NOT optimize into CreateModel if it's an FK to a model
that's between them.
"""
self.assertOptimizesTo(
[
migrations.CreateModel("Foo", [("name", models.CharField(max_length=255)... | [
"def",
"test_create_model_add_field_not_through_fk",
"(",
"self",
")",
":",
"self",
".",
"assertOptimizesTo",
"(",
"[",
"migrations",
".",
"CreateModel",
"(",
"\"Foo\"",
",",
"[",
"(",
"\"name\"",
",",
"models",
".",
"CharField",
"(",
"max_length",
"=",
"255",
... | [
203,
4
] | [
219,
9
] | python | en | ['en', 'error', 'th'] | False |
OptimizerTests.test_create_model_add_field_not_through_m2m_through | (self) |
AddField should NOT optimize into CreateModel if it's an M2M using a
through that's created between them.
|
AddField should NOT optimize into CreateModel if it's an M2M using a
through that's created between them.
| def test_create_model_add_field_not_through_m2m_through(self):
"""
AddField should NOT optimize into CreateModel if it's an M2M using a
through that's created between them.
"""
# Note: The middle model is not actually a valid through model,
# but that doesn't matter, as w... | [
"def",
"test_create_model_add_field_not_through_m2m_through",
"(",
"self",
")",
":",
"# Note: The middle model is not actually a valid through model,",
"# but that doesn't matter, as we never render it.",
"self",
".",
"assertOptimizesTo",
"(",
"[",
"migrations",
".",
"CreateModel",
"... | [
221,
4
] | [
239,
9
] | python | en | ['en', 'error', 'th'] | False |
OptimizerTests.test_create_model_alter_field | (self) |
AlterField should optimize into CreateModel.
|
AlterField should optimize into CreateModel.
| def test_create_model_alter_field(self):
"""
AlterField should optimize into CreateModel.
"""
self.assertOptimizesTo(
[
migrations.CreateModel("Foo", [("name", models.CharField(max_length=255))]),
migrations.AlterField("Foo", "name", models.Int... | [
"def",
"test_create_model_alter_field",
"(",
"self",
")",
":",
"self",
".",
"assertOptimizesTo",
"(",
"[",
"migrations",
".",
"CreateModel",
"(",
"\"Foo\"",
",",
"[",
"(",
"\"name\"",
",",
"models",
".",
"CharField",
"(",
"max_length",
"=",
"255",
")",
")",
... | [
241,
4
] | [
255,
9
] | python | en | ['en', 'error', 'th'] | False |
OptimizerTests.test_create_model_rename_field | (self) |
RenameField should optimize into CreateModel.
|
RenameField should optimize into CreateModel.
| def test_create_model_rename_field(self):
"""
RenameField should optimize into CreateModel.
"""
self.assertOptimizesTo(
[
migrations.CreateModel("Foo", [("name", models.CharField(max_length=255))]),
migrations.RenameField("Foo", "name", "title"... | [
"def",
"test_create_model_rename_field",
"(",
"self",
")",
":",
"self",
".",
"assertOptimizesTo",
"(",
"[",
"migrations",
".",
"CreateModel",
"(",
"\"Foo\"",
",",
"[",
"(",
"\"name\"",
",",
"models",
".",
"CharField",
"(",
"max_length",
"=",
"255",
")",
")",... | [
257,
4
] | [
271,
9
] | python | en | ['en', 'error', 'th'] | False |
OptimizerTests.test_add_field_rename_field | (self) |
RenameField should optimize into AddField
|
RenameField should optimize into AddField
| def test_add_field_rename_field(self):
"""
RenameField should optimize into AddField
"""
self.assertOptimizesTo(
[
migrations.AddField("Foo", "name", models.CharField(max_length=255)),
migrations.RenameField("Foo", "name", "title"),
... | [
"def",
"test_add_field_rename_field",
"(",
"self",
")",
":",
"self",
".",
"assertOptimizesTo",
"(",
"[",
"migrations",
".",
"AddField",
"(",
"\"Foo\"",
",",
"\"name\"",
",",
"models",
".",
"CharField",
"(",
"max_length",
"=",
"255",
")",
")",
",",
"migration... | [
273,
4
] | [
285,
9
] | python | en | ['en', 'error', 'th'] | False |
OptimizerTests.test_alter_field_rename_field | (self) |
RenameField should optimize to the other side of AlterField,
and into itself.
|
RenameField should optimize to the other side of AlterField,
and into itself.
| def test_alter_field_rename_field(self):
"""
RenameField should optimize to the other side of AlterField,
and into itself.
"""
self.assertOptimizesTo(
[
migrations.AlterField("Foo", "name", models.CharField(max_length=255)),
migrations.... | [
"def",
"test_alter_field_rename_field",
"(",
"self",
")",
":",
"self",
".",
"assertOptimizesTo",
"(",
"[",
"migrations",
".",
"AlterField",
"(",
"\"Foo\"",
",",
"\"name\"",
",",
"models",
".",
"CharField",
"(",
"max_length",
"=",
"255",
")",
")",
",",
"migra... | [
287,
4
] | [
302,
9
] | python | en | ['en', 'error', 'th'] | False |
OptimizerTests.test_create_model_remove_field | (self) |
RemoveField should optimize into CreateModel.
|
RemoveField should optimize into CreateModel.
| def test_create_model_remove_field(self):
"""
RemoveField should optimize into CreateModel.
"""
self.assertOptimizesTo(
[
migrations.CreateModel("Foo", [
("name", models.CharField(max_length=255)),
("age", models.Integer... | [
"def",
"test_create_model_remove_field",
"(",
"self",
")",
":",
"self",
".",
"assertOptimizesTo",
"(",
"[",
"migrations",
".",
"CreateModel",
"(",
"\"Foo\"",
",",
"[",
"(",
"\"name\"",
",",
"models",
".",
"CharField",
"(",
"max_length",
"=",
"255",
")",
")",... | [
304,
4
] | [
321,
9
] | python | en | ['en', 'error', 'th'] | False |
OptimizerTests.test_add_field_alter_field | (self) |
AlterField should optimize into AddField.
|
AlterField should optimize into AddField.
| def test_add_field_alter_field(self):
"""
AlterField should optimize into AddField.
"""
self.assertOptimizesTo(
[
migrations.AddField("Foo", "age", models.IntegerField()),
migrations.AlterField("Foo", "age", models.FloatField(default=2.4)),
... | [
"def",
"test_add_field_alter_field",
"(",
"self",
")",
":",
"self",
".",
"assertOptimizesTo",
"(",
"[",
"migrations",
".",
"AddField",
"(",
"\"Foo\"",
",",
"\"age\"",
",",
"models",
".",
"IntegerField",
"(",
")",
")",
",",
"migrations",
".",
"AlterField",
"(... | [
323,
4
] | [
335,
9
] | python | en | ['en', 'error', 'th'] | False |
OptimizerTests.test_add_field_delete_field | (self) |
RemoveField should cancel AddField
|
RemoveField should cancel AddField
| def test_add_field_delete_field(self):
"""
RemoveField should cancel AddField
"""
self.assertOptimizesTo(
[
migrations.AddField("Foo", "age", models.IntegerField()),
migrations.RemoveField("Foo", "age"),
],
[],
) | [
"def",
"test_add_field_delete_field",
"(",
"self",
")",
":",
"self",
".",
"assertOptimizesTo",
"(",
"[",
"migrations",
".",
"AddField",
"(",
"\"Foo\"",
",",
"\"age\"",
",",
"models",
".",
"IntegerField",
"(",
")",
")",
",",
"migrations",
".",
"RemoveField",
... | [
337,
4
] | [
347,
9
] | python | en | ['en', 'error', 'th'] | False |
OptimizerTests.test_alter_field_delete_field | (self) |
RemoveField should absorb AlterField
|
RemoveField should absorb AlterField
| def test_alter_field_delete_field(self):
"""
RemoveField should absorb AlterField
"""
self.assertOptimizesTo(
[
migrations.AlterField("Foo", "age", models.IntegerField()),
migrations.RemoveField("Foo", "age"),
],
[
... | [
"def",
"test_alter_field_delete_field",
"(",
"self",
")",
":",
"self",
".",
"assertOptimizesTo",
"(",
"[",
"migrations",
".",
"AlterField",
"(",
"\"Foo\"",
",",
"\"age\"",
",",
"models",
".",
"IntegerField",
"(",
")",
")",
",",
"migrations",
".",
"RemoveField"... | [
349,
4
] | [
361,
9
] | python | en | ['en', 'error', 'th'] | False |
OptimizerTests.test_optimize_through_fields | (self) |
Checks that field-level through checking is working.
This should manage to collapse model Foo to nonexistence,
and model Bar to a single IntegerField called "width".
|
Checks that field-level through checking is working.
This should manage to collapse model Foo to nonexistence,
and model Bar to a single IntegerField called "width".
| def test_optimize_through_fields(self):
"""
Checks that field-level through checking is working.
This should manage to collapse model Foo to nonexistence,
and model Bar to a single IntegerField called "width".
"""
self.assertOptimizesTo(
[
migr... | [
"def",
"test_optimize_through_fields",
"(",
"self",
")",
":",
"self",
".",
"assertOptimizesTo",
"(",
"[",
"migrations",
".",
"CreateModel",
"(",
"\"Foo\"",
",",
"[",
"(",
"\"name\"",
",",
"models",
".",
"CharField",
"(",
"max_length",
"=",
"255",
")",
")",
... | [
363,
4
] | [
386,
9
] | python | en | ['en', 'error', 'th'] | False |
SessionMiddleware.process_response | (self, request, response) |
If request.session was modified, or if the configuration is to save the
session every time, save the changes and set a session cookie or delete
the session cookie if the session has been emptied.
|
If request.session was modified, or if the configuration is to save the
session every time, save the changes and set a session cookie or delete
the session cookie if the session has been emptied.
| def process_response(self, request, response):
"""
If request.session was modified, or if the configuration is to save the
session every time, save the changes and set a session cookie or delete
the session cookie if the session has been emptied.
"""
try:
acce... | [
"def",
"process_response",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"try",
":",
"accessed",
"=",
"request",
".",
"session",
".",
"accessed",
"modified",
"=",
"request",
".",
"session",
".",
"modified",
"empty",
"=",
"request",
".",
"session"... | [
21,
4
] | [
73,
23
] | python | en | ['en', 'error', 'th'] | False |
DatabaseSchemaEditor._delete_composed_index | (self, model, fields, *args) |
MySQL can remove an implicit FK index on a field when that field is
covered by another index like a unique_together. "covered" here means
that the more complex index starts like the simpler one.
http://bugs.mysql.com/bug.php?id=37910 / Django ticket #24757
We check here before r... |
MySQL can remove an implicit FK index on a field when that field is
covered by another index like a unique_together. "covered" here means
that the more complex index starts like the simpler one.
http://bugs.mysql.com/bug.php?id=37910 / Django ticket #24757
We check here before r... | def _delete_composed_index(self, model, fields, *args):
"""
MySQL can remove an implicit FK index on a field when that field is
covered by another index like a unique_together. "covered" here means
that the more complex index starts like the simpler one.
http://bugs.mysql.com/bug... | [
"def",
"_delete_composed_index",
"(",
"self",
",",
"model",
",",
"fields",
",",
"*",
"args",
")",
":",
"first_field",
"=",
"model",
".",
"_meta",
".",
"get_field",
"(",
"fields",
"[",
"0",
"]",
")",
"if",
"first_field",
".",
"get_internal_type",
"(",
")"... | [
105,
4
] | [
119,
67
] | python | en | ['en', 'error', 'th'] | False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.