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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
TestRelatedFieldsAdminOrdering.test_custom_queryset_still_wins | (self) | Test that custom queryset has still precedence (#21405) | Test that custom queryset has still precedence (#21405) | def test_custom_queryset_still_wins(self):
"""Test that custom queryset has still precedence (#21405)"""
class SongAdmin(admin.ModelAdmin):
# Exclude one of the two Bands from the querysets
def formfield_for_foreignkey(self, db_field, **kwargs):
if db_field.name =... | [
"def",
"test_custom_queryset_still_wins",
"(",
"self",
")",
":",
"class",
"SongAdmin",
"(",
"admin",
".",
"ModelAdmin",
")",
":",
"# Exclude one of the two Bands from the querysets",
"def",
"formfield_for_foreignkey",
"(",
"self",
",",
"db_field",
",",
"*",
"*",
"kwar... | [
153,
4
] | [
174,
55
] | python | en | ['en', 'sv', 'en'] | True |
ListFilter.has_output | (self) |
Returns True if some choices would be output for this filter.
|
Returns True if some choices would be output for this filter.
| def has_output(self):
"""
Returns True if some choices would be output for this filter.
"""
raise NotImplementedError('subclasses of ListFilter must provide a has_output() method') | [
"def",
"has_output",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of ListFilter must provide a has_output() method'",
")"
] | [
33,
4
] | [
37,
96
] | python | en | ['en', 'error', 'th'] | False |
ListFilter.choices | (self, cl) |
Returns choices ready to be output in the template.
|
Returns choices ready to be output in the template.
| def choices(self, cl):
"""
Returns choices ready to be output in the template.
"""
raise NotImplementedError('subclasses of ListFilter must provide a choices() method') | [
"def",
"choices",
"(",
"self",
",",
"cl",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of ListFilter must provide a choices() method'",
")"
] | [
39,
4
] | [
43,
93
] | python | en | ['en', 'error', 'th'] | False |
ListFilter.queryset | (self, request, queryset) |
Returns the filtered queryset.
|
Returns the filtered queryset.
| def queryset(self, request, queryset):
"""
Returns the filtered queryset.
"""
raise NotImplementedError('subclasses of ListFilter must provide a queryset() method') | [
"def",
"queryset",
"(",
"self",
",",
"request",
",",
"queryset",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of ListFilter must provide a queryset() method'",
")"
] | [
45,
4
] | [
49,
94
] | python | en | ['en', 'error', 'th'] | False |
ListFilter.expected_parameters | (self) |
Returns the list of parameter names that are expected from the
request's query string and that will be used by this filter.
|
Returns the list of parameter names that are expected from the
request's query string and that will be used by this filter.
| def expected_parameters(self):
"""
Returns the list of parameter names that are expected from the
request's query string and that will be used by this filter.
"""
raise NotImplementedError('subclasses of ListFilter must provide an expected_parameters() method') | [
"def",
"expected_parameters",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of ListFilter must provide an expected_parameters() method'",
")"
] | [
51,
4
] | [
56,
106
] | python | en | ['en', 'error', 'th'] | False |
SimpleListFilter.value | (self) |
Returns the value (in string format) provided in the request's
query string for this filter, if any. If the value wasn't provided then
returns None.
|
Returns the value (in string format) provided in the request's
query string for this filter, if any. If the value wasn't provided then
returns None.
| def value(self):
"""
Returns the value (in string format) provided in the request's
query string for this filter, if any. If the value wasn't provided then
returns None.
"""
return self.used_parameters.get(self.parameter_name, None) | [
"def",
"value",
"(",
"self",
")",
":",
"return",
"self",
".",
"used_parameters",
".",
"get",
"(",
"self",
".",
"parameter_name",
",",
"None",
")"
] | [
81,
4
] | [
87,
66
] | python | en | ['en', 'error', 'th'] | False |
SimpleListFilter.lookups | (self, request, model_admin) |
Must be overridden to return a list of tuples (value, verbose value)
|
Must be overridden to return a list of tuples (value, verbose value)
| def lookups(self, request, model_admin):
"""
Must be overridden to return a list of tuples (value, verbose value)
"""
raise NotImplementedError(
'The SimpleListFilter.lookups() method must be overridden to '
'return a list of tuples (value, verbose value)') | [
"def",
"lookups",
"(",
"self",
",",
"request",
",",
"model_admin",
")",
":",
"raise",
"NotImplementedError",
"(",
"'The SimpleListFilter.lookups() method must be overridden to '",
"'return a list of tuples (value, verbose value)'",
")"
] | [
89,
4
] | [
95,
61
] | python | en | ['en', 'error', 'th'] | False |
get_display_profile | (handle=None) | (experimental) Fetches the profile for the current display device.
:returns: ``None`` if the profile is not known.
| (experimental) Fetches the profile for the current display device.
:returns: ``None`` if the profile is not known.
| def get_display_profile(handle=None):
""" (experimental) Fetches the profile for the current display device.
:returns: ``None`` if the profile is not known.
"""
if sys.platform != "win32":
return None
from PIL import ImageWin
if isinstance(handle, ImageWin.HDC):
profile = core... | [
"def",
"get_display_profile",
"(",
"handle",
"=",
"None",
")",
":",
"if",
"sys",
".",
"platform",
"!=",
"\"win32\"",
":",
"return",
"None",
"from",
"PIL",
"import",
"ImageWin",
"if",
"isinstance",
"(",
"handle",
",",
"ImageWin",
".",
"HDC",
")",
":",
"pr... | [
251,
0
] | [
267,
35
] | python | en | ['en', 'en', 'en'] | True |
profileToProfile | (
im,
inputProfile,
outputProfile,
renderingIntent=INTENT_PERCEPTUAL,
outputMode=None,
inPlace=False,
flags=0,
) |
(pyCMS) Applies an ICC transformation to a given image, mapping from
``inputProfile`` to ``outputProfile``.
If the input or output profiles specified are not valid filenames, a
:exc:`PyCMSError` will be raised. If ``inPlace`` is ``True`` and
``outputMode != im.mode``, a :exc:`PyCMSError` will be ... |
(pyCMS) Applies an ICC transformation to a given image, mapping from
``inputProfile`` to ``outputProfile``. | def profileToProfile(
im,
inputProfile,
outputProfile,
renderingIntent=INTENT_PERCEPTUAL,
outputMode=None,
inPlace=False,
flags=0,
):
"""
(pyCMS) Applies an ICC transformation to a given image, mapping from
``inputProfile`` to ``outputProfile``.
If the input or output profil... | [
"def",
"profileToProfile",
"(",
"im",
",",
"inputProfile",
",",
"outputProfile",
",",
"renderingIntent",
"=",
"INTENT_PERCEPTUAL",
",",
"outputMode",
"=",
"None",
",",
"inPlace",
"=",
"False",
",",
"flags",
"=",
"0",
",",
")",
":",
"if",
"outputMode",
"is",
... | [
283,
0
] | [
374,
16
] | python | en | ['en', 'error', 'th'] | False |
getOpenProfile | (profileFilename) |
(pyCMS) Opens an ICC profile file.
The PyCMSProfile object can be passed back into pyCMS for use in creating
transforms and such (as in ImageCms.buildTransformFromOpenProfiles()).
If ``profileFilename`` is not a valid filename for an ICC profile,
a :exc:`PyCMSError` will be raised.
:param pr... |
(pyCMS) Opens an ICC profile file. | def getOpenProfile(profileFilename):
"""
(pyCMS) Opens an ICC profile file.
The PyCMSProfile object can be passed back into pyCMS for use in creating
transforms and such (as in ImageCms.buildTransformFromOpenProfiles()).
If ``profileFilename`` is not a valid filename for an ICC profile,
a :exc... | [
"def",
"getOpenProfile",
"(",
"profileFilename",
")",
":",
"try",
":",
"return",
"ImageCmsProfile",
"(",
"profileFilename",
")",
"except",
"(",
"OSError",
",",
"TypeError",
",",
"ValueError",
")",
"as",
"v",
":",
"raise",
"PyCMSError",
"(",
"v",
")",
"from",... | [
377,
0
] | [
396,
34
] | python | en | ['en', 'error', 'th'] | False |
buildTransform | (
inputProfile,
outputProfile,
inMode,
outMode,
renderingIntent=INTENT_PERCEPTUAL,
flags=0,
) |
(pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
``outputProfile``. Use applyTransform to apply the transform to a given
image.
If the input or output profiles specified are not valid filenames, a
:exc:`PyCMSError` will be raised. If an error occurs during creation
of t... |
(pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
``outputProfile``. Use applyTransform to apply the transform to a given
image. | def buildTransform(
inputProfile,
outputProfile,
inMode,
outMode,
renderingIntent=INTENT_PERCEPTUAL,
flags=0,
):
"""
(pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
``outputProfile``. Use applyTransform to apply the transform to a given
image.
If the... | [
"def",
"buildTransform",
"(",
"inputProfile",
",",
"outputProfile",
",",
"inMode",
",",
"outMode",
",",
"renderingIntent",
"=",
"INTENT_PERCEPTUAL",
",",
"flags",
"=",
"0",
",",
")",
":",
"if",
"not",
"isinstance",
"(",
"renderingIntent",
",",
"int",
")",
"o... | [
399,
0
] | [
477,
34
] | python | en | ['en', 'error', 'th'] | False |
buildProofTransform | (
inputProfile,
outputProfile,
proofProfile,
inMode,
outMode,
renderingIntent=INTENT_PERCEPTUAL,
proofRenderingIntent=INTENT_ABSOLUTE_COLORIMETRIC,
flags=FLAGS["SOFTPROOFING"],
) |
(pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
``outputProfile``, but tries to simulate the result that would be
obtained on the ``proofProfile`` device.
If the input, output, or proof profiles specified are not valid
filenames, a :exc:`PyCMSError` will be raised.
If... |
(pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
``outputProfile``, but tries to simulate the result that would be
obtained on the ``proofProfile`` device. | def buildProofTransform(
inputProfile,
outputProfile,
proofProfile,
inMode,
outMode,
renderingIntent=INTENT_PERCEPTUAL,
proofRenderingIntent=INTENT_ABSOLUTE_COLORIMETRIC,
flags=FLAGS["SOFTPROOFING"],
):
"""
(pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
... | [
"def",
"buildProofTransform",
"(",
"inputProfile",
",",
"outputProfile",
",",
"proofProfile",
",",
"inMode",
",",
"outMode",
",",
"renderingIntent",
"=",
"INTENT_PERCEPTUAL",
",",
"proofRenderingIntent",
"=",
"INTENT_ABSOLUTE_COLORIMETRIC",
",",
"flags",
"=",
"FLAGS",
... | [
480,
0
] | [
588,
34
] | python | en | ['en', 'error', 'th'] | False |
applyTransform | (im, transform, inPlace=False) |
(pyCMS) Applies a transform to a given image.
If ``im.mode != transform.inMode``, a :exc:`PyCMSError` is raised.
If ``inPlace`` is ``True`` and ``transform.inMode != transform.outMode``, a
:exc:`PyCMSError` is raised.
If ``im.mode``, ``transform.inMode`` or ``transform.outMode`` is not
suppo... |
(pyCMS) Applies a transform to a given image. | def applyTransform(im, transform, inPlace=False):
"""
(pyCMS) Applies a transform to a given image.
If ``im.mode != transform.inMode``, a :exc:`PyCMSError` is raised.
If ``inPlace`` is ``True`` and ``transform.inMode != transform.outMode``, a
:exc:`PyCMSError` is raised.
If ``im.mode``, ``tra... | [
"def",
"applyTransform",
"(",
"im",
",",
"transform",
",",
"inPlace",
"=",
"False",
")",
":",
"try",
":",
"if",
"inPlace",
":",
"transform",
".",
"apply_in_place",
"(",
"im",
")",
"imOut",
"=",
"None",
"else",
":",
"imOut",
"=",
"transform",
".",
"appl... | [
595,
0
] | [
645,
16
] | python | en | ['en', 'error', 'th'] | False |
createProfile | (colorSpace, colorTemp=-1) |
(pyCMS) Creates a profile.
If colorSpace not in ``["LAB", "XYZ", "sRGB"]``,
a :exc:`PyCMSError` is raised.
If using LAB and ``colorTemp`` is not a positive integer,
a :exc:`PyCMSError` is raised.
If an error occurs while creating the profile,
a :exc:`PyCMSError` is raised.
Use this ... |
(pyCMS) Creates a profile. | def createProfile(colorSpace, colorTemp=-1):
"""
(pyCMS) Creates a profile.
If colorSpace not in ``["LAB", "XYZ", "sRGB"]``,
a :exc:`PyCMSError` is raised.
If using LAB and ``colorTemp`` is not a positive integer,
a :exc:`PyCMSError` is raised.
If an error occurs while creating the profil... | [
"def",
"createProfile",
"(",
"colorSpace",
",",
"colorTemp",
"=",
"-",
"1",
")",
":",
"if",
"colorSpace",
"not",
"in",
"[",
"\"LAB\"",
",",
"\"XYZ\"",
",",
"\"sRGB\"",
"]",
":",
"raise",
"PyCMSError",
"(",
"\"Color space not supported for on-the-fly profile creati... | [
648,
0
] | [
695,
34
] | python | en | ['en', 'error', 'th'] | False |
getProfileName | (profile) |
(pyCMS) Gets the internal product name for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile,
a :exc:`PyCMSError` is raised If an error occurs while trying
to obtain the name tag, a :exc:`PyCMSError` is raised.
Use this function to obtain the INTERNAL nam... | def getProfileName(profile):
"""
(pyCMS) Gets the internal product name for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile,
a :exc:`PyCMSError` is raised If an error occurs while trying
to obtain the name tag, a :exc:`PyCMSError` is raised.
Use this... | [
"def",
"getProfileName",
"(",
"profile",
")",
":",
"try",
":",
"# add an extra newline to preserve pyCMS compatibility",
"if",
"not",
"isinstance",
"(",
"profile",
",",
"ImageCmsProfile",
")",
":",
"profile",
"=",
"ImageCmsProfile",
"(",
"profile",
")",
"# do it in py... | [
698,
0
] | [
737,
34
] | python | en | ['en', 'error', 'th'] | False | |
getProfileInfo | (profile) |
(pyCMS) Gets the internal product information for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile,
a :exc:`PyCMSError` is raised.
If an error occurs while trying to obtain the info tag,
a :exc:`PyCMSError` is raised.
Use this function to obtain the ... |
(pyCMS) Gets the internal product information for the given profile. | def getProfileInfo(profile):
"""
(pyCMS) Gets the internal product information for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile,
a :exc:`PyCMSError` is raised.
If an error occurs while trying to obtain the info tag,
a :exc:`PyCMSError` is raised.
... | [
"def",
"getProfileInfo",
"(",
"profile",
")",
":",
"try",
":",
"if",
"not",
"isinstance",
"(",
"profile",
",",
"ImageCmsProfile",
")",
":",
"profile",
"=",
"ImageCmsProfile",
"(",
"profile",
")",
"# add an extra newline to preserve pyCMS compatibility",
"# Python, not... | [
740,
0
] | [
777,
34
] | python | en | ['en', 'error', 'th'] | False |
getProfileCopyright | (profile) |
(pyCMS) Gets the copyright for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
:exc:`PyCMSError` is raised.
If an error occurs while trying to obtain the copyright tag,
a :exc:`PyCMSError` is raised.
Use this function to obtain the information st... |
(pyCMS) Gets the copyright for the given profile. | def getProfileCopyright(profile):
"""
(pyCMS) Gets the copyright for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
:exc:`PyCMSError` is raised.
If an error occurs while trying to obtain the copyright tag,
a :exc:`PyCMSError` is raised.
Use t... | [
"def",
"getProfileCopyright",
"(",
"profile",
")",
":",
"try",
":",
"# add an extra newline to preserve pyCMS compatibility",
"if",
"not",
"isinstance",
"(",
"profile",
",",
"ImageCmsProfile",
")",
":",
"profile",
"=",
"ImageCmsProfile",
"(",
"profile",
")",
"return",... | [
780,
0
] | [
805,
34
] | python | en | ['en', 'error', 'th'] | False |
getProfileManufacturer | (profile) |
(pyCMS) Gets the manufacturer for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
:exc:`PyCMSError` is raised.
If an error occurs while trying to obtain the manufacturer tag, a
:exc:`PyCMSError` is raised.
Use this function to obtain the informat... |
(pyCMS) Gets the manufacturer for the given profile. | def getProfileManufacturer(profile):
"""
(pyCMS) Gets the manufacturer for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
:exc:`PyCMSError` is raised.
If an error occurs while trying to obtain the manufacturer tag, a
:exc:`PyCMSError` is raised.
... | [
"def",
"getProfileManufacturer",
"(",
"profile",
")",
":",
"try",
":",
"# add an extra newline to preserve pyCMS compatibility",
"if",
"not",
"isinstance",
"(",
"profile",
",",
"ImageCmsProfile",
")",
":",
"profile",
"=",
"ImageCmsProfile",
"(",
"profile",
")",
"retur... | [
808,
0
] | [
833,
34
] | python | en | ['en', 'error', 'th'] | False |
getProfileModel | (profile) |
(pyCMS) Gets the model for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
:exc:`PyCMSError` is raised.
If an error occurs while trying to obtain the model tag,
a :exc:`PyCMSError` is raised.
Use this function to obtain the information stored in ... |
(pyCMS) Gets the model for the given profile. | def getProfileModel(profile):
"""
(pyCMS) Gets the model for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
:exc:`PyCMSError` is raised.
If an error occurs while trying to obtain the model tag,
a :exc:`PyCMSError` is raised.
Use this function... | [
"def",
"getProfileModel",
"(",
"profile",
")",
":",
"try",
":",
"# add an extra newline to preserve pyCMS compatibility",
"if",
"not",
"isinstance",
"(",
"profile",
",",
"ImageCmsProfile",
")",
":",
"profile",
"=",
"ImageCmsProfile",
"(",
"profile",
")",
"return",
"... | [
836,
0
] | [
862,
34
] | python | en | ['en', 'error', 'th'] | False |
getProfileDescription | (profile) |
(pyCMS) Gets the description for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
:exc:`PyCMSError` is raised.
If an error occurs while trying to obtain the description tag,
a :exc:`PyCMSError` is raised.
Use this function to obtain the informatio... |
(pyCMS) Gets the description for the given profile. | def getProfileDescription(profile):
"""
(pyCMS) Gets the description for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
:exc:`PyCMSError` is raised.
If an error occurs while trying to obtain the description tag,
a :exc:`PyCMSError` is raised.
... | [
"def",
"getProfileDescription",
"(",
"profile",
")",
":",
"try",
":",
"# add an extra newline to preserve pyCMS compatibility",
"if",
"not",
"isinstance",
"(",
"profile",
",",
"ImageCmsProfile",
")",
":",
"profile",
"=",
"ImageCmsProfile",
"(",
"profile",
")",
"return... | [
865,
0
] | [
891,
34
] | python | en | ['en', 'error', 'th'] | False |
getDefaultIntent | (profile) |
(pyCMS) Gets the default intent name for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
:exc:`PyCMSError` is raised.
If an error occurs while trying to obtain the default intent, a
:exc:`PyCMSError` is raised.
Use this function to determine the ... |
(pyCMS) Gets the default intent name for the given profile. | def getDefaultIntent(profile):
"""
(pyCMS) Gets the default intent name for the given profile.
If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
:exc:`PyCMSError` is raised.
If an error occurs while trying to obtain the default intent, a
:exc:`PyCMSError` is raised.
... | [
"def",
"getDefaultIntent",
"(",
"profile",
")",
":",
"try",
":",
"if",
"not",
"isinstance",
"(",
"profile",
",",
"ImageCmsProfile",
")",
":",
"profile",
"=",
"ImageCmsProfile",
"(",
"profile",
")",
"return",
"profile",
".",
"profile",
".",
"rendering_intent",
... | [
894,
0
] | [
930,
34
] | python | en | ['en', 'error', 'th'] | False |
isIntentSupported | (profile, intent, direction) |
(pyCMS) Checks if a given intent is supported.
Use this function to verify that you can use your desired
``intent`` with ``profile``, and that ``profile`` can be used for the
input/output/proof profile as you desire.
Some profiles are created specifically for one "direction", can cannot
be us... |
(pyCMS) Checks if a given intent is supported. | def isIntentSupported(profile, intent, direction):
"""
(pyCMS) Checks if a given intent is supported.
Use this function to verify that you can use your desired
``intent`` with ``profile``, and that ``profile`` can be used for the
input/output/proof profile as you desire.
Some profiles are crea... | [
"def",
"isIntentSupported",
"(",
"profile",
",",
"intent",
",",
"direction",
")",
":",
"try",
":",
"if",
"not",
"isinstance",
"(",
"profile",
",",
"ImageCmsProfile",
")",
":",
"profile",
"=",
"ImageCmsProfile",
"(",
"profile",
")",
"# FIXME: I get different resu... | [
933,
0
] | [
981,
34
] | python | en | ['en', 'error', 'th'] | False |
versions | () |
(pyCMS) Fetches versions.
|
(pyCMS) Fetches versions.
| def versions():
"""
(pyCMS) Fetches versions.
"""
return (VERSION, core.littlecms_version, sys.version.split()[0], Image.__version__) | [
"def",
"versions",
"(",
")",
":",
"return",
"(",
"VERSION",
",",
"core",
".",
"littlecms_version",
",",
"sys",
".",
"version",
".",
"split",
"(",
")",
"[",
"0",
"]",
",",
"Image",
".",
"__version__",
")"
] | [
984,
0
] | [
989,
87
] | python | en | ['en', 'error', 'th'] | False |
ImageCmsProfile.__init__ | (self, profile) |
:param profile: Either a string representing a filename,
a file like object containing a profile or a
low-level profile object
|
:param profile: Either a string representing a filename,
a file like object containing a profile or a
low-level profile object | def __init__(self, profile):
"""
:param profile: Either a string representing a filename,
a file like object containing a profile or a
low-level profile object
"""
if isinstance(profile, str):
self._set(core.profile_open(profile), profile)
el... | [
"def",
"__init__",
"(",
"self",
",",
"profile",
")",
":",
"if",
"isinstance",
"(",
"profile",
",",
"str",
")",
":",
"self",
".",
"_set",
"(",
"core",
".",
"profile_open",
"(",
"profile",
")",
",",
"profile",
")",
"elif",
"hasattr",
"(",
"profile",
",... | [
152,
4
] | [
167,
55
] | python | en | ['en', 'error', 'th'] | False |
ImageCmsProfile.tobytes | (self) |
Returns the profile in a format suitable for embedding in
saved images.
:returns: a bytes object containing the ICC profile.
|
Returns the profile in a format suitable for embedding in
saved images. | def tobytes(self):
"""
Returns the profile in a format suitable for embedding in
saved images.
:returns: a bytes object containing the ICC profile.
"""
return core.profile_tobytes(self.profile) | [
"def",
"tobytes",
"(",
"self",
")",
":",
"return",
"core",
".",
"profile_tobytes",
"(",
"self",
".",
"profile",
")"
] | [
179,
4
] | [
187,
49
] | python | en | ['en', 'error', 'th'] | False |
ConfigSource.config | (self) | Current Config Content. | Current Config Content. | def config(self) -> dict:
"""Current Config Content."""
return self._config | [
"def",
"config",
"(",
"self",
")",
"->",
"dict",
":",
"return",
"self",
".",
"_config"
] | [
25,
4
] | [
27,
27
] | python | ca | ['de', 'ca', 'en'] | False |
ConfigSource.config | (self, value: dict) | Set current config content.
Args:
value (dict): New value to set
Returns:
dict: Current config
| Set current config content. | def config(self, value: dict) -> dict:
"""Set current config content.
Args:
value (dict): New value to set
Returns:
dict: Current config
"""
self._config = value
return self._config | [
"def",
"config",
"(",
"self",
",",
"value",
":",
"dict",
")",
"->",
"dict",
":",
"self",
".",
"_config",
"=",
"value",
"return",
"self",
".",
"_config"
] | [
30,
4
] | [
41,
27
] | python | ca | ['de', 'ca', 'en'] | False |
ConfigSource.exists | (self) | Property to check if source exists. | Property to check if source exists. | def exists(self) -> bool:
"""Property to check if source exists.""" | [
"def",
"exists",
"(",
"self",
")",
"->",
"bool",
":"
] | [
44,
4
] | [
45,
49
] | python | en | ['en', 'en', 'en'] | True |
ConfigSource.save | (self, content: Any) | Method to save config. | Method to save config. | def save(self, content: Any) -> Any:
"""Method to save config.""" | [
"def",
"save",
"(",
"self",
",",
"content",
":",
"Any",
")",
"->",
"Any",
":"
] | [
48,
4
] | [
49,
36
] | python | en | ['en', 'en', 'en'] | True |
ConfigSource.process | (self) | Read and process config file.
Returns:
dict: Config file content
| Read and process config file. | def process(self) -> dict:
"""Read and process config file.
Returns:
dict: Config file content
""" | [
"def",
"process",
"(",
"self",
")",
"->",
"dict",
":"
] | [
52,
4
] | [
58,
11
] | python | en | ['en', 'en', 'en'] | True |
ConfigSource.prepare | (self) | Method to prepare on enter. | Method to prepare on enter. | def prepare(self) -> Any:
"""Method to prepare on enter.""" | [
"def",
"prepare",
"(",
"self",
")",
"->",
"Any",
":"
] | [
61,
4
] | [
62,
41
] | python | en | ['en', 'el-Latn', 'en'] | True |
OpenLayersWidget.map_options | (self) | Build the map options hash for the OpenLayers template. | Build the map options hash for the OpenLayers template. | def map_options(self):
"""Build the map options hash for the OpenLayers template."""
# JavaScript construction utilities for the Bounds and Projection.
def ol_bounds(extent):
return 'new OpenLayers.Bounds(%s)' % extent
def ol_projection(srid):
return 'new OpenLay... | [
"def",
"map_options",
"(",
"self",
")",
":",
"# JavaScript construction utilities for the Bounds and Projection.",
"def",
"ol_bounds",
"(",
"extent",
")",
":",
"return",
"'new OpenLayers.Bounds(%s)'",
"%",
"extent",
"def",
"ol_projection",
"(",
"srid",
")",
":",
"return... | [
80,
4
] | [
116,
26
] | python | en | ['en', 'en', 'en'] | True |
BmpImageFile._bitmap | (self, header=0, offset=0) | Read relevant info about the BMP | Read relevant info about the BMP | def _bitmap(self, header=0, offset=0):
""" Read relevant info about the BMP """
read, seek = self.fp.read, self.fp.seek
if header:
seek(header)
file_info = {}
# read bmp header size @offset 14 (this is part of the header size)
file_info["header_size"] = i32(re... | [
"def",
"_bitmap",
"(",
"self",
",",
"header",
"=",
"0",
",",
"offset",
"=",
"0",
")",
":",
"read",
",",
"seek",
"=",
"self",
".",
"fp",
".",
"read",
",",
"self",
".",
"fp",
".",
"seek",
"if",
"header",
":",
"seek",
"(",
"header",
")",
"file_inf... | [
67,
4
] | [
258,
9
] | python | en | ['en', 'en', 'en'] | True |
BmpImageFile._open | (self) | Open file, check magic number and read header | Open file, check magic number and read header | def _open(self):
""" Open file, check magic number and read header """
# read 14 bytes: magic number, filesize, reserved, header final offset
head_data = self.fp.read(14)
# choke if the file does not have the required magic bytes
if not _accept(head_data):
raise Synta... | [
"def",
"_open",
"(",
"self",
")",
":",
"# read 14 bytes: magic number, filesize, reserved, header final offset",
"head_data",
"=",
"self",
".",
"fp",
".",
"read",
"(",
"14",
")",
"# choke if the file does not have the required magic bytes",
"if",
"not",
"_accept",
"(",
"h... | [
260,
4
] | [
270,
35
] | python | en | ['en', 'en', 'en'] | True |
BaseSessionManager.encode | (self, session_dict) |
Return the given session dictionary serialized and encoded as a string.
|
Return the given session dictionary serialized and encoded as a string.
| def encode(self, session_dict):
"""
Return the given session dictionary serialized and encoded as a string.
"""
session_store_class = self.model.get_session_store_class()
return session_store_class().encode(session_dict) | [
"def",
"encode",
"(",
"self",
",",
"session_dict",
")",
":",
"session_store_class",
"=",
"self",
".",
"model",
".",
"get_session_store_class",
"(",
")",
"return",
"session_store_class",
"(",
")",
".",
"encode",
"(",
"session_dict",
")"
] | [
9,
4
] | [
14,
57
] | python | en | ['en', 'error', 'th'] | False |
upath | (path) |
Always return a unicode path.
|
Always return a unicode path.
| def upath(path):
"""
Always return a unicode path.
"""
if six.PY2 and not isinstance(path, six.text_type):
return path.decode(fs_encoding)
return path | [
"def",
"upath",
"(",
"path",
")",
":",
"if",
"six",
".",
"PY2",
"and",
"not",
"isinstance",
"(",
"path",
",",
"six",
".",
"text_type",
")",
":",
"return",
"path",
".",
"decode",
"(",
"fs_encoding",
")",
"return",
"path"
] | [
38,
0
] | [
44,
15
] | python | en | ['en', 'error', 'th'] | False |
npath | (path) |
Always return a native path, that is unicode on Python 3 and bytestring on
Python 2.
|
Always return a native path, that is unicode on Python 3 and bytestring on
Python 2.
| def npath(path):
"""
Always return a native path, that is unicode on Python 3 and bytestring on
Python 2.
"""
if six.PY2 and not isinstance(path, bytes):
return path.encode(fs_encoding)
return path | [
"def",
"npath",
"(",
"path",
")",
":",
"if",
"six",
".",
"PY2",
"and",
"not",
"isinstance",
"(",
"path",
",",
"bytes",
")",
":",
"return",
"path",
".",
"encode",
"(",
"fs_encoding",
")",
"return",
"path"
] | [
47,
0
] | [
54,
15
] | python | en | ['en', 'error', 'th'] | False |
safe_join | (base, *paths) |
Joins one or more path components to the base path component intelligently.
Returns a normalized, absolute version of the final path.
The final path must be located inside of the base path component (otherwise
a ValueError is raised).
|
Joins one or more path components to the base path component intelligently.
Returns a normalized, absolute version of the final path. | def safe_join(base, *paths):
"""
Joins one or more path components to the base path component intelligently.
Returns a normalized, absolute version of the final path.
The final path must be located inside of the base path component (otherwise
a ValueError is raised).
"""
base = force_text(b... | [
"def",
"safe_join",
"(",
"base",
",",
"*",
"paths",
")",
":",
"base",
"=",
"force_text",
"(",
"base",
")",
"paths",
"=",
"[",
"force_text",
"(",
"p",
")",
"for",
"p",
"in",
"paths",
"]",
"final_path",
"=",
"abspathu",
"(",
"join",
"(",
"base",
",",... | [
57,
0
] | [
81,
21
] | python | en | ['en', 'error', 'th'] | False |
rmtree_errorhandler | (func, path, exc_info) |
On Windows, some files are read-only (e.g. in in .svn dirs), so when
rmtree() tries to remove them, an exception is thrown.
We catch that here, remove the read-only attribute, and hopefully
continue without problems.
|
On Windows, some files are read-only (e.g. in in .svn dirs), so when
rmtree() tries to remove them, an exception is thrown.
We catch that here, remove the read-only attribute, and hopefully
continue without problems.
| def rmtree_errorhandler(func, path, exc_info):
"""
On Windows, some files are read-only (e.g. in in .svn dirs), so when
rmtree() tries to remove them, an exception is thrown.
We catch that here, remove the read-only attribute, and hopefully
continue without problems.
"""
exctype, value = exc... | [
"def",
"rmtree_errorhandler",
"(",
"func",
",",
"path",
",",
"exc_info",
")",
":",
"exctype",
",",
"value",
"=",
"exc_info",
"[",
":",
"2",
"]",
"# looking for a windows error",
"if",
"exctype",
"is",
"not",
"WindowsError",
"or",
"'Access is denied'",
"not",
"... | [
84,
0
] | [
101,
14
] | python | en | ['en', 'error', 'th'] | False |
symlinks_supported | () |
A function to check if creating symlinks are supported in the
host platform and/or if they are allowed to be created (e.g.
on Windows it requires admin permissions).
|
A function to check if creating symlinks are supported in the
host platform and/or if they are allowed to be created (e.g.
on Windows it requires admin permissions).
| def symlinks_supported():
"""
A function to check if creating symlinks are supported in the
host platform and/or if they are allowed to be created (e.g.
on Windows it requires admin permissions).
"""
tmpdir = tempfile.mkdtemp()
original_path = os.path.join(tmpdir, 'original')
symlink_pat... | [
"def",
"symlinks_supported",
"(",
")",
":",
"tmpdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"original_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tmpdir",
",",
"'original'",
")",
"symlink_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tmp... | [
104,
0
] | [
124,
24
] | python | en | ['en', 'error', 'th'] | False |
get_flatpages | (parser, token) |
Retrieve all flatpage objects available for the current site and
visible to the specific user (or visible to all users if no user is
specified). Populate the template context with them in a variable
whose name is defined by the ``as`` clause.
An optional ``for`` clause controls the user whose perm... |
Retrieve all flatpage objects available for the current site and
visible to the specific user (or visible to all users if no user is
specified). Populate the template context with them in a variable
whose name is defined by the ``as`` clause. | def get_flatpages(parser, token):
"""
Retrieve all flatpage objects available for the current site and
visible to the specific user (or visible to all users if no user is
specified). Populate the template context with them in a variable
whose name is defined by the ``as`` clause.
An optional ``... | [
"def",
"get_flatpages",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"syntax_message",
"=",
"(",
"\"%(tag_name)s expects a syntax of %(tag_name)s \"",
"\"['url_starts_with'] [for user] as context_name\"",
"%",
"{",
"'tag_na... | [
45,
0
] | [
98,
58
] | python | en | ['en', 'error', 'th'] | False |
add_ratelimit_rule | (range_seconds: int, num_requests: int, domain: str = "api_by_user") | Add a rate-limiting rule to the ratelimiter | Add a rate-limiting rule to the ratelimiter | def add_ratelimit_rule(range_seconds: int, num_requests: int, domain: str = "api_by_user") -> None:
"Add a rate-limiting rule to the ratelimiter"
global rules
if domain not in rules:
# If we don't have any rules for domain yet, the domain key needs to be
# added to the rules dictionary.
... | [
"def",
"add_ratelimit_rule",
"(",
"range_seconds",
":",
"int",
",",
"num_requests",
":",
"int",
",",
"domain",
":",
"str",
"=",
"\"api_by_user\"",
")",
"->",
"None",
":",
"global",
"rules",
"if",
"domain",
"not",
"in",
"rules",
":",
"# If we don't have any rul... | [
139,
0
] | [
149,
42
] | python | en | ['en', 'en', 'en'] | True |
RateLimitedObject.block_access | (self, seconds: int) | Manually blocks an entity for the desired number of seconds | Manually blocks an entity for the desired number of seconds | def block_access(self, seconds: int) -> None:
"Manually blocks an entity for the desired number of seconds"
self.backend.block_access(self.key(), seconds) | [
"def",
"block_access",
"(",
"self",
",",
"seconds",
":",
"int",
")",
"->",
"None",
":",
"self",
".",
"backend",
".",
"block_access",
"(",
"self",
".",
"key",
"(",
")",
",",
"seconds",
")"
] | [
66,
4
] | [
68,
54
] | python | en | ['en', 'en', 'en'] | True |
RateLimitedObject.max_api_calls | (self) | Returns the API rate limit for the highest limit | Returns the API rate limit for the highest limit | def max_api_calls(self) -> int:
"Returns the API rate limit for the highest limit"
return self.get_rules()[-1][1] | [
"def",
"max_api_calls",
"(",
"self",
")",
"->",
"int",
":",
"return",
"self",
".",
"get_rules",
"(",
")",
"[",
"-",
"1",
"]",
"[",
"1",
"]"
] | [
76,
4
] | [
78,
38
] | python | en | ['en', 'en', 'en'] | True |
RateLimitedObject.max_api_window | (self) | Returns the API time window for the highest limit | Returns the API time window for the highest limit | def max_api_window(self) -> int:
"Returns the API time window for the highest limit"
return self.get_rules()[-1][0] | [
"def",
"max_api_window",
"(",
"self",
")",
"->",
"int",
":",
"return",
"self",
".",
"get_rules",
"(",
")",
"[",
"-",
"1",
"]",
"[",
"0",
"]"
] | [
80,
4
] | [
82,
38
] | python | en | ['en', 'en', 'en'] | True |
RateLimitedObject.api_calls_left | (self) | Returns how many API calls in this range this client has, as well as when
the rate-limit will be reset to 0 | Returns how many API calls in this range this client has, as well as when
the rate-limit will be reset to 0 | def api_calls_left(self) -> Tuple[int, float]:
"""Returns how many API calls in this range this client has, as well as when
the rate-limit will be reset to 0"""
max_window = self.max_api_window()
max_calls = self.max_api_calls()
return self.backend.get_api_calls_left(self.key(), ... | [
"def",
"api_calls_left",
"(",
"self",
")",
"->",
"Tuple",
"[",
"int",
",",
"float",
"]",
":",
"max_window",
"=",
"self",
".",
"max_api_window",
"(",
")",
"max_calls",
"=",
"self",
".",
"max_api_calls",
"(",
")",
"return",
"self",
".",
"backend",
".",
"... | [
84,
4
] | [
89,
81
] | python | en | ['en', 'en', 'en'] | True |
RateLimitedObject.get_rules | (self) |
This is a simple wrapper meant to protect against having to deal with
an empty list of rules, as it would require fiddling with that special case
all around this system. "9999 max request per seconds" should be a good proxy
for "no rules".
|
This is a simple wrapper meant to protect against having to deal with
an empty list of rules, as it would require fiddling with that special case
all around this system. "9999 max request per seconds" should be a good proxy
for "no rules".
| def get_rules(self) -> List[Tuple[int, int]]:
"""
This is a simple wrapper meant to protect against having to deal with
an empty list of rules, as it would require fiddling with that special case
all around this system. "9999 max request per seconds" should be a good proxy
for "n... | [
"def",
"get_rules",
"(",
"self",
")",
"->",
"List",
"[",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
":",
"rules_list",
"=",
"self",
".",
"rules",
"(",
")",
"return",
"rules_list",
"or",
"[",
"(",
"1",
",",
"9999",
")",
"]"
] | [
91,
4
] | [
99,
40
] | python | en | ['en', 'error', 'th'] | False |
RateLimiterBackend.block_access | (cls, entity_key: str, seconds: int) | Manually blocks an entity for the desired number of seconds | Manually blocks an entity for the desired number of seconds | def block_access(cls, entity_key: str, seconds: int) -> None:
"Manually blocks an entity for the desired number of seconds" | [
"def",
"block_access",
"(",
"cls",
",",
"entity_key",
":",
"str",
",",
"seconds",
":",
"int",
")",
"->",
"None",
":"
] | [
162,
4
] | [
163,
69
] | python | en | ['en', 'en', 'en'] | True |
TornadoInMemoryRateLimiterBackend.need_to_limit | (cls, entity_key: str, time_window: int, max_count: int) |
Returns a tuple of `(rate_limited, time_till_free)`.
For simplicity, we have loosened the semantics here from
- each key may make atmost `count * (t / window)` request within any t
time interval.
to
- each key may make atmost `count * [(t / window) + 1]` request within... |
Returns a tuple of `(rate_limited, time_till_free)`.
For simplicity, we have loosened the semantics here from
- each key may make atmost `count * (t / window)` request within any t
time interval.
to
- each key may make atmost `count * [(t / window) + 1]` request within... | def need_to_limit(cls, entity_key: str, time_window: int, max_count: int) -> Tuple[bool, float]:
"""
Returns a tuple of `(rate_limited, time_till_free)`.
For simplicity, we have loosened the semantics here from
- each key may make atmost `count * (t / window)` request within any t
... | [
"def",
"need_to_limit",
"(",
"cls",
",",
"entity_key",
":",
"str",
",",
"time_window",
":",
"int",
",",
"max_count",
":",
"int",
")",
"->",
"Tuple",
"[",
"bool",
",",
"float",
"]",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"# Remove all timestamp... | [
224,
4
] | [
254,
25
] | python | en | ['en', 'error', 'th'] | False |
RedisRateLimiterBackend.block_access | (cls, entity_key: str, seconds: int) | Manually blocks an entity for the desired number of seconds | Manually blocks an entity for the desired number of seconds | def block_access(cls, entity_key: str, seconds: int) -> None:
"Manually blocks an entity for the desired number of seconds"
_, _, blocking_key = cls.get_keys(entity_key)
with client.pipeline() as pipe:
pipe.set(blocking_key, 1)
pipe.expire(blocking_key, seconds)
... | [
"def",
"block_access",
"(",
"cls",
",",
"entity_key",
":",
"str",
",",
"seconds",
":",
"int",
")",
"->",
"None",
":",
"_",
",",
"_",
",",
"blocking_key",
"=",
"cls",
".",
"get_keys",
"(",
"entity_key",
")",
"with",
"client",
".",
"pipeline",
"(",
")"... | [
318,
4
] | [
324,
26
] | python | en | ['en', 'en', 'en'] | True |
RedisRateLimiterBackend.is_ratelimited | (cls, entity_key: str, rules: List[Tuple[int, int]]) | Returns a tuple of (rate_limited, time_till_free) | Returns a tuple of (rate_limited, time_till_free) | def is_ratelimited(cls, entity_key: str, rules: List[Tuple[int, int]]) -> Tuple[bool, float]:
"Returns a tuple of (rate_limited, time_till_free)"
assert rules
list_key, set_key, blocking_key = cls.get_keys(entity_key)
# Go through the rules from shortest to longest,
# seeing if ... | [
"def",
"is_ratelimited",
"(",
"cls",
",",
"entity_key",
":",
"str",
",",
"rules",
":",
"List",
"[",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
")",
"->",
"Tuple",
"[",
"bool",
",",
"float",
"]",
":",
"assert",
"rules",
"list_key",
",",
"set_key",
"... | [
367,
4
] | [
409,
25
] | python | en | ['en', 'en', 'en'] | True |
RedisRateLimiterBackend.incr_ratelimit | (cls, entity_key: str, max_api_calls: int, max_api_window: int) | Increases the rate-limit for the specified entity | Increases the rate-limit for the specified entity | def incr_ratelimit(cls, entity_key: str, max_api_calls: int, max_api_window: int) -> None:
"""Increases the rate-limit for the specified entity"""
list_key, set_key, _ = cls.get_keys(entity_key)
now = time.time()
# Start Redis transaction
with client.pipeline() as pipe:
... | [
"def",
"incr_ratelimit",
"(",
"cls",
",",
"entity_key",
":",
"str",
",",
"max_api_calls",
":",
"int",
",",
"max_api_window",
":",
"int",
")",
"->",
"None",
":",
"list_key",
",",
"set_key",
",",
"_",
"=",
"cls",
".",
"get_keys",
"(",
"entity_key",
")",
... | [
412,
4
] | [
463,
28
] | python | en | ['en', 'en', 'en'] | True |
compile_requirements | (requirements, lockfile) |
Run piptools compile over a requirement file to generate an output lockfile.
We use `--allow-unsafe` as we want to include wheel, pip, and setuptools in our output.
|
Run piptools compile over a requirement file to generate an output lockfile.
We use `--allow-unsafe` as we want to include wheel, pip, and setuptools in our output.
| def compile_requirements(requirements, lockfile):
"""
Run piptools compile over a requirement file to generate an output lockfile.
We use `--allow-unsafe` as we want to include wheel, pip, and setuptools in our output.
"""
subprocess.check_call(
[
sys.executable,
"-m"... | [
"def",
"compile_requirements",
"(",
"requirements",
",",
"lockfile",
")",
":",
"subprocess",
".",
"check_call",
"(",
"[",
"sys",
".",
"executable",
",",
"\"-m\"",
",",
"\"piptools\"",
",",
"\"compile\"",
",",
"\"--no-header\"",
",",
"\"--no-annotate\"",
",",
"\"... | [
18,
0
] | [
37,
5
] | python | en | ['en', 'error', 'th'] | False |
delete_selected | (modeladmin, request, queryset) |
Default action which deletes the selected objects.
This action first displays a confirmation page which shows all the
deletable objects, or, if the user has no permission one of the related
childs (foreignkeys), a "permission denied" message.
Next, it deletes all selected objects and redirects ba... |
Default action which deletes the selected objects. | def delete_selected(modeladmin, request, queryset):
"""
Default action which deletes the selected objects.
This action first displays a confirmation page which shows all the
deletable objects, or, if the user has no permission one of the related
childs (foreignkeys), a "permission denied" message.
... | [
"def",
"delete_selected",
"(",
"modeladmin",
",",
"request",
",",
"queryset",
")",
":",
"opts",
"=",
"modeladmin",
".",
"model",
".",
"_meta",
"app_label",
"=",
"opts",
".",
"app_label",
"# Populate deletable_objects, a data structure of all related objects that",
"# wi... | [
12,
0
] | [
74,
15
] | python | en | ['en', 'error', 'th'] | False |
lru_cache | (maxsize=100) | Least-recently-used cache decorator.
Arguments to the cached function must be hashable.
See: http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used
| Least-recently-used cache decorator. | def lru_cache(maxsize=100):
"""Least-recently-used cache decorator.
Arguments to the cached function must be hashable.
See: http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used
"""
def decorating_function(user_function):
cache = dict()
stats = [0, 0] ... | [
"def",
"lru_cache",
"(",
"maxsize",
"=",
"100",
")",
":",
"def",
"decorating_function",
"(",
"user_function",
")",
":",
"cache",
"=",
"dict",
"(",
")",
"stats",
"=",
"[",
"0",
",",
"0",
"]",
"# make statistics updateable non-locally",
"HITS",
",",
"MISSES",
... | [
14,
0
] | [
103,
30
] | python | en | ['en', 'en', 'en'] | True |
main | () | Run administrative tasks. | Run administrative tasks. | def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'OnlineIde.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's install... | [
"def",
"main",
"(",
")",
":",
"os",
".",
"environ",
".",
"setdefault",
"(",
"'DJANGO_SETTINGS_MODULE'",
",",
"'OnlineIde.settings'",
")",
"try",
":",
"from",
"django",
".",
"core",
".",
"management",
"import",
"execute_from_command_line",
"except",
"ImportError",
... | [
6,
0
] | [
17,
39
] | python | en | ['lv', 'gd', 'en'] | False |
pack | (directory, dest_dir, build_number) | Repack a previously unpacked wheel directory into a new wheel file.
The .dist-info/WHEEL file must contain one or more tags so that the target
wheel file name can be determined.
:param directory: The unpacked wheel directory
:param dest_dir: Destination directory (defaults to the current directory)
... | Repack a previously unpacked wheel directory into a new wheel file. | def pack(directory, dest_dir, build_number):
"""Repack a previously unpacked wheel directory into a new wheel file.
The .dist-info/WHEEL file must contain one or more tags so that the target
wheel file name can be determined.
:param directory: The unpacked wheel directory
:param dest_dir: Destinat... | [
"def",
"pack",
"(",
"directory",
",",
"dest_dir",
",",
"build_number",
")",
":",
"# Find the .dist-info directory",
"dist_info_dirs",
"=",
"[",
"fn",
"for",
"fn",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"("... | [
13,
0
] | [
78,
15
] | python | en | ['en', 'en', 'en'] | True |
dumps | (obj, key=None, salt='django.core.signing', serializer=JSONSerializer, compress=False) |
Return URL-safe, hmac/SHA1 signed base64 compressed JSON string. If key is
None, use settings.SECRET_KEY instead.
If compress is True (not the default), check if compressing using zlib can
save some space. Prepend a '.' to signify compression. This is included
in the signature, to protect against ... |
Return URL-safe, hmac/SHA1 signed base64 compressed JSON string. If key is
None, use settings.SECRET_KEY instead. | def dumps(obj, key=None, salt='django.core.signing', serializer=JSONSerializer, compress=False):
"""
Return URL-safe, hmac/SHA1 signed base64 compressed JSON string. If key is
None, use settings.SECRET_KEY instead.
If compress is True (not the default), check 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... | [
92,
0
] | [
122,
56
] | python | en | ['en', 'error', 'th'] | False |
loads | (s, key=None, salt='django.core.signing', serializer=JSONSerializer, max_age=None) |
Reverse of dumps(), raise BadSignature if signature fails.
The serializer is expected to accept a bytestring.
|
Reverse of dumps(), raise BadSignature if signature fails. | def loads(s, key=None, salt='django.core.signing', serializer=JSONSerializer, max_age=None):
"""
Reverse of dumps(), raise BadSignature if signature fails.
The serializer is expected to accept a bytestring.
"""
# TimestampSigner.unsign() returns str but base64 and zlib compression
# operate on ... | [
"def",
"loads",
"(",
"s",
",",
"key",
"=",
"None",
",",
"salt",
"=",
"'django.core.signing'",
",",
"serializer",
"=",
"JSONSerializer",
",",
"max_age",
"=",
"None",
")",
":",
"# TimestampSigner.unsign() returns str but base64 and zlib compression",
"# operate on bytes."... | [
125,
0
] | [
141,
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().unsign(value)
value, timestamp = result.rsplit(self.sep, 1)
timestamp = baseconv.base62.decode(timestamp)
if m... | [
"def",
"unsign",
"(",
"self",
",",
"value",
",",
"max_age",
"=",
"None",
")",
":",
"result",
"=",
"super",
"(",
")",
".",
"unsign",
"(",
"value",
")",
"value",
",",
"timestamp",
"=",
"result",
".",
"rsplit",
"(",
"self",
".",
"sep",
",",
"1",
")"... | [
181,
4
] | [
197,
20
] | python | en | ['en', 'error', 'th'] | False |
StatementSplitter._reset | (self) | Set the filter attributes to its default values | Set the filter attributes to its default values | def _reset(self):
"""Set the filter attributes to its default values"""
self._in_declare = False
self._is_create = False
self._begin_depth = 0
self.consume_ws = False
self.tokens = []
self.level = 0 | [
"def",
"_reset",
"(",
"self",
")",
":",
"self",
".",
"_in_declare",
"=",
"False",
"self",
".",
"_is_create",
"=",
"False",
"self",
".",
"_begin_depth",
"=",
"0",
"self",
".",
"consume_ws",
"=",
"False",
"self",
".",
"tokens",
"=",
"[",
"]",
"self",
"... | [
17,
4
] | [
25,
22
] | python | en | ['en', 'en', 'en'] | True |
StatementSplitter._change_splitlevel | (self, ttype, value) | Get the new split level (increase, decrease or remain equal) | Get the new split level (increase, decrease or remain equal) | def _change_splitlevel(self, ttype, value):
"""Get the new split level (increase, decrease or remain equal)"""
# parenthesis increase/decrease a level
if ttype is T.Punctuation and value == '(':
return 1
elif ttype is T.Punctuation and value == ')':
return -1
... | [
"def",
"_change_splitlevel",
"(",
"self",
",",
"ttype",
",",
"value",
")",
":",
"# parenthesis increase/decrease a level",
"if",
"ttype",
"is",
"T",
".",
"Punctuation",
"and",
"value",
"==",
"'('",
":",
"return",
"1",
"elif",
"ttype",
"is",
"T",
".",
"Punctu... | [
27,
4
] | [
77,
16
] | python | en | ['en', 'en', 'en'] | True |
StatementSplitter.process | (self, stream) | Process the stream | Process the stream | def process(self, stream):
"""Process the stream"""
EOS_TTYPE = T.Whitespace, T.Comment.Single
# Run over all stream tokens
for ttype, value in stream:
# Yield token if we finished a statement and there's no whitespaces
# It will count newline token as a non whit... | [
"def",
"process",
"(",
"self",
",",
"stream",
")",
":",
"EOS_TTYPE",
"=",
"T",
".",
"Whitespace",
",",
"T",
".",
"Comment",
".",
"Single",
"# Run over all stream tokens",
"for",
"ttype",
",",
"value",
"in",
"stream",
":",
"# Yield token if we finished a statemen... | [
79,
4
] | [
107,
44
] | python | en | ['en', 'zh', 'en'] | True |
sanitize_username | (value) |
Sanitize Respa username.
None, empty string and AnonymousUser will be returned as is.
Otherwise a sanitized value is generated.
>>> sanitize_username('')
''
>>> sanitize_username(None)
>>> sanitize_username('AnonymousUser')
'AnonymousUser'
>>> assert sanitize_username('john-doe... |
Sanitize Respa username. | def sanitize_username(value):
"""
Sanitize Respa username.
None, empty string and AnonymousUser will be returned as is.
Otherwise a sanitized value is generated.
>>> sanitize_username('')
''
>>> sanitize_username(None)
>>> sanitize_username('AnonymousUser')
'AnonymousUser'
>... | [
"def",
"sanitize_username",
"(",
"value",
")",
":",
"if",
"not",
"value",
"or",
"value",
"==",
"'AnonymousUser'",
":",
"return",
"value",
"return",
"base",
".",
"sanitize_username",
"(",
"value",
")"
] | [
3,
0
] | [
22,
40
] | python | en | ['en', 'error', 'th'] | False |
csrf_exempt | (view_func) |
Marks a view function as being exempt from the CSRF view protection.
|
Marks a view function as being exempt from the CSRF view protection.
| def csrf_exempt(view_func):
"""
Marks a view function as being exempt from the CSRF view protection.
"""
# We could just do view_func.csrf_exempt = True, but decorators
# are nicer if they don't have side-effects, so we return a new
# function.
def wrapped_view(*args, **kwargs):
retu... | [
"def",
"csrf_exempt",
"(",
"view_func",
")",
":",
"# We could just do view_func.csrf_exempt = True, but decorators",
"# are nicer if they don't have side-effects, so we return a new",
"# function.",
"def",
"wrapped_view",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"... | [
48,
0
] | [
58,
78
] | python | en | ['en', 'error', 'th'] | False |
concat_all_gather | (tensor: Tensor) |
Performs all_gather operation on the provided tensors.
*** Warning ***: torch.distributed.all_gather has no gradient.
|
Performs all_gather operation on the provided tensors.
*** Warning ***: torch.distributed.all_gather has no gradient.
| def concat_all_gather(tensor: Tensor) -> Tensor:
"""
Performs all_gather operation on the provided tensors.
*** Warning ***: torch.distributed.all_gather has no gradient.
"""
tensors_gather = [
torch.ones_like(tensor) for _ in range(torch.distributed.get_world_size())
]
torch.distrib... | [
"def",
"concat_all_gather",
"(",
"tensor",
":",
"Tensor",
")",
"->",
"Tensor",
":",
"tensors_gather",
"=",
"[",
"torch",
".",
"ones_like",
"(",
"tensor",
")",
"for",
"_",
"in",
"range",
"(",
"torch",
".",
"distributed",
".",
"get_world_size",
"(",
")",
"... | [
199,
0
] | [
211,
17
] | python | en | ['en', 'error', 'th'] | False |
MoCo.__init__ | (
self,
encoder_q: nn.Module,
encoder_k: nn.Module,
dim: int = 128,
K: int = 65536,
m: float = 0.999,
T: float = 0.07,
mlp: bool = False,
) |
dim: feature dimension (default: 128)
K: queue size; number of negative keys (default: 65536)
m: moco momentum of updating key encoder (default: 0.999)
T: softmax temperature (default: 0.07)
|
dim: feature dimension (default: 128)
K: queue size; number of negative keys (default: 65536)
m: moco momentum of updating key encoder (default: 0.999)
T: softmax temperature (default: 0.07)
| def __init__(
self,
encoder_q: nn.Module,
encoder_k: nn.Module,
dim: int = 128,
K: int = 65536,
m: float = 0.999,
T: float = 0.07,
mlp: bool = False,
):
"""
dim: feature dimension (default: 128)
K: queue size; number of negative... | [
"def",
"__init__",
"(",
"self",
",",
"encoder_q",
":",
"nn",
".",
"Module",
",",
"encoder_k",
":",
"nn",
".",
"Module",
",",
"dim",
":",
"int",
"=",
"128",
",",
"K",
":",
"int",
"=",
"65536",
",",
"m",
":",
"float",
"=",
"0.999",
",",
"T",
":",... | [
15,
4
] | [
70,
75
] | python | en | ['en', 'error', 'th'] | False |
MoCo._momentum_update_key_encoder | (self) |
Momentum update of the key encoder
|
Momentum update of the key encoder
| def _momentum_update_key_encoder(self):
"""
Momentum update of the key encoder
"""
for param_q, param_k in zip(
self.encoder_q.parameters(), self.encoder_k.parameters()
):
param_k.data = param_k.data * self.m + param_q.data * (1.0 - self.m) | [
"def",
"_momentum_update_key_encoder",
"(",
"self",
")",
":",
"for",
"param_q",
",",
"param_k",
"in",
"zip",
"(",
"self",
".",
"encoder_q",
".",
"parameters",
"(",
")",
",",
"self",
".",
"encoder_k",
".",
"parameters",
"(",
")",
")",
":",
"param_k",
".",... | [
73,
4
] | [
80,
80
] | python | en | ['en', 'error', 'th'] | False |
MoCo._batch_shuffle_ddp | (self, x: Tensor) |
Batch shuffle, for making use of BatchNorm.
*** Only support DistributedDataParallel (DDP) model. ***
|
Batch shuffle, for making use of BatchNorm.
*** Only support DistributedDataParallel (DDP) model. ***
| def _batch_shuffle_ddp(self, x: Tensor) -> Tuple[Tensor, Tensor]:
"""
Batch shuffle, for making use of BatchNorm.
*** Only support DistributedDataParallel (DDP) model. ***
"""
# gather from all gpus
batch_size_this = x.shape[0]
x_gather = concat_all_gather(x)
... | [
"def",
"_batch_shuffle_ddp",
"(",
"self",
",",
"x",
":",
"Tensor",
")",
"->",
"Tuple",
"[",
"Tensor",
",",
"Tensor",
"]",
":",
"# gather from all gpus",
"batch_size_this",
"=",
"x",
".",
"shape",
"[",
"0",
"]",
"x_gather",
"=",
"concat_all_gather",
"(",
"x... | [
102,
4
] | [
127,
48
] | python | en | ['en', 'error', 'th'] | False |
MoCo._batch_unshuffle_ddp | (self, x: Tensor, idx_unshuffle: Tensor) |
Undo batch shuffle.
*** Only support DistributedDataParallel (DDP) model. ***
|
Undo batch shuffle.
*** Only support DistributedDataParallel (DDP) model. ***
| def _batch_unshuffle_ddp(self, x: Tensor, idx_unshuffle: Tensor) -> Tensor:
"""
Undo batch shuffle.
*** Only support DistributedDataParallel (DDP) model. ***
"""
# gather from all gpus
batch_size_this = x.shape[0]
x_gather = concat_all_gather(x)
batch_size... | [
"def",
"_batch_unshuffle_ddp",
"(",
"self",
",",
"x",
":",
"Tensor",
",",
"idx_unshuffle",
":",
"Tensor",
")",
"->",
"Tensor",
":",
"# gather from all gpus",
"batch_size_this",
"=",
"x",
".",
"shape",
"[",
"0",
"]",
"x_gather",
"=",
"concat_all_gather",
"(",
... | [
130,
4
] | [
146,
33
] | python | en | ['en', 'error', 'th'] | False |
MoCo.forward | (self, im_q: Tensor, im_k: Tensor) |
Input:
im_q: a batch of query images
im_k: a batch of key images
Output:
logits, targets
|
Input:
im_q: a batch of query images
im_k: a batch of key images | def forward(self, im_q: Tensor, im_k: Tensor) -> Tuple[Tensor, Tensor]:
"""
Input:
im_q: a batch of query images
im_k: a batch of key images
Output:
logits, targets
"""
# compute query features
q = self.encoder_q(im_q) # queries: NxC... | [
"def",
"forward",
"(",
"self",
",",
"im_q",
":",
"Tensor",
",",
"im_k",
":",
"Tensor",
")",
"->",
"Tuple",
"[",
"Tensor",
",",
"Tensor",
"]",
":",
"# compute query features",
"q",
"=",
"self",
".",
"encoder_q",
"(",
"im_q",
")",
"# queries: NxC",
"q",
... | [
148,
4
] | [
194,
29
] | python | en | ['en', 'error', 'th'] | False |
train | (
model,
X_train=None,
Y_train=None,
save=False,
predictions_adv=None,
evaluate=None,
args=None,
rng=None,
var_list=None,
attack=None,
attack_args=None,
) |
Train a TF Eager model
:param model: cleverhans.model.Model
:param X_train: numpy array with training inputs
:param Y_train: numpy array with training outputs
:param save: boolean controlling the save operation
:param predictions_adv: if set with the adversarial example tensor,
... |
Train a TF Eager model
:param model: cleverhans.model.Model
:param X_train: numpy array with training inputs
:param Y_train: numpy array with training outputs
:param save: boolean controlling the save operation
:param predictions_adv: if set with the adversarial example tensor,
... | def train(
model,
X_train=None,
Y_train=None,
save=False,
predictions_adv=None,
evaluate=None,
args=None,
rng=None,
var_list=None,
attack=None,
attack_args=None,
):
"""
Train a TF Eager model
:param model: cleverhans.model.Model
:param X_train: numpy array wit... | [
"def",
"train",
"(",
"model",
",",
"X_train",
"=",
"None",
",",
"Y_train",
"=",
"None",
",",
"save",
"=",
"False",
",",
"predictions_adv",
"=",
"None",
",",
"evaluate",
"=",
"None",
",",
"args",
"=",
"None",
",",
"rng",
"=",
"None",
",",
"var_list",
... | [
23,
0
] | [
131,
15
] | python | en | ['en', 'error', 'th'] | False |
model_eval | (
model, X_test=None, Y_test=None, args=None, attack=None, attack_args=None
) |
Compute the accuracy of a TF Eager model on some data
:param model: instance of cleverhans.model.Model_Eager
with pretrained weights for evaluation.
:param X_test: numpy array with training inputs
:param Y_test: numpy array with training outputs
:param args: dict or argparse `Na... |
Compute the accuracy of a TF Eager model on some data
:param model: instance of cleverhans.model.Model_Eager
with pretrained weights for evaluation.
:param X_test: numpy array with training inputs
:param Y_test: numpy array with training outputs
:param args: dict or argparse `Na... | def model_eval(
model, X_test=None, Y_test=None, args=None, attack=None, attack_args=None
):
"""
Compute the accuracy of a TF Eager model on some data
:param model: instance of cleverhans.model.Model_Eager
with pretrained weights for evaluation.
:param X_test: numpy array with tr... | [
"def",
"model_eval",
"(",
"model",
",",
"X_test",
"=",
"None",
",",
"Y_test",
"=",
"None",
",",
"args",
"=",
"None",
",",
"attack",
"=",
"None",
",",
"attack_args",
"=",
"None",
")",
":",
"args",
"=",
"_ArgsWrapper",
"(",
"args",
"or",
"{",
"}",
")... | [
134,
0
] | [
203,
19
] | python | en | ['en', 'error', 'th'] | False |
model_argmax | (model, samples) |
Helper function that computes the current class prediction
:param samples: numpy array with input samples (dims must match x)
:return: the argmax output of predictions, i.e. the current predicted class
|
Helper function that computes the current class prediction
:param samples: numpy array with input samples (dims must match x)
:return: the argmax output of predictions, i.e. the current predicted class
| def model_argmax(model, samples):
"""
Helper function that computes the current class prediction
:param samples: numpy array with input samples (dims must match x)
:return: the argmax output of predictions, i.e. the current predicted class
"""
tfe = tf.contrib.eager
tf_samples = tfe.Variable... | [
"def",
"model_argmax",
"(",
"model",
",",
"samples",
")",
":",
"tfe",
"=",
"tf",
".",
"contrib",
".",
"eager",
"tf_samples",
"=",
"tfe",
".",
"Variable",
"(",
"samples",
")",
"probabilities",
"=",
"model",
".",
"get_probs",
"(",
"tf_samples",
")",
"if",
... | [
206,
0
] | [
219,
47
] | python | en | ['en', 'error', 'th'] | False |
Loader.find_template | (self, name, dirs=None) |
Helper method. Lookup the template :param name: in all the configured loaders
|
Helper method. Lookup the template :param name: in all the configured loaders
| def find_template(self, name, dirs=None):
"""
Helper method. Lookup the template :param name: in all the configured loaders
"""
key = self.cache_key(name, dirs)
try:
result = self.find_template_cache[key]
except KeyError:
result = None
... | [
"def",
"find_template",
"(",
"self",
",",
"name",
",",
"dirs",
"=",
"None",
")",
":",
"key",
"=",
"self",
".",
"cache_key",
"(",
"name",
",",
"dirs",
")",
"try",
":",
"result",
"=",
"self",
".",
"find_template_cache",
"[",
"key",
"]",
"except",
"KeyE... | [
39,
4
] | [
61,
44
] | python | en | ['en', 'error', 'th'] | False |
Loader.reset | (self) | Empty the template cache. | Empty the template cache. | def reset(self):
"Empty the template cache."
self.template_cache.clear()
self.find_template_cache.clear() | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"template_cache",
".",
"clear",
"(",
")",
"self",
".",
"find_template_cache",
".",
"clear",
"(",
")"
] | [
83,
4
] | [
86,
40
] | python | en | ['en', 'en', 'en'] | True |
DirectedGraph.copy | (self) | Return a shallow copy of this graph.
| Return a shallow copy of this graph.
| def copy(self):
"""Return a shallow copy of this graph.
"""
other = DirectedGraph()
other._vertices = set(self._vertices)
other._forwards = {k: set(v) for k, v in self._forwards.items()}
other._backwards = {k: set(v) for k, v in self._backwards.items()}
return oth... | [
"def",
"copy",
"(",
"self",
")",
":",
"other",
"=",
"DirectedGraph",
"(",
")",
"other",
".",
"_vertices",
"=",
"set",
"(",
"self",
".",
"_vertices",
")",
"other",
".",
"_forwards",
"=",
"{",
"k",
":",
"set",
"(",
"v",
")",
"for",
"k",
",",
"v",
... | [
18,
4
] | [
25,
20
] | python | en | ['en', 'en', 'en'] | True |
DirectedGraph.add | (self, key) | Add a new vertex to the graph.
| Add a new vertex to the graph.
| def add(self, key):
"""Add a new vertex to the graph.
"""
if key in self._vertices:
raise ValueError("vertex exists")
self._vertices.add(key)
self._forwards[key] = set()
self._backwards[key] = set() | [
"def",
"add",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
".",
"_vertices",
":",
"raise",
"ValueError",
"(",
"\"vertex exists\"",
")",
"self",
".",
"_vertices",
".",
"add",
"(",
"key",
")",
"self",
".",
"_forwards",
"[",
"key",
"]",... | [
27,
4
] | [
34,
36
] | python | en | ['en', 'en', 'en'] | True |
DirectedGraph.remove | (self, key) | Remove a vertex from the graph, disconnecting all edges from/to it.
| Remove a vertex from the graph, disconnecting all edges from/to it.
| def remove(self, key):
"""Remove a vertex from the graph, disconnecting all edges from/to it.
"""
self._vertices.remove(key)
for f in self._forwards.pop(key):
self._backwards[f].remove(key)
for t in self._backwards.pop(key):
self._forwards[t].remove(key) | [
"def",
"remove",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"_vertices",
".",
"remove",
"(",
"key",
")",
"for",
"f",
"in",
"self",
".",
"_forwards",
".",
"pop",
"(",
"key",
")",
":",
"self",
".",
"_backwards",
"[",
"f",
"]",
".",
"remove",
... | [
36,
4
] | [
43,
41
] | python | en | ['en', 'en', 'en'] | True |
DirectedGraph.connect | (self, f, t) | Connect two existing vertices.
Nothing happens if the vertices are already connected.
| Connect two existing vertices. | def connect(self, f, t):
"""Connect two existing vertices.
Nothing happens if the vertices are already connected.
"""
if t not in self._vertices:
raise KeyError(t)
self._forwards[f].add(t)
self._backwards[t].add(f) | [
"def",
"connect",
"(",
"self",
",",
"f",
",",
"t",
")",
":",
"if",
"t",
"not",
"in",
"self",
".",
"_vertices",
":",
"raise",
"KeyError",
"(",
"t",
")",
"self",
".",
"_forwards",
"[",
"f",
"]",
".",
"add",
"(",
"t",
")",
"self",
".",
"_backwards... | [
48,
4
] | [
56,
33
] | python | en | ['nl', 'en', 'en'] | True |
collate_fn | (batch) | Collate function to handle X-ray metadata. | Collate function to handle X-ray metadata. | def collate_fn(batch):
"""Collate function to handle X-ray metadata."""
metadata = []
for el in batch:
metadata.append(el["metadata"])
del el["metadata"]
batch = default_collate(batch)
batch["metadata"] = metadata
return batch | [
"def",
"collate_fn",
"(",
"batch",
")",
":",
"metadata",
"=",
"[",
"]",
"for",
"el",
"in",
"batch",
":",
"metadata",
".",
"append",
"(",
"el",
"[",
"\"metadata\"",
"]",
")",
"del",
"el",
"[",
"\"metadata\"",
"]",
"batch",
"=",
"default_collate",
"(",
... | [
9,
0
] | [
20,
16
] | python | en | ['en', 'en', 'en'] | True |
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 https://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_NODE:
... | [
"def",
"getInnerText",
"(",
"node",
")",
":",
"# inspired by https://mail.python.org/pipermail/xml-sig/2005-March/011022.html",
"inner_text",
"=",
"[",
"]",
"for",
"child",
"in",
"node",
".",
"childNodes",
":",
"if",
"child",
".",
"nodeType",
"==",
"child",
".",
"TE... | [
322,
0
] | [
333,
30
] | python | en | ['en', 'en', 'en'] | True |
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",
".",
... | [
25,
4
] | [
31,
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",
"(",
")"
] | [
33,
4
] | [
39,
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': str(obj._meta)}
i... | [
"def",
"start_object",
"(",
"self",
",",
"obj",
")",
":",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"\"_meta\"",
")",
":",
"raise",
"base",
".",
"SerializationError",
"(",
"\"Non-model object (%s) encountered during serialization\"",
"%",
"type",
"(",
"obj",
")",... | [
41,
4
] | [
55,
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\"",
")"
] | [
57,
4
] | [
62,
37
] | python | en | ['en', 'error', 'th'] | False |
Serializer.handle_field | (self, obj, field) |
Handle each field on an object (except for ForeignKeys and
ManyToManyFields).
|
Handle each field on an object (except for ForeignKeys and
ManyToManyFields).
| def handle_field(self, obj, field):
"""
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(),
})
# G... | [
"def",
"handle_field",
"(",
"self",
",",
"obj",
",",
"field",
")",
":",
"self",
".",
"indent",
"(",
"2",
")",
"self",
".",
"xml",
".",
"startElement",
"(",
"'field'",
",",
"{",
"'name'",
":",
"field",
".",
"name",
",",
"'type'",
":",
"field",
".",
... | [
64,
4
] | [
85,
36
] | python | en | ['en', 'error', 'th'] | False |
Serializer.handle_fk_field | (self, obj, field) |
Handle a ForeignKey (they need to be treated slightly
differently from regular fields).
|
Handle a ForeignKey (they need to be treated slightly
differently from regular fields).
| def handle_fk_field(self, obj, field):
"""
Handle a ForeignKey (they need to be treated slightly
differently from regular fields).
"""
self._start_relational_field(field)
related_att = getattr(obj, field.get_attname())
if related_att is not None:
if se... | [
"def",
"handle_fk_field",
"(",
"self",
",",
"obj",
",",
"field",
")",
":",
"self",
".",
"_start_relational_field",
"(",
"field",
")",
"related_att",
"=",
"getattr",
"(",
"obj",
",",
"field",
".",
"get_attname",
"(",
")",
")",
"if",
"related_att",
"is",
"... | [
87,
4
] | [
108,
36
] | python | en | ['en', 'error', 'th'] | False |
Serializer.handle_m2m_field | (self, obj, field) |
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).
|
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):
"""
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.remote_field.through._meta.auto_created:
self._s... | [
"def",
"handle_m2m_field",
"(",
"self",
",",
"obj",
",",
"field",
")",
":",
"if",
"field",
".",
"remote_field",
".",
"through",
".",
"_meta",
".",
"auto_created",
":",
"self",
".",
"_start_relational_field",
"(",
"field",
")",
"if",
"self",
".",
"use_natur... | [
110,
4
] | [
137,
40
] | python | en | ['en', 'error', 'th'] | False |
Serializer._start_relational_field | (self, field) | Output the <field> element for relational fields. | Output the <field> element for relational fields. | def _start_relational_field(self, field):
"""Output the <field> element for relational fields."""
self.indent(2)
self.xml.startElement('field', {
'name': field.name,
'rel': field.remote_field.__class__.__name__,
'to': str(field.remote_field.model._meta),
... | [
"def",
"_start_relational_field",
"(",
"self",
",",
"field",
")",
":",
"self",
".",
"indent",
"(",
"2",
")",
"self",
".",
"xml",
".",
"startElement",
"(",
"'field'",
",",
"{",
"'name'",
":",
"field",
".",
"name",
",",
"'rel'",
":",
"field",
".",
"rem... | [
139,
4
] | [
146,
10
] | python | en | ['en', 'en', 'en'] | True |
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 object.
data... | [
"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
] | [
235,
70
] | python | en | ['en', 'en', 'en'] | True |
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:
model = field.remote_field.mod... | [
"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",
":",
"model",
"=",
... | [
237,
4
] | [
270,
98
] | 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.
"""
model = field.remote_field.model
default_manager = model._default_manager
if hasattr(default_manager, 'get_by_natural_key'):
def m2m_convert(n):
... | [
"def",
"_handle_m2m_field_node",
"(",
"self",
",",
"node",
",",
"field",
")",
":",
"model",
"=",
"field",
".",
"remote_field",
".",
"model",
"default_manager",
"=",
"model",
".",
"_default_manager",
"if",
"hasattr",
"(",
"default_manager",
",",
"'get_by_natural_... | [
272,
4
] | [
302,
25
] | python | en | ['en', 'error', 'th'] | False |
Deserializer._get_model_from_node | (self, node, attr) |
Look up a model from a <object model=...> or a <field rel=... to=...>
node.
|
Look up a model from a <object model=...> or a <field rel=... to=...>
node.
| def _get_model_from_node(self, node, attr):
"""
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> node is m... | [
"def",
"_get_model_from_node",
"(",
"self",
",",
"node",
",",
"attr",
")",
":",
"model_identifier",
"=",
"node",
".",
"getAttribute",
"(",
"attr",
")",
"if",
"not",
"model_identifier",
":",
"raise",
"base",
".",
"DeserializationError",
"(",
"\"<%s> node is missi... | [
304,
4
] | [
319,
52
] | python | en | ['en', 'error', 'th'] | False |
Draw.settransform | (self, offset) | Sets a transformation offset. | Sets a transformation offset. | def settransform(self, offset):
"""Sets a transformation offset."""
(xoffset, yoffset) = offset
self.transform = (1, 0, xoffset, 0, 1, yoffset) | [
"def",
"settransform",
"(",
"self",
",",
"offset",
")",
":",
"(",
"xoffset",
",",
"yoffset",
")",
"=",
"offset",
"self",
".",
"transform",
"=",
"(",
"1",
",",
"0",
",",
"xoffset",
",",
"0",
",",
"1",
",",
"yoffset",
")"
] | [
92,
4
] | [
95,
55
] | python | en | ['en', 'en', 'en'] | True |
Draw.arc | (self, xy, start, end, *options) |
Draws an arc (a portion of a circle outline) between the start and end
angles, inside the given bounding box.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.arc`
|
Draws an arc (a portion of a circle outline) between the start and end
angles, inside the given bounding box. | def arc(self, xy, start, end, *options):
"""
Draws an arc (a portion of a circle outline) between the start and end
angles, inside the given bounding box.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.arc`
"""
self.render("arc", xy, start, end, *options) | [
"def",
"arc",
"(",
"self",
",",
"xy",
",",
"start",
",",
"end",
",",
"*",
"options",
")",
":",
"self",
".",
"render",
"(",
"\"arc\"",
",",
"xy",
",",
"start",
",",
"end",
",",
"*",
"options",
")"
] | [
97,
4
] | [
104,
52
] | python | en | ['en', 'error', 'th'] | False |
Draw.chord | (self, xy, start, end, *options) |
Same as :py:meth:`~PIL.ImageDraw2.Draw.arc`, but connects the end points
with a straight line.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.chord`
|
Same as :py:meth:`~PIL.ImageDraw2.Draw.arc`, but connects the end points
with a straight line. | def chord(self, xy, start, end, *options):
"""
Same as :py:meth:`~PIL.ImageDraw2.Draw.arc`, but connects the end points
with a straight line.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.chord`
"""
self.render("chord", xy, start, end, *options) | [
"def",
"chord",
"(",
"self",
",",
"xy",
",",
"start",
",",
"end",
",",
"*",
"options",
")",
":",
"self",
".",
"render",
"(",
"\"chord\"",
",",
"xy",
",",
"start",
",",
"end",
",",
"*",
"options",
")"
] | [
106,
4
] | [
113,
54
] | python | en | ['en', 'error', 'th'] | False |
Draw.ellipse | (self, xy, *options) |
Draws an ellipse inside the given bounding box.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.ellipse`
|
Draws an ellipse inside the given bounding box. | def ellipse(self, xy, *options):
"""
Draws an ellipse inside the given bounding box.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.ellipse`
"""
self.render("ellipse", xy, *options) | [
"def",
"ellipse",
"(",
"self",
",",
"xy",
",",
"*",
"options",
")",
":",
"self",
".",
"render",
"(",
"\"ellipse\"",
",",
"xy",
",",
"*",
"options",
")"
] | [
115,
4
] | [
121,
44
] | python | en | ['en', 'error', 'th'] | False |
Draw.line | (self, xy, *options) |
Draws a line between the coordinates in the ``xy`` list.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.line`
|
Draws a line between the coordinates in the ``xy`` list. | def line(self, xy, *options):
"""
Draws a line between the coordinates in the ``xy`` list.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.line`
"""
self.render("line", xy, *options) | [
"def",
"line",
"(",
"self",
",",
"xy",
",",
"*",
"options",
")",
":",
"self",
".",
"render",
"(",
"\"line\"",
",",
"xy",
",",
"*",
"options",
")"
] | [
123,
4
] | [
129,
41
] | 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.