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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
normalize | (pattern) | r"""
Given a reg-exp pattern, normalize it to an iterable of forms that
suffice for reverse matching. This does the following:
(1) For any repeating sections, keeps the minimum number of occurrences
permitted (this means zero for optional groups).
(2) If an optional group includes parameters, i... | r"""
Given a reg-exp pattern, normalize it to an iterable of forms that
suffice for reverse matching. This does the following: | def normalize(pattern):
r"""
Given a reg-exp pattern, normalize it to an iterable of forms that
suffice for reverse matching. This does the following:
(1) For any repeating sections, keeps the minimum number of occurrences
permitted (this means zero for optional groups).
(2) If an optional ... | [
"def",
"normalize",
"(",
"pattern",
")",
":",
"# Do a linear scan to work out the special features of this pattern. The",
"# idea is that we scan once here and collect all the information we need to",
"# make future decisions.",
"result",
"=",
"[",
"]",
"non_capturing_groups",
"=",
"["... | [
36,
0
] | [
185,
45
] | python | cy | ['en', 'cy', 'hi'] | False |
next_char | (input_iter) | r"""
An iterator that yields the next character from "pattern_iter", respecting
escape sequences. An escaped character is replaced by a representative of
its class (e.g. \w -> "x"). If the escaped character is one that is
skipped, it is not returned (the next character is returned instead).
Yield t... | r"""
An iterator that yields the next character from "pattern_iter", respecting
escape sequences. An escaped character is replaced by a representative of
its class (e.g. \w -> "x"). If the escaped character is one that is
skipped, it is not returned (the next character is returned instead). | def next_char(input_iter):
r"""
An iterator that yields the next character from "pattern_iter", respecting
escape sequences. An escaped character is replaced by a representative of
its class (e.g. \w -> "x"). If the escaped character is one that is
skipped, it is not returned (the next character is ... | [
"def",
"next_char",
"(",
"input_iter",
")",
":",
"for",
"ch",
"in",
"input_iter",
":",
"if",
"ch",
"!=",
"'\\\\'",
":",
"yield",
"ch",
",",
"False",
"continue",
"ch",
"=",
"next",
"(",
"input_iter",
")",
"representative",
"=",
"ESCAPE_MAPPINGS",
".",
"ge... | [
188,
0
] | [
206,
34
] | python | cy | ['en', 'cy', 'hi'] | False |
walk_to_end | (ch, input_iter) |
The iterator is currently inside a capturing group. Walk to the close of
this group, skipping over any nested groups and handling escaped
parentheses correctly.
|
The iterator is currently inside a capturing group. Walk to the close of
this group, skipping over any nested groups and handling escaped
parentheses correctly.
| def walk_to_end(ch, input_iter):
"""
The iterator is currently inside a capturing group. Walk to the close of
this group, skipping over any nested groups and handling escaped
parentheses correctly.
"""
if ch == '(':
nesting = 1
else:
nesting = 0
for ch, escaped in input_i... | [
"def",
"walk_to_end",
"(",
"ch",
",",
"input_iter",
")",
":",
"if",
"ch",
"==",
"'('",
":",
"nesting",
"=",
"1",
"else",
":",
"nesting",
"=",
"0",
"for",
"ch",
",",
"escaped",
"in",
"input_iter",
":",
"if",
"escaped",
":",
"continue",
"elif",
"ch",
... | [
209,
0
] | [
227,
24
] | python | en | ['en', 'error', 'th'] | False |
get_quantifier | (ch, input_iter) |
Parse a quantifier from the input, where "ch" is the first character in the
quantifier.
Return the minimum number of occurrences permitted by the quantifier and
either None or the next character from the input_iter if the next character
is not part of the quantifier.
|
Parse a quantifier from the input, where "ch" is the first character in the
quantifier. | def get_quantifier(ch, input_iter):
"""
Parse a quantifier from the input, where "ch" is the first character in the
quantifier.
Return the minimum number of occurrences permitted by the quantifier and
either None or the next character from the input_iter if the next character
is not part of the... | [
"def",
"get_quantifier",
"(",
"ch",
",",
"input_iter",
")",
":",
"if",
"ch",
"in",
"'*?+'",
":",
"try",
":",
"ch2",
",",
"escaped",
"=",
"next",
"(",
"input_iter",
")",
"except",
"StopIteration",
":",
"ch2",
"=",
"None",
"if",
"ch2",
"==",
"'?'",
":"... | [
230,
0
] | [
264,
29
] | python | en | ['en', 'error', 'th'] | False |
contains | (source, inst) |
Return True if the "source" contains an instance of "inst". False,
otherwise.
|
Return True if the "source" contains an instance of "inst". False,
otherwise.
| def contains(source, inst):
"""
Return True if the "source" contains an instance of "inst". False,
otherwise.
"""
if isinstance(source, inst):
return True
if isinstance(source, NonCapture):
for elt in source:
if contains(elt, inst):
return True
ret... | [
"def",
"contains",
"(",
"source",
",",
"inst",
")",
":",
"if",
"isinstance",
"(",
"source",
",",
"inst",
")",
":",
"return",
"True",
"if",
"isinstance",
"(",
"source",
",",
"NonCapture",
")",
":",
"for",
"elt",
"in",
"source",
":",
"if",
"contains",
... | [
267,
0
] | [
278,
16
] | python | en | ['en', 'error', 'th'] | False |
flatten_result | (source) |
Turn the given source sequence into a list of reg-exp possibilities and
their arguments. Return a list of strings and a list of argument lists.
Each of the two lists will be of the same length.
|
Turn the given source sequence into a list of reg-exp possibilities and
their arguments. Return a list of strings and a list of argument lists.
Each of the two lists will be of the same length.
| def flatten_result(source):
"""
Turn the given source sequence into a list of reg-exp possibilities and
their arguments. Return a list of strings and a list of argument lists.
Each of the two lists will be of the same length.
"""
if source is None:
return [''], [[]]
if isinstance(sou... | [
"def",
"flatten_result",
"(",
"source",
")",
":",
"if",
"source",
"is",
"None",
":",
"return",
"[",
"''",
"]",
",",
"[",
"[",
"]",
"]",
"if",
"isinstance",
"(",
"source",
",",
"Group",
")",
":",
"if",
"source",
"[",
"1",
"]",
"is",
"None",
":",
... | [
281,
0
] | [
332,
30
] | python | en | ['en', 'error', 'th'] | False |
LookupTests.test_regex_null | (self) |
Ensure that a regex lookup does not fail on null/None values
|
Ensure that a regex lookup does not fail on null/None values
| def test_regex_null(self):
"""
Ensure that a regex lookup does not fail on null/None values
"""
Season.objects.create(year=2012, gt=None)
self.assertQuerysetEqual(Season.objects.filter(gt__regex=r'^$'), []) | [
"def",
"test_regex_null",
"(",
"self",
")",
":",
"Season",
".",
"objects",
".",
"create",
"(",
"year",
"=",
"2012",
",",
"gt",
"=",
"None",
")",
"self",
".",
"assertQuerysetEqual",
"(",
"Season",
".",
"objects",
".",
"filter",
"(",
"gt__regex",
"=",
"r... | [
616,
4
] | [
621,
76
] | python | en | ['en', 'error', 'th'] | False |
LookupTests.test_regex_non_string | (self) |
Ensure that a regex lookup does not fail on non-string fields
|
Ensure that a regex lookup does not fail on non-string fields
| def test_regex_non_string(self):
"""
Ensure that a regex lookup does not fail on non-string fields
"""
Season.objects.create(year=2013, gt=444)
self.assertQuerysetEqual(Season.objects.filter(gt__regex=r'^444$'),
['<Season: 2013>']) | [
"def",
"test_regex_non_string",
"(",
"self",
")",
":",
"Season",
".",
"objects",
".",
"create",
"(",
"year",
"=",
"2013",
",",
"gt",
"=",
"444",
")",
"self",
".",
"assertQuerysetEqual",
"(",
"Season",
".",
"objects",
".",
"filter",
"(",
"gt__regex",
"=",... | [
623,
4
] | [
629,
31
] | python | en | ['en', 'error', 'th'] | False |
LookupTests.test_regex_non_ascii | (self) |
Ensure that a regex lookup does not trip on non-ASCII characters.
|
Ensure that a regex lookup does not trip on non-ASCII characters.
| def test_regex_non_ascii(self):
"""
Ensure that a regex lookup does not trip on non-ASCII characters.
"""
Player.objects.create(name='\u2660')
Player.objects.get(name__regex='\u2660') | [
"def",
"test_regex_non_ascii",
"(",
"self",
")",
":",
"Player",
".",
"objects",
".",
"create",
"(",
"name",
"=",
"'\\u2660'",
")",
"Player",
".",
"objects",
".",
"get",
"(",
"name__regex",
"=",
"'\\u2660'",
")"
] | [
631,
4
] | [
636,
48
] | python | en | ['en', 'error', 'th'] | False |
LookupTests.test_nonfield_lookups | (self) |
Ensure that a lookup query containing non-fields raises the proper
exception.
|
Ensure that a lookup query containing non-fields raises the proper
exception.
| def test_nonfield_lookups(self):
"""
Ensure that a lookup query containing non-fields raises the proper
exception.
"""
with self.assertRaises(FieldError):
Article.objects.filter(headline__blahblah=99)
with self.assertRaises(FieldError):
Article.obj... | [
"def",
"test_nonfield_lookups",
"(",
"self",
")",
":",
"with",
"self",
".",
"assertRaises",
"(",
"FieldError",
")",
":",
"Article",
".",
"objects",
".",
"filter",
"(",
"headline__blahblah",
"=",
"99",
")",
"with",
"self",
".",
"assertRaises",
"(",
"FieldErro... | [
638,
4
] | [
648,
47
] | python | en | ['en', 'error', 'th'] | False |
LookupTests.test_lookup_collision | (self) |
Ensure that genuine field names don't collide with built-in lookup
types ('year', 'gt', 'range', 'in' etc.).
Refs #11670.
|
Ensure that genuine field names don't collide with built-in lookup
types ('year', 'gt', 'range', 'in' etc.).
Refs #11670.
| def test_lookup_collision(self):
"""
Ensure that genuine field names don't collide with built-in lookup
types ('year', 'gt', 'range', 'in' etc.).
Refs #11670.
"""
# Here we're using 'gt' as a code number for the year, e.g. 111=>2009.
season_2009 = Season.objects.... | [
"def",
"test_lookup_collision",
"(",
"self",
")",
":",
"# Here we're using 'gt' as a code number for the year, e.g. 111=>2009.",
"season_2009",
"=",
"Season",
".",
"objects",
".",
"create",
"(",
"year",
"=",
"2009",
",",
"gt",
"=",
"111",
")",
"season_2009",
".",
"g... | [
650,
4
] | [
713,
96
] | python | en | ['en', 'error', 'th'] | False |
Command.run_from_argv | (self, argv) |
Pre-parse the command line to extract the value of the --testrunner
option. This allows a test runner to define additional command line
arguments.
|
Pre-parse the command line to extract the value of the --testrunner
option. This allows a test runner to define additional command line
arguments.
| def run_from_argv(self, argv):
"""
Pre-parse the command line to extract the value of the --testrunner
option. This allows a test runner to define additional command line
arguments.
"""
option = '--testrunner='
for arg in argv[2:]:
if arg.startswith(op... | [
"def",
"run_from_argv",
"(",
"self",
",",
"argv",
")",
":",
"option",
"=",
"'--testrunner='",
"for",
"arg",
"in",
"argv",
"[",
"2",
":",
"]",
":",
"if",
"arg",
".",
"startswith",
"(",
"option",
")",
":",
"self",
".",
"test_runner",
"=",
"arg",
"[",
... | [
18,
4
] | [
29,
48
] | python | en | ['en', 'error', 'th'] | False |
ModelPickleTestCase.test_missing_django_version_unpickling | (self) |
#21430 -- Verifies a warning is raised for models that are
unpickled without a Django version
|
#21430 -- Verifies a warning is raised for models that are
unpickled without a Django version
| def test_missing_django_version_unpickling(self):
"""
#21430 -- Verifies a warning is raised for models that are
unpickled without a Django version
"""
class MissingDjangoVersion(models.Model):
title = models.CharField(max_length=10)
def __reduce__(self):... | [
"def",
"test_missing_django_version_unpickling",
"(",
"self",
")",
":",
"class",
"MissingDjangoVersion",
"(",
"models",
".",
"Model",
")",
":",
"title",
"=",
"models",
".",
"CharField",
"(",
"max_length",
"=",
"10",
")",
"def",
"__reduce__",
"(",
"self",
")",
... | [
10,
4
] | [
29,
76
] | python | en | ['en', 'error', 'th'] | False |
ModelPickleTestCase.test_unsupported_unpickle | (self) |
#21430 -- Verifies a warning is raised for models that are
unpickled with a different Django version than the current
|
#21430 -- Verifies a warning is raised for models that are
unpickled with a different Django version than the current
| def test_unsupported_unpickle(self):
"""
#21430 -- Verifies a warning is raised for models that are
unpickled with a different Django version than the current
"""
class DifferentDjangoVersion(models.Model):
title = models.CharField(max_length=10)
def __re... | [
"def",
"test_unsupported_unpickle",
"(",
"self",
")",
":",
"class",
"DifferentDjangoVersion",
"(",
"models",
".",
"Model",
")",
":",
"title",
"=",
"models",
".",
"CharField",
"(",
"max_length",
"=",
"10",
")",
"def",
"__reduce__",
"(",
"self",
")",
":",
"r... | [
31,
4
] | [
52,
73
] | python | en | ['en', 'error', 'th'] | False |
serve_file_url_backend | (
request: HttpRequest, user_profile: UserProfile, realm_id_str: str, filename: str
) |
We should return a signed, short-lived URL
that the client can use for native mobile download, rather than serving a redirect.
|
We should return a signed, short-lived URL
that the client can use for native mobile download, rather than serving a redirect.
| def serve_file_url_backend(
request: HttpRequest, user_profile: UserProfile, realm_id_str: str, filename: str
) -> HttpResponse:
"""
We should return a signed, short-lived URL
that the client can use for native mobile download, rather than serving a redirect.
"""
return serve_file(request, user... | [
"def",
"serve_file_url_backend",
"(",
"request",
":",
"HttpRequest",
",",
"user_profile",
":",
"UserProfile",
",",
"realm_id_str",
":",
"str",
",",
"filename",
":",
"str",
")",
"->",
"HttpResponse",
":",
"return",
"serve_file",
"(",
"request",
",",
"user_profile... | [
72,
0
] | [
80,
83
] | python | en | ['en', 'error', 'th'] | False |
_multi_decorate | (decorators, method) |
Decorate `method` with one or more function decorators. `decorators` can be
a single decorator or an iterable of decorators.
|
Decorate `method` with one or more function decorators. `decorators` can be
a single decorator or an iterable of decorators.
| def _multi_decorate(decorators, method):
"""
Decorate `method` with one or more function decorators. `decorators` can be
a single decorator or an iterable of decorators.
"""
if hasattr(decorators, '__iter__'):
# Apply a list/tuple of decorators if 'decorators' is one. Decorator
# fun... | [
"def",
"_multi_decorate",
"(",
"decorators",
",",
"method",
")",
":",
"if",
"hasattr",
"(",
"decorators",
",",
"'__iter__'",
")",
":",
"# Apply a list/tuple of decorators if 'decorators' is one. Decorator",
"# functions are applied so that the call order is the same as the",
"# o... | [
21,
0
] | [
49,
19
] | python | en | ['en', 'error', 'th'] | False |
method_decorator | (decorator, name='') |
Convert a function decorator into a method decorator
|
Convert a function decorator into a method decorator
| def method_decorator(decorator, name=''):
"""
Convert a function decorator into a method decorator
"""
# 'obj' can be a class or a function. If 'obj' is a function at the time it
# is passed to _dec, it will eventually be a method of the class it is
# defined on. If 'obj' is a class, the 'name'... | [
"def",
"method_decorator",
"(",
"decorator",
",",
"name",
"=",
"''",
")",
":",
"# 'obj' can be a class or a function. If 'obj' is a function at the time it",
"# is passed to _dec, it will eventually be a method of the class it is",
"# defined on. If 'obj' is a class, the 'name' is required ... | [
52,
0
] | [
85,
15
] | python | en | ['en', 'error', 'th'] | False |
decorator_from_middleware_with_args | (middleware_class) |
Like decorator_from_middleware, but return a function
that accepts the arguments to be passed to the middleware_class.
Use like::
cache_page = decorator_from_middleware_with_args(CacheMiddleware)
# ...
@cache_page(3600)
def my_view(request):
# ...
|
Like decorator_from_middleware, but return a function
that accepts the arguments to be passed to the middleware_class.
Use like:: | def decorator_from_middleware_with_args(middleware_class):
"""
Like decorator_from_middleware, but return a function
that accepts the arguments to be passed to the middleware_class.
Use like::
cache_page = decorator_from_middleware_with_args(CacheMiddleware)
# ...
@cache_pag... | [
"def",
"decorator_from_middleware_with_args",
"(",
"middleware_class",
")",
":",
"return",
"make_middleware_decorator",
"(",
"middleware_class",
")"
] | [
88,
0
] | [
101,
54
] | python | en | ['en', 'error', 'th'] | False |
decorator_from_middleware | (middleware_class) |
Given a middleware class (not an instance), return a view decorator. This
lets you use middleware functionality on a per-view basis. The middleware
is created with no params passed.
|
Given a middleware class (not an instance), return a view decorator. This
lets you use middleware functionality on a per-view basis. The middleware
is created with no params passed.
| def decorator_from_middleware(middleware_class):
"""
Given a middleware class (not an instance), return a view decorator. This
lets you use middleware functionality on a per-view basis. The middleware
is created with no params passed.
"""
return make_middleware_decorator(middleware_class)() | [
"def",
"decorator_from_middleware",
"(",
"middleware_class",
")",
":",
"return",
"make_middleware_decorator",
"(",
"middleware_class",
")",
"(",
")"
] | [
104,
0
] | [
110,
56
] | python | en | ['en', 'error', 'th'] | False |
select_related_descend | (field, restricted, requested, load_fields, reverse=False) |
Return True if this field should be used to descend deeper for
select_related() purposes. Used by both the query construction code
(sql.query.fill_related_selections()) and the model instance creation code
(query.get_klass_info()).
Arguments:
* field - the field to be checked
* restricte... |
Return True if this field should be used to descend deeper for
select_related() purposes. Used by both the query construction code
(sql.query.fill_related_selections()) and the model instance creation code
(query.get_klass_info()). | def select_related_descend(field, restricted, requested, load_fields, reverse=False):
"""
Return True if this field should be used to descend deeper for
select_related() purposes. Used by both the query construction code
(sql.query.fill_related_selections()) and the model instance creation code
(que... | [
"def",
"select_related_descend",
"(",
"field",
",",
"restricted",
",",
"requested",
",",
"load_fields",
",",
"reverse",
"=",
"False",
")",
":",
"if",
"not",
"field",
".",
"remote_field",
":",
"return",
"False",
"if",
"field",
".",
"remote_field",
".",
"paren... | [
223,
0
] | [
256,
15
] | python | en | ['en', 'error', 'th'] | False |
refs_expression | (lookup_parts, annotations) |
Check if the lookup_parts contains references to the given annotations set.
Because the LOOKUP_SEP is contained in the default annotation names, check
each prefix of the lookup_parts for a match.
|
Check if the lookup_parts contains references to the given annotations set.
Because the LOOKUP_SEP is contained in the default annotation names, check
each prefix of the lookup_parts for a match.
| def refs_expression(lookup_parts, annotations):
"""
Check if the lookup_parts contains references to the given annotations set.
Because the LOOKUP_SEP is contained in the default annotation names, check
each prefix of the lookup_parts for a match.
"""
for n in range(1, len(lookup_parts) + 1):
... | [
"def",
"refs_expression",
"(",
"lookup_parts",
",",
"annotations",
")",
":",
"for",
"n",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"lookup_parts",
")",
"+",
"1",
")",
":",
"level_n_lookup",
"=",
"LOOKUP_SEP",
".",
"join",
"(",
"lookup_parts",
"[",
"0",
... | [
259,
0
] | [
269,
20
] | python | en | ['en', 'error', 'th'] | False |
check_rel_lookup_compatibility | (model, target_opts, field) |
Check that self.model is compatible with target_opts. Compatibility
is OK if:
1) model and opts match (where proxy inheritance is removed)
2) model is parent of opts' model or the other way around
|
Check that self.model is compatible with target_opts. Compatibility
is OK if:
1) model and opts match (where proxy inheritance is removed)
2) model is parent of opts' model or the other way around
| def check_rel_lookup_compatibility(model, target_opts, field):
"""
Check that self.model is compatible with target_opts. Compatibility
is OK if:
1) model and opts match (where proxy inheritance is removed)
2) model is parent of opts' model or the other way around
"""
def check(opts):
... | [
"def",
"check_rel_lookup_compatibility",
"(",
"model",
",",
"target_opts",
",",
"field",
")",
":",
"def",
"check",
"(",
"opts",
")",
":",
"return",
"(",
"model",
".",
"_meta",
".",
"concrete_model",
"==",
"opts",
".",
"concrete_model",
"or",
"opts",
".",
"... | [
272,
0
] | [
297,
5
] | python | en | ['en', 'error', 'th'] | False |
DeferredAttribute.__get__ | (self, instance, cls=None) |
Retrieve and caches the value from the datastore on the first lookup.
Return the cached value.
|
Retrieve and caches the value from the datastore on the first lookup.
Return the cached value.
| def __get__(self, instance, cls=None):
"""
Retrieve and caches the value from the datastore on the first lookup.
Return the cached value.
"""
if instance is None:
return self
data = instance.__dict__
field_name = self.field.attname
if data.get(... | [
"def",
"__get__",
"(",
"self",
",",
"instance",
",",
"cls",
"=",
"None",
")",
":",
"if",
"instance",
"is",
"None",
":",
"return",
"self",
"data",
"=",
"instance",
".",
"__dict__",
"field_name",
"=",
"self",
".",
"field",
".",
"attname",
"if",
"data",
... | [
124,
4
] | [
141,
31
] | python | en | ['en', 'error', 'th'] | False |
DeferredAttribute._check_parent_chain | (self, instance) |
Check if the field value can be fetched from a parent field already
loaded in the instance. This can be done if the to-be fetched
field is a primary key field.
|
Check if the field value can be fetched from a parent field already
loaded in the instance. This can be done if the to-be fetched
field is a primary key field.
| def _check_parent_chain(self, instance):
"""
Check if the field value can be fetched from a parent field already
loaded in the instance. This can be done if the to-be fetched
field is a primary key field.
"""
opts = instance._meta
link_field = opts.get_ancestor_li... | [
"def",
"_check_parent_chain",
"(",
"self",
",",
"instance",
")",
":",
"opts",
"=",
"instance",
".",
"_meta",
"link_field",
"=",
"opts",
".",
"get_ancestor_link",
"(",
"self",
".",
"field",
".",
"model",
")",
"if",
"self",
".",
"field",
".",
"primary_key",
... | [
143,
4
] | [
153,
19
] | python | en | ['en', 'error', 'th'] | False |
RegisterLookupMixin.merge_dicts | (dicts) |
Merge dicts in reverse to preference the order of the original list. e.g.,
merge_dicts([a, b]) will preference the keys in 'a' over those in 'b'.
|
Merge dicts in reverse to preference the order of the original list. e.g.,
merge_dicts([a, b]) will preference the keys in 'a' over those in 'b'.
| def merge_dicts(dicts):
"""
Merge dicts in reverse to preference the order of the original list. e.g.,
merge_dicts([a, b]) will preference the keys in 'a' over those in 'b'.
"""
merged = {}
for d in reversed(dicts):
merged.update(d)
return merged | [
"def",
"merge_dicts",
"(",
"dicts",
")",
":",
"merged",
"=",
"{",
"}",
"for",
"d",
"in",
"reversed",
"(",
"dicts",
")",
":",
"merged",
".",
"update",
"(",
"d",
")",
"return",
"merged"
] | [
187,
4
] | [
195,
21
] | python | en | ['en', 'error', 'th'] | False |
RegisterLookupMixin._unregister_lookup | (cls, lookup, lookup_name=None) |
Remove given lookup from cls lookups. For use in tests only as it's
not thread-safe.
|
Remove given lookup from cls lookups. For use in tests only as it's
not thread-safe.
| def _unregister_lookup(cls, lookup, lookup_name=None):
"""
Remove given lookup from cls lookups. For use in tests only as it's
not thread-safe.
"""
if lookup_name is None:
lookup_name = lookup.lookup_name
del cls.class_lookups[lookup_name] | [
"def",
"_unregister_lookup",
"(",
"cls",
",",
"lookup",
",",
"lookup_name",
"=",
"None",
")",
":",
"if",
"lookup_name",
"is",
"None",
":",
"lookup_name",
"=",
"lookup",
".",
"lookup_name",
"del",
"cls",
".",
"class_lookups",
"[",
"lookup_name",
"]"
] | [
213,
4
] | [
220,
42
] | python | en | ['en', 'error', 'th'] | False |
FilteredRelation.resolve_expression | (self, *args, **kwargs) |
QuerySet.annotate() only accepts expression-like arguments
(with a resolve_expression() method).
|
QuerySet.annotate() only accepts expression-like arguments
(with a resolve_expression() method).
| def resolve_expression(self, *args, **kwargs):
"""
QuerySet.annotate() only accepts expression-like arguments
(with a resolve_expression() method).
"""
raise NotImplementedError('FilteredRelation.resolve_expression() is unused.') | [
"def",
"resolve_expression",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"NotImplementedError",
"(",
"'FilteredRelation.resolve_expression() is unused.'",
")"
] | [
327,
4
] | [
332,
85
] | python | en | ['en', 'error', 'th'] | False |
set_language | (request) |
Redirect to a given url while setting the chosen language in the
session or cookie. The url and the language code need to be
specified in the request parameters.
Since this view changes how the user will see the rest of the site, it must
only be accessed as a POST request. If called as a GET reque... |
Redirect to a given url while setting the chosen language in the
session or cookie. The url and the language code need to be
specified in the request parameters. | def set_language(request):
"""
Redirect to a given url while setting the chosen language in the
session or cookie. The url and the language code need to be
specified in the request parameters.
Since this view changes how the user will see the rest of the site, it must
only be accessed as a POST... | [
"def",
"set_language",
"(",
"request",
")",
":",
"next",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"'next'",
",",
"request",
".",
"GET",
".",
"get",
"(",
"'next'",
")",
")",
"if",
"not",
"is_safe_url",
"(",
"url",
"=",
"next",
",",
"host",
"=",... | [
17,
0
] | [
44,
19
] | python | en | ['en', 'error', 'th'] | False |
get_formats | () |
Returns all formats strings required for i18n to work
|
Returns all formats strings required for i18n to work
| def get_formats():
"""
Returns all formats strings required for i18n to work
"""
FORMAT_SETTINGS = (
'DATE_FORMAT', 'DATETIME_FORMAT', 'TIME_FORMAT',
'YEAR_MONTH_FORMAT', 'MONTH_DAY_FORMAT', 'SHORT_DATE_FORMAT',
'SHORT_DATETIME_FORMAT', 'FIRST_DAY_OF_WEEK', 'DECIMAL_SEPARATOR',
... | [
"def",
"get_formats",
"(",
")",
":",
"FORMAT_SETTINGS",
"=",
"(",
"'DATE_FORMAT'",
",",
"'DATETIME_FORMAT'",
",",
"'TIME_FORMAT'",
",",
"'YEAR_MONTH_FORMAT'",
",",
"'MONTH_DAY_FORMAT'",
",",
"'SHORT_DATE_FORMAT'",
",",
"'SHORT_DATETIME_FORMAT'",
",",
"'FIRST_DAY_OF_WEEK'"... | [
47,
0
] | [
68,
18
] | python | en | ['en', 'error', 'th'] | False |
null_javascript_catalog | (request, domain=None, packages=None) |
Returns "identity" versions of the JavaScript i18n functions -- i.e.,
versions that don't actually do anything.
|
Returns "identity" versions of the JavaScript i18n functions -- i.e.,
versions that don't actually do anything.
| def null_javascript_catalog(request, domain=None, packages=None):
"""
Returns "identity" versions of the JavaScript i18n functions -- i.e.,
versions that don't actually do anything.
"""
return render_javascript_catalog() | [
"def",
"null_javascript_catalog",
"(",
"request",
",",
"domain",
"=",
"None",
",",
"packages",
"=",
"None",
")",
":",
"return",
"render_javascript_catalog",
"(",
")"
] | [
280,
0
] | [
285,
38
] | python | en | ['en', 'error', 'th'] | False |
javascript_catalog | (request, domain='djangojs', packages=None) |
Returns the selected language catalog as a javascript library.
Receives the list of packages to check for translations in the
packages parameter either from an infodict or as a +-delimited
string from the request. Default is 'django.conf'.
Additionally you can override the gettext domain for this... |
Returns the selected language catalog as a javascript library. | def javascript_catalog(request, domain='djangojs', packages=None):
"""
Returns the selected language catalog as a javascript library.
Receives the list of packages to check for translations in the
packages parameter either from an infodict or as a +-delimited
string from the request. Default is 'dj... | [
"def",
"javascript_catalog",
"(",
"request",
",",
"domain",
"=",
"'djangojs'",
",",
"packages",
"=",
"None",
")",
":",
"locale",
"=",
"to_locale",
"(",
"get_language",
"(",
")",
")",
"if",
"request",
".",
"GET",
"and",
"'language'",
"in",
"request",
".",
... | [
288,
0
] | [
313,
53
] | python | en | ['en', 'error', 'th'] | False |
CaseInsensitiveDict.lower_items | (self) | Like iteritems(), but with all lowercase keys. | Like iteritems(), but with all lowercase keys. | def lower_items(self):
"""Like iteritems(), but with all lowercase keys."""
return (
(lowerkey, keyval[1])
for (lowerkey, keyval)
in self._store.items()
) | [
"def",
"lower_items",
"(",
"self",
")",
":",
"return",
"(",
"(",
"lowerkey",
",",
"keyval",
"[",
"1",
"]",
")",
"for",
"(",
"lowerkey",
",",
"keyval",
")",
"in",
"self",
".",
"_store",
".",
"items",
"(",
")",
")"
] | [
64,
4
] | [
70,
9
] | python | en | ['en', 'en', 'en'] | True |
nagios_from_file | (results_file: str) | Returns a nagios-appropriate string and return code obtained by
parsing the desired file on disk. The file on disk should be of format
%s|%s % (timestamp, nagios_string)
This file is created by various nagios checking cron jobs such as
check-rabbitmq-queues and check-rabbitmq-consumers | Returns a nagios-appropriate string and return code obtained by
parsing the desired file on disk. The file on disk should be of format | def nagios_from_file(results_file: str) -> Tuple[int, str]:
"""Returns a nagios-appropriate string and return code obtained by
parsing the desired file on disk. The file on disk should be of format
%s|%s % (timestamp, nagios_string)
This file is created by various nagios checking cron jobs such as
... | [
"def",
"nagios_from_file",
"(",
"results_file",
":",
"str",
")",
"->",
"Tuple",
"[",
"int",
",",
"str",
"]",
":",
"try",
":",
"with",
"open",
"(",
"results_file",
")",
"as",
"f",
":",
"data",
"=",
"f",
".",
"read",
"(",
")",
".",
"strip",
"(",
")... | [
4,
0
] | [
40,
36
] | python | en | ['en', 'en', 'en'] | True |
GeometryProxy.__init__ | (self, klass, field) |
Proxy initializes on the given Geometry class (not an instance) and
the GeometryField.
|
Proxy initializes on the given Geometry class (not an instance) and
the GeometryField.
| def __init__(self, klass, field):
"""
Proxy initializes on the given Geometry class (not an instance) and
the GeometryField.
"""
self._field = field
self._klass = klass | [
"def",
"__init__",
"(",
"self",
",",
"klass",
",",
"field",
")",
":",
"self",
".",
"_field",
"=",
"field",
"self",
".",
"_klass",
"=",
"klass"
] | [
11,
4
] | [
17,
27
] | python | en | ['en', 'error', 'th'] | False |
GeometryProxy.__get__ | (self, obj, type=None) |
This accessor retrieves the geometry, initializing it using the geometry
class specified during initialization and the HEXEWKB value of the field.
Currently, only GEOS or OGR geometries are supported.
|
This accessor retrieves the geometry, initializing it using the geometry
class specified during initialization and the HEXEWKB value of the field.
Currently, only GEOS or OGR geometries are supported.
| def __get__(self, obj, type=None):
"""
This accessor retrieves the geometry, initializing it using the geometry
class specified during initialization and the HEXEWKB value of the field.
Currently, only GEOS or OGR geometries are supported.
"""
if obj is None:
... | [
"def",
"__get__",
"(",
"self",
",",
"obj",
",",
"type",
"=",
"None",
")",
":",
"if",
"obj",
"is",
"None",
":",
"# Accessed on a class, not an instance",
"return",
"self",
"# Getting the value of the field.",
"geom_value",
"=",
"obj",
".",
"__dict__",
"[",
"self"... | [
19,
4
] | [
41,
19
] | python | en | ['en', 'error', 'th'] | False |
GeometryProxy.__set__ | (self, obj, value) |
This accessor sets the proxied geometry with the geometry class
specified during initialization. Values of None, HEXEWKB, or WKT may
be used to set the geometry as well.
|
This accessor sets the proxied geometry with the geometry class
specified during initialization. Values of None, HEXEWKB, or WKT may
be used to set the geometry as well.
| def __set__(self, obj, value):
"""
This accessor sets the proxied geometry with the geometry class
specified during initialization. Values of None, HEXEWKB, or WKT may
be used to set the geometry as well.
"""
# The OGC Geometry type of the field.
gtype = self._fi... | [
"def",
"__set__",
"(",
"self",
",",
"obj",
",",
"value",
")",
":",
"# The OGC Geometry type of the field.",
"gtype",
"=",
"self",
".",
"_field",
".",
"geom_type",
"# The geometry type must match that of the field -- unless the",
"# general GeometryField is used.",
"if",
"is... | [
43,
4
] | [
67,
20
] | python | en | ['en', 'error', 'th'] | False |
make_context | (context, request=None, **kwargs) |
Create a suitable Context from a plain dict and optionally an HttpRequest.
|
Create a suitable Context from a plain dict and optionally an HttpRequest.
| def make_context(context, request=None, **kwargs):
"""
Create a suitable Context from a plain dict and optionally an HttpRequest.
"""
if context is not None and not isinstance(context, dict):
raise TypeError('context must be a dict rather than %s.' % context.__class__.__name__)
if request is... | [
"def",
"make_context",
"(",
"context",
",",
"request",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"context",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"context",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"'context must be a... | [
264,
0
] | [
279,
18
] | python | en | ['en', 'error', 'th'] | False |
BaseContext.__setitem__ | (self, key, value) | Set a variable in the current context | Set a variable in the current context | def __setitem__(self, key, value):
"Set a variable in the current context"
self.dicts[-1][key] = value | [
"def",
"__setitem__",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"dicts",
"[",
"-",
"1",
"]",
"[",
"key",
"]",
"=",
"value"
] | [
61,
4
] | [
63,
35
] | python | en | ['en', 'en', 'en'] | True |
BaseContext.set_upward | (self, key, value) |
Set a variable in one of the higher contexts if it exists there,
otherwise in the current context.
|
Set a variable in one of the higher contexts if it exists there,
otherwise in the current context.
| def set_upward(self, key, value):
"""
Set a variable in one of the higher contexts if it exists there,
otherwise in the current context.
"""
context = self.dicts[-1]
for d in reversed(self.dicts):
if key in d:
context = d
break
... | [
"def",
"set_upward",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"context",
"=",
"self",
".",
"dicts",
"[",
"-",
"1",
"]",
"for",
"d",
"in",
"reversed",
"(",
"self",
".",
"dicts",
")",
":",
"if",
"key",
"in",
"d",
":",
"context",
"=",
"d",... | [
65,
4
] | [
75,
28
] | python | en | ['en', 'error', 'th'] | False |
BaseContext.__getitem__ | (self, key) | Get a variable's value, starting at the current context and going upward | Get a variable's value, starting at the current context and going upward | def __getitem__(self, key):
"Get a variable's value, starting at the current context and going upward"
for d in reversed(self.dicts):
if key in d:
return d[key]
raise KeyError(key) | [
"def",
"__getitem__",
"(",
"self",
",",
"key",
")",
":",
"for",
"d",
"in",
"reversed",
"(",
"self",
".",
"dicts",
")",
":",
"if",
"key",
"in",
"d",
":",
"return",
"d",
"[",
"key",
"]",
"raise",
"KeyError",
"(",
"key",
")"
] | [
77,
4
] | [
82,
27
] | python | en | ['en', 'en', 'en'] | True |
BaseContext.__delitem__ | (self, key) | Delete a variable from the current context | Delete a variable from the current context | def __delitem__(self, key):
"Delete a variable from the current context"
del self.dicts[-1][key] | [
"def",
"__delitem__",
"(",
"self",
",",
"key",
")",
":",
"del",
"self",
".",
"dicts",
"[",
"-",
"1",
"]",
"[",
"key",
"]"
] | [
84,
4
] | [
86,
31
] | python | en | ['en', 'en', 'en'] | True |
BaseContext.new | (self, values=None) |
Return a new context with the same properties, but with only the
values given in 'values' stored.
|
Return a new context with the same properties, but with only the
values given in 'values' stored.
| def new(self, values=None):
"""
Return a new context with the same properties, but with only the
values given in 'values' stored.
"""
new_context = copy(self)
new_context._reset_dicts(values)
return new_context | [
"def",
"new",
"(",
"self",
",",
"values",
"=",
"None",
")",
":",
"new_context",
"=",
"copy",
"(",
"self",
")",
"new_context",
".",
"_reset_dicts",
"(",
"values",
")",
"return",
"new_context"
] | [
104,
4
] | [
111,
26
] | python | en | ['en', 'error', 'th'] | False |
BaseContext.flatten | (self) |
Return self.dicts as one dictionary.
|
Return self.dicts as one dictionary.
| def flatten(self):
"""
Return self.dicts as one dictionary.
"""
flat = {}
for d in self.dicts:
flat.update(d)
return flat | [
"def",
"flatten",
"(",
"self",
")",
":",
"flat",
"=",
"{",
"}",
"for",
"d",
"in",
"self",
".",
"dicts",
":",
"flat",
".",
"update",
"(",
"d",
")",
"return",
"flat"
] | [
113,
4
] | [
120,
19
] | python | en | ['en', 'error', 'th'] | False |
BaseContext.__eq__ | (self, other) |
Compare two contexts by comparing theirs 'dicts' attributes.
|
Compare two contexts by comparing theirs 'dicts' attributes.
| def __eq__(self, other):
"""
Compare two contexts by comparing theirs 'dicts' attributes.
"""
return (
isinstance(other, BaseContext) and
# because dictionaries can be put in different order
# we have to flatten them like in templates
self.... | [
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"return",
"(",
"isinstance",
"(",
"other",
",",
"BaseContext",
")",
"and",
"# because dictionaries can be put in different order",
"# we have to flatten them like in templates",
"self",
".",
"flatten",
"(",
")",
"=... | [
122,
4
] | [
131,
9
] | python | en | ['en', 'error', 'th'] | False |
Context.update | (self, other_dict) | Push other_dict to the stack of dictionaries in the Context | Push other_dict to the stack of dictionaries in the Context | def update(self, other_dict):
"Push other_dict to the stack of dictionaries in the Context"
if not hasattr(other_dict, '__getitem__'):
raise TypeError('other_dict must be a mapping (dictionary-like) object.')
if isinstance(other_dict, BaseContext):
other_dict = other_dict... | [
"def",
"update",
"(",
"self",
",",
"other_dict",
")",
":",
"if",
"not",
"hasattr",
"(",
"other_dict",
",",
"'__getitem__'",
")",
":",
"raise",
"TypeError",
"(",
"'other_dict must be a mapping (dictionary-like) object.'",
")",
"if",
"isinstance",
"(",
"other_dict",
... | [
162,
4
] | [
168,
44
] | python | en | ['en', 'en', 'en'] | True |
get_git_revision_hash | () |
We need a way to retrieve git revision hash for sentry reports
|
We need a way to retrieve git revision hash for sentry reports
| def get_git_revision_hash():
"""
We need a way to retrieve git revision hash for sentry reports
"""
try:
# We are not interested in gits complaints, stderr -> null
git_hash = subprocess.check_output(['git', 'describe', '--tags', '--long', '--always'], stderr=subprocess.DEVNULL, encoding=... | [
"def",
"get_git_revision_hash",
"(",
")",
":",
"try",
":",
"# We are not interested in gits complaints, stderr -> null",
"git_hash",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'git'",
",",
"'describe'",
",",
"'--tags'",
",",
"'--long'",
",",
"'--always'",
"]",... | [
21,
0
] | [
37,
28
] | python | en | ['en', 'error', 'th'] | False |
create_tf_strings_model | () |
A model that concatenates two input strings
|
A model that concatenates two input strings
| def create_tf_strings_model():
"""
A model that concatenates two input strings
"""
g = tf.Graph()
with g.as_default():
with tf.name_scope("some_namespace"):
x = tf.placeholder(tf.string, name="in_x")
y = tf.placeholder(tf.string, name="in_y")
# Assigned t... | [
"def",
"create_tf_strings_model",
"(",
")",
":",
"g",
"=",
"tf",
".",
"Graph",
"(",
")",
"with",
"g",
".",
"as_default",
"(",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"\"some_namespace\"",
")",
":",
"x",
"=",
"tf",
".",
"placeholder",
"(",
"tf... | [
23,
0
] | [
36,
27
] | python | en | ['en', 'error', 'th'] | False |
TestDataset.test_factory | (self) | test_factory: Test that dataset->factory->dataset preserves type | test_factory: Test that dataset->factory->dataset preserves type | def test_factory(self):
"""test_factory: Test that dataset->factory->dataset preserves type"""
d1 = LightweightDataset()
factory = d1.get_factory()
d2 = factory()
self.assertTrue(type(d1) is type(d2)) | [
"def",
"test_factory",
"(",
"self",
")",
":",
"d1",
"=",
"LightweightDataset",
"(",
")",
"factory",
"=",
"d1",
".",
"get_factory",
"(",
")",
"d2",
"=",
"factory",
"(",
")",
"self",
".",
"assertTrue",
"(",
"type",
"(",
"d1",
")",
"is",
"type",
"(",
... | [
17,
4
] | [
22,
45
] | python | en | ['en', 'en', 'en'] | True |
smart_str | (s, encoding='utf-8', strings_only=False, errors='strict') |
Return a string representing 's'. Treat bytestrings using the 'encoding'
codec.
If strings_only is True, don't convert (some) non-string-like objects.
|
Return a string representing 's'. Treat bytestrings using the 'encoding'
codec. | def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Return a string representing 's'. Treat bytestrings using the 'encoding'
codec.
If strings_only is True, don't convert (some) non-string-like objects.
"""
if isinstance(s, Promise):
# The input is the result of... | [
"def",
"smart_str",
"(",
"s",
",",
"encoding",
"=",
"'utf-8'",
",",
"strings_only",
"=",
"False",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"Promise",
")",
":",
"# The input is the result of a gettext_lazy() call.",
"return",
... | [
20,
0
] | [
30,
55
] | python | en | ['en', 'error', 'th'] | False |
is_protected_type | (obj) | Determine if the object instance is of a protected type.
Objects of protected types are preserved as-is when passed to
force_str(strings_only=True).
| Determine if the object instance is of a protected type. | def is_protected_type(obj):
"""Determine if the object instance is of a protected type.
Objects of protected types are preserved as-is when passed to
force_str(strings_only=True).
"""
return isinstance(obj, _PROTECTED_TYPES) | [
"def",
"is_protected_type",
"(",
"obj",
")",
":",
"return",
"isinstance",
"(",
"obj",
",",
"_PROTECTED_TYPES",
")"
] | [
38,
0
] | [
44,
44
] | python | en | ['en', 'en', 'en'] | True |
force_str | (s, encoding='utf-8', strings_only=False, errors='strict') |
Similar to smart_str(), except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
|
Similar to smart_str(), except that lazy instances are resolved to
strings, rather than kept as lazy objects. | def force_str(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Similar to smart_str(), except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
"""
# Handle the common case first fo... | [
"def",
"force_str",
"(",
"s",
",",
"encoding",
"=",
"'utf-8'",
",",
"strings_only",
"=",
"False",
",",
"errors",
"=",
"'strict'",
")",
":",
"# Handle the common case first for performance reasons.",
"if",
"issubclass",
"(",
"type",
"(",
"s",
")",
",",
"str",
"... | [
47,
0
] | [
66,
12
] | python | en | ['en', 'error', 'th'] | False |
smart_bytes | (s, encoding='utf-8', strings_only=False, errors='strict') |
Return a bytestring version of 's', encoded as specified in 'encoding'.
If strings_only is True, don't convert (some) non-string-like objects.
|
Return a bytestring version of 's', encoded as specified in 'encoding'. | def smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Return a bytestring version of 's', encoded as specified in 'encoding'.
If strings_only is True, don't convert (some) non-string-like objects.
"""
if isinstance(s, Promise):
# The input is the result of a gettext... | [
"def",
"smart_bytes",
"(",
"s",
",",
"encoding",
"=",
"'utf-8'",
",",
"strings_only",
"=",
"False",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"Promise",
")",
":",
"# The input is the result of a gettext_lazy() call.",
"return",... | [
69,
0
] | [
78,
57
] | python | en | ['en', 'error', 'th'] | False |
force_bytes | (s, encoding='utf-8', strings_only=False, errors='strict') |
Similar to smart_bytes, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
|
Similar to smart_bytes, except that lazy instances are resolved to
strings, rather than kept as lazy objects. | def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Similar to smart_bytes, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
"""
# Handle the common case first ... | [
"def",
"force_bytes",
"(",
"s",
",",
"encoding",
"=",
"'utf-8'",
",",
"strings_only",
"=",
"False",
",",
"errors",
"=",
"'strict'",
")",
":",
"# Handle the common case first for performance reasons.",
"if",
"isinstance",
"(",
"s",
",",
"bytes",
")",
":",
"if",
... | [
81,
0
] | [
98,
42
] | python | en | ['en', 'error', 'th'] | False |
iri_to_uri | (iri) |
Convert an Internationalized Resource Identifier (IRI) portion to a URI
portion that is suitable for inclusion in a URL.
This is the algorithm from section 3.1 of RFC 3987, slightly simplified
since the input is assumed to be a string rather than an arbitrary byte
stream.
Take an IRI (string ... |
Convert an Internationalized Resource Identifier (IRI) portion to a URI
portion that is suitable for inclusion in a URL. | def iri_to_uri(iri):
"""
Convert an Internationalized Resource Identifier (IRI) portion to a URI
portion that is suitable for inclusion in a URL.
This is the algorithm from section 3.1 of RFC 3987, slightly simplified
since the input is assumed to be a string rather than an arbitrary byte
strea... | [
"def",
"iri_to_uri",
"(",
"iri",
")",
":",
"# The list of safe characters here is constructed from the \"reserved\" and",
"# \"unreserved\" characters specified in sections 2.2 and 2.3 of RFC 3986:",
"# reserved = gen-delims / sub-delims",
"# gen-delims = \":\" / \"/\" / \"?\" / \"#\" ... | [
117,
0
] | [
146,
50
] | python | en | ['en', 'error', 'th'] | False |
uri_to_iri | (uri) |
Convert a Uniform Resource Identifier(URI) into an Internationalized
Resource Identifier(IRI).
This is the algorithm from section 3.2 of RFC 3987, excluding step 4.
Take an URI in ASCII bytes (e.g. '/I%20%E2%99%A5%20Django/') and return
a string containing the encoded result (e.g. '/I%20♥%20Djang... |
Convert a Uniform Resource Identifier(URI) into an Internationalized
Resource Identifier(IRI). | def uri_to_iri(uri):
"""
Convert a Uniform Resource Identifier(URI) into an Internationalized
Resource Identifier(IRI).
This is the algorithm from section 3.2 of RFC 3987, excluding step 4.
Take an URI in ASCII bytes (e.g. '/I%20%E2%99%A5%20Django/') and return
a string containing the encoded ... | [
"def",
"uri_to_iri",
"(",
"uri",
")",
":",
"if",
"uri",
"is",
"None",
":",
"return",
"uri",
"uri",
"=",
"force_bytes",
"(",
"uri",
")",
"# Fast selective unqote: First, split on '%' and then starting with the",
"# second block, decode the first 2 bytes if they represent a hex... | [
167,
0
] | [
200,
49
] | python | en | ['en', 'error', 'th'] | False |
escape_uri_path | (path) |
Escape the unsafe characters from the path portion of a Uniform Resource
Identifier (URI).
|
Escape the unsafe characters from the path portion of a Uniform Resource
Identifier (URI).
| def escape_uri_path(path):
"""
Escape the unsafe characters from the path portion of a Uniform Resource
Identifier (URI).
"""
# These are the "reserved" and "unreserved" characters specified in
# sections 2.2 and 2.3 of RFC 2396:
# reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+... | [
"def",
"escape_uri_path",
"(",
"path",
")",
":",
"# These are the \"reserved\" and \"unreserved\" characters specified in",
"# sections 2.2 and 2.3 of RFC 2396:",
"# reserved = \";\" | \"/\" | \"?\" | \":\" | \"@\" | \"&\" | \"=\" | \"+\" | \"$\" | \",\"",
"# unreserved = alphanum | mark",... | [
203,
0
] | [
217,
47
] | python | en | ['en', 'error', 'th'] | False |
punycode | (domain) | Return the Punycode of the given domain if it's non-ASCII. | Return the Punycode of the given domain if it's non-ASCII. | def punycode(domain):
"""Return the Punycode of the given domain if it's non-ASCII."""
return domain.encode('idna').decode('ascii') | [
"def",
"punycode",
"(",
"domain",
")",
":",
"return",
"domain",
".",
"encode",
"(",
"'idna'",
")",
".",
"decode",
"(",
"'ascii'",
")"
] | [
220,
0
] | [
222,
48
] | python | en | ['en', 'en', 'en'] | True |
repercent_broken_unicode | (path) |
As per section 3.2 of RFC 3987, step three of converting a URI into an IRI,
repercent-encode any octet produced that is not part of a strictly legal
UTF-8 octet sequence.
|
As per section 3.2 of RFC 3987, step three of converting a URI into an IRI,
repercent-encode any octet produced that is not part of a strictly legal
UTF-8 octet sequence.
| def repercent_broken_unicode(path):
"""
As per section 3.2 of RFC 3987, step three of converting a URI into an IRI,
repercent-encode any octet produced that is not part of a strictly legal
UTF-8 octet sequence.
"""
while True:
try:
path.decode()
except UnicodeDecodeEr... | [
"def",
"repercent_broken_unicode",
"(",
"path",
")",
":",
"while",
"True",
":",
"try",
":",
"path",
".",
"decode",
"(",
")",
"except",
"UnicodeDecodeError",
"as",
"e",
":",
"# CVE-2019-14235: A recursion shouldn't be used since the exception",
"# handling uses massive amo... | [
225,
0
] | [
240,
23
] | python | en | ['en', 'error', 'th'] | False |
filepath_to_uri | (path) | Convert a file system path to a URI portion that is suitable for
inclusion in a URL.
Encode certain chars that would normally be recognized as special chars
for URIs. Do not encode the ' character, as it is a valid character
within URIs. See the encodeURIComponent() JavaScript function for details.
... | Convert a file system path to a URI portion that is suitable for
inclusion in a URL. | def filepath_to_uri(path):
"""Convert a file system path to a URI portion that is suitable for
inclusion in a URL.
Encode certain chars that would normally be recognized as special chars
for URIs. Do not encode the ' character, as it is a valid character
within URIs. See the encodeURIComponent() Ja... | [
"def",
"filepath_to_uri",
"(",
"path",
")",
":",
"if",
"path",
"is",
"None",
":",
"return",
"path",
"# I know about `os.sep` and `os.altsep` but I want to leave",
"# some flexibility for hardcoding separators.",
"return",
"quote",
"(",
"path",
".",
"replace",
"(",
"\"\\\\... | [
243,
0
] | [
255,
57
] | python | en | ['en', 'en', 'en'] | True |
get_system_encoding | () |
The encoding of the default system locale. Fallback to 'ascii' if the
#encoding is unsupported by Python or could not be determined. See tickets
#10335 and #5846.
|
The encoding of the default system locale. Fallback to 'ascii' if the
#encoding is unsupported by Python or could not be determined. See tickets
#10335 and #5846.
| def get_system_encoding():
"""
The encoding of the default system locale. Fallback to 'ascii' if the
#encoding is unsupported by Python or could not be determined. See tickets
#10335 and #5846.
"""
try:
encoding = locale.getdefaultlocale()[1] or 'ascii'
codecs.lookup(encoding)
... | [
"def",
"get_system_encoding",
"(",
")",
":",
"try",
":",
"encoding",
"=",
"locale",
".",
"getdefaultlocale",
"(",
")",
"[",
"1",
"]",
"or",
"'ascii'",
"codecs",
".",
"lookup",
"(",
"encoding",
")",
"except",
"Exception",
":",
"encoding",
"=",
"'ascii'",
... | [
258,
0
] | [
269,
19
] | python | en | ['en', 'error', 'th'] | False |
MultipleObjectMixin.get_queryset | (self) |
Return the list of items for this view.
The return value must be an iterable and may be an instance of
`QuerySet` in which case `QuerySet` specific behavior will be enabled.
|
Return the list of items for this view. | def get_queryset(self):
"""
Return the list of items for this view.
The return value must be an iterable and may be an instance of
`QuerySet` in which case `QuerySet` specific behavior will be enabled.
"""
if self.queryset is not None:
queryset = self.queryse... | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"if",
"self",
".",
"queryset",
"is",
"not",
"None",
":",
"queryset",
"=",
"self",
".",
"queryset",
"if",
"isinstance",
"(",
"queryset",
",",
"QuerySet",
")",
":",
"queryset",
"=",
"queryset",
".",
"all",
"(... | [
20,
4
] | [
47,
23
] | python | en | ['en', 'error', 'th'] | False |
MultipleObjectMixin.get_ordering | (self) | Return the field or fields to use for ordering the queryset. | Return the field or fields to use for ordering the queryset. | def get_ordering(self):
"""Return the field or fields to use for ordering the queryset."""
return self.ordering | [
"def",
"get_ordering",
"(",
"self",
")",
":",
"return",
"self",
".",
"ordering"
] | [
49,
4
] | [
51,
28
] | python | en | ['en', 'en', 'en'] | True |
MultipleObjectMixin.paginate_queryset | (self, queryset, page_size) | Paginate the queryset, if needed. | Paginate the queryset, if needed. | def paginate_queryset(self, queryset, page_size):
"""Paginate the queryset, if needed."""
paginator = self.get_paginator(
queryset, page_size, orphans=self.get_paginate_orphans(),
allow_empty_first_page=self.get_allow_empty())
page_kwarg = self.page_kwarg
page = s... | [
"def",
"paginate_queryset",
"(",
"self",
",",
"queryset",
",",
"page_size",
")",
":",
"paginator",
"=",
"self",
".",
"get_paginator",
"(",
"queryset",
",",
"page_size",
",",
"orphans",
"=",
"self",
".",
"get_paginate_orphans",
"(",
")",
",",
"allow_empty_first... | [
53,
4
] | [
74,
14
] | python | en | ['en', 'en', 'en'] | True |
MultipleObjectMixin.get_paginate_by | (self, queryset) |
Get the number of items to paginate by, or ``None`` for no pagination.
|
Get the number of items to paginate by, or ``None`` for no pagination.
| def get_paginate_by(self, queryset):
"""
Get the number of items to paginate by, or ``None`` for no pagination.
"""
return self.paginate_by | [
"def",
"get_paginate_by",
"(",
"self",
",",
"queryset",
")",
":",
"return",
"self",
".",
"paginate_by"
] | [
76,
4
] | [
80,
31
] | python | en | ['en', 'error', 'th'] | False |
MultipleObjectMixin.get_paginator | (self, queryset, per_page, orphans=0,
allow_empty_first_page=True, **kwargs) | Return an instance of the paginator for this view. | Return an instance of the paginator for this view. | def get_paginator(self, queryset, per_page, orphans=0,
allow_empty_first_page=True, **kwargs):
"""Return an instance of the paginator for this view."""
return self.paginator_class(
queryset, per_page, orphans=orphans,
allow_empty_first_page=allow_empty_first... | [
"def",
"get_paginator",
"(",
"self",
",",
"queryset",
",",
"per_page",
",",
"orphans",
"=",
"0",
",",
"allow_empty_first_page",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"paginator_class",
"(",
"queryset",
",",
"per_page",
",",... | [
82,
4
] | [
87,
68
] | python | en | ['en', 'en', 'en'] | True |
MultipleObjectMixin.get_paginate_orphans | (self) |
Return the maximum number of orphans extend the last page by when
paginating.
|
Return the maximum number of orphans extend the last page by when
paginating.
| def get_paginate_orphans(self):
"""
Return the maximum number of orphans extend the last page by when
paginating.
"""
return self.paginate_orphans | [
"def",
"get_paginate_orphans",
"(",
"self",
")",
":",
"return",
"self",
".",
"paginate_orphans"
] | [
89,
4
] | [
94,
36
] | python | en | ['en', 'error', 'th'] | False |
MultipleObjectMixin.get_allow_empty | (self) |
Return ``True`` if the view should display empty lists and ``False``
if a 404 should be raised instead.
|
Return ``True`` if the view should display empty lists and ``False``
if a 404 should be raised instead.
| def get_allow_empty(self):
"""
Return ``True`` if the view should display empty lists and ``False``
if a 404 should be raised instead.
"""
return self.allow_empty | [
"def",
"get_allow_empty",
"(",
"self",
")",
":",
"return",
"self",
".",
"allow_empty"
] | [
96,
4
] | [
101,
31
] | python | en | ['en', 'error', 'th'] | False |
MultipleObjectMixin.get_context_object_name | (self, object_list) | Get the name of the item to be used in the context. | Get the name of the item to be used in the context. | def get_context_object_name(self, object_list):
"""Get the name of the item to be used in the context."""
if self.context_object_name:
return self.context_object_name
elif hasattr(object_list, 'model'):
return '%s_list' % object_list.model._meta.model_name
else:
... | [
"def",
"get_context_object_name",
"(",
"self",
",",
"object_list",
")",
":",
"if",
"self",
".",
"context_object_name",
":",
"return",
"self",
".",
"context_object_name",
"elif",
"hasattr",
"(",
"object_list",
",",
"'model'",
")",
":",
"return",
"'%s_list'",
"%",... | [
103,
4
] | [
110,
23
] | python | en | ['en', 'en', 'en'] | True |
MultipleObjectMixin.get_context_data | (self, *, object_list=None, **kwargs) | Get the context for this view. | Get the context for this view. | def get_context_data(self, *, object_list=None, **kwargs):
"""Get the context for this view."""
queryset = object_list if object_list is not None else self.object_list
page_size = self.get_paginate_by(queryset)
context_object_name = self.get_context_object_name(queryset)
if page_... | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
",",
"object_list",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"queryset",
"=",
"object_list",
"if",
"object_list",
"is",
"not",
"None",
"else",
"self",
".",
"object_list",
"page_size",
"=",
"self",
... | [
112,
4
] | [
135,
50
] | python | en | ['en', 'en', 'en'] | True |
MultipleObjectTemplateResponseMixin.get_template_names | (self) |
Return a list of template names to be used for the request. Must return
a list. May not be called if render_to_response is overridden.
|
Return a list of template names to be used for the request. Must return
a list. May not be called if render_to_response is overridden.
| def get_template_names(self):
"""
Return a list of template names to be used for the request. Must return
a list. May not be called if render_to_response is overridden.
"""
try:
names = super().get_template_names()
except ImproperlyConfigured:
# If... | [
"def",
"get_template_names",
"(",
"self",
")",
":",
"try",
":",
"names",
"=",
"super",
"(",
")",
".",
"get_template_names",
"(",
")",
"except",
"ImproperlyConfigured",
":",
"# If template_name isn't specified, it's not a problem --",
"# we just start with an empty list.",
... | [
164,
4
] | [
190,
20
] | python | en | ['en', 'error', 'th'] | False |
load | (filename) |
Load a font file. This function loads a font object from the given
bitmap font file, and returns the corresponding font object.
:param filename: Name of font file.
:return: A font object.
:exception OSError: If the file could not be read.
|
Load a font file. This function loads a font object from the given
bitmap font file, and returns the corresponding font object. | def load(filename):
"""
Load a font file. This function loads a font object from the given
bitmap font file, and returns the corresponding font object.
:param filename: Name of font file.
:return: A font object.
:exception OSError: If the file could not be read.
"""
f = ImageFont()
... | [
"def",
"load",
"(",
"filename",
")",
":",
"f",
"=",
"ImageFont",
"(",
")",
"f",
".",
"_load_pilfont",
"(",
"filename",
")",
"return",
"f"
] | [
583,
0
] | [
594,
12
] | python | en | ['en', 'error', 'th'] | False |
truetype | (font=None, size=10, index=0, encoding="", layout_engine=None) |
Load a TrueType or OpenType font from a file or file-like object,
and create a font object.
This function loads a font object from the given file or file-like
object, and creates a font object for a font of the given size.
Pillow uses FreeType to open font files. If you are opening many fonts
... |
Load a TrueType or OpenType font from a file or file-like object,
and create a font object.
This function loads a font object from the given file or file-like
object, and creates a font object for a font of the given size. | def truetype(font=None, size=10, index=0, encoding="", layout_engine=None):
"""
Load a TrueType or OpenType font from a file or file-like object,
and create a font object.
This function loads a font object from the given file or file-like
object, and creates a font object for a font of the given siz... | [
"def",
"truetype",
"(",
"font",
"=",
"None",
",",
"size",
"=",
"10",
",",
"index",
"=",
"0",
",",
"encoding",
"=",
"\"\"",
",",
"layout_engine",
"=",
"None",
")",
":",
"def",
"freetype",
"(",
"font",
")",
":",
"return",
"FreeTypeFont",
"(",
"font",
... | [
597,
0
] | [
697,
13
] | python | en | ['en', 'error', 'th'] | False |
load_path | (filename) |
Load font file. Same as :py:func:`~PIL.ImageFont.load`, but searches for a
bitmap font along the Python path.
:param filename: Name of font file.
:return: A font object.
:exception OSError: If the file could not be read.
|
Load font file. Same as :py:func:`~PIL.ImageFont.load`, but searches for a
bitmap font along the Python path. | def load_path(filename):
"""
Load font file. Same as :py:func:`~PIL.ImageFont.load`, but searches for a
bitmap font along the Python path.
:param filename: Name of font file.
:return: A font object.
:exception OSError: If the file could not be read.
"""
for directory in sys.path:
... | [
"def",
"load_path",
"(",
"filename",
")",
":",
"for",
"directory",
"in",
"sys",
".",
"path",
":",
"if",
"isDirectory",
"(",
"directory",
")",
":",
"if",
"not",
"isinstance",
"(",
"filename",
",",
"str",
")",
":",
"filename",
"=",
"filename",
".",
"deco... | [
700,
0
] | [
717,
42
] | python | en | ['en', 'error', 'th'] | False |
load_default | () | Load a "better than nothing" default font.
.. versionadded:: 1.1.4
:return: A font object.
| Load a "better than nothing" default font. | def load_default():
"""Load a "better than nothing" default font.
.. versionadded:: 1.1.4
:return: A font object.
"""
f = ImageFont()
f._load_pilfont_data(
# courB08
BytesIO(
base64.b64decode(
b"""
UElMZm9udAo7Ozs7OzsxMDsKREFUQQoAAAAAAAAAAAAAAAAAAAAA... | [
"def",
"load_default",
"(",
")",
":",
"f",
"=",
"ImageFont",
"(",
")",
"f",
".",
"_load_pilfont_data",
"(",
"# courB08",
"BytesIO",
"(",
"base64",
".",
"b64decode",
"(",
"b\"\"\"\nUElMZm9udAo7Ozs7OzsxMDsKREFUQQoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAA... | [
720,
0
] | [
859,
12
] | python | en | ['en', 'en', 'en'] | True |
ImageFont.getsize | (self, text, *args, **kwargs) |
Returns width and height (in pixels) of given text.
:param text: Text to measure.
:return: (width, height)
|
Returns width and height (in pixels) of given text. | def getsize(self, text, *args, **kwargs):
"""
Returns width and height (in pixels) of given text.
:param text: Text to measure.
:return: (width, height)
"""
return self.font.getsize(text) | [
"def",
"getsize",
"(",
"self",
",",
"text",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"font",
".",
"getsize",
"(",
"text",
")"
] | [
119,
4
] | [
127,
38
] | python | en | ['en', 'error', 'th'] | False |
ImageFont.getmask | (self, text, mode="", *args, **kwargs) |
Create a bitmap for the text.
If the font uses antialiasing, the bitmap should have mode ``L`` and use a
maximum value of 255. Otherwise, it should have mode ``1``.
:param text: Text to render.
:param mode: Used by some graphics drivers to indicate what mode the
... |
Create a bitmap for the text. | def getmask(self, text, mode="", *args, **kwargs):
"""
Create a bitmap for the text.
If the font uses antialiasing, the bitmap should have mode ``L`` and use a
maximum value of 255. Otherwise, it should have mode ``1``.
:param text: Text to render.
:param mode: Used by ... | [
"def",
"getmask",
"(",
"self",
",",
"text",
",",
"mode",
"=",
"\"\"",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"font",
".",
"getmask",
"(",
"text",
",",
"mode",
")"
] | [
129,
4
] | [
147,
44
] | python | en | ['en', 'error', 'th'] | False |
FreeTypeFont.getname | (self) |
:return: A tuple of the font family (e.g. Helvetica) and the font style
(e.g. Bold)
|
:return: A tuple of the font family (e.g. Helvetica) and the font style
(e.g. Bold)
| def getname(self):
"""
:return: A tuple of the font family (e.g. Helvetica) and the font style
(e.g. Bold)
"""
return self.font.family, self.font.style | [
"def",
"getname",
"(",
"self",
")",
":",
"return",
"self",
".",
"font",
".",
"family",
",",
"self",
".",
"font",
".",
"style"
] | [
202,
4
] | [
207,
48
] | python | en | ['en', 'error', 'th'] | False |
FreeTypeFont.getmetrics | (self) |
:return: A tuple of the font ascent (the distance from the baseline to
the highest outline point) and descent (the distance from the
baseline to the lowest outline point, a negative value)
|
:return: A tuple of the font ascent (the distance from the baseline to
the highest outline point) and descent (the distance from the
baseline to the lowest outline point, a negative value)
| def getmetrics(self):
"""
:return: A tuple of the font ascent (the distance from the baseline to
the highest outline point) and descent (the distance from the
baseline to the lowest outline point, a negative value)
"""
return self.font.ascent, self.font.descent | [
"def",
"getmetrics",
"(",
"self",
")",
":",
"return",
"self",
".",
"font",
".",
"ascent",
",",
"self",
".",
"font",
".",
"descent"
] | [
209,
4
] | [
215,
50
] | python | en | ['en', 'error', 'th'] | False |
FreeTypeFont.getsize | (
self, text, direction=None, features=None, language=None, stroke_width=0
) |
Returns width and height (in pixels) of given text if rendered in font with
provided direction, features, and language.
:param text: Text to measure.
:param direction: Direction of the text. It can be 'rtl' (right to
left), 'ltr' (left to right) or 'ttb' (top... |
Returns width and height (in pixels) of given text if rendered in font with
provided direction, features, and language. | def getsize(
self, text, direction=None, features=None, language=None, stroke_width=0
):
"""
Returns width and height (in pixels) of given text if rendered in font with
provided direction, features, and language.
:param text: Text to measure.
:param direction: Direc... | [
"def",
"getsize",
"(",
"self",
",",
"text",
",",
"direction",
"=",
"None",
",",
"features",
"=",
"None",
",",
"language",
"=",
"None",
",",
"stroke_width",
"=",
"0",
")",
":",
"size",
",",
"offset",
"=",
"self",
".",
"font",
".",
"getsize",
"(",
"t... | [
217,
4
] | [
265,
9
] | python | en | ['en', 'error', 'th'] | False |
FreeTypeFont.getsize_multiline | (
self,
text,
direction=None,
spacing=4,
features=None,
language=None,
stroke_width=0,
) |
Returns width and height (in pixels) of given text if rendered in font
with provided direction, features, and language, while respecting
newline characters.
:param text: Text to measure.
:param direction: Direction of the text. It can be 'rtl' (right to
... |
Returns width and height (in pixels) of given text if rendered in font
with provided direction, features, and language, while respecting
newline characters. | def getsize_multiline(
self,
text,
direction=None,
spacing=4,
features=None,
language=None,
stroke_width=0,
):
"""
Returns width and height (in pixels) of given text if rendered in font
with provided direction, features, and language, w... | [
"def",
"getsize_multiline",
"(",
"self",
",",
"text",
",",
"direction",
"=",
"None",
",",
"spacing",
"=",
"4",
",",
"features",
"=",
"None",
",",
"language",
"=",
"None",
",",
"stroke_width",
"=",
"0",
",",
")",
":",
"max_width",
"=",
"0",
"lines",
"... | [
267,
4
] | [
325,
61
] | python | en | ['en', 'error', 'th'] | False |
FreeTypeFont.getoffset | (self, text) |
Returns the offset of given text. This is the gap between the
starting coordinate and the first marking. Note that this gap is
included in the result of :py:func:`~PIL.ImageFont.FreeTypeFont.getsize`.
:param text: Text to measure.
:return: A tuple of the x and y offset
... |
Returns the offset of given text. This is the gap between the
starting coordinate and the first marking. Note that this gap is
included in the result of :py:func:`~PIL.ImageFont.FreeTypeFont.getsize`. | def getoffset(self, text):
"""
Returns the offset of given text. This is the gap between the
starting coordinate and the first marking. Note that this gap is
included in the result of :py:func:`~PIL.ImageFont.FreeTypeFont.getsize`.
:param text: Text to measure.
:return:... | [
"def",
"getoffset",
"(",
"self",
",",
"text",
")",
":",
"return",
"self",
".",
"font",
".",
"getsize",
"(",
"text",
")",
"[",
"1",
"]"
] | [
327,
4
] | [
337,
41
] | python | en | ['en', 'error', 'th'] | False |
FreeTypeFont.getmask | (
self,
text,
mode="",
direction=None,
features=None,
language=None,
stroke_width=0,
) |
Create a bitmap for the text.
If the font uses antialiasing, the bitmap should have mode ``L`` and use a
maximum value of 255. Otherwise, it should have mode ``1``.
:param text: Text to render.
:param mode: Used by some graphics drivers to indicate what mode the
... |
Create a bitmap for the text. | def getmask(
self,
text,
mode="",
direction=None,
features=None,
language=None,
stroke_width=0,
):
"""
Create a bitmap for the text.
If the font uses antialiasing, the bitmap should have mode ``L`` and use a
maximum value of 25... | [
"def",
"getmask",
"(",
"self",
",",
"text",
",",
"mode",
"=",
"\"\"",
",",
"direction",
"=",
"None",
",",
"features",
"=",
"None",
",",
"language",
"=",
"None",
",",
"stroke_width",
"=",
"0",
",",
")",
":",
"return",
"self",
".",
"getmask2",
"(",
"... | [
339,
4
] | [
405,
12
] | python | en | ['en', 'error', 'th'] | False |
FreeTypeFont.getmask2 | (
self,
text,
mode="",
fill=Image.core.fill,
direction=None,
features=None,
language=None,
stroke_width=0,
*args,
**kwargs
) |
Create a bitmap for the text.
If the font uses antialiasing, the bitmap should have mode ``L`` and use a
maximum value of 255. Otherwise, it should have mode ``1``.
:param text: Text to render.
:param mode: Used by some graphics drivers to indicate what mode the
... |
Create a bitmap for the text. | def getmask2(
self,
text,
mode="",
fill=Image.core.fill,
direction=None,
features=None,
language=None,
stroke_width=0,
*args,
**kwargs
):
"""
Create a bitmap for the text.
If the font uses antialiasing, the bitm... | [
"def",
"getmask2",
"(",
"self",
",",
"text",
",",
"mode",
"=",
"\"\"",
",",
"fill",
"=",
"Image",
".",
"core",
".",
"fill",
",",
"direction",
"=",
"None",
",",
"features",
"=",
"None",
",",
"language",
"=",
"None",
",",
"stroke_width",
"=",
"0",
",... | [
407,
4
] | [
478,
25
] | python | en | ['en', 'error', 'th'] | False |
FreeTypeFont.font_variant | (
self, font=None, size=None, index=None, encoding=None, layout_engine=None
) |
Create a copy of this FreeTypeFont object,
using any specified arguments to override the settings.
Parameters are identical to the parameters used to initialize this
object.
:return: A FreeTypeFont object.
|
Create a copy of this FreeTypeFont object,
using any specified arguments to override the settings. | def font_variant(
self, font=None, size=None, index=None, encoding=None, layout_engine=None
):
"""
Create a copy of this FreeTypeFont object,
using any specified arguments to override the settings.
Parameters are identical to the parameters used to initialize this
ob... | [
"def",
"font_variant",
"(",
"self",
",",
"font",
"=",
"None",
",",
"size",
"=",
"None",
",",
"index",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"layout_engine",
"=",
"None",
")",
":",
"return",
"FreeTypeFont",
"(",
"font",
"=",
"self",
".",
"pa... | [
480,
4
] | [
498,
9
] | python | en | ['en', 'error', 'th'] | False |
FreeTypeFont.get_variation_names | (self) |
:returns: A list of the named styles in a variation font.
:exception OSError: If the font is not a variation font.
|
:returns: A list of the named styles in a variation font.
:exception OSError: If the font is not a variation font.
| def get_variation_names(self):
"""
:returns: A list of the named styles in a variation font.
:exception OSError: If the font is not a variation font.
"""
try:
names = self.font.getvarnames()
except AttributeError as e:
raise NotImplementedError("Fr... | [
"def",
"get_variation_names",
"(",
"self",
")",
":",
"try",
":",
"names",
"=",
"self",
".",
"font",
".",
"getvarnames",
"(",
")",
"except",
"AttributeError",
"as",
"e",
":",
"raise",
"NotImplementedError",
"(",
"\"FreeType 2.9.1 or greater is required\"",
")",
"... | [
500,
4
] | [
509,
61
] | python | en | ['en', 'error', 'th'] | False |
FreeTypeFont.set_variation_by_name | (self, name) |
:param name: The name of the style.
:exception OSError: If the font is not a variation font.
|
:param name: The name of the style.
:exception OSError: If the font is not a variation font.
| def set_variation_by_name(self, name):
"""
:param name: The name of the style.
:exception OSError: If the font is not a variation font.
"""
names = self.get_variation_names()
if not isinstance(name, bytes):
name = name.encode()
index = names.index(name... | [
"def",
"set_variation_by_name",
"(",
"self",
",",
"name",
")",
":",
"names",
"=",
"self",
".",
"get_variation_names",
"(",
")",
"if",
"not",
"isinstance",
"(",
"name",
",",
"bytes",
")",
":",
"name",
"=",
"name",
".",
"encode",
"(",
")",
"index",
"=",
... | [
511,
4
] | [
528,
35
] | python | en | ['en', 'error', 'th'] | False |
FreeTypeFont.get_variation_axes | (self) |
:returns: A list of the axes in a variation font.
:exception OSError: If the font is not a variation font.
|
:returns: A list of the axes in a variation font.
:exception OSError: If the font is not a variation font.
| def get_variation_axes(self):
"""
:returns: A list of the axes in a variation font.
:exception OSError: If the font is not a variation font.
"""
try:
axes = self.font.getvaraxes()
except AttributeError as e:
raise NotImplementedError("FreeType 2.9.... | [
"def",
"get_variation_axes",
"(",
"self",
")",
":",
"try",
":",
"axes",
"=",
"self",
".",
"font",
".",
"getvaraxes",
"(",
")",
"except",
"AttributeError",
"as",
"e",
":",
"raise",
"NotImplementedError",
"(",
"\"FreeType 2.9.1 or greater is required\"",
")",
"fro... | [
530,
4
] | [
541,
19
] | python | en | ['en', 'error', 'th'] | False |
FreeTypeFont.set_variation_by_axes | (self, axes) |
:param axes: A list of values for each axis.
:exception OSError: If the font is not a variation font.
|
:param axes: A list of values for each axis.
:exception OSError: If the font is not a variation font.
| def set_variation_by_axes(self, axes):
"""
:param axes: A list of values for each axis.
:exception OSError: If the font is not a variation font.
"""
try:
self.font.setvaraxes(axes)
except AttributeError as e:
raise NotImplementedError("FreeType 2.9... | [
"def",
"set_variation_by_axes",
"(",
"self",
",",
"axes",
")",
":",
"try",
":",
"self",
".",
"font",
".",
"setvaraxes",
"(",
"axes",
")",
"except",
"AttributeError",
"as",
"e",
":",
"raise",
"NotImplementedError",
"(",
"\"FreeType 2.9.1 or greater is required\"",
... | [
543,
4
] | [
551,
85
] | python | en | ['en', 'error', 'th'] | False |
TransposedFont.__init__ | (self, font, orientation=None) |
Wrapper that creates a transposed font from any existing font
object.
:param font: A font object.
:param orientation: An optional orientation. If given, this should
be one of Image.FLIP_LEFT_RIGHT, Image.FLIP_TOP_BOTTOM,
Image.ROTATE_90, Image.ROTATE_180, or Im... |
Wrapper that creates a transposed font from any existing font
object. | def __init__(self, font, orientation=None):
"""
Wrapper that creates a transposed font from any existing font
object.
:param font: A font object.
:param orientation: An optional orientation. If given, this should
be one of Image.FLIP_LEFT_RIGHT, Image.FLIP_TOP_BOTTO... | [
"def",
"__init__",
"(",
"self",
",",
"font",
",",
"orientation",
"=",
"None",
")",
":",
"self",
".",
"font",
"=",
"font",
"self",
".",
"orientation",
"=",
"orientation"
] | [
557,
4
] | [
568,
38
] | python | en | ['en', 'error', 'th'] | False |
_fd | (f) | Get a filedescriptor from something which could be a file or an fd. | Get a filedescriptor from something which could be a file or an fd. | def _fd(f):
"""Get a filedescriptor from something which could be a file or an fd."""
return f.fileno() if hasattr(f, 'fileno') else f | [
"def",
"_fd",
"(",
"f",
")",
":",
"return",
"f",
".",
"fileno",
"(",
")",
"if",
"hasattr",
"(",
"f",
",",
"'fileno'",
")",
"else",
"f"
] | [
23,
0
] | [
25,
52
] | python | en | ['en', 'en', 'en'] | True |
FastFeatureAdversaries.__init__ | (self, model, sess=None, dtypestr="float32", **kwargs) |
Create a FastFeatureAdversaries instance.
|
Create a FastFeatureAdversaries instance.
| def __init__(self, model, sess=None, dtypestr="float32", **kwargs):
"""
Create a FastFeatureAdversaries instance.
"""
super(FastFeatureAdversaries, self).__init__(model, sess, dtypestr, **kwargs)
self.feedable_kwargs = ("eps", "eps_iter", "clip_min", "clip_max")
self.stru... | [
"def",
"__init__",
"(",
"self",
",",
"model",
",",
"sess",
"=",
"None",
",",
"dtypestr",
"=",
"\"float32\"",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"FastFeatureAdversaries",
",",
"self",
")",
".",
"__init__",
"(",
"model",
",",
"sess",
",",
... | [
32,
4
] | [
40,
44
] | python | en | ['en', 'error', 'th'] | False |
FastFeatureAdversaries.parse_params | (
self,
layer=None,
eps=0.3,
eps_iter=0.05,
nb_iter=10,
ord=np.inf,
clip_min=None,
clip_max=None,
**kwargs
) |
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
Attack-specific parameters:
:param layer: (required str) name of the layer to target.
:param eps: (optional float) maximum distortion of adversarial example
... |
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes. | def parse_params(
self,
layer=None,
eps=0.3,
eps_iter=0.05,
nb_iter=10,
ord=np.inf,
clip_min=None,
clip_max=None,
**kwargs
):
"""
Take in a dictionary of parameters and applies attack-specific checks
before saving them a... | [
"def",
"parse_params",
"(",
"self",
",",
"layer",
"=",
"None",
",",
"eps",
"=",
"0.3",
",",
"eps_iter",
"=",
"0.05",
",",
"nb_iter",
"=",
"10",
",",
"ord",
"=",
"np",
".",
"inf",
",",
"clip_min",
"=",
"None",
",",
"clip_max",
"=",
"None",
",",
"*... | [
42,
4
] | [
87,
19
] | python | en | ['en', 'error', 'th'] | False |
FastFeatureAdversaries.attack_single_step | (self, x, eta, g_feat) |
TensorFlow implementation of the Fast Feature Gradient. This is a
single step attack similar to Fast Gradient Method that attacks an
internal representation.
:param x: the input placeholder
:param eta: A tensor the same shape as x that holds the perturbation.
:param g_f... |
TensorFlow implementation of the Fast Feature Gradient. This is a
single step attack similar to Fast Gradient Method that attacks an
internal representation. | def attack_single_step(self, x, eta, g_feat):
"""
TensorFlow implementation of the Fast Feature Gradient. This is a
single step attack similar to Fast Gradient Method that attacks an
internal representation.
:param x: the input placeholder
:param eta: A tensor the same s... | [
"def",
"attack_single_step",
"(",
"self",
",",
"x",
",",
"eta",
",",
"g_feat",
")",
":",
"adv_x",
"=",
"x",
"+",
"eta",
"a_feat",
"=",
"self",
".",
"model",
".",
"fprop",
"(",
"adv_x",
")",
"[",
"self",
".",
"layer",
"]",
"# feat.shape = (batch, c) or ... | [
89,
4
] | [
130,
18
] | python | en | ['en', 'error', 'th'] | False |
FastFeatureAdversaries.generate | (self, x, g, **kwargs) |
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param g: The target value of the symbolic representation
:param kwargs: See `parse_params`
|
Generate symbolic graph for adversarial examples and return. | def generate(self, x, g, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param g: The target value of the symbolic representation
:param kwargs: See `parse_params`
"""
# Parse and save attack-sp... | [
"def",
"generate",
"(",
"self",
",",
"x",
",",
"g",
",",
"*",
"*",
"kwargs",
")",
":",
"# Parse and save attack-specific parameters",
"assert",
"self",
".",
"parse_params",
"(",
"*",
"*",
"kwargs",
")",
"g_feat",
"=",
"self",
".",
"model",
".",
"fprop",
... | [
132,
4
] | [
170,
20
] | python | en | ['en', 'error', 'th'] | False |
ChangeList.get_filters_params | (self, params=None) |
Returns all params except IGNORED_PARAMS
|
Returns all params except IGNORED_PARAMS
| def get_filters_params(self, params=None):
"""
Returns all params except IGNORED_PARAMS
"""
if not params:
params = self.params
lookup_params = params.copy() # a dictionary of the query string
# Remove all the parameters that are globally and systematically
... | [
"def",
"get_filters_params",
"(",
"self",
",",
"params",
"=",
"None",
")",
":",
"if",
"not",
"params",
":",
"params",
"=",
"self",
".",
"params",
"lookup_params",
"=",
"params",
".",
"copy",
"(",
")",
"# a dictionary of the query string",
"# Remove all the param... | [
86,
4
] | [
98,
28
] | python | en | ['en', 'error', 'th'] | False |
ChangeList.get_ordering_field | (self, field_name) |
Returns the proper model field name corresponding to the given
field_name to use for ordering. field_name may either be the name of a
proper model field or the name of a method (on the admin or model) or a
callable with the 'admin_order_field' attribute. Returns None if no
prope... |
Returns the proper model field name corresponding to the given
field_name to use for ordering. field_name may either be the name of a
proper model field or the name of a method (on the admin or model) or a
callable with the 'admin_order_field' attribute. Returns None if no
prope... | def get_ordering_field(self, field_name):
"""
Returns the proper model field name corresponding to the given
field_name to use for ordering. field_name may either be the name of a
proper model field or the name of a method (on the admin or model) or a
callable with the 'admin_ord... | [
"def",
"get_ordering_field",
"(",
"self",
",",
"field_name",
")",
":",
"try",
":",
"field",
"=",
"self",
".",
"lookup_opts",
".",
"get_field",
"(",
"field_name",
")",
"return",
"field",
".",
"name",
"except",
"models",
".",
"FieldDoesNotExist",
":",
"# See w... | [
217,
4
] | [
237,
59
] | python | en | ['en', 'error', 'th'] | False |
ChangeList.get_ordering | (self, request, queryset) |
Returns the list of ordering fields for the change list.
First we check the get_ordering() method in model admin, then we check
the object's default ordering. Then, any manually-specified ordering
from the query string overrides anything. Finally, a deterministic
order is guaran... |
Returns the list of ordering fields for the change list.
First we check the get_ordering() method in model admin, then we check
the object's default ordering. Then, any manually-specified ordering
from the query string overrides anything. Finally, a deterministic
order is guaran... | def get_ordering(self, request, queryset):
"""
Returns the list of ordering fields for the change list.
First we check the get_ordering() method in model admin, then we check
the object's default ordering. Then, any manually-specified ordering
from the query string overrides anyt... | [
"def",
"get_ordering",
"(",
"self",
",",
"request",
",",
"queryset",
")",
":",
"params",
"=",
"self",
".",
"params",
"ordering",
"=",
"list",
"(",
"self",
".",
"model_admin",
".",
"get_ordering",
"(",
"request",
")",
"or",
"self",
".",
"_get_default_orderi... | [
239,
4
] | [
282,
23
] | python | en | ['en', 'error', 'th'] | False |
ChangeList.get_ordering_field_columns | (self) |
Returns an OrderedDict of ordering field column numbers and asc/desc
|
Returns an OrderedDict of ordering field column numbers and asc/desc
| def get_ordering_field_columns(self):
"""
Returns an OrderedDict of ordering field column numbers and asc/desc
"""
# We must cope with more than one column having the same underlying sort
# field, so we base things on column numbers.
ordering = self._get_default_ordering... | [
"def",
"get_ordering_field_columns",
"(",
"self",
")",
":",
"# We must cope with more than one column having the same underlying sort",
"# field, so we base things on column numbers.",
"ordering",
"=",
"self",
".",
"_get_default_ordering",
"(",
")",
"ordering_fields",
"=",
"Ordered... | [
284,
4
] | [
315,
30
] | python | en | ['en', 'error', 'th'] | False |
test_stub_validation | (shared_datadir) | should pass validation | should pass validation | def test_stub_validation(shared_datadir):
"""should pass validation"""
stub_path = shared_datadir / "esp8266_test_stub"
manager = stubs.StubManager()
manager.validate(stub_path)
assert manager.is_valid(stub_path)
assert not manager.is_valid(Path("/foobar/bar")) | [
"def",
"test_stub_validation",
"(",
"shared_datadir",
")",
":",
"stub_path",
"=",
"shared_datadir",
"/",
"\"esp8266_test_stub\"",
"manager",
"=",
"stubs",
".",
"StubManager",
"(",
")",
"manager",
".",
"validate",
"(",
"stub_path",
")",
"assert",
"manager",
".",
... | [
20,
0
] | [
26,
52
] | python | en | ['en', 'fil', 'en'] | True |
test_bad_stub_validation | (shared_datadir, mocker) | should fail validation | should fail validation | def test_bad_stub_validation(shared_datadir, mocker):
"""should fail validation"""
stub_path = shared_datadir / "esp8266_test_stub"
manager = stubs.StubManager()
mock_validate = mocker.patch.object(stubs.stubs.utils, "Validator")
mock_validate.return_value.validate.side_effect = [Exception, FileNotF... | [
"def",
"test_bad_stub_validation",
"(",
"shared_datadir",
",",
"mocker",
")",
":",
"stub_path",
"=",
"shared_datadir",
"/",
"\"esp8266_test_stub\"",
"manager",
"=",
"stubs",
".",
"StubManager",
"(",
")",
"mock_validate",
"=",
"mocker",
".",
"patch",
".",
"object",... | [
29,
0
] | [
38,
45
] | python | en | ['en', 'fil', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.