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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
TarIter.__next__ | (self) | Return the next item using TarFile's next() method.
When all members have been read, set TarFile as _loaded.
| Return the next item using TarFile's next() method.
When all members have been read, set TarFile as _loaded.
| def __next__(self):
"""Return the next item using TarFile's next() method.
When all members have been read, set TarFile as _loaded.
"""
# Fix for SF #1100429: Under rare circumstances it can
# happen that getmembers() is called during iteration,
# which will cause TarI... | [
"def",
"__next__",
"(",
"self",
")",
":",
"# Fix for SF #1100429: Under rare circumstances it can",
"# happen that getmembers() is called during iteration,",
"# which will cause TarIter to stop prematurely.",
"if",
"not",
"self",
".",
"tarfile",
".",
"_loaded",
":",
"tarinfo",
"=... | [
2569,
4
] | [
2587,
22
] | python | en | ['en', 'lt', 'en'] | True |
pack | (o, stream, **kwargs) |
Pack object `o` and write it to `stream`
See :class:`Packer` for options.
|
Pack object `o` and write it to `stream` | def pack(o, stream, **kwargs):
"""
Pack object `o` and write it to `stream`
See :class:`Packer` for options.
"""
packer = Packer(**kwargs)
stream.write(packer.pack(o)) | [
"def",
"pack",
"(",
"o",
",",
"stream",
",",
"*",
"*",
"kwargs",
")",
":",
"packer",
"=",
"Packer",
"(",
"*",
"*",
"kwargs",
")",
"stream",
".",
"write",
"(",
"packer",
".",
"pack",
"(",
"o",
")",
")"
] | [
18,
0
] | [
25,
32
] | python | en | ['en', 'error', 'th'] | False |
packb | (o, **kwargs) |
Pack object `o` and return packed bytes
See :class:`Packer` for options.
|
Pack object `o` and return packed bytes | def packb(o, **kwargs):
"""
Pack object `o` and return packed bytes
See :class:`Packer` for options.
"""
return Packer(**kwargs).pack(o) | [
"def",
"packb",
"(",
"o",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"Packer",
"(",
"*",
"*",
"kwargs",
")",
".",
"pack",
"(",
"o",
")"
] | [
28,
0
] | [
34,
35
] | python | en | ['en', 'error', 'th'] | False |
unpack | (stream, **kwargs) |
Unpack an object from `stream`.
Raises `ExtraData` when `stream` contains extra bytes.
See :class:`Unpacker` for options.
|
Unpack an object from `stream`. | def unpack(stream, **kwargs):
"""
Unpack an object from `stream`.
Raises `ExtraData` when `stream` contains extra bytes.
See :class:`Unpacker` for options.
"""
data = stream.read()
return unpackb(data, **kwargs) | [
"def",
"unpack",
"(",
"stream",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"stream",
".",
"read",
"(",
")",
"return",
"unpackb",
"(",
"data",
",",
"*",
"*",
"kwargs",
")"
] | [
37,
0
] | [
45,
34
] | python | en | ['en', 'error', 'th'] | False |
check_auth | (username, password) | This function is called to check if a username /
password combination is valid.
| This function is called to check if a username /
password combination is valid.
| def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
uname="myuser"
pwd="mypassword"
return username == uname and password == pwd | [
"def",
"check_auth",
"(",
"username",
",",
"password",
")",
":",
"uname",
"=",
"\"myuser\"",
"pwd",
"=",
"\"mypassword\"",
"return",
"username",
"==",
"uname",
"and",
"password",
"==",
"pwd"
] | [
19,
0
] | [
26,
48
] | python | en | ['en', 'en', 'en'] | True |
authenticate | () | Sends a 401 response that enables basic auth | Sends a 401 response that enables basic auth | def authenticate():
"""Sends a 401 response that enables basic auth"""
logging.info("inside authenticate")
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'}) | [
"def",
"authenticate",
"(",
")",
":",
"logging",
".",
"info",
"(",
"\"inside authenticate\"",
")",
"return",
"Response",
"(",
"'Could not verify your access level for that URL.\\n'",
"'You have to login with proper credentials'",
",",
"401",
",",
"{",
"'WWW-Authenticate'",
... | [
28,
0
] | [
34,
57
] | python | en | ['en', 'en', 'en'] | True |
dummy_constant_bed_cliff | (hmax=3000., hmin=1000., nx=200, map_dx=100.,
cliff_height=250.) |
I introduce a cliff in the bed to test the mass conservation of the models
Such a cliff could be real or a DEM error/artifact
|
I introduce a cliff in the bed to test the mass conservation of the models
Such a cliff could be real or a DEM error/artifact
| def dummy_constant_bed_cliff(hmax=3000., hmin=1000., nx=200, map_dx=100.,
cliff_height=250.):
"""
I introduce a cliff in the bed to test the mass conservation of the models
Such a cliff could be real or a DEM error/artifact
"""
dx = 1.
surface_h = np.linspace(hmax, ... | [
"def",
"dummy_constant_bed_cliff",
"(",
"hmax",
"=",
"3000.",
",",
"hmin",
"=",
"1000.",
",",
"nx",
"=",
"200",
",",
"map_dx",
"=",
"100.",
",",
"cliff_height",
"=",
"250.",
")",
":",
"dx",
"=",
"1.",
"surface_h",
"=",
"np",
".",
"linspace",
"(",
"hm... | [
37,
0
] | [
55,
59
] | python | en | ['en', 'error', 'th'] | False |
dummy_constant_bed_obstacle | (hmax=3000., hmin=1000., nx=200) |
I introduce an obstacle in the bed
|
I introduce an obstacle in the bed
| def dummy_constant_bed_obstacle(hmax=3000., hmin=1000., nx=200):
"""
I introduce an obstacle in the bed
"""
map_dx = 100.
dx = 1.
surface_h = np.linspace(hmax, hmin, nx)
cliff_height = 200.0
surface_h[60:] = surface_h[60:] + cliff_height
bed_h = surface_h
widths = surface_h *... | [
"def",
"dummy_constant_bed_obstacle",
"(",
"hmax",
"=",
"3000.",
",",
"hmin",
"=",
"1000.",
",",
"nx",
"=",
"200",
")",
":",
"map_dx",
"=",
"100.",
"dx",
"=",
"1.",
"surface_h",
"=",
"np",
".",
"linspace",
"(",
"hmax",
",",
"hmin",
",",
"nx",
")",
... | [
58,
0
] | [
77,
59
] | python | en | ['en', 'error', 'th'] | False |
dummy_width_bed | () | This bed has a width of 6 during the first 20 points and then 3 | This bed has a width of 6 during the first 20 points and then 3 | def dummy_width_bed():
"""This bed has a width of 6 during the first 20 points and then 3"""
map_dx = 100.
dx = 1.
nx = 200
surface_h = np.linspace(3000, 1000, nx)
bed_h = surface_h
widths = surface_h * 0. + 3.
widths[0:20] = 6.
coords = np.arange(0, nx - 0.5, 1)
line = shpg.L... | [
"def",
"dummy_width_bed",
"(",
")",
":",
"map_dx",
"=",
"100.",
"dx",
"=",
"1.",
"nx",
"=",
"200",
"surface_h",
"=",
"np",
".",
"linspace",
"(",
"3000",
",",
"1000",
",",
"nx",
")",
"bed_h",
"=",
"surface_h",
"widths",
"=",
"surface_h",
"*",
"0.",
... | [
179,
0
] | [
194,
59
] | python | en | ['en', 'en', 'en'] | True |
patch_minimal_download_oggm_files | (*args, **kwargs) | A simple patch to make sure we don't download. | A simple patch to make sure we don't download. | def patch_minimal_download_oggm_files(*args, **kwargs):
"""A simple patch to make sure we don't download."""
raise RuntimeError('We should not be there in minimal mode') | [
"def",
"patch_minimal_download_oggm_files",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"RuntimeError",
"(",
"'We should not be there in minimal mode'",
")"
] | [
292,
0
] | [
295,
64
] | python | en | ['en', 'en', 'en'] | True |
lookup_needs_distinct | (opts, lookup_path) |
Returns True if 'distinct()' should be used to query the given lookup path.
|
Returns True if 'distinct()' should be used to query the given lookup path.
| def lookup_needs_distinct(opts, lookup_path):
"""
Returns True if 'distinct()' should be used to query the given lookup path.
"""
lookup_fields = lookup_path.split(LOOKUP_SEP)
# Remove the last item of the lookup path if it is a query term
if lookup_fields[-1] in QUERY_TERMS:
lookup_fiel... | [
"def",
"lookup_needs_distinct",
"(",
"opts",
",",
"lookup_path",
")",
":",
"lookup_fields",
"=",
"lookup_path",
".",
"split",
"(",
"LOOKUP_SEP",
")",
"# Remove the last item of the lookup path if it is a query term",
"if",
"lookup_fields",
"[",
"-",
"1",
"]",
"in",
"Q... | [
28,
0
] | [
48,
16
] | python | en | ['en', 'error', 'th'] | False |
prepare_lookup_value | (key, value) |
Returns a lookup value prepared to be used in queryset filtering.
|
Returns a lookup value prepared to be used in queryset filtering.
| def prepare_lookup_value(key, value):
"""
Returns a lookup value prepared to be used in queryset filtering.
"""
# if key ends with __in, split parameter into separate values
if key.endswith('__in'):
value = value.split(',')
# if key ends with __isnull, special case '' and the string lite... | [
"def",
"prepare_lookup_value",
"(",
"key",
",",
"value",
")",
":",
"# if key ends with __in, split parameter into separate values",
"if",
"key",
".",
"endswith",
"(",
"'__in'",
")",
":",
"value",
"=",
"value",
".",
"split",
"(",
"','",
")",
"# if key ends with __isn... | [
51,
0
] | [
64,
16
] | python | en | ['en', 'error', 'th'] | False |
quote | (s) |
Ensure that primary key values do not confuse the admin URLs by escaping
any '/', '_' and ':' and similarly problematic characters.
Similar to urllib.quote, except that the quoting is slightly different so
that it doesn't get automatically unquoted by the Web browser.
|
Ensure that primary key values do not confuse the admin URLs by escaping
any '/', '_' and ':' and similarly problematic characters.
Similar to urllib.quote, except that the quoting is slightly different so
that it doesn't get automatically unquoted by the Web browser.
| def quote(s):
"""
Ensure that primary key values do not confuse the admin URLs by escaping
any '/', '_' and ':' and similarly problematic characters.
Similar to urllib.quote, except that the quoting is slightly different so
that it doesn't get automatically unquoted by the Web browser.
"""
i... | [
"def",
"quote",
"(",
"s",
")",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"six",
".",
"string_types",
")",
":",
"return",
"s",
"res",
"=",
"list",
"(",
"s",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"res",
")",
")",
":",
"c",
"=",
... | [
67,
0
] | [
81,
23
] | python | en | ['en', 'error', 'th'] | False |
unquote | (s) |
Undo the effects of quote(). Based heavily on urllib.unquote().
|
Undo the effects of quote(). Based heavily on urllib.unquote().
| def unquote(s):
"""
Undo the effects of quote(). Based heavily on urllib.unquote().
"""
mychr = chr
myatoi = int
list = s.split('_')
res = [list[0]]
myappend = res.append
del list[0]
for item in list:
if item[1:2]:
try:
myappend(mychr(myatoi(it... | [
"def",
"unquote",
"(",
"s",
")",
":",
"mychr",
"=",
"chr",
"myatoi",
"=",
"int",
"list",
"=",
"s",
".",
"split",
"(",
"'_'",
")",
"res",
"=",
"[",
"list",
"[",
"0",
"]",
"]",
"myappend",
"=",
"res",
".",
"append",
"del",
"list",
"[",
"0",
"]"... | [
84,
0
] | [
102,
23
] | python | en | ['en', 'error', 'th'] | False |
flatten | (fields) | Returns a list which is a single level of flattening of the
original list. | Returns a list which is a single level of flattening of the
original list. | def flatten(fields):
"""Returns a list which is a single level of flattening of the
original list."""
flat = []
for field in fields:
if isinstance(field, (list, tuple)):
flat.extend(field)
else:
flat.append(field)
return flat | [
"def",
"flatten",
"(",
"fields",
")",
":",
"flat",
"=",
"[",
"]",
"for",
"field",
"in",
"fields",
":",
"if",
"isinstance",
"(",
"field",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"flat",
".",
"extend",
"(",
"field",
")",
"else",
":",
"flat",... | [
105,
0
] | [
114,
15
] | python | en | ['en', 'en', 'en'] | True |
flatten_fieldsets | (fieldsets) | Returns a list of field names from an admin fieldsets structure. | Returns a list of field names from an admin fieldsets structure. | def flatten_fieldsets(fieldsets):
"""Returns a list of field names from an admin fieldsets structure."""
field_names = []
for name, opts in fieldsets:
field_names.extend(
flatten(opts['fields'])
)
return field_names | [
"def",
"flatten_fieldsets",
"(",
"fieldsets",
")",
":",
"field_names",
"=",
"[",
"]",
"for",
"name",
",",
"opts",
"in",
"fieldsets",
":",
"field_names",
".",
"extend",
"(",
"flatten",
"(",
"opts",
"[",
"'fields'",
"]",
")",
")",
"return",
"field_names"
] | [
117,
0
] | [
124,
22
] | python | en | ['en', 'en', 'en'] | True |
get_deleted_objects | (objs, opts, user, admin_site, using) |
Find all objects related to ``objs`` that should also be deleted. ``objs``
must be a homogeneous iterable of objects (e.g. a QuerySet).
Returns a nested list of strings suitable for display in the
template with the ``unordered_list`` filter.
|
Find all objects related to ``objs`` that should also be deleted. ``objs``
must be a homogeneous iterable of objects (e.g. a QuerySet). | def get_deleted_objects(objs, opts, user, admin_site, using):
"""
Find all objects related to ``objs`` that should also be deleted. ``objs``
must be a homogeneous iterable of objects (e.g. a QuerySet).
Returns a nested list of strings suitable for display in the
template with the ``unordered_list``... | [
"def",
"get_deleted_objects",
"(",
"objs",
",",
"opts",
",",
"user",
",",
"admin_site",
",",
"using",
")",
":",
"collector",
"=",
"NestedObjects",
"(",
"using",
"=",
"using",
")",
"collector",
".",
"collect",
"(",
"objs",
")",
"perms_needed",
"=",
"set",
... | [
127,
0
] | [
176,
58
] | python | en | ['en', 'error', 'th'] | False |
model_format_dict | (obj) |
Return a `dict` with keys 'verbose_name' and 'verbose_name_plural',
typically for use with string formatting.
`obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.
|
Return a `dict` with keys 'verbose_name' and 'verbose_name_plural',
typically for use with string formatting. | def model_format_dict(obj):
"""
Return a `dict` with keys 'verbose_name' and 'verbose_name_plural',
typically for use with string formatting.
`obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.
"""
if isinstance(obj, (models.Model, models.base.ModelBase)):
opts = ... | [
"def",
"model_format_dict",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"models",
".",
"Model",
",",
"models",
".",
"base",
".",
"ModelBase",
")",
")",
":",
"opts",
"=",
"obj",
".",
"_meta",
"elif",
"isinstance",
"(",
"obj",
",",
... | [
242,
0
] | [
258,
5
] | python | en | ['en', 'error', 'th'] | False |
model_ngettext | (obj, n=None) |
Return the appropriate `verbose_name` or `verbose_name_plural` value for
`obj` depending on the count `n`.
`obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.
If `obj` is a `QuerySet` instance, `n` is optional and the length of the
`QuerySet` is used.
|
Return the appropriate `verbose_name` or `verbose_name_plural` value for
`obj` depending on the count `n`. | def model_ngettext(obj, n=None):
"""
Return the appropriate `verbose_name` or `verbose_name_plural` value for
`obj` depending on the count `n`.
`obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance.
If `obj` is a `QuerySet` instance, `n` is optional and the length of the
`Qu... | [
"def",
"model_ngettext",
"(",
"obj",
",",
"n",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"models",
".",
"query",
".",
"QuerySet",
")",
":",
"if",
"n",
"is",
"None",
":",
"n",
"=",
"obj",
".",
"count",
"(",
")",
"obj",
"=",
"ob... | [
261,
0
] | [
276,
46
] | python | en | ['en', 'error', 'th'] | False |
_get_non_gfk_field | (opts, name) |
For historical reasons, the admin app relies on GenericForeignKeys as being
"not found" by get_field(). This could likely be cleaned up.
Reverse relations should also be excluded as these aren't attributes of the
model (rather something like `foo_set`).
|
For historical reasons, the admin app relies on GenericForeignKeys as being
"not found" by get_field(). This could likely be cleaned up. | def _get_non_gfk_field(opts, name):
"""
For historical reasons, the admin app relies on GenericForeignKeys as being
"not found" by get_field(). This could likely be cleaned up.
Reverse relations should also be excluded as these aren't attributes of the
model (rather something like `foo_set`).
"... | [
"def",
"_get_non_gfk_field",
"(",
"opts",
",",
"name",
")",
":",
"field",
"=",
"opts",
".",
"get_field",
"(",
"name",
")",
"if",
"(",
"field",
".",
"is_relation",
"and",
"# Generic foreign keys OR reverse relations",
"(",
"(",
"field",
".",
"many_to_one",
"and... | [
308,
0
] | [
326,
16
] | python | en | ['en', 'error', 'th'] | False |
label_for_field | (name, model, model_admin=None, return_attr=False) |
Returns a sensible label for a field name. The name can be a callable,
property (but not created with @property decorator) or the name of an
object's attribute, as well as a genuine fields. If return_attr is
True, the resolved attribute (which could be a callable) is also returned.
This will be Non... |
Returns a sensible label for a field name. The name can be a callable,
property (but not created with | def label_for_field(name, model, model_admin=None, return_attr=False):
"""
Returns a sensible label for a field name. The name can be a callable,
property (but not created with @property decorator) or the name of an
object's attribute, as well as a genuine fields. If return_attr is
True, the resolve... | [
"def",
"label_for_field",
"(",
"name",
",",
"model",
",",
"model_admin",
"=",
"None",
",",
"return_attr",
"=",
"False",
")",
":",
"attr",
"=",
"None",
"try",
":",
"field",
"=",
"_get_non_gfk_field",
"(",
"model",
".",
"_meta",
",",
"name",
")",
"try",
... | [
329,
0
] | [
385,
20
] | python | en | ['en', 'error', 'th'] | False |
reverse_field_path | (model, path) | Create a reversed field path.
E.g. Given (Order, "user__groups"),
return (Group, "user__order").
Final field must be a related model, not a data field.
| Create a reversed field path. | def reverse_field_path(model, path):
""" Create a reversed field path.
E.g. Given (Order, "user__groups"),
return (Group, "user__order").
Final field must be a related model, not a data field.
"""
reversed_path = []
parent = model
pieces = path.split(LOOKUP_SEP)
for piece in pieces... | [
"def",
"reverse_field_path",
"(",
"model",
",",
"path",
")",
":",
"reversed_path",
"=",
"[",
"]",
"parent",
"=",
"model",
"pieces",
"=",
"path",
".",
"split",
"(",
"LOOKUP_SEP",
")",
"for",
"piece",
"in",
"pieces",
":",
"field",
"=",
"parent",
".",
"_m... | [
455,
0
] | [
483,
51
] | python | en | ['en', 'co', 'en'] | True |
get_fields_from_path | (model, path) | Return list of Fields given path relative to model.
e.g. (ModelX, "user__groups__name") -> [
<django.db.models.fields.related.ForeignKey object at 0x...>,
<django.db.models.fields.related.ManyToManyField object at 0x...>,
<django.db.models.fields.CharField object at 0x...>,
]
| Return list of Fields given path relative to model. | def get_fields_from_path(model, path):
""" Return list of Fields given path relative to model.
e.g. (ModelX, "user__groups__name") -> [
<django.db.models.fields.related.ForeignKey object at 0x...>,
<django.db.models.fields.related.ManyToManyField object at 0x...>,
<django.db.models.fiel... | [
"def",
"get_fields_from_path",
"(",
"model",
",",
"path",
")",
":",
"pieces",
"=",
"path",
".",
"split",
"(",
"LOOKUP_SEP",
")",
"fields",
"=",
"[",
"]",
"for",
"piece",
"in",
"pieces",
":",
"if",
"fields",
":",
"parent",
"=",
"get_model_from_relation",
... | [
486,
0
] | [
503,
17
] | python | en | ['en', 'en', 'en'] | True |
construct_change_message | (form, formsets, add) |
Construct a JSON structure describing changes from a changed object.
Translations are deactivated so that strings are stored untranslated.
Translation happens later on LogEntry access.
|
Construct a JSON structure describing changes from a changed object.
Translations are deactivated so that strings are stored untranslated.
Translation happens later on LogEntry access.
| def construct_change_message(form, formsets, add):
"""
Construct a JSON structure describing changes from a changed object.
Translations are deactivated so that strings are stored untranslated.
Translation happens later on LogEntry access.
"""
change_message = []
if add:
change_messa... | [
"def",
"construct_change_message",
"(",
"form",
",",
"formsets",
",",
"add",
")",
":",
"change_message",
"=",
"[",
"]",
"if",
"add",
":",
"change_message",
".",
"append",
"(",
"{",
"'added'",
":",
"{",
"}",
"}",
")",
"elif",
"form",
".",
"changed_data",
... | [
506,
0
] | [
543,
25
] | python | en | ['en', 'error', 'th'] | False |
NestedObjects.nested | (self, format_callback=None) |
Return the graph as a nested list.
|
Return the graph as a nested list.
| def nested(self, format_callback=None):
"""
Return the graph as a nested list.
"""
seen = set()
roots = []
for root in self.edges.get(None, ()):
roots.extend(self._nested(root, seen, format_callback))
return roots | [
"def",
"nested",
"(",
"self",
",",
"format_callback",
"=",
"None",
")",
":",
"seen",
"=",
"set",
"(",
")",
"roots",
"=",
"[",
"]",
"for",
"root",
"in",
"self",
".",
"edges",
".",
"get",
"(",
"None",
",",
"(",
")",
")",
":",
"roots",
".",
"exten... | [
224,
4
] | [
232,
20
] | python | en | ['en', 'error', 'th'] | False |
NestedObjects.can_fast_delete | (self, *args, **kwargs) |
We always want to load the objects into memory so that we can display
them to the user in confirm page.
|
We always want to load the objects into memory so that we can display
them to the user in confirm page.
| def can_fast_delete(self, *args, **kwargs):
"""
We always want to load the objects into memory so that we can display
them to the user in confirm page.
"""
return False | [
"def",
"can_fast_delete",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"False"
] | [
234,
4
] | [
239,
20
] | python | en | ['en', 'error', 'th'] | False |
TestContextProcessor.test_accessing_setting | (self) | Check that the context processor works | Check that the context processor works | def test_accessing_setting(self):
""" Check that the context processor works """
request = self.get_request()
self.assertEqual(
self.render(request, '{{ settings.tests.TestSetting.title }}'),
self.default_site_settings.title) | [
"def",
"test_accessing_setting",
"(",
"self",
")",
":",
"request",
"=",
"self",
".",
"get_request",
"(",
")",
"self",
".",
"assertEqual",
"(",
"self",
".",
"render",
"(",
"request",
",",
"'{{ settings.tests.TestSetting.title }}'",
")",
",",
"self",
".",
"defau... | [
22,
4
] | [
27,
45
] | python | en | ['en', 'en', 'en'] | True |
TestContextProcessor.test_multisite | (self) | Check that the correct setting for the current site is returned | Check that the correct setting for the current site is returned | def test_multisite(self):
""" Check that the correct setting for the current site is returned """
request = self.get_request(site=self.default_site)
self.assertEqual(
self.render(request, '{{ settings.tests.TestSetting.title }}'),
self.default_site_settings.title)
... | [
"def",
"test_multisite",
"(",
"self",
")",
":",
"request",
"=",
"self",
".",
"get_request",
"(",
"site",
"=",
"self",
".",
"default_site",
")",
"self",
".",
"assertEqual",
"(",
"self",
".",
"render",
"(",
"request",
",",
"'{{ settings.tests.TestSetting.title }... | [
29,
4
] | [
39,
43
] | python | en | ['en', 'en', 'en'] | True |
TestContextProcessor.test_model_case_insensitive | (self) | Model names should be case insensitive | Model names should be case insensitive | def test_model_case_insensitive(self):
""" Model names should be case insensitive """
request = self.get_request()
self.assertEqual(
self.render(request, '{{ settings.tests.testsetting.title }}'),
self.default_site_settings.title)
self.assertEqual(
sel... | [
"def",
"test_model_case_insensitive",
"(",
"self",
")",
":",
"request",
"=",
"self",
".",
"get_request",
"(",
")",
"self",
".",
"assertEqual",
"(",
"self",
".",
"render",
"(",
"request",
",",
"'{{ settings.tests.testsetting.title }}'",
")",
",",
"self",
".",
"... | [
41,
4
] | [
55,
45
] | python | en | ['en', 'da', 'en'] | True |
TestContextProcessor.test_models_cached | (self) | Accessing a setting should only hit the DB once per request instance,
even if using that request to rendering multiple times | Accessing a setting should only hit the DB once per request instance,
even if using that request to rendering multiple times | def test_models_cached(self):
""" Accessing a setting should only hit the DB once per request instance,
even if using that request to rendering multiple times"""
request = self.get_request()
get_title = '{{ settings.tests.testsetting.title }}'
# force site query beforehand
... | [
"def",
"test_models_cached",
"(",
"self",
")",
":",
"request",
"=",
"self",
".",
"get_request",
"(",
")",
"get_title",
"=",
"'{{ settings.tests.testsetting.title }}'",
"# force site query beforehand",
"Site",
".",
"find_for_request",
"(",
"request",
")",
"with",
"self... | [
57,
4
] | [
72,
21
] | python | en | ['en', 'en', 'en'] | True |
TestTemplateTag.test_no_context_processor | (self) |
Assert that not running the context processor means settings are not in
the context, as expected.
|
Assert that not running the context processor means settings are not in
the context, as expected.
| def test_no_context_processor(self):
"""
Assert that not running the context processor means settings are not in
the context, as expected.
"""
template = Template('{{ settings.tests.TestSetting.title }}')
context = Context()
self.assertEqual(template.render(contex... | [
"def",
"test_no_context_processor",
"(",
"self",
")",
":",
"template",
"=",
"Template",
"(",
"'{{ settings.tests.TestSetting.title }}'",
")",
"context",
"=",
"Context",
"(",
")",
"self",
".",
"assertEqual",
"(",
"template",
".",
"render",
"(",
"context",
")",
",... | [
76,
4
] | [
83,
54
] | python | en | ['en', 'error', 'th'] | False |
TestTemplateTag.test_get_settings_request_context | (self) | Check that the {% get_settings %} tag works | Check that the {% get_settings %} tag works | def test_get_settings_request_context(self):
""" Check that the {% get_settings %} tag works """
request = self.get_request(site=self.other_site)
context = Context({'request': request})
# This should use the site in the request
template = Template('{% load wagtailsettings_tags %... | [
"def",
"test_get_settings_request_context",
"(",
"self",
")",
":",
"request",
"=",
"self",
".",
"get_request",
"(",
"site",
"=",
"self",
".",
"other_site",
")",
"context",
"=",
"Context",
"(",
"{",
"'request'",
":",
"request",
"}",
")",
"# This should use the ... | [
85,
4
] | [
95,
82
] | python | en | ['en', 'en', 'en'] | True |
TestTemplateTag.test_get_settings_request_context_use_default | (self) |
Check that the {% get_settings use_default_site=True %} option
overrides a request in the context.
|
Check that the {% get_settings use_default_site=True %} option
overrides a request in the context.
| def test_get_settings_request_context_use_default(self):
"""
Check that the {% get_settings use_default_site=True %} option
overrides a request in the context.
"""
request = self.get_request(site=self.other_site)
context = Context({'request': request})
# This sho... | [
"def",
"test_get_settings_request_context_use_default",
"(",
"self",
")",
":",
"request",
"=",
"self",
".",
"get_request",
"(",
"site",
"=",
"self",
".",
"other_site",
")",
"context",
"=",
"Context",
"(",
"{",
"'request'",
":",
"request",
"}",
")",
"# This sho... | [
97,
4
] | [
110,
84
] | python | en | ['en', 'error', 'th'] | False |
TestTemplateTag.test_get_settings_use_default | (self) |
Check that the {% get_settings use_default_site=True %} option works
|
Check that the {% get_settings use_default_site=True %} option works
| def test_get_settings_use_default(self):
"""
Check that the {% get_settings use_default_site=True %} option works
"""
context = Context()
# This should use the default site
template = Template('{% load wagtailsettings_tags %}'
'{% get_settings... | [
"def",
"test_get_settings_use_default",
"(",
"self",
")",
":",
"context",
"=",
"Context",
"(",
")",
"# This should use the default site",
"template",
"=",
"Template",
"(",
"'{% load wagtailsettings_tags %}'",
"'{% get_settings use_default_site=True %}'",
"'{{ settings.tests.tests... | [
112,
4
] | [
123,
84
] | python | en | ['en', 'error', 'th'] | False |
TestTemplateTag.test_get_settings_no_request_no_default | (self) |
Check that the {% get_settings %} throws an error if it can not find a
site to work with
|
Check that the {% get_settings %} throws an error if it can not find a
site to work with
| def test_get_settings_no_request_no_default(self):
"""
Check that the {% get_settings %} throws an error if it can not find a
site to work with
"""
context = Context()
# Without a request in the context, and without use_default_site, this
# should bail with an er... | [
"def",
"test_get_settings_no_request_no_default",
"(",
"self",
")",
":",
"context",
"=",
"Context",
"(",
")",
"# Without a request in the context, and without use_default_site, this",
"# should bail with an error",
"template",
"=",
"Template",
"(",
"'{% load wagtailsettings_tags %}... | [
125,
4
] | [
138,
36
] | python | en | ['en', 'error', 'th'] | False |
TestTemplateTag.test_get_settings_variable_assignment_request_context | (self) |
Check that assigning the setting to a context variable with
{% get_settings as wagtail_settings %} works.
|
Check that assigning the setting to a context variable with
{% get_settings as wagtail_settings %} works.
| def test_get_settings_variable_assignment_request_context(self):
"""
Check that assigning the setting to a context variable with
{% get_settings as wagtail_settings %} works.
"""
request = self.get_request(site=self.other_site)
context = Context({'request': request})
... | [
"def",
"test_get_settings_variable_assignment_request_context",
"(",
"self",
")",
":",
"request",
"=",
"self",
".",
"get_request",
"(",
"site",
"=",
"self",
".",
"other_site",
")",
"context",
"=",
"Context",
"(",
"{",
"'request'",
":",
"request",
"}",
")",
"te... | [
140,
4
] | [
157,
54
] | python | en | ['en', 'error', 'th'] | False |
TestTemplateTag.test_get_settings_variable_assigment_use_default | (self) |
Check that assigning the setting to a context variable with
{% get_settings use_default_site=True as wagtail_settings %} works.
|
Check that assigning the setting to a context variable with
{% get_settings use_default_site=True as wagtail_settings %} works.
| def test_get_settings_variable_assigment_use_default(self):
"""
Check that assigning the setting to a context variable with
{% get_settings use_default_site=True as wagtail_settings %} works.
"""
context = Context()
template = Template('{% load wagtailsettings_tags %}'
... | [
"def",
"test_get_settings_variable_assigment_use_default",
"(",
"self",
")",
":",
"context",
"=",
"Context",
"(",
")",
"template",
"=",
"Template",
"(",
"'{% load wagtailsettings_tags %}'",
"'{% get_settings use_default_site=True as wagtail_settings %}'",
"'{{ wagtail_settings.test... | [
159,
4
] | [
169,
84
] | python | en | ['en', 'error', 'th'] | False |
TestSettingsJinja.test_accessing_setting | (self) | Check that the context processor works | Check that the context processor works | def test_accessing_setting(self):
""" Check that the context processor works """
self.assertEqual(
self.render('{{ settings("tests.TestSetting").title }}'),
self.default_site_settings.title) | [
"def",
"test_accessing_setting",
"(",
"self",
")",
":",
"self",
".",
"assertEqual",
"(",
"self",
".",
"render",
"(",
"'{{ settings(\"tests.TestSetting\").title }}'",
")",
",",
"self",
".",
"default_site_settings",
".",
"title",
")"
] | [
196,
4
] | [
200,
45
] | python | en | ['en', 'en', 'en'] | True |
TestSettingsJinja.test_multisite | (self) | Check that the correct setting for the current site is returned | Check that the correct setting for the current site is returned | def test_multisite(self):
""" Check that the correct setting for the current site is returned """
context = {'site': self.default_site}
self.assertEqual(
self.render('{{ settings("tests.TestSetting").title }}', context),
self.default_site_settings.title)
context ... | [
"def",
"test_multisite",
"(",
"self",
")",
":",
"context",
"=",
"{",
"'site'",
":",
"self",
".",
"default_site",
"}",
"self",
".",
"assertEqual",
"(",
"self",
".",
"render",
"(",
"'{{ settings(\"tests.TestSetting\").title }}'",
",",
"context",
")",
",",
"self"... | [
202,
4
] | [
212,
43
] | python | en | ['en', 'en', 'en'] | True |
TestSettingsJinja.test_model_case_insensitive | (self) | Model names should be case insensitive | Model names should be case insensitive | def test_model_case_insensitive(self):
""" Model names should be case insensitive """
self.assertEqual(
self.render('{{ settings("tests.testsetting").title }}'),
self.default_site_settings.title)
self.assertEqual(
self.render('{{ settings("tests.TESTSETTING").... | [
"def",
"test_model_case_insensitive",
"(",
"self",
")",
":",
"self",
".",
"assertEqual",
"(",
"self",
".",
"render",
"(",
"'{{ settings(\"tests.testsetting\").title }}'",
")",
",",
"self",
".",
"default_site_settings",
".",
"title",
")",
"self",
".",
"assertEqual",
... | [
214,
4
] | [
227,
45
] | python | en | ['en', 'da', 'en'] | True |
TestSettingsJinja.test_models_cached | (self) | Accessing a setting should only hit the DB once per render | Accessing a setting should only hit the DB once per render | def test_models_cached(self):
""" Accessing a setting should only hit the DB once per render """
get_title = '{{ settings("tests.testsetting").title }}'
request = self.get_request()
# run extra query before hand
Site.find_for_request(request)
for i in range(1, 4):
... | [
"def",
"test_models_cached",
"(",
"self",
")",
":",
"get_title",
"=",
"'{{ settings(\"tests.testsetting\").title }}'",
"request",
"=",
"self",
".",
"get_request",
"(",
")",
"# run extra query before hand",
"Site",
".",
"find_for_request",
"(",
"request",
")",
"for",
"... | [
229,
4
] | [
243,
57
] | python | en | ['en', 'en', 'en'] | True |
TestSettingsJinja.test_settings_use_default_site_override | (self) |
Check that {{ settings(use_default_site=True) }} overrides a site in
the context.
|
Check that {{ settings(use_default_site=True) }} overrides a site in
the context.
| def test_settings_use_default_site_override(self):
"""
Check that {{ settings(use_default_site=True) }} overrides a site in
the context.
"""
request = self.get_request(site=self.other_site)
context = {'request': request}
# This should use the default site, ignori... | [
"def",
"test_settings_use_default_site_override",
"(",
"self",
")",
":",
"request",
"=",
"self",
".",
"get_request",
"(",
"site",
"=",
"self",
".",
"other_site",
")",
"context",
"=",
"{",
"'request'",
":",
"request",
"}",
"# This should use the default site, ignorin... | [
245,
4
] | [
258,
45
] | python | en | ['en', 'error', 'th'] | False |
TestSettingsJinja.test_settings_use_default_site | (self) |
Check that the {{ settings(use_default_site=True) }} option works with
no site in the context
|
Check that the {{ settings(use_default_site=True) }} option works with
no site in the context
| def test_settings_use_default_site(self):
"""
Check that the {{ settings(use_default_site=True) }} option works with
no site in the context
"""
context = {}
# This should use the default site
template = '{{ settings("tests.testsetting", use_default_site=True).tit... | [
"def",
"test_settings_use_default_site",
"(",
"self",
")",
":",
"context",
"=",
"{",
"}",
"# This should use the default site",
"template",
"=",
"'{{ settings(\"tests.testsetting\", use_default_site=True).title}}'",
"self",
".",
"assertEqual",
"(",
"self",
".",
"render",
"(... | [
260,
4
] | [
272,
45
] | python | en | ['en', 'error', 'th'] | False |
TestSettingsJinja.test_settings_no_request_no_use_default | (self) |
Check that {{ settings }} throws an error if it can not find a
site to work with
|
Check that {{ settings }} throws an error if it can not find a
site to work with
| def test_settings_no_request_no_use_default(self):
"""
Check that {{ settings }} throws an error if it can not find a
site to work with
"""
context = {}
# Without a request in the context, and without use_default_site, this
# should bail with an error
tem... | [
"def",
"test_settings_no_request_no_use_default",
"(",
"self",
")",
":",
"context",
"=",
"{",
"}",
"# Without a request in the context, and without use_default_site, this",
"# should bail with an error",
"template",
"=",
"'{{ settings(\"tests.testsetting\").title}}'",
"with",
"self",... | [
274,
4
] | [
285,
65
] | python | en | ['en', 'error', 'th'] | False |
_tree_hash | (node: SExp, precalculated: Set[bytes32]) |
Hash values in `precalculated` are presumed to have been hashed already.
|
Hash values in `precalculated` are presumed to have been hashed already.
| def _tree_hash(node: SExp, precalculated: Set[bytes32]) -> bytes32:
"""
Hash values in `precalculated` are presumed to have been hashed already.
"""
if node.listp():
left = _tree_hash(node.first(), precalculated)
right = _tree_hash(node.rest(), precalculated)
s = b"\2" + left + r... | [
"def",
"_tree_hash",
"(",
"node",
":",
"SExp",
",",
"precalculated",
":",
"Set",
"[",
"bytes32",
"]",
")",
"->",
"bytes32",
":",
"if",
"node",
".",
"listp",
"(",
")",
":",
"left",
"=",
"_tree_hash",
"(",
"node",
".",
"first",
"(",
")",
",",
"precal... | [
118,
0
] | [
131,
31
] | python | en | ['en', 'error', 'th'] | False |
Program.get_tree_hash | (self, *args: List[bytes32]) |
Any values in `args` that appear in the tree
are presumed to have been hashed already.
|
Any values in `args` that appear in the tree
are presumed to have been hashed already.
| def get_tree_hash(self, *args: List[bytes32]) -> bytes32:
"""
Any values in `args` that appear in the tree
are presumed to have been hashed already.
"""
return sha256_treehash(self, set(args)) | [
"def",
"get_tree_hash",
"(",
"self",
",",
"*",
"args",
":",
"List",
"[",
"bytes32",
"]",
")",
"->",
"bytes32",
":",
"return",
"sha256_treehash",
"(",
"self",
",",
"set",
"(",
"args",
")",
")"
] | [
64,
4
] | [
69,
47
] | python | en | ['en', 'error', 'th'] | False |
Program.as_atom_list | (self) |
Pretend `self` is a list of atoms. Return the corresponding
python list of atoms.
At each step, we always assume a node to be an atom or a pair.
If the assumption is wrong, we exit early. This way we never fail
and always return SOMETHING.
|
Pretend `self` is a list of atoms. Return the corresponding
python list of atoms. | def as_atom_list(self) -> List[bytes]:
"""
Pretend `self` is a list of atoms. Return the corresponding
python list of atoms.
At each step, we always assume a node to be an atom or a pair.
If the assumption is wrong, we exit early. This way we never fail
and always return... | [
"def",
"as_atom_list",
"(",
"self",
")",
"->",
"List",
"[",
"bytes",
"]",
":",
"items",
"=",
"[",
"]",
"obj",
"=",
"self",
"while",
"True",
":",
"pair",
"=",
"obj",
".",
"pair",
"if",
"pair",
"is",
"None",
":",
"break",
"atom",
"=",
"pair",
"[",
... | [
90,
4
] | [
110,
20
] | python | en | ['en', 'error', 'th'] | False |
SerializedProgram.get_tree_hash | (self, *args: List[bytes32]) |
Any values in `args` that appear in the tree
are presumed to have been hashed already.
|
Any values in `args` that appear in the tree
are presumed to have been hashed already.
| def get_tree_hash(self, *args: List[bytes32]) -> bytes32:
"""
Any values in `args` that appear in the tree
are presumed to have been hashed already.
"""
tmp = sexp_from_stream(io.BytesIO(self._buf), SExp.to)
return _tree_hash(tmp, set(args)) | [
"def",
"get_tree_hash",
"(",
"self",
",",
"*",
"args",
":",
"List",
"[",
"bytes32",
"]",
")",
"->",
"bytes32",
":",
"tmp",
"=",
"sexp_from_stream",
"(",
"io",
".",
"BytesIO",
"(",
"self",
".",
"_buf",
")",
",",
"SExp",
".",
"to",
")",
"return",
"_t... | [
181,
4
] | [
187,
41
] | python | en | ['en', 'error', 'th'] | False |
SearchScope.create | (
cls,
find_links, # type: List[str]
index_urls, # type: List[str]
) |
Create a SearchScope object after normalizing the `find_links`.
|
Create a SearchScope object after normalizing the `find_links`.
| def create(
cls,
find_links, # type: List[str]
index_urls, # type: List[str]
):
# type: (...) -> SearchScope
"""
Create a SearchScope object after normalizing the `find_links`.
"""
# Build find_links. If an argument starts with ~, it may be
#... | [
"def",
"create",
"(",
"cls",
",",
"find_links",
",",
"# type: List[str]",
"index_urls",
",",
"# type: List[str]",
")",
":",
"# type: (...) -> SearchScope",
"# Build find_links. If an argument starts with ~, it may be",
"# a local file relative to a home directory. So try normalizing",
... | [
29,
4
] | [
67,
9
] | python | en | ['en', 'error', 'th'] | False |
SearchScope.get_index_urls_locations | (self, project_name) | Returns the locations found via self.index_urls
Checks the url_name on the main (first in the list) index and
use this url_name to produce all locations
| Returns the locations found via self.index_urls | def get_index_urls_locations(self, project_name):
# type: (str) -> List[str]
"""Returns the locations found via self.index_urls
Checks the url_name on the main (first in the list) index and
use this url_name to produce all locations
"""
def mkurl_pypi_url(url):
... | [
"def",
"get_index_urls_locations",
"(",
"self",
",",
"project_name",
")",
":",
"# type: (str) -> List[str]",
"def",
"mkurl_pypi_url",
"(",
"url",
")",
":",
"# type: (str) -> str",
"loc",
"=",
"posixpath",
".",
"join",
"(",
"url",
",",
"urllib_parse",
".",
"quote",... | [
112,
4
] | [
134,
63
] | python | en | ['en', 'la', 'en'] | True |
_get_failure_view | () |
Returns the view to be used for CSRF rejections
|
Returns the view to be used for CSRF rejections
| def _get_failure_view():
"""
Returns the view to be used for CSRF rejections
"""
return get_callable(settings.CSRF_FAILURE_VIEW) | [
"def",
"_get_failure_view",
"(",
")",
":",
"return",
"get_callable",
"(",
"settings",
".",
"CSRF_FAILURE_VIEW",
")"
] | [
38,
0
] | [
42,
51
] | python | en | ['en', 'error', 'th'] | False |
_salt_cipher_secret | (secret) |
Given a secret (assumed to be a string of CSRF_ALLOWED_CHARS), generate a
token by adding a salt and using it to encrypt the secret.
|
Given a secret (assumed to be a string of CSRF_ALLOWED_CHARS), generate a
token by adding a salt and using it to encrypt the secret.
| def _salt_cipher_secret(secret):
"""
Given a secret (assumed to be a string of CSRF_ALLOWED_CHARS), generate a
token by adding a salt and using it to encrypt the secret.
"""
salt = _get_new_csrf_string()
chars = CSRF_ALLOWED_CHARS
pairs = zip((chars.index(x) for x in secret), (chars.index(x)... | [
"def",
"_salt_cipher_secret",
"(",
"secret",
")",
":",
"salt",
"=",
"_get_new_csrf_string",
"(",
")",
"chars",
"=",
"CSRF_ALLOWED_CHARS",
"pairs",
"=",
"zip",
"(",
"(",
"chars",
".",
"index",
"(",
"x",
")",
"for",
"x",
"in",
"secret",
")",
",",
"(",
"c... | [
49,
0
] | [
58,
24
] | python | en | ['en', 'error', 'th'] | False |
_unsalt_cipher_token | (token) |
Given a token (assumed to be a string of CSRF_ALLOWED_CHARS, of length
CSRF_TOKEN_LENGTH, and that its first half is a salt), use it to decrypt
the second half to produce the original secret.
|
Given a token (assumed to be a string of CSRF_ALLOWED_CHARS, of length
CSRF_TOKEN_LENGTH, and that its first half is a salt), use it to decrypt
the second half to produce the original secret.
| def _unsalt_cipher_token(token):
"""
Given a token (assumed to be a string of CSRF_ALLOWED_CHARS, of length
CSRF_TOKEN_LENGTH, and that its first half is a salt), use it to decrypt
the second half to produce the original secret.
"""
salt = token[:CSRF_SECRET_LENGTH]
token = token[CSRF_SECRET... | [
"def",
"_unsalt_cipher_token",
"(",
"token",
")",
":",
"salt",
"=",
"token",
"[",
":",
"CSRF_SECRET_LENGTH",
"]",
"token",
"=",
"token",
"[",
"CSRF_SECRET_LENGTH",
":",
"]",
"chars",
"=",
"CSRF_ALLOWED_CHARS",
"pairs",
"=",
"zip",
"(",
"(",
"chars",
".",
"... | [
61,
0
] | [
72,
17
] | python | en | ['en', 'error', 'th'] | False |
get_token | (request) |
Returns the CSRF token required for a POST form. The token is an
alphanumeric value. A new token is created if one is not already set.
A side effect of calling this function is to make the csrf_protect
decorator and the CsrfViewMiddleware add a CSRF cookie and a 'Vary: Cookie'
header to the outgoi... |
Returns the CSRF token required for a POST form. The token is an
alphanumeric value. A new token is created if one is not already set. | def get_token(request):
"""
Returns the CSRF token required for a POST form. The token is an
alphanumeric value. A new token is created if one is not already set.
A side effect of calling this function is to make the csrf_protect
decorator and the CsrfViewMiddleware add a CSRF cookie and a 'Vary: C... | [
"def",
"get_token",
"(",
"request",
")",
":",
"if",
"\"CSRF_COOKIE\"",
"not",
"in",
"request",
".",
"META",
":",
"csrf_secret",
"=",
"_get_new_csrf_string",
"(",
")",
"request",
".",
"META",
"[",
"\"CSRF_COOKIE\"",
"]",
"=",
"_salt_cipher_secret",
"(",
"csrf_s... | [
79,
0
] | [
95,
43
] | python | en | ['en', 'error', 'th'] | False |
rotate_token | (request) |
Changes the CSRF token in use for a request - should be done on login
for security purposes.
|
Changes the CSRF token in use for a request - should be done on login
for security purposes.
| def rotate_token(request):
"""
Changes the CSRF token in use for a request - should be done on login
for security purposes.
"""
request.META.update({
"CSRF_COOKIE_USED": True,
"CSRF_COOKIE": _get_new_csrf_token(),
})
request.csrf_cookie_needs_reset = True | [
"def",
"rotate_token",
"(",
"request",
")",
":",
"request",
".",
"META",
".",
"update",
"(",
"{",
"\"CSRF_COOKIE_USED\"",
":",
"True",
",",
"\"CSRF_COOKIE\"",
":",
"_get_new_csrf_token",
"(",
")",
",",
"}",
")",
"request",
".",
"csrf_cookie_needs_reset",
"=",
... | [
98,
0
] | [
107,
42
] | python | en | ['en', 'error', 'th'] | False |
newer | (source, target) | Return true if 'source' exists and is more recently modified than
'target', or if 'source' exists and 'target' doesn't. Return false if
both exist and 'target' is the same age or younger than 'source'.
Raise DistutilsFileError if 'source' does not exist.
| Return true if 'source' exists and is more recently modified than
'target', or if 'source' exists and 'target' doesn't. Return false if
both exist and 'target' is the same age or younger than 'source'.
Raise DistutilsFileError if 'source' does not exist.
| def newer (source, target):
"""Return true if 'source' exists and is more recently modified than
'target', or if 'source' exists and 'target' doesn't. Return false if
both exist and 'target' is the same age or younger than 'source'.
Raise DistutilsFileError if 'source' does not exist.
"""
if no... | [
"def",
"newer",
"(",
"source",
",",
"target",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"source",
")",
":",
"raise",
"DistutilsFileError",
"(",
"\"file '%s' does not exist\"",
"%",
"os",
".",
"path",
".",
"abspath",
"(",
"source",
")"... | [
10,
0
] | [
26,
26
] | python | en | ['en', 'en', 'en'] | True |
newer_pairwise | (sources, targets) | Walk two filename lists in parallel, testing if each source is newer
than its corresponding target. Return a pair of lists (sources,
targets) where source is newer than target, according to the semantics
of 'newer()'.
| Walk two filename lists in parallel, testing if each source is newer
than its corresponding target. Return a pair of lists (sources,
targets) where source is newer than target, according to the semantics
of 'newer()'.
| def newer_pairwise (sources, targets):
"""Walk two filename lists in parallel, testing if each source is newer
than its corresponding target. Return a pair of lists (sources,
targets) where source is newer than target, according to the semantics
of 'newer()'.
"""
if len(sources) != len(targets)... | [
"def",
"newer_pairwise",
"(",
"sources",
",",
"targets",
")",
":",
"if",
"len",
"(",
"sources",
")",
"!=",
"len",
"(",
"targets",
")",
":",
"raise",
"ValueError",
"(",
"\"'sources' and 'targets' must be same length\"",
")",
"# build a pair of lists (sources, targets) ... | [
31,
0
] | [
48,
33
] | python | en | ['en', 'en', 'en'] | True |
newer_group | (sources, target, missing='error') | Return true if 'target' is out-of-date with respect to any file
listed in 'sources'. In other words, if 'target' exists and is newer
than every file in 'sources', return false; otherwise return true.
'missing' controls what we do when a source file is missing; the
default ("error") is to blow up with a... | Return true if 'target' is out-of-date with respect to any file
listed in 'sources'. In other words, if 'target' exists and is newer
than every file in 'sources', return false; otherwise return true.
'missing' controls what we do when a source file is missing; the
default ("error") is to blow up with a... | def newer_group (sources, target, missing='error'):
"""Return true if 'target' is out-of-date with respect to any file
listed in 'sources'. In other words, if 'target' exists and is newer
than every file in 'sources', return false; otherwise return true.
'missing' controls what we do when a source file... | [
"def",
"newer_group",
"(",
"sources",
",",
"target",
",",
"missing",
"=",
"'error'",
")",
":",
"# If the target doesn't even exist, then it's definitely out-of-date.",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"target",
")",
":",
"return",
"1",
"# Otherw... | [
53,
0
] | [
89,
16
] | python | en | ['en', 'en', 'en'] | True |
temp_file | (suffix="", prefix="tmp", dir=None) | Creates temporary file, returns name of it. User is responsible for deleting the file | Creates temporary file, returns name of it. User is responsible for deleting the file | def temp_file(suffix="", prefix="tmp", dir=None):
""" Creates temporary file, returns name of it. User is responsible for deleting the file """
fd, fname = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir)
os.close(fd)
return fname | [
"def",
"temp_file",
"(",
"suffix",
"=",
"\"\"",
",",
"prefix",
"=",
"\"tmp\"",
",",
"dir",
"=",
"None",
")",
":",
"fd",
",",
"fname",
"=",
"tempfile",
".",
"mkstemp",
"(",
"suffix",
"=",
"suffix",
",",
"prefix",
"=",
"prefix",
",",
"dir",
"=",
"dir... | [
117,
0
] | [
121,
16
] | python | en | ['en', 'en', 'en'] | True |
simple_body_dict | (dic) | body dict must have just one level for sending with form params | body dict must have just one level for sending with form params | def simple_body_dict(dic):
""" body dict must have just one level for sending with form params"""
if isinstance(dic, dict):
for key in dic:
if not isinstance(dic[key], (str, numeric_types)):
return False
return True
return False | [
"def",
"simple_body_dict",
"(",
"dic",
")",
":",
"if",
"isinstance",
"(",
"dic",
",",
"dict",
")",
":",
"for",
"key",
"in",
"dic",
":",
"if",
"not",
"isinstance",
"(",
"dic",
"[",
"key",
"]",
",",
"(",
"str",
",",
"numeric_types",
")",
")",
":",
... | [
124,
0
] | [
131,
16
] | python | en | ['en', 'en', 'en'] | True |
get_full_path | (path, default=None, step_up=0) |
Function expands '~' and adds cwd to path if it's not absolute (relative)
Target doesn't have to exist
:param path:
:param default:
:param step_up:
:return:
|
Function expands '~' and adds cwd to path if it's not absolute (relative)
Target doesn't have to exist | def get_full_path(path, default=None, step_up=0):
"""
Function expands '~' and adds cwd to path if it's not absolute (relative)
Target doesn't have to exist
:param path:
:param default:
:param step_up:
:return:
"""
if not path:
return default
res = os.path.abspath(os.pa... | [
"def",
"get_full_path",
"(",
"path",
",",
"default",
"=",
"None",
",",
"step_up",
"=",
"0",
")",
":",
"if",
"not",
"path",
":",
"return",
"default",
"res",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"pat... | [
134,
0
] | [
150,
14
] | python | en | ['en', 'error', 'th'] | False |
run_once | (func) |
A decorator to run function only once
:type func: __builtin__.function
:return:
|
A decorator to run function only once | def run_once(func):
"""
A decorator to run function only once
:type func: __builtin__.function
:return:
"""
def wrapper(*args, **kwargs):
"""
:param kwargs:
:param args:
"""
if not wrapper.has_run:
wrapper.has_run = True
return fu... | [
"def",
"run_once",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"\n :param kwargs:\n :param args:\n \"\"\"",
"if",
"not",
"wrapper",
".",
"has_run",
":",
"wrapper",
".",
"has_run",
"=",
... | [
177,
0
] | [
195,
18
] | python | en | ['en', 'error', 'th'] | False |
dehumanize_time | (str_time) |
Convert value like 1d4h33m12s103ms into seconds
Also, incidentally translates strings like "inf" into float("inf")
:param str_time: string to convert
:return: float value in seconds
:raise TaurusInternalException: in case of unsupported unit
|
Convert value like 1d4h33m12s103ms into seconds | def dehumanize_time(str_time):
"""
Convert value like 1d4h33m12s103ms into seconds
Also, incidentally translates strings like "inf" into float("inf")
:param str_time: string to convert
:return: float value in seconds
:raise TaurusInternalException: in case of unsupported unit
"""
if no... | [
"def",
"dehumanize_time",
"(",
"str_time",
")",
":",
"if",
"not",
"str_time",
":",
"return",
"0",
"parser",
"=",
"re",
".",
"compile",
"(",
"r'([\\d\\.\\-infa]+)([a-zA-Z]*)'",
")",
"parts",
"=",
"parser",
".",
"findall",
"(",
"str",
"(",
"str_time",
")",
"... | [
208,
0
] | [
253,
17
] | python | en | ['en', 'error', 'th'] | False |
shell_exec | (args, cwd=None, stdout=PIPE, stderr=PIPE, stdin=PIPE, shell=False, env=None, pgrp=True) |
Wrapper for subprocess starting
|
Wrapper for subprocess starting | def shell_exec(args, cwd=None, stdout=PIPE, stderr=PIPE, stdin=PIPE, shell=False, env=None, pgrp=True):
"""
Wrapper for subprocess starting
"""
if stdout and not isinstance(stdout, (int, IOBase)):
LOG.warning("stdout is not IOBase: %s", stdout)
stdout = None
if stderr and not isins... | [
"def",
"shell_exec",
"(",
"args",
",",
"cwd",
"=",
"None",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"PIPE",
",",
"stdin",
"=",
"PIPE",
",",
"shell",
"=",
"False",
",",
"env",
"=",
"None",
",",
"pgrp",
"=",
"True",
")",
":",
"if",
"stdout",... | [
500,
0
] | [
535,
43
] | python | en | ['en', 'error', 'th'] | False |
ensure_is_dict | (container, key, sub_key) |
Ensure that dict item is dict, convert if needed
:type container: dict or list
:type key: basestring or int
:type sub_key: basestring
:return:
|
Ensure that dict item is dict, convert if needed | def ensure_is_dict(container, key, sub_key):
"""
Ensure that dict item is dict, convert if needed
:type container: dict or list
:type key: basestring or int
:type sub_key: basestring
:return:
"""
if isinstance(container, BetterDict):
container.get(key, force_set=True)
elif i... | [
"def",
"ensure_is_dict",
"(",
"container",
",",
"key",
",",
"sub_key",
")",
":",
"if",
"isinstance",
"(",
"container",
",",
"BetterDict",
")",
":",
"container",
".",
"get",
"(",
"key",
",",
"force_set",
"=",
"True",
")",
"elif",
"isinstance",
"(",
"conta... | [
741,
0
] | [
758,
25
] | python | en | ['en', 'error', 'th'] | False |
to_json | (obj, indent=True) |
Convert object into indented json
:param indent: whether to generate indented JSON
:param obj: object to convert
:return:
|
Convert object into indented json | def to_json(obj, indent=True):
"""
Convert object into indented json
:param indent: whether to generate indented JSON
:param obj: object to convert
:return:
"""
# NOTE: you can set allow_nan=False to fail when serializing NaN/Infinity
return json.dumps(obj, indent=indent, cls=ComplexEnc... | [
"def",
"to_json",
"(",
"obj",
",",
"indent",
"=",
"True",
")",
":",
"# NOTE: you can set allow_nan=False to fail when serializing NaN/Infinity",
"return",
"json",
".",
"dumps",
"(",
"obj",
",",
"indent",
"=",
"indent",
",",
"cls",
"=",
"ComplexEncoder",
")"
] | [
864,
0
] | [
873,
61
] | python | en | ['en', 'error', 'th'] | False |
humanize_time | (secs) |
taken from http://testingreflections.com/node/6534
:param secs:
:return:
|
taken from http://testingreflections.com/node/6534 | def humanize_time(secs):
"""
taken from http://testingreflections.com/node/6534
:param secs:
:return:
"""
mins, secs = divmod(secs, 60)
hours, mins = divmod(mins, 60)
return '%02d:%02d:%02d' % (hours, mins, secs) | [
"def",
"humanize_time",
"(",
"secs",
")",
":",
"mins",
",",
"secs",
"=",
"divmod",
"(",
"secs",
",",
"60",
")",
"hours",
",",
"mins",
"=",
"divmod",
"(",
"mins",
",",
"60",
")",
"return",
"'%02d:%02d:%02d'",
"%",
"(",
"hours",
",",
"mins",
",",
"se... | [
948,
0
] | [
957,
49
] | python | en | ['en', 'error', 'th'] | False |
guess_csv_dialect | (header, force_doublequote=False) | completely arbitrary fn to detect the delimiter
:param force_doublequote: bool
:type header: str
:rtype: csv.Dialect
| completely arbitrary fn to detect the delimiter | def guess_csv_dialect(header, force_doublequote=False):
""" completely arbitrary fn to detect the delimiter
:param force_doublequote: bool
:type header: str
:rtype: csv.Dialect
"""
possible_delims = ",;\t"
dialect = csv.Sniffer().sniff(header, delimiters=possible_delims)
if force_doubl... | [
"def",
"guess_csv_dialect",
"(",
"header",
",",
"force_doublequote",
"=",
"False",
")",
":",
"possible_delims",
"=",
"\",;\\t\"",
"dialect",
"=",
"csv",
".",
"Sniffer",
"(",
")",
".",
"sniff",
"(",
"header",
",",
"delimiters",
"=",
"possible_delims",
")",
"i... | [
960,
0
] | [
972,
18
] | python | en | ['en', 'en', 'en'] | True |
load_class | (full_name) |
Load class by its full name like bzt.cli.CLI
:type full_name: str
:return:
:rtype: callable
|
Load class by its full name like bzt.cli.CLI | def load_class(full_name):
"""
Load class by its full name like bzt.cli.CLI
:type full_name: str
:return:
:rtype: callable
"""
module_name = full_name[:full_name.rfind('.')]
class_name = full_name[full_name.rfind('.') + 1:]
LOG.debug("Importing module: %s", module_name)
module =... | [
"def",
"load_class",
"(",
"full_name",
")",
":",
"module_name",
"=",
"full_name",
"[",
":",
"full_name",
".",
"rfind",
"(",
"'.'",
")",
"]",
"class_name",
"=",
"full_name",
"[",
"full_name",
".",
"rfind",
"(",
"'.'",
")",
"+",
"1",
":",
"]",
"LOG",
"... | [
975,
0
] | [
991,
38
] | python | en | ['en', 'error', 'th'] | False |
unzip | (source_filename, dest_dir, rel_path=None) |
:param source_filename:
:param dest_dir:
:param rel_path:
:return:
|
:param source_filename:
:param dest_dir:
:param rel_path:
:return:
| def unzip(source_filename, dest_dir, rel_path=None):
"""
:param source_filename:
:param dest_dir:
:param rel_path:
:return:
"""
LOG.debug("Extracting %s to %s", source_filename, dest_dir)
with zipfile.ZipFile(source_filename) as zfd:
for member in zfd.infolist():
if ... | [
"def",
"unzip",
"(",
"source_filename",
",",
"dest_dir",
",",
"rel_path",
"=",
"None",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Extracting %s to %s\"",
",",
"source_filename",
",",
"dest_dir",
")",
"with",
"zipfile",
".",
"ZipFile",
"(",
"source_filename",
")",
... | [
994,
0
] | [
1018,
41
] | python | en | ['en', 'error', 'th'] | False |
make_boundary | (text=None) |
Generate boundary id
:param text:
:return:
|
Generate boundary id
:param text:
:return:
| def make_boundary(text=None):
"""
Generate boundary id
:param text:
:return:
"""
_width = len(repr(sys.maxsize - 1))
_fmt = '%%0%dd' % _width
token = random.randrange(sys.maxsize)
boundary = ('=' * 15) + (_fmt % token) + '=='
if text is None:
return boundary
bnd = bou... | [
"def",
"make_boundary",
"(",
"text",
"=",
"None",
")",
":",
"_width",
"=",
"len",
"(",
"repr",
"(",
"sys",
".",
"maxsize",
"-",
"1",
")",
")",
"_fmt",
"=",
"'%%0%dd'",
"%",
"_width",
"token",
"=",
"random",
".",
"randrange",
"(",
"sys",
".",
"maxsi... | [
1036,
0
] | [
1056,
14
] | python | en | ['en', 'error', 'th'] | False |
is_int | (str_val) |
Check if str_val is int type
:param str_val: str
:return: bool
|
Check if str_val is int type
:param str_val: str
:return: bool
| def is_int(str_val):
"""
Check if str_val is int type
:param str_val: str
:return: bool
"""
if str_val.startswith('-') and str_val[1:].isdigit():
return True
elif str_val.isdigit():
return True
else:
return False | [
"def",
"is_int",
"(",
"str_val",
")",
":",
"if",
"str_val",
".",
"startswith",
"(",
"'-'",
")",
"and",
"str_val",
"[",
"1",
":",
"]",
".",
"isdigit",
"(",
")",
":",
"return",
"True",
"elif",
"str_val",
".",
"isdigit",
"(",
")",
":",
"return",
"True... | [
1059,
0
] | [
1070,
20
] | python | en | ['en', 'error', 'th'] | False |
log_std_streams | (logger=None, stdout_level=logging.DEBUG, stderr_level=logging.DEBUG) |
redirect standard output/error to taurus logger
|
redirect standard output/error to taurus logger
| def log_std_streams(logger=None, stdout_level=logging.DEBUG, stderr_level=logging.DEBUG):
"""
redirect standard output/error to taurus logger
"""
out_descriptor = os.dup(1)
err_descriptor = os.dup(2)
stdout = tempfile.SpooledTemporaryFile(mode='w+')
stderr = tempfile.SpooledTemporaryFile(mod... | [
"def",
"log_std_streams",
"(",
"logger",
"=",
"None",
",",
"stdout_level",
"=",
"logging",
".",
"DEBUG",
",",
"stderr_level",
"=",
"logging",
".",
"DEBUG",
")",
":",
"out_descriptor",
"=",
"os",
".",
"dup",
"(",
"1",
")",
"err_descriptor",
"=",
"os",
"."... | [
1523,
0
] | [
1554,
65
] | python | en | ['en', 'error', 'th'] | False |
str_representer | (dumper, data) | Representer for PyYAML that dumps multiline strings as | scalars | Representer for PyYAML that dumps multiline strings as | scalars | def str_representer(dumper, data):
""" Representer for PyYAML that dumps multiline strings as | scalars """
if len(data.splitlines()) > 1:
return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')
return dumper.represent_scalar('tag:yaml.org,2002:str', data) | [
"def",
"str_representer",
"(",
"dumper",
",",
"data",
")",
":",
"if",
"len",
"(",
"data",
".",
"splitlines",
"(",
")",
")",
">",
"1",
":",
"return",
"dumper",
".",
"represent_scalar",
"(",
"'tag:yaml.org,2002:str'",
",",
"data",
",",
"style",
"=",
"'|'",... | [
1692,
0
] | [
1696,
65
] | python | en | ['en', 'en', 'en'] | True |
get_host_ips | (filter_loopbacks=True) |
Returns a list of all IP addresses assigned to this host.
:param filter_loopbacks: filter out loopback addresses
|
Returns a list of all IP addresses assigned to this host. | def get_host_ips(filter_loopbacks=True):
"""
Returns a list of all IP addresses assigned to this host.
:param filter_loopbacks: filter out loopback addresses
"""
ips = []
for _, interfaces in iteritems(psutil.net_if_addrs()):
for iface in interfaces:
addr = str(iface.address... | [
"def",
"get_host_ips",
"(",
"filter_loopbacks",
"=",
"True",
")",
":",
"ips",
"=",
"[",
"]",
"for",
"_",
",",
"interfaces",
"in",
"iteritems",
"(",
"psutil",
".",
"net_if_addrs",
"(",
")",
")",
":",
"for",
"iface",
"in",
"interfaces",
":",
"addr",
"=",... | [
1733,
0
] | [
1750,
14
] | python | en | ['en', 'error', 'th'] | False |
get_assembled_value | (configs, key, protect=False) |
Joins values from several configs, "the last is the most important" (strings, lists or dictionaries).
:param configs: list of dicts with target configs
:param key: name of target config
:param protect: use safely, make deepcopy
|
Joins values from several configs, "the last is the most important" (strings, lists or dictionaries). | def get_assembled_value(configs, key, protect=False):
"""
Joins values from several configs, "the last is the most important" (strings, lists or dictionaries).
:param configs: list of dicts with target configs
:param key: name of target config
:param protect: use safely, make deepcopy
"""
t... | [
"def",
"get_assembled_value",
"(",
"configs",
",",
"key",
",",
"protect",
"=",
"False",
")",
":",
"target_configs",
"=",
"[",
"]",
"for",
"config",
"in",
"configs",
":",
"target_config",
"=",
"config",
".",
"get",
"(",
"key",
")",
"if",
"target_config",
... | [
1770,
0
] | [
1802,
14
] | python | en | ['en', 'error', 'th'] | False |
BetterDict.from_dict | (cls, orig) |
# https://stackoverflow.com/questions/50013768/how-can-i-convert-nested-dictionary-to-defaultdict/50013806
|
# https://stackoverflow.com/questions/50013768/how-can-i-convert-nested-dictionary-to-defaultdict/50013806
| def from_dict(cls, orig):
"""
# https://stackoverflow.com/questions/50013768/how-can-i-convert-nested-dictionary-to-defaultdict/50013806
"""
if isinstance(orig, dict):
return cls(lambda: None, {k: cls.from_dict(v) for k, v in orig.items()})
elif isinstance(orig, list)... | [
"def",
"from_dict",
"(",
"cls",
",",
"orig",
")",
":",
"if",
"isinstance",
"(",
"orig",
",",
"dict",
")",
":",
"return",
"cls",
"(",
"lambda",
":",
"None",
",",
"{",
"k",
":",
"cls",
".",
"from_dict",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
... | [
296,
4
] | [
305,
23
] | python | en | ['en', 'error', 'th'] | False |
BetterDict.get | (self, key, default=defaultdict, force_set=False) |
Change get with setdefault
:param force_set:
:type key: object
:type default: object
|
Change get with setdefault | def get(self, key, default=defaultdict, force_set=False):
"""
Change get with setdefault
:param force_set:
:type key: object
:type default: object
"""
if default == defaultdict:
default = BetterDict()
if isinstance(default, BaseException) and... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"defaultdict",
",",
"force_set",
"=",
"False",
")",
":",
"if",
"default",
"==",
"defaultdict",
":",
"default",
"=",
"BetterDict",
"(",
")",
"if",
"isinstance",
"(",
"default",
",",
"BaseExceptio... | [
307,
4
] | [
326,
20
] | python | en | ['en', 'error', 'th'] | False |
BetterDict.merge | (self, src) |
Deep merge other dict into current
:type src: dict
|
Deep merge other dict into current
:type src: dict
| def merge(self, src):
"""
Deep merge other dict into current
:type src: dict
"""
if not isinstance(src, dict):
raise TaurusInternalException("Loaded object is not dict [%s]: %s" % (src.__class__, src))
for key, val in iteritems(src):
prefix = ""... | [
"def",
"merge",
"(",
"self",
",",
"src",
")",
":",
"if",
"not",
"isinstance",
"(",
"src",
",",
"dict",
")",
":",
"raise",
"TaurusInternalException",
"(",
"\"Loaded object is not dict [%s]: %s\"",
"%",
"(",
"src",
".",
"__class__",
",",
"src",
")",
")",
"fo... | [
328,
4
] | [
360,
19
] | python | en | ['en', 'error', 'th'] | False |
BetterDict.__ensure_list_type | (self, values) |
Ensure that values is a list, convert if needed
:param values: dict or list
:return:
|
Ensure that values is a list, convert if needed
:param values: dict or list
:return:
| def __ensure_list_type(self, values):
"""
Ensure that values is a list, convert if needed
:param values: dict or list
:return:
"""
for idx, obj in enumerate(values):
if isinstance(obj, dict):
values[idx] = BetterDict.from_dict(obj)
... | [
"def",
"__ensure_list_type",
"(",
"self",
",",
"values",
")",
":",
"for",
"idx",
",",
"obj",
"in",
"enumerate",
"(",
"values",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"values",
"[",
"idx",
"]",
"=",
"BetterDict",
".",
"from_d... | [
398,
4
] | [
408,
44
] | python | en | ['en', 'error', 'th'] | False |
BetterDict.traverse | (cls, obj, visitor) |
Deep traverse dict with visitor. If visitor returns any value, don't traverse into
:type obj: list or dict or object
:type visitor: callable
|
Deep traverse dict with visitor. If visitor returns any value, don't traverse into | def traverse(cls, obj, visitor):
"""
Deep traverse dict with visitor. If visitor returns any value, don't traverse into
:type obj: list or dict or object
:type visitor: callable
"""
if isinstance(obj, dict):
for key, val in iteritems(obj):
if ... | [
"def",
"traverse",
"(",
"cls",
",",
"obj",
",",
"visitor",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"for",
"key",
",",
"val",
"in",
"iteritems",
"(",
"obj",
")",
":",
"if",
"not",
"visitor",
"(",
"val",
",",
"key",
",",
... | [
411,
4
] | [
425,
51
] | python | en | ['en', 'error', 'th'] | False |
TaurusCalledProcessError.__init__ | (self, *args, **kwargs) | join output and stderr for compatibility | join output and stderr for compatibility | def __init__(self, *args, **kwargs):
""" join output and stderr for compatibility """
output = ""
if "output" in kwargs:
output += u"\n>>> {out_start} >>>\n{out}\n<<< {out_end} <<<\n".format(
out_start="START OF STDOUT", out=kwargs["output"], out_end="END OF STDOUT")
... | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"output",
"=",
"\"\"",
"if",
"\"output\"",
"in",
"kwargs",
":",
"output",
"+=",
"u\"\\n>>> {out_start} >>>\\n{out}\\n<<< {out_end} <<<\\n\"",
".",
"format",
"(",
"out_start",
... | [
465,
4
] | [
479,
71
] | python | en | ['en', 'en', 'en'] | True |
Environment._set | (self, env) |
:type env: dict
|
:type env: dict
| def _set(self, env):
"""
:type env: dict
"""
for key in env:
key = str(key)
val = env[key]
if is_windows():
key = key.upper()
if key in self.data:
if val is None:
self.log.debug("Remove ... | [
"def",
"_set",
"(",
"self",
",",
"env",
")",
":",
"for",
"key",
"in",
"env",
":",
"key",
"=",
"str",
"(",
"key",
")",
"val",
"=",
"env",
"[",
"key",
"]",
"if",
"is_windows",
"(",
")",
":",
"key",
"=",
"key",
".",
"upper",
"(",
")",
"if",
"k... | [
569,
4
] | [
588,
55
] | python | en | ['en', 'error', 'th'] | False |
MultiPartForm.get_content_type | (self) | returns content type | returns content type | def get_content_type(self):
""" returns content type """
return 'multipart/form-data; boundary=%s' % self.boundary | [
"def",
"get_content_type",
"(",
"self",
")",
":",
"return",
"'multipart/form-data; boundary=%s'",
"%",
"self",
".",
"boundary"
] | [
775,
4
] | [
777,
65
] | python | en | ['fr', 'la', 'en'] | False |
MultiPartForm.add_field | (self, name, value) |
Add a simple field to the form data.
:type name: str
:type value: str
|
Add a simple field to the form data.
:type name: str
:type value: str
| def add_field(self, name, value):
"""
Add a simple field to the form data.
:type name: str
:type value: str
"""
self.form_fields.append((name, value)) | [
"def",
"add_field",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"self",
".",
"form_fields",
".",
"append",
"(",
"(",
"name",
",",
"value",
")",
")"
] | [
779,
4
] | [
785,
46
] | python | en | ['en', 'error', 'th'] | False |
MultiPartForm.add_file_as_string | (self, fieldname, filename, body, mimetype=None) | add raw string file
:type fieldname: str
:type filename: str
:type body: str | bytes
:type mimetype: str
| add raw string file
:type fieldname: str
:type filename: str
:type body: str | bytes
:type mimetype: str
| def add_file_as_string(self, fieldname, filename, body, mimetype=None):
""" add raw string file
:type fieldname: str
:type filename: str
:type body: str | bytes
:type mimetype: str
"""
default = 'application/octet-stream'
if mimetype is None:
m... | [
"def",
"add_file_as_string",
"(",
"self",
",",
"fieldname",
",",
"filename",
",",
"body",
",",
"mimetype",
"=",
"None",
")",
":",
"default",
"=",
"'application/octet-stream'",
"if",
"mimetype",
"is",
"None",
":",
"mimetype",
"=",
"mimetypes",
".",
"guess_type"... | [
787,
4
] | [
798,
64
] | python | cy | ['pl', 'cy', 'en'] | False |
MultiPartForm.add_file | (self, fieldname, filename, file_handle=None, mimetype=None) | Add a file to be uploaded.
:type mimetype: str
:type file_handle: file
:type filename: str
:type fieldname: str
| Add a file to be uploaded.
:type mimetype: str
:type file_handle: file
:type filename: str
:type fieldname: str
| def add_file(self, fieldname, filename, file_handle=None, mimetype=None):
"""Add a file to be uploaded.
:type mimetype: str
:type file_handle: file
:type filename: str
:type fieldname: str
"""
if not file_handle:
with open(filename, 'rb') as fds:
... | [
"def",
"add_file",
"(",
"self",
",",
"fieldname",
",",
"filename",
",",
"file_handle",
"=",
"None",
",",
"mimetype",
"=",
"None",
")",
":",
"if",
"not",
"file_handle",
":",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"fds",
":",
"body",
... | [
800,
4
] | [
814,
68
] | python | en | ['en', 'en', 'en'] | True |
MultiPartForm.__convert_to_list | (self) | Return a string representing the form, including attached files. | Return a string representing the form, including attached files. | def __convert_to_list(self):
"""Return a string representing the form, including attached files."""
# Build a list of lists, each containing "lines" of the
# request. Each part is separated by a boundary string.
# Once the list is built, return a string where each
# line is sepa... | [
"def",
"__convert_to_list",
"(",
"self",
")",
":",
"# Build a list of lists, each containing \"lines\" of the",
"# request. Each part is separated by a boundary string.",
"# Once the list is built, return a string where each",
"# line is separated by '\\r\\n'.",
"parts",
"=",
"[",
"]",
... | [
816,
4
] | [
843,
24
] | python | en | ['en', 'en', 'en'] | True |
MultiPartForm.form_as_bytes | (self) |
represents form contents as bytes
|
represents form contents as bytes
| def form_as_bytes(self):
"""
represents form contents as bytes
"""
result_list = []
for item in self.__convert_to_list():
# if (bytes (3.x), then no processing, just add, else - encode)
if isinstance(item, bytes):
result_list.append(item)
... | [
"def",
"form_as_bytes",
"(",
"self",
")",
":",
"result_list",
"=",
"[",
"]",
"for",
"item",
"in",
"self",
".",
"__convert_to_list",
"(",
")",
":",
"# if (bytes (3.x), then no processing, just add, else - encode)",
"if",
"isinstance",
"(",
"item",
",",
"bytes",
")"... | [
845,
4
] | [
861,
24
] | python | en | ['en', 'error', 'th'] | False |
JSONConvertible.__json__ | (self) | Convert class instance into JSON-dumpable structure (e.g. dict) | Convert class instance into JSON-dumpable structure (e.g. dict) | def __json__(self):
"Convert class instance into JSON-dumpable structure (e.g. dict)"
pass | [
"def",
"__json__",
"(",
"self",
")",
":",
"pass"
] | [
885,
4
] | [
887,
12
] | python | en | ['en', 'fr', 'en'] | True |
ComplexEncoder.default | (self, obj) |
Filters out protected and private fields
:param obj:
:return:
|
Filters out protected and private fields | def default(self, obj): # pylint: disable=method-hidden
"""
Filters out protected and private fields
:param obj:
:return:
"""
if self.__dumpable(obj):
res = {}
for key, val in iteritems(obj.__dict__):
if not self.__dumpable(val):... | [
"def",
"default",
"(",
"self",
",",
"obj",
")",
":",
"# pylint: disable=method-hidden",
"if",
"self",
".",
"__dumpable",
"(",
"obj",
")",
":",
"res",
"=",
"{",
"}",
"for",
"key",
",",
"val",
"in",
"iteritems",
"(",
"obj",
".",
"__dict__",
")",
":",
"... | [
897,
4
] | [
920,
23
] | python | en | ['en', 'error', 'th'] | False |
ComplexEncoder.__dumpable | (cls, obj) |
Re
:param obj:
:rtype: bool
|
Re | def __dumpable(cls, obj):
"""
Re
:param obj:
:rtype: bool
"""
dumpable_types = tuple(cls.TYPES + (JSONDumpable,))
return isinstance(obj, dumpable_types) | [
"def",
"__dumpable",
"(",
"cls",
",",
"obj",
")",
":",
"dumpable_types",
"=",
"tuple",
"(",
"cls",
".",
"TYPES",
"+",
"(",
"JSONDumpable",
",",
")",
")",
"return",
"isinstance",
"(",
"obj",
",",
"dumpable_types",
")"
] | [
923,
4
] | [
931,
46
] | python | en | ['en', 'error', 'th'] | False |
ComplexEncoder.of_basic_type | (cls, val) |
Returns true if val is of basic type
:param val:
:return:
|
Returns true if val is of basic type | def of_basic_type(cls, val):
"""
Returns true if val is of basic type
:param val:
:return:
"""
return isinstance(val, cls.TYPES) | [
"def",
"of_basic_type",
"(",
"cls",
",",
"val",
")",
":",
"return",
"isinstance",
"(",
"val",
",",
"cls",
".",
"TYPES",
")"
] | [
938,
4
] | [
945,
41
] | python | en | ['en', 'error', 'th'] | False |
LocalFileAdapter._chkpath | (method, path) | Return an HTTP status for the given filesystem path. | Return an HTTP status for the given filesystem path. | def _chkpath(method, path):
"""Return an HTTP status for the given filesystem path."""
if method.lower() in ('put', 'delete'):
return 501, "Not Implemented" # TODO
elif method.lower() not in ('get', 'head'):
return 405, "Method Not Allowed"
elif os.path.isdir(pat... | [
"def",
"_chkpath",
"(",
"method",
",",
"path",
")",
":",
"if",
"method",
".",
"lower",
"(",
")",
"in",
"(",
"'put'",
",",
"'delete'",
")",
":",
"return",
"501",
",",
"\"Not Implemented\"",
"# TODO",
"elif",
"method",
".",
"lower",
"(",
")",
"not",
"i... | [
1101,
4
] | [
1114,
28
] | python | en | ['en', 'en', 'en'] | True |
LocalFileAdapter.send | (self, req, **kwargs) | Return the file specified by the given request
| Return the file specified by the given request
| def send(self, req, **kwargs): # pylint: disable=unused-argument
"""Return the file specified by the given request
"""
path = os.path.normcase(os.path.normpath(url2pathname(req.path_url)))
response = requests.Response()
response.status_code, response.reason = self._chkpath(req.... | [
"def",
"send",
"(",
"self",
",",
"req",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"path",
"=",
"os",
".",
"path",
".",
"normcase",
"(",
"os",
".",
"path",
".",
"normpath",
"(",
"url2pathname",
"(",
"req",
".",
"path_url",
... | [
1116,
4
] | [
1138,
23
] | python | en | ['en', 'en', 'en'] | True |
ExceptionalDownloader.__init__ | (self, http_client) |
:type http_client: HTTPClient
| def __init__(self, http_client):
"""
:type http_client: HTTPClient
"""
super(ExceptionalDownloader, self).__init__()
self.http_client = http_client | [
"def",
"__init__",
"(",
"self",
",",
"http_client",
")",
":",
"super",
"(",
"ExceptionalDownloader",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"http_client",
"=",
"http_client"
] | [
1236,
4
] | [
1242,
38
] | python | en | ['en', 'error', 'th'] | False | |
TclLibrary.check_if_installed | (self) |
Check if tcl is available
:return:
|
Check if tcl is available
:return:
| def check_if_installed(self):
"""
Check if tcl is available
:return:
"""
if is_windows():
self.log.debug("Checking if %s variable is present in environment", TclLibrary.ENV_NAME)
if not os.environ.get(TclLibrary.ENV_NAME, None):
self.log.de... | [
"def",
"check_if_installed",
"(",
"self",
")",
":",
"if",
"is_windows",
"(",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Checking if %s variable is present in environment\"",
",",
"TclLibrary",
".",
"ENV_NAME",
")",
"if",
"not",
"os",
".",
"environ",
"... | [
1426,
4
] | [
1441,
23
] | python | en | ['en', 'error', 'th'] | False |
TclLibrary.install | (self) |
:return:
|
:return:
| def install(self):
"""
:return:
"""
tcl_dir = self._find_tcl_dir()
if tcl_dir:
self.log.debug("Tcl directory was found: %s", tcl_dir)
self._set_env_variable(tcl_dir)
if not self.check_if_installed():
self.log.warning("No Tcl library wa... | [
"def",
"install",
"(",
"self",
")",
":",
"tcl_dir",
"=",
"self",
".",
"_find_tcl_dir",
"(",
")",
"if",
"tcl_dir",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Tcl directory was found: %s\"",
",",
"tcl_dir",
")",
"self",
".",
"_set_env_variable",
"(",
"tc... | [
1457,
4
] | [
1467,
56
] | python | en | ['en', 'error', 'th'] | False |
MirrorsManager.__init__ | (self, http_client, base_link, parent_logger) |
:type base_link: str
:type http_client: HTTPClient
| def __init__(self, http_client, base_link, parent_logger):
"""
:type base_link: str
:type http_client: HTTPClient
"""
self.base_link = base_link
self.log = parent_logger.getChild(self.__class__.__name__)
self.http_client = http_client
self.page_source = N... | [
"def",
"__init__",
"(",
"self",
",",
"http_client",
",",
"base_link",
",",
"parent_logger",
")",
":",
"self",
".",
"base_link",
"=",
"base_link",
"self",
".",
"log",
"=",
"parent_logger",
".",
"getChild",
"(",
"self",
".",
"__class__",
".",
"__name__",
")"... | [
1494,
4
] | [
1503,
31
] | python | en | ['en', 'error', 'th'] | False | |
DummyScreen.get_cols_rows | (self) |
Dummy cols and rows
:return:
|
Dummy cols and rows | def get_cols_rows(self):
"""
Dummy cols and rows
:return:
"""
return self.size | [
"def",
"get_cols_rows",
"(",
"self",
")",
":",
"return",
"self",
".",
"size"
] | [
1596,
4
] | [
1602,
24
] | 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.